...
1 package audit
2
3 import (
4 "bytes"
5 "context"
6
7 "github.com/99designs/gqlgen/graphql"
8 "github.com/vektah/gqlparser/v2/formatter"
9
10 "edge-infra.dev/pkg/edge/api/graphqlhelpers"
11 "edge-infra.dev/pkg/edge/api/middleware"
12 "edge-infra.dev/pkg/edge/api/middleware/request"
13 "edge-infra.dev/pkg/edge/audit"
14 "edge-infra.dev/pkg/edge/bsl"
15 )
16
17 func (a Provider) ExtensionName() string { return "AuditLog" }
18 func (a Provider) Validate(_ graphql.ExecutableSchema) error { return nil }
19
20 func (a Provider) InterceptResponse(ctx context.Context, next graphql.ResponseHandler) *graphql.Response {
21 user := middleware.ForContext(ctx)
22 resp := next(ctx)
23 auditlogger := audit.New("edge-api")
24 opts := []audit.Option{
25 audit.WithStatus(graphqlhelpers.GetResponseStatus(resp)),
26 audit.WithUserIP(request.FromContext(ctx, request.IPCtxKey{})),
27 audit.WithUserAgent(request.FromContext(ctx, request.UserAgentCtxKey{})),
28 audit.WithRequestURL(request.FromContext(ctx, request.URLCtxKey{})),
29 audit.WithMethod(request.FromContext(ctx, request.MethodCtxKey{})),
30 audit.WithIdentifier(request.FromContext(ctx, request.CorrelationIDCtxKey{})),
31 }
32 if user != nil {
33 opts = append(opts, audit.WithActor(user.Username),
34 audit.WithAuthProvider(user.AuthProvider),
35 audit.WithTenant(bsl.GetOrgShortName(user.Organization)))
36 }
37 opctx := graphql.GetOperationContext(ctx)
38 op := graphqlhelpers.GetOperation(opctx)
39 if op != nil {
40 opts = append(opts, audit.WithOperationName(string(*op)))
41 }
42 rawquery := graphqlhelpers.GetRawQuery(opctx)
43 schema, err := graphqlhelpers.ParseQuery(rawquery)
44 if err != nil {
45 return resp
46 }
47 graphqlhelpers.SanitizeDocument(schema)
48 variables := graphqlhelpers.GetVariables(opctx)
49 graphqlhelpers.UpdateQueryWithVariables(schema, variables)
50 buf := bytes.NewBuffer(nil)
51 formatter.NewFormatter(buf).FormatQueryDocument(schema)
52 opts = append(opts, audit.WithInput(buf.String()))
53 params := graphqlhelpers.GetParams(opctx, schema)
54 auditlogger.Log(append(opts, audit.WithParameters(params))...)
55 return resp
56 }
57
View as plain text