Files
hetty/pkg/reqlog/reqlog.go

314 lines
8.0 KiB
Go
Raw Normal View History

2019-12-01 14:07:12 +01:00
package reqlog
import (
"bytes"
2020-09-26 23:36:48 +02:00
"context"
"errors"
"fmt"
2022-01-21 11:45:54 +01:00
"io"
2019-12-01 14:07:12 +01:00
"net/http"
"connectrpc.com/connect"
"github.com/oklog/ulid/v2"
2022-01-21 11:45:54 +01:00
"github.com/dstotijn/hetty/pkg/filter"
httppb "github.com/dstotijn/hetty/pkg/http"
2022-02-27 14:28:28 +01:00
"github.com/dstotijn/hetty/pkg/log"
2020-09-22 18:33:02 +02:00
"github.com/dstotijn/hetty/pkg/proxy"
2020-10-01 21:46:35 +02:00
"github.com/dstotijn/hetty/pkg/scope"
2019-12-01 14:07:12 +01:00
)
2020-10-01 21:46:35 +02:00
type contextKey int
2022-03-23 14:31:27 +01:00
const (
LogBypassedKey contextKey = iota
ReqLogIDKey
)
2020-10-01 21:46:35 +02:00
2022-01-21 11:45:54 +01:00
var (
ErrRequestLogNotFound = errors.New("reqlog: request not found")
2022-01-21 11:45:54 +01:00
ErrProjectIDMustBeSet = errors.New("reqlog: project ID must be set")
)
type Service struct {
2022-02-22 14:10:39 +01:00
bypassOutOfScopeRequests bool
reqsFilter *RequestLogsFilter
activeProjectID string
2022-02-22 14:10:39 +01:00
scope *scope.Scope
repo Repository
2022-02-27 14:28:28 +01:00
logger log.Logger
2020-10-01 21:46:35 +02:00
}
type Config struct {
ActiveProjectID string
2025-01-13 23:15:18 +01:00
Scope *scope.Scope
Repository Repository
Logger log.Logger
2019-12-01 14:07:12 +01:00
}
func NewService(cfg Config) *Service {
s := &Service{
2025-01-13 23:15:18 +01:00
activeProjectID: cfg.ActiveProjectID,
repo: cfg.Repository,
scope: cfg.Scope,
logger: cfg.Logger,
2020-10-01 21:46:35 +02:00
}
2022-02-27 14:28:28 +01:00
if s.logger == nil {
s.logger = log.NewNopLogger()
}
return s
2020-10-29 20:54:17 +01:00
}
func (svc *Service) ListHttpRequestLogs(ctx context.Context, req *connect.Request[ListHttpRequestLogsRequest]) (*connect.Response[ListHttpRequestLogsResponse], error) {
projectID := svc.activeProjectID
if projectID == "" {
return nil, connect.NewError(connect.CodeFailedPrecondition, ErrProjectIDMustBeSet)
}
reqLogs, err := svc.repo.FindRequestLogs(ctx, projectID, svc.filterRequestLog)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("reqlog: failed to find request logs: %w", err))
}
return connect.NewResponse(&ListHttpRequestLogsResponse{
HttpRequestLogs: reqLogs,
}), nil
}
func (svc *Service) filterRequestLog(reqLog *HttpRequestLog) (bool, error) {
if svc.reqsFilter.GetOnlyInScope() && svc.scope != nil && !reqLog.MatchScope(svc.scope) {
return false, nil
}
var f filter.Expression
var err error
if expr := svc.reqsFilter.GetSearchExpr(); expr != "" {
f, err = filter.ParseQuery(expr)
if err != nil {
return false, fmt.Errorf("failed to parse search expression: %w", err)
}
}
if f == nil {
return true, nil
}
match, err := reqLog.Matches(f)
if err != nil {
return false, fmt.Errorf("failed to match search expression for request log (id: %v): %w", reqLog.Id, err)
}
return match, nil
}
func (svc *Service) FindRequestLogByID(ctx context.Context, id string) (*HttpRequestLog, error) {
if svc.activeProjectID == "" {
return nil, connect.NewError(connect.CodeFailedPrecondition, ErrProjectIDMustBeSet)
}
2025-01-13 23:15:18 +01:00
return svc.repo.FindRequestLogByID(ctx, svc.activeProjectID, id)
}
// GetHttpRequestLog implements HttpRequestLogServiceHandler.
func (svc *Service) GetHttpRequestLog(ctx context.Context, req *connect.Request[GetHttpRequestLogRequest]) (*connect.Response[GetHttpRequestLogResponse], error) {
id, err := ulid.Parse(req.Msg.Id)
if err != nil {
return nil, connect.NewError(connect.CodeInvalidArgument, err)
}
reqLog, err := svc.repo.FindRequestLogByID(ctx, svc.activeProjectID, id.String())
if errors.Is(err, ErrRequestLogNotFound) {
return nil, connect.NewError(connect.CodeNotFound, err)
}
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
return connect.NewResponse(&GetHttpRequestLogResponse{
HttpRequestLog: reqLog,
}), nil
}
func (svc *Service) ClearHttpRequestLogs(ctx context.Context, req *connect.Request[ClearHttpRequestLogsRequest]) (*connect.Response[ClearHttpRequestLogsResponse], error) {
err := svc.repo.ClearRequestLogs(ctx, svc.activeProjectID)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, fmt.Errorf("reqlog: failed to clear request logs: %w", err))
}
return connect.NewResponse(&ClearHttpRequestLogsResponse{}), nil
}
func (svc *Service) storeResponse(ctx context.Context, reqLogID string, res *http.Response) error {
respb, err := httppb.ParseHTTPResponse(res)
2022-01-21 11:45:54 +01:00
if err != nil {
2022-02-22 14:10:39 +01:00
return err
2022-01-21 11:45:54 +01:00
}
return svc.repo.StoreResponseLog(ctx, svc.activeProjectID, reqLogID, respb)
}
func (svc *Service) RequestModifier(next proxy.RequestModifyFunc) proxy.RequestModifyFunc {
return func(req *http.Request) {
next(req)
clone := req.Clone(req.Context())
2021-04-25 16:23:53 +02:00
var body []byte
2021-04-25 16:23:53 +02:00
if req.Body != nil {
// TODO: Use io.LimitReader.
var err error
2021-04-25 16:23:53 +02:00
body, err = io.ReadAll(req.Body)
if err != nil {
2022-02-27 14:28:28 +01:00
svc.logger.Errorw("Failed to read request body for logging.",
"error", err)
return
}
2021-04-25 16:23:53 +02:00
req.Body = io.NopCloser(bytes.NewBuffer(body))
clone.Body = io.NopCloser(bytes.NewBuffer(body))
}
2022-01-21 11:45:54 +01:00
// Bypass logging if no project is active.
if svc.activeProjectID == "" {
2020-10-01 21:46:35 +02:00
ctx := context.WithValue(req.Context(), LogBypassedKey, true)
2020-10-04 11:50:03 +02:00
*req = *req.WithContext(ctx)
2021-04-25 16:23:53 +02:00
2022-02-27 14:28:28 +01:00
svc.logger.Debugw("Bypassed logging: no active project.",
"url", req.URL.String())
2020-10-01 21:46:35 +02:00
return
}
2022-01-21 11:45:54 +01:00
// Bypass logging if this setting is enabled and the incoming request
// doesn't match any scope rules.
2022-02-22 14:10:39 +01:00
if svc.bypassOutOfScopeRequests && !svc.scope.Match(clone, body) {
2020-10-11 17:09:39 +02:00
ctx := context.WithValue(req.Context(), LogBypassedKey, true)
*req = *req.WithContext(ctx)
2021-04-25 16:23:53 +02:00
2022-02-27 14:28:28 +01:00
svc.logger.Debugw("Bypassed logging: request doesn't match any scope rules.",
"url", req.URL.String())
2020-10-11 17:09:39 +02:00
return
2022-01-21 11:45:54 +01:00
}
2022-03-23 14:31:27 +01:00
reqID, ok := proxy.RequestIDFromContext(req.Context())
if !ok {
svc.logger.Errorw("Bypassed logging: request doesn't have an ID.")
return
}
proto, ok := httppb.ProtoMap[clone.Proto]
if !ok {
svc.logger.Errorw("Bypassed logging: request has an invalid protocol.",
"proto", clone.Proto)
return
}
method, ok := httppb.MethodMap[clone.Method]
if !ok {
svc.logger.Errorw("Bypassed logging: request has an invalid method.",
"method", clone.Method)
return
}
headers := []*httppb.Header{}
for k, v := range clone.Header {
for _, vv := range v {
headers = append(headers, &httppb.Header{Key: k, Value: vv})
}
}
reqLog := &HttpRequestLog{
Id: reqID.String(),
ProjectId: svc.activeProjectID,
Request: &httppb.Request{
Url: clone.URL.String(),
Method: method,
Protocol: proto,
Headers: headers,
Body: body,
},
2022-01-21 11:45:54 +01:00
}
err := svc.repo.StoreRequestLog(req.Context(), reqLog)
if err != nil {
2022-02-27 14:28:28 +01:00
svc.logger.Errorw("Failed to store request log.",
"error", err)
return
}
2021-04-25 16:23:53 +02:00
2022-02-27 14:28:28 +01:00
svc.logger.Debugw("Stored request log.",
"reqLogID", reqLog.Id,
"url", reqLog.Request.Url,
)
ctx := context.WithValue(req.Context(), ReqLogIDKey, reqID)
2020-10-04 11:50:03 +02:00
*req = *req.WithContext(ctx)
}
}
func (svc *Service) ResponseModifier(next proxy.ResponseModifyFunc) proxy.ResponseModifyFunc {
return func(res *http.Response) error {
if err := next(res); err != nil {
return err
}
2020-10-01 21:46:35 +02:00
if bypassed, _ := res.Request.Context().Value(LogBypassedKey).(bool); bypassed {
return nil
}
2022-03-23 14:31:27 +01:00
reqLogID, ok := res.Request.Context().Value(ReqLogIDKey).(ulid.ULID)
2022-01-21 11:45:54 +01:00
if !ok {
return errors.New("reqlog: request is missing ID")
}
clone := *res
2022-03-23 14:31:27 +01:00
if res.Body != nil {
// TODO: Use io.LimitReader.
body, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("reqlog: could not read response body: %w", err)
}
2021-04-25 16:23:53 +02:00
2022-03-23 14:31:27 +01:00
res.Body = io.NopCloser(bytes.NewBuffer(body))
clone.Body = io.NopCloser(bytes.NewBuffer(body))
}
go func() {
if err := svc.storeResponse(context.Background(), reqLogID.String(), &clone); err != nil {
2022-02-27 14:28:28 +01:00
svc.logger.Errorw("Failed to store response log.",
"error", err)
} else {
svc.logger.Debugw("Stored response log.",
"reqLogID", reqLogID.String())
}
}()
return nil
}
2019-12-01 14:07:12 +01:00
}
2022-02-22 14:10:39 +01:00
func (svc *Service) SetActiveProjectID(id string) {
2022-02-22 14:10:39 +01:00
svc.activeProjectID = id
}
func (svc *Service) ActiveProjectID() string {
2022-02-22 14:10:39 +01:00
return svc.activeProjectID
}
func (svc *Service) SetRequestLogsFilter(filter *RequestLogsFilter) {
svc.reqsFilter = filter
2022-02-22 14:10:39 +01:00
}
func (svc *Service) SetBypassOutOfScopeRequests(bypass bool) {
2022-02-22 14:10:39 +01:00
svc.bypassOutOfScopeRequests = bypass
}
func (svc *Service) BypassOutOfScopeRequests() bool {
2022-02-22 14:10:39 +01:00
return svc.bypassOutOfScopeRequests
}