From 5c3b0b97143ad76d2996ba0af828973a1bde1ce1 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Fri, 27 Nov 2026 21:06:32 +1100 Subject: [PATCH] feat(audit,telemetry): add append-only audit module, OTel tracing, and /metrics (#2156) --- .../pg/migrations/00020_audit_events.sql | 24 ++ internal/platform/pg/pg.go | 12 +- internal/platform/pg/pg_test.go | 26 ++ internal/platform/telemetry/telemetry.go | 260 +++++++++++++++++ internal/platform/telemetry/telemetry_test.go | 136 +++++++++ modules/audit/api.go | 257 +++++++++++++++++ modules/audit/audit.go | 222 +++++++++++++++ modules/audit/audit_test.go | 264 ++++++++++++++++++ modules/audit/internal/store/store.go | 95 +++++++ 9 files changed, 1295 insertions(+), 1 deletion(-) create mode 100644 internal/platform/pg/migrations/00020_audit_events.sql create mode 100644 internal/platform/telemetry/telemetry.go create mode 100644 internal/platform/telemetry/telemetry_test.go create mode 100644 modules/audit/api.go create mode 100644 modules/audit/audit.go create mode 100644 modules/audit/audit_test.go create mode 100644 modules/audit/internal/store/store.go diff --git a/internal/platform/pg/migrations/00020_audit_events.sql b/internal/platform/pg/migrations/00020_audit_events.sql new file mode 100644 index 000000000..11c9ebb36 --- /dev/null +++ b/internal/platform/pg/migrations/00020_audit_events.sql @@ -0,0 +1,24 @@ +-- +goose Up +CREATE SCHEMA audit; + +-- Append-only audit events. The runtime database role holds only SELECT and +-- INSERT privileges on this schema so records cannot be modified or deleted. +CREATE TABLE audit.events ( + id uuid PRIMARY KEY, + org_id text NOT NULL, + at timestamptz NOT NULL DEFAULT now(), + category text NOT NULL, + action text NOT NULL, + actor_id text NOT NULL, + actor_kind text NOT NULL DEFAULT '', + resource_kind text NOT NULL DEFAULT '', + resource_id text NOT NULL DEFAULT '', + outcome text NOT NULL, + trace_id text NOT NULL DEFAULT '', + detail jsonb NOT NULL DEFAULT '{}' +); +CREATE INDEX idx_audit_events_org_at ON audit.events (org_id, at DESC); +CREATE INDEX idx_audit_events_org_category_at ON audit.events (org_id, category, at DESC); + +-- +goose Down +DROP SCHEMA audit CASCADE; diff --git a/internal/platform/pg/pg.go b/internal/platform/pg/pg.go index 9db99ec50..8a24b9d9e 100644 --- a/internal/platform/pg/pg.go +++ b/internal/platform/pg/pg.go @@ -102,6 +102,15 @@ func lockMigrate(ctx context.Context, db *sqlx.DB) (release func(), err error) { func migrateLockKey() string { return "archie." + migrateLockName + ".owner" } +// schemaPrivileges returns the runtime DML privileges for schema. The audit +// schema is append-only so the runtime role may never UPDATE or DELETE rows. +func schemaPrivileges(schema string) string { + if schema == "audit" { + return "SELECT, INSERT" + } + return "SELECT, INSERT, UPDATE, DELETE" +} + // grantRuntime gives the runtime role USAGE and DML on each schema, never DDL. func grantRuntime(ctx context.Context, db *sqlx.DB, runtimeURL string, schemas []string) error { cfg, err := pgx.ParseConfig(runtimeURL) @@ -111,9 +120,10 @@ func grantRuntime(ctx context.Context, db *sqlx.DB, runtimeURL string, schemas [ role := pgx.Identifier{cfg.User}.Sanitize() for _, schema := range schemas { name := pgx.Identifier{schema}.Sanitize() + privs := schemaPrivileges(schema) for _, stmt := range []string{ "GRANT USAGE ON SCHEMA " + name + " TO " + role, - "GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA " + name + " TO " + role, + "GRANT " + privs + " ON ALL TABLES IN SCHEMA " + name + " TO " + role, // A table keyed by a serial draws from a sequence, which is its // own grant: a module whose insert draws on one would fail DML it // is otherwise allowed. diff --git a/internal/platform/pg/pg_test.go b/internal/platform/pg/pg_test.go index 225916398..46b08660c 100644 --- a/internal/platform/pg/pg_test.go +++ b/internal/platform/pg/pg_test.go @@ -2,6 +2,7 @@ package pg import ( "slices" + "strings" "testing" ) @@ -41,3 +42,28 @@ func TestMissingMigrations(t *testing.T) { }) } } + +// TestSchemaPrivileges guards the append-only privilege split for the audit +// schema so runtime database credentials can never UPDATE or DELETE audit rows. +func TestSchemaPrivileges(t *testing.T) { + tests := []struct { + schema string + want string + }{ + {schema: "audit", want: "SELECT, INSERT"}, + {schema: "governance", want: "SELECT, INSERT, UPDATE, DELETE"}, + {schema: "runs", want: "SELECT, INSERT, UPDATE, DELETE"}, + {schema: "", want: "SELECT, INSERT, UPDATE, DELETE"}, + } + for _, tc := range tests { + t.Run(tc.schema, func(t *testing.T) { + got := schemaPrivileges(tc.schema) + if got != tc.want { + t.Fatalf("schemaPrivileges(%q) = %q, want %q", tc.schema, got, tc.want) + } + if tc.schema == "audit" && (strings.Contains(got, "UPDATE") || strings.Contains(got, "DELETE")) { + t.Fatalf("audit schema must not grant UPDATE or DELETE, got %q", got) + } + }) + } +} diff --git a/internal/platform/telemetry/telemetry.go b/internal/platform/telemetry/telemetry.go new file mode 100644 index 000000000..05e0475fa --- /dev/null +++ b/internal/platform/telemetry/telemetry.go @@ -0,0 +1,260 @@ +// Package telemetry configures OpenTelemetry trace export, trace-correlated +// structured logging, HTTP span middleware, and an internal Prometheus /metrics +// endpoint using the Go standard library. +package telemetry + +import ( + "context" + "fmt" + "log/slog" + "net/http" + "os" + "runtime" + "strconv" + "strings" + "sync/atomic" + "time" + + "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/sdk/resource" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + semconv "go.opentelemetry.io/otel/semconv/v1.43.0" + "go.opentelemetry.io/otel/trace" +) + +const ( + otlpEndpointEnv = "OTEL_EXPORTER_OTLP_ENDPOINT" + metricsMediaType = "text/plain; version=0.0.4; charset=utf-8" + shutdownTimeout = 5 * time.Second +) + +// Setup registers the W3C TraceContext propagator and, when +// OTEL_EXPORTER_OTLP_ENDPOINT is set, installs an OTLP/gRPC TracerProvider. +// The returned shutdown function flushes pending spans on exit. +func Setup(ctx context.Context, serviceName, version string) (func(context.Context) error, error) { + otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator( + propagation.TraceContext{}, + propagation.Baggage{}, + )) + if strings.TrimSpace(os.Getenv(otlpEndpointEnv)) == "" { + return func(context.Context) error { return nil }, nil + } + res, err := resource.Merge(resource.Default(), resource.NewWithAttributes( + semconv.SchemaURL, + semconv.ServiceName(serviceName), + semconv.ServiceVersion(version), + semconv.ServiceInstanceID(instanceID()), + )) + if err != nil { + return nil, fmt.Errorf("telemetry resource: %w", err) + } + exporter, err := otlptracegrpc.New(ctx) + if err != nil { + return nil, fmt.Errorf("telemetry exporter: %w", err) + } + tp := sdktrace.NewTracerProvider( + sdktrace.WithBatcher(exporter), + sdktrace.WithResource(res), + ) + otel.SetTracerProvider(tp) + return func(shutdownCtx context.Context) error { + if _, hasDeadline := shutdownCtx.Deadline(); !hasDeadline { + var cancel context.CancelFunc + shutdownCtx, cancel = context.WithTimeout(context.WithoutCancel(shutdownCtx), shutdownTimeout) + defer cancel() + } + return tp.Shutdown(shutdownCtx) + }, nil +} + +func instanceID() string { + host, _ := os.Hostname() + return host + "-" + strconv.Itoa(os.Getpid()) +} + +// stampedKey marks a context whose log record already carries trace_id and +// span_id so nested trace handlers do not emit duplicate attributes. +type stampedKey struct{} + +type logHandler struct { + inner slog.Handler +} + +// NewLogHandler wraps base so log records emitted with an active span in ctx +// include trace_id and span_id attributes. +func NewLogHandler(base slog.Handler) slog.Handler { + return logHandler{inner: base} +} + +func (h logHandler) Enabled(ctx context.Context, level slog.Level) bool { + return h.inner.Enabled(ctx, level) +} + +func (h logHandler) Handle(ctx context.Context, r slog.Record) error { + if sc := trace.SpanContextFromContext(ctx); sc.IsValid() && ctx.Value(stampedKey{}) == nil { + r.AddAttrs( + slog.String("trace_id", sc.TraceID().String()), + slog.String("span_id", sc.SpanID().String()), + ) + ctx = context.WithValue(ctx, stampedKey{}, true) + } + return h.inner.Handle(ctx, r) +} + +func (h logHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + return logHandler{inner: h.inner.WithAttrs(attrs)} +} + +func (h logHandler) WithGroup(name string) slog.Handler { + return logHandler{inner: h.inner.WithGroup(name)} +} + +// Metrics tracks process-local HTTP request counts, latency sums, and Go +// runtime metrics for Prometheus scraping. +type Metrics struct { + started time.Time + inFlight atomic.Int64 + requests2xx atomic.Int64 + requests3xx atomic.Int64 + requests4xx atomic.Int64 + requests5xx atomic.Int64 + requestsOther atomic.Int64 + durationNanos atomic.Int64 + durationCount atomic.Int64 +} + +// NewMetrics returns a Metrics collector anchored at the current time. +func NewMetrics() *Metrics { + return &Metrics{started: time.Now()} +} + +// Middleware records HTTP request counts, durations, and in-flight requests, +// and wraps next in otelhttp.NewHandler for HTTP span creation. +func (m *Metrics) Middleware(next http.Handler) http.Handler { + instrumented := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + m.inFlight.Add(1) + start := time.Now() + sw := &statusWriter{ResponseWriter: w, status: http.StatusOK} + defer func() { + m.inFlight.Add(-1) + m.recordRequest(sw.status, time.Since(start)) + }() + next.ServeHTTP(sw, r) + }) + return otelhttp.NewHandler(instrumented, "http", + otelhttp.WithFilter(func(r *http.Request) bool { + return !isProbeOrMetrics(r.URL.Path) + }), + ) +} + +func isProbeOrMetrics(path string) bool { + return strings.HasPrefix(path, "/health") || path == "/readyz" || path == "/startupz" || path == "/metrics" +} + +func (m *Metrics) recordRequest(status int, took time.Duration) { + m.durationCount.Add(1) + m.durationNanos.Add(took.Nanoseconds()) + switch status / 100 { + case 2: + m.requests2xx.Add(1) + case 3: + m.requests3xx.Add(1) + case 4: + m.requests4xx.Add(1) + case 5: + m.requests5xx.Add(1) + default: + m.requestsOther.Add(1) + } +} + +type statusWriter struct { + http.ResponseWriter + status int + wroteHeader bool +} + +func (w *statusWriter) WriteHeader(code int) { + if !w.wroteHeader { + w.status = code + w.wroteHeader = true + } + w.ResponseWriter.WriteHeader(code) +} + +func (w *statusWriter) Write(p []byte) (int, error) { + if !w.wroteHeader { + w.wroteHeader = true + } + return w.ResponseWriter.Write(p) +} + +func (w *statusWriter) Unwrap() http.ResponseWriter { + return w.ResponseWriter +} + +// MetricsHandler serves Prometheus text format metrics on an internal endpoint. +func (m *Metrics) MetricsHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + var ms runtime.MemStats + runtime.ReadMemStats(&ms) + + uptime := time.Since(m.started).Seconds() + durSec := float64(m.durationNanos.Load()) / float64(time.Second) + + w.Header().Set("Content-Type", metricsMediaType) + w.Header().Set("Cache-Control", "no-store") + _, _ = fmt.Fprintf(w, + "# HELP archie_uptime_seconds Process uptime in seconds.\n"+ + "# TYPE archie_uptime_seconds gauge\n"+ + "archie_uptime_seconds %.6f\n"+ + "# HELP archie_http_requests_in_flight Current number of in-flight HTTP requests.\n"+ + "# TYPE archie_http_requests_in_flight gauge\n"+ + "archie_http_requests_in_flight %d\n"+ + "# HELP archie_http_requests_total Total number of HTTP requests handled by status class.\n"+ + "# TYPE archie_http_requests_total counter\n"+ + "archie_http_requests_total{status=\"2xx\"} %d\n"+ + "archie_http_requests_total{status=\"3xx\"} %d\n"+ + "archie_http_requests_total{status=\"4xx\"} %d\n"+ + "archie_http_requests_total{status=\"5xx\"} %d\n"+ + "archie_http_requests_total{status=\"other\"} %d\n"+ + "# HELP archie_http_request_duration_seconds Total HTTP request duration and count.\n"+ + "# TYPE archie_http_request_duration_seconds summary\n"+ + "archie_http_request_duration_seconds_sum %.6f\n"+ + "archie_http_request_duration_seconds_count %d\n"+ + "# HELP go_goroutines Number of goroutines that currently exist.\n"+ + "# TYPE go_goroutines gauge\n"+ + "go_goroutines %d\n"+ + "# HELP go_memstats_alloc_bytes Number of bytes allocated and still in use.\n"+ + "# TYPE go_memstats_alloc_bytes gauge\n"+ + "go_memstats_alloc_bytes %d\n"+ + "# HELP go_memstats_heap_inuse_bytes Number of heap bytes that are in use.\n"+ + "# TYPE go_memstats_heap_inuse_bytes gauge\n"+ + "go_memstats_heap_inuse_bytes %d\n"+ + "# HELP go_memstats_sys_bytes Number of bytes obtained from system.\n"+ + "# TYPE go_memstats_sys_bytes gauge\n"+ + "go_memstats_sys_bytes %d\n"+ + "# HELP go_gc_cycles_total Total number of completed GC cycles.\n"+ + "# TYPE go_gc_cycles_total counter\n"+ + "go_gc_cycles_total %d\n", + uptime, + m.inFlight.Load(), + m.requests2xx.Load(), + m.requests3xx.Load(), + m.requests4xx.Load(), + m.requests5xx.Load(), + m.requestsOther.Load(), + durSec, + m.durationCount.Load(), + runtime.NumGoroutine(), + ms.Alloc, + ms.HeapInuse, + ms.Sys, + ms.NumGC, + ) + }) +} diff --git a/internal/platform/telemetry/telemetry_test.go b/internal/platform/telemetry/telemetry_test.go new file mode 100644 index 000000000..a0c126648 --- /dev/null +++ b/internal/platform/telemetry/telemetry_test.go @@ -0,0 +1,136 @@ +package telemetry + +import ( + "bytes" + "context" + json "encoding/json/v2" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "go.opentelemetry.io/otel" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/trace" +) + +// TestLogHandlerInjectsTraceAndSpanIDs guards that NewLogHandler attaches +// trace_id and span_id once when a valid span exists in ctx, and omits them +// when no span is active. +func TestLogHandlerInjectsTraceAndSpanIDs(t *testing.T) { + var buf bytes.Buffer + handler := NewLogHandler(NewLogHandler(slog.NewJSONHandler(&buf, nil))) + logger := slog.New(handler) + + logger.InfoContext(t.Context(), "without span") + if strings.Contains(buf.String(), "trace_id") || strings.Contains(buf.String(), "span_id") { + t.Fatalf("unexpected trace fields without span: %s", buf.String()) + } + buf.Reset() + + tp := sdktrace.NewTracerProvider() + t.Cleanup(func() { _ = tp.Shutdown(context.Background()) }) + ctx, span := tp.Tracer("telemetry-test").Start(t.Context(), "op") + defer span.End() + + logger.InfoContext(ctx, "with span") + line := buf.String() + if strings.Count(line, `"trace_id"`) != 1 || strings.Count(line, `"span_id"`) != 1 { + t.Fatalf("expected single trace_id and span_id fields, got: %s", line) + } + + var parsed map[string]any + if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &parsed); err != nil { + t.Fatalf("unmarshal log line: %v (%s)", err, line) + } + if parsed["trace_id"] != span.SpanContext().TraceID().String() { + t.Fatalf("trace_id = %v, want %s", parsed["trace_id"], span.SpanContext().TraceID().String()) + } + if parsed["span_id"] != span.SpanContext().SpanID().String() { + t.Fatalf("span_id = %v, want %s", parsed["span_id"], span.SpanContext().SpanID().String()) + } +} + +// TestMetricsMiddlewareAndPrometheusOutput guards HTTP span creation, request +// status counting, and Prometheus text exposition formatting. +func TestMetricsMiddlewareAndPrometheusOutput(t *testing.T) { + prevTP := otel.GetTracerProvider() + tp := sdktrace.NewTracerProvider() + otel.SetTracerProvider(tp) + t.Cleanup(func() { + otel.SetTracerProvider(prevTP) + _ = tp.Shutdown(context.Background()) + }) + + m := NewMetrics() + var sawValidSpan bool + var probeHadSpan bool + mux := http.NewServeMux() + mux.HandleFunc("/api/ok", func(w http.ResponseWriter, r *http.Request) { + sawValidSpan = trace.SpanContextFromContext(r.Context()).IsValid() + w.WriteHeader(http.StatusOK) + }) + mux.HandleFunc("/api/missing", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNotFound) + }) + mux.HandleFunc("/api/fail", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + }) + mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { + probeHadSpan = trace.SpanContextFromContext(r.Context()).IsValid() + w.WriteHeader(http.StatusOK) + }) + + wrapped := m.Middleware(mux) + for _, path := range []string{"/api/ok", "/api/missing", "/api/fail", "/healthz"} { + rec := httptest.NewRecorder() + wrapped.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil)) + } + if !sawValidSpan { + t.Fatal("expected otelhttp middleware to create a valid span for /api/ok") + } + if probeHadSpan { + t.Fatal("expected /healthz probe to be excluded from otelhttp span creation") + } + + metricsRec := httptest.NewRecorder() + m.MetricsHandler().ServeHTTP(metricsRec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/metrics", nil)) + if metricsRec.Code != http.StatusOK { + t.Fatalf("/metrics status = %d, want 200", metricsRec.Code) + } + if gotCT := metricsRec.Header().Get("Content-Type"); gotCT != metricsMediaType { + t.Fatalf("/metrics Content-Type = %q, want %q", gotCT, metricsMediaType) + } + + body := metricsRec.Body.String() + for _, want := range []string{ + "archie_uptime_seconds ", + "archie_http_requests_in_flight 0", + `archie_http_requests_total{status="2xx"} 2`, + `archie_http_requests_total{status="4xx"} 1`, + `archie_http_requests_total{status="5xx"} 1`, + "archie_http_request_duration_seconds_count 4", + "archie_http_request_duration_seconds_sum ", + "go_goroutines ", + "go_memstats_alloc_bytes ", + "go_gc_cycles_total ", + } { + if !strings.Contains(body, want) { + t.Fatalf("/metrics output missing %q:\n%s", want, body) + } + } +} + +// TestSetupWithoutEndpoint guards that Setup succeeds as a no-op when +// OTEL_EXPORTER_OTLP_ENDPOINT is unset. +func TestSetupWithoutEndpoint(t *testing.T) { + t.Setenv(otlpEndpointEnv, "") + shutdown, err := Setup(t.Context(), "archie", "test") + if err != nil { + t.Fatalf("Setup() error = %v", err) + } + if err := shutdown(t.Context()); err != nil { + t.Fatalf("shutdown() error = %v", err) + } +} diff --git a/modules/audit/api.go b/modules/audit/api.go new file mode 100644 index 000000000..770d861c9 --- /dev/null +++ b/modules/audit/api.go @@ -0,0 +1,257 @@ +package audit + +import ( + "context" + "encoding/csv" + "encoding/json/jsontext" + json "encoding/json/v2" + "errors" + "fmt" + "io" + "net/http" + "time" + + "github.com/danielgtaylor/huma/v2" + + "github.com/samcharles93/archie-core/internal/platform/httpapi" + "github.com/samcharles93/archie-core/modules/audit/internal/store" + "github.com/samcharles93/archie-core/modules/governance" +) + +const ( + exportFormatJSONL = "jsonl" + exportFormatCSV = "csv" +) + +type eventsInput struct { + Category string `query:"category" doc:"Only events in this category"` + Action string `query:"action" doc:"Only events for this action"` + Actor string `query:"actor" doc:"Only events by this actor ID"` + Since time.Time `query:"since" doc:"Only events recorded at or after this time"` + Until time.Time `query:"until" doc:"Only events recorded before this time"` + Limit int `query:"limit" default:"100" minimum:"1" maximum:"1000" doc:"How many events to return"` + Offset int `query:"offset" default:"0" minimum:"0" doc:"How many of the newest matching events to skip"` +} + +type exportInput struct { + Category string `query:"category" doc:"Only events in this category"` + Action string `query:"action" doc:"Only events for this action"` + Actor string `query:"actor" doc:"Only events by this actor ID"` + Since time.Time `query:"since" doc:"Only events recorded at or after this time"` + Until time.Time `query:"until" doc:"Only events recorded before this time"` + Limit int `query:"limit" default:"1000" minimum:"1" maximum:"1000" doc:"Maximum number of events to export"` + Offset int `query:"offset" default:"0" minimum:"0" doc:"How many of the newest matching events to skip"` + Format string `query:"format" default:"jsonl" enum:"jsonl,csv" doc:"Export format: jsonl or csv"` +} + +type eventsBody struct { + Events []Event `json:"events"` + More bool `json:"more" doc:"Whether older events match beyond this page"` +} + +// Register adds the Cedar-gated audit query and export routes. +func (m *Module) Register(api huma.API) { + tags := []string{"Audit"} + httpapi.Register(api, httpapi.Authorized(governance.ActionReadAudit, governance.KindAudit), huma.Operation{ + OperationID: "list-audit-events", + Method: http.MethodGet, + Path: "/api/audit/events", + Summary: "List append-only audit events", + Tags: tags, + }, m.listEvents) + httpapi.Register(api, httpapi.Authorized(governance.ActionReadAudit, governance.KindAudit), huma.Operation{ + OperationID: "export-audit-events", + Method: http.MethodGet, + Path: "/api/audit/events/export", + Summary: "Export append-only audit events as JSONL or CSV", + Tags: tags, + Responses: map[string]*huma.Response{"200": { + Description: "Audit events exported as JSON Lines or CSV", + Content: map[string]*huma.MediaType{ + "application/x-ndjson": {Schema: &huma.Schema{Type: huma.TypeString}}, + "text/csv": {Schema: &huma.Schema{Type: huma.TypeString}}, + }, + }}, + }, m.exportEvents) +} + +func (m *Module) listEvents(ctx context.Context, in *eventsInput) (*httpapi.Reply[eventsBody], error) { + if m.store == nil { + return nil, huma.Error503ServiceUnavailable("audit store is unavailable") + } + f := Filter{ + OrgID: m.callerOrg(ctx), + Category: in.Category, + Action: in.Action, + Actor: in.Actor, + Since: in.Since, + Until: in.Until, + Limit: in.Limit, + Offset: in.Offset, + } + if err := f.Validate(); err != nil { + return nil, huma.Error400BadRequest(err.Error()) + } + rows, err := m.store.List(ctx, store.Filter{ + OrgID: f.OrgID, + Category: f.Category, + Action: f.Action, + ActorID: f.Actor, + Since: f.Since, + Until: f.Until, + Limit: f.Limit + 1, + Offset: f.Offset, + }) + if err != nil { + if m.log != nil { + m.log.ErrorContext(ctx, "list audit events", "error", err) + } + return nil, huma.Error500InternalServerError("could not list audit events") + } + more := len(rows) > f.Limit + events := eventsFromRows(rows[:min(len(rows), f.Limit)]) + return httpapi.OK(eventsBody{Events: events, More: more}), nil +} + +func (m *Module) exportEvents(ctx context.Context, in *exportInput) (*huma.StreamResponse, error) { + if m.store == nil { + return nil, huma.Error503ServiceUnavailable("audit store is unavailable") + } + format := in.Format + if format == "" { + format = exportFormatJSONL + } + if format != exportFormatJSONL && format != exportFormatCSV { + return nil, huma.Error400BadRequest(fmt.Sprintf("unsupported export format %q", format)) + } + f := Filter{ + OrgID: m.callerOrg(ctx), + Category: in.Category, + Action: in.Action, + Actor: in.Actor, + Since: in.Since, + Until: in.Until, + Limit: in.Limit, + Offset: in.Offset, + } + if err := f.Validate(); err != nil { + return nil, huma.Error400BadRequest(err.Error()) + } + events, err := m.List(ctx, f) + if err != nil { + if errors.Is(err, ErrInvalidFilter) { + return nil, huma.Error400BadRequest(err.Error()) + } + if m.log != nil { + m.log.ErrorContext(ctx, "export audit events", "error", err) + } + return nil, huma.Error500InternalServerError("could not export audit events") + } + return &huma.StreamResponse{Body: func(hc huma.Context) { + writeExport(hc, format, events) + }}, nil +} + +func (m *Module) callerOrg(ctx context.Context) string { + if p, ok := governance.PrincipalFromContext(ctx); ok && p.Org != "" { + return string(p.Org) + } + return m.orgID +} + +func writeExport(hc huma.Context, format string, events []Event) { + hc.SetHeader("Cache-Control", "no-store") + w := hc.BodyWriter() + if format == exportFormatCSV { + hc.SetHeader("Content-Type", "text/csv; charset=utf-8") + hc.SetHeader("Content-Disposition", `attachment; filename="audit-events.csv"`) + hc.SetStatus(http.StatusOK) + _ = writeCSV(w, events) + return + } + hc.SetHeader("Content-Type", "application/x-ndjson; charset=utf-8") + hc.SetHeader("Content-Disposition", `attachment; filename="audit-events.jsonl"`) + hc.SetStatus(http.StatusOK) + _ = writeJSONL(w, events) +} + +func writeJSONL(w io.Writer, events []Event) error { + for _, ev := range events { + raw, err := json.Marshal(ev) + if err != nil { + return err + } + if _, err := w.Write(raw); err != nil { + return err + } + if _, err := w.Write([]byte("\n")); err != nil { + return err + } + } + return nil +} + +func writeCSV(w io.Writer, events []Event) error { + cw := csv.NewWriter(w) + header := []string{ + "id", "org_id", "at", "category", "action", + "actor_id", "actor_kind", "resource_kind", "resource_id", + "outcome", "trace_id", "detail", + } + if err := cw.Write(header); err != nil { + return err + } + for _, ev := range events { + detail := formatDetailString(ev.Detail) + row := []string{ + neutralizeCSVFormula(ev.ID.String()), + neutralizeCSVFormula(ev.OrgID), + neutralizeCSVFormula(ev.At.UTC().Format(time.RFC3339Nano)), + neutralizeCSVFormula(ev.Category), + neutralizeCSVFormula(ev.Action), + neutralizeCSVFormula(ev.ActorID), + neutralizeCSVFormula(ev.ActorKind), + neutralizeCSVFormula(ev.ResourceKind), + neutralizeCSVFormula(ev.ResourceID), + neutralizeCSVFormula(ev.Outcome), + neutralizeCSVFormula(ev.TraceID), + neutralizeCSVFormula(detail), + } + if err := cw.Write(row); err != nil { + return err + } + } + cw.Flush() + return cw.Error() +} + +func formatDetailString(detail any) string { + if detail == nil { + return "{}" + } + if raw, ok := detail.(jsontext.Value); ok { + if len(raw) == 0 { + return "{}" + } + return string(raw) + } + raw, err := json.Marshal(detail) + if err != nil { + return "{}" + } + return string(raw) +} + +// neutralizeCSVFormula prefixes spreadsheet formula triggers (=, +, -, @, tab, +// carriage return) with a single quote so exported CSV cells cannot execute as +// formulas when opened in Excel or LibreOffice Calc. +func neutralizeCSVFormula(s string) string { + if s == "" { + return s + } + switch s[0] { + case '=', '+', '-', '@', '\t', '\r': + return "'" + s + } + return s +} diff --git a/modules/audit/audit.go b/modules/audit/audit.go new file mode 100644 index 000000000..d73df8ba1 --- /dev/null +++ b/modules/audit/audit.go @@ -0,0 +1,222 @@ +// Package audit records and exports append-only security and operational audit +// events, backed by PostgreSQL and a structured stdout log stream. +package audit + +import ( + "bytes" + "context" + "encoding/json/jsontext" + json "encoding/json/v2" + "errors" + "fmt" + "log/slog" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" + "go.opentelemetry.io/otel/trace" + + "github.com/samcharles93/archie-core/internal/platform/auditjson" + "github.com/samcharles93/archie-core/modules/audit/internal/store" +) + +const ( + defaultLimit = 100 + maxLimit = 1000 +) + +// ErrInvalidFilter indicates invalid query or export filter parameters. +var ErrInvalidFilter = errors.New("invalid audit filter") + +// Event is a single immutable audit record. +type Event struct { + ID uuid.UUID `json:"id"` + OrgID string `json:"org_id"` + At time.Time `json:"at"` + Category string `json:"category"` + Action string `json:"action"` + ActorID string `json:"actor_id"` + ActorKind string `json:"actor_kind,omitzero"` + ResourceKind string `json:"resource_kind,omitzero"` + ResourceID string `json:"resource_id,omitzero"` + Outcome string `json:"outcome"` + TraceID string `json:"trace_id,omitzero"` + Detail any `json:"detail,omitzero"` +} + +// Filter narrows audit event queries. +type Filter struct { + OrgID string + Category string + Action string + Actor string + Since time.Time + Until time.Time + Limit int + Offset int +} + +// Validate checks filter bounds and time range ordering. +func (f Filter) Validate() error { + if f.Limit < 1 || f.Limit > maxLimit { + return fmt.Errorf("%w: limit must be between 1 and %d", ErrInvalidFilter, maxLimit) + } + if f.Offset < 0 { + return fmt.Errorf("%w: offset must be non-negative", ErrInvalidFilter) + } + if !f.Since.IsZero() && !f.Until.IsZero() && f.Since.After(f.Until) { + return fmt.Errorf("%w: since must not be after until", ErrInvalidFilter) + } + return nil +} + +type auditStore interface { + Insert(ctx context.Context, row store.EventRow) error + List(ctx context.Context, f store.Filter) ([]store.EventRow, error) +} + +// Module records and serves one organisation's append-only audit stream. +type Module struct { + orgID string + store auditStore + log *slog.Logger +} + +// NewModule returns the audit module for orgID. +func NewModule(db *sqlx.DB, log *slog.Logger, orgID string) *Module { + var st auditStore + if db != nil { + st = store.New(db) + } + return &Module{orgID: orgID, store: st, log: log} +} + +// Record redacts e.Detail, persists the event to audit.events, and emits a +// structured JSON log record tagged with "audit", true. +func (m *Module) Record(ctx context.Context, e Event) error { + if m.store == nil { + return errors.New("audit store is not configured") + } + if e.Category == "" || e.Action == "" || e.ActorID == "" || e.Outcome == "" { + return errors.New("audit event requires category, action, actor_id, and outcome") + } + if e.ID == uuid.Nil { + e.ID = uuid.New() + } + if e.OrgID == "" { + e.OrgID = m.orgID + } + if e.At.IsZero() { + e.At = time.Now().UTC() + } + if e.TraceID == "" { + if sc := trace.SpanContextFromContext(ctx); sc.IsValid() { + e.TraceID = sc.TraceID().String() + } + } + detail := redactDetail(e.Detail) + row := store.EventRow{ + ID: e.ID, + OrgID: e.OrgID, + At: e.At.UTC(), + Category: e.Category, + Action: e.Action, + ActorID: e.ActorID, + ActorKind: e.ActorKind, + ResourceKind: e.ResourceKind, + ResourceID: e.ResourceID, + Outcome: e.Outcome, + TraceID: e.TraceID, + Detail: detail, + } + if err := m.store.Insert(ctx, row); err != nil { + return err + } + if m.log != nil { + m.log.InfoContext(ctx, "audit event", + "audit", true, + "audit_id", row.ID.String(), + "org_id", row.OrgID, + "at", row.At.Format(time.RFC3339Nano), + "category", row.Category, + "action", row.Action, + "actor_id", row.ActorID, + "actor_kind", row.ActorKind, + "resource_kind", row.ResourceKind, + "resource_id", row.ResourceID, + "outcome", row.Outcome, + "trace_id", row.TraceID, + "detail", detail, + ) + } + return nil +} + +// List returns matching audit events ordered newest first. +func (m *Module) List(ctx context.Context, f Filter) ([]Event, error) { + if m.store == nil { + return nil, errors.New("audit store is not configured") + } + if f.OrgID == "" { + f.OrgID = m.orgID + } + if f.Limit == 0 { + f.Limit = defaultLimit + } + if err := f.Validate(); err != nil { + return nil, err + } + rows, err := m.store.List(ctx, store.Filter{ + OrgID: f.OrgID, + Category: f.Category, + Action: f.Action, + ActorID: f.Actor, + Since: f.Since, + Until: f.Until, + Limit: f.Limit, + Offset: f.Offset, + }) + if err != nil { + return nil, err + } + return eventsFromRows(rows), nil +} + +func redactDetail(v any) jsontext.Value { + if v == nil { + return jsontext.Value(`{}`) + } + if raw, ok := v.(jsontext.Value); ok && len(bytes.TrimSpace(raw)) == 0 { + return jsontext.Value(`{}`) + } + payload := auditjson.FromValue(v) + if !payload.Truncated && len(payload.JSON) > 0 { + return payload.JSON + } + raw, err := json.Marshal(payload) + if err != nil { + return jsontext.Value(`{}`) + } + return raw +} + +func eventsFromRows(rows []store.EventRow) []Event { + out := make([]Event, 0, len(rows)) + for _, r := range rows { + out = append(out, Event{ + ID: r.ID, + OrgID: r.OrgID, + At: r.At, + Category: r.Category, + Action: r.Action, + ActorID: r.ActorID, + ActorKind: r.ActorKind, + ResourceKind: r.ResourceKind, + ResourceID: r.ResourceID, + Outcome: r.Outcome, + TraceID: r.TraceID, + Detail: r.Detail, + }) + } + return out +} diff --git a/modules/audit/audit_test.go b/modules/audit/audit_test.go new file mode 100644 index 000000000..39bc89692 --- /dev/null +++ b/modules/audit/audit_test.go @@ -0,0 +1,264 @@ +package audit + +import ( + "bytes" + "context" + "encoding/csv" + "encoding/json/jsontext" + json "encoding/json/v2" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/google/uuid" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + + "github.com/samcharles93/archie-core/internal/platform/httpapi" + "github.com/samcharles93/archie-core/modules/audit/internal/store" + "github.com/samcharles93/archie-core/modules/governance" +) + +type fakeAuditStore struct { + inserted []store.EventRow + rows []store.EventRow +} + +func (f *fakeAuditStore) Insert(_ context.Context, row store.EventRow) error { + f.inserted = append(f.inserted, row) + return nil +} + +func (f *fakeAuditStore) List(_ context.Context, _ store.Filter) ([]store.EventRow, error) { + return f.rows, nil +} + +// TestRecordRedactsDetailAndEmitsAuditLog guards that Record strips credentials +// from detail before persistence and stdout logging, attaches the active trace +// ID, and marks stdout records with audit=true. +func TestRecordRedactsDetailAndEmitsAuditLog(t *testing.T) { + var buf bytes.Buffer + st := &fakeAuditStore{} + m := &Module{ + orgID: "default", + store: st, + log: slog.New(slog.NewJSONHandler(&buf, nil)), + } + + tp := sdktrace.NewTracerProvider() + t.Cleanup(func() { _ = tp.Shutdown(context.Background()) }) + ctx, span := tp.Tracer("audit-test").Start(t.Context(), "record") + defer span.End() + + err := m.Record(ctx, Event{ + Category: "auth", + Action: "oidc.login", + ActorID: "user-1", + ActorKind: "user", + ResourceKind: "session", + ResourceID: "sess-1", + Outcome: "allowed", + Detail: map[string]any{ + "password": "hunter2-secret", + "api_key": "sk-live-12345", + "host": "prod-web-1", + }, + }) + if err != nil { + t.Fatalf("Record() error = %v", err) + } + if len(st.inserted) != 1 { + t.Fatalf("inserted rows = %d, want 1", len(st.inserted)) + } + row := st.inserted[0] + if row.TraceID != span.SpanContext().TraceID().String() { + t.Fatalf("row.TraceID = %q, want %q", row.TraceID, span.SpanContext().TraceID().String()) + } + detailText := string(row.Detail) + for _, secret := range []string{"hunter2-secret", "sk-live-12345"} { + if strings.Contains(detailText, secret) { + t.Fatalf("persisted detail leaked secret %q: %s", secret, detailText) + } + if strings.Contains(buf.String(), secret) { + t.Fatalf("stdout audit log leaked secret %q: %s", secret, buf.String()) + } + } + if !strings.Contains(detailText, "[redacted]") || !strings.Contains(detailText, "prod-web-1") { + t.Fatalf("persisted detail unexpected: %s", detailText) + } + + var logged map[string]any + if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &logged); err != nil { + t.Fatalf("unmarshal stdout log: %v (%s)", err, buf.String()) + } + if logged["audit"] != true { + t.Fatalf("log audit flag = %v, want true", logged["audit"]) + } + if logged["trace_id"] != span.SpanContext().TraceID().String() { + t.Fatalf("log trace_id = %v, want %s", logged["trace_id"], span.SpanContext().TraceID().String()) + } +} + +// TestCSVFormulaNeutralisation guards CSV export against spreadsheet formula +// injection on every dangerous prefix. +func TestCSVFormulaNeutralisation(t *testing.T) { + tests := []struct { + name string + in string + want string + }{ + {name: "equals", in: "=CMD|'/C calc'!A0", want: "'=CMD|'/C calc'!A0"}, + {name: "plus", in: "+1+1", want: "'+1+1"}, + {name: "minus", in: "-2+3", want: "'-2+3"}, + {name: "at", in: "@SUM(1+1)", want: "'@SUM(1+1)"}, + {name: "tab", in: "\t=1+1", want: "'\t=1+1"}, + {name: "carriage return", in: "\r=1+1", want: "'\r=1+1"}, + {name: "safe text", in: "alice@example.com", want: "alice@example.com"}, + {name: "empty", in: "", want: ""}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := neutralizeCSVFormula(tc.in); got != tc.want { + t.Fatalf("neutralizeCSVFormula(%q) = %q, want %q", tc.in, got, tc.want) + } + }) + } + + var out bytes.Buffer + now := time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC) + err := writeCSV(&out, []Event{{ + ID: uuid.MustParse("11111111-1111-1111-1111-111111111111"), + OrgID: "default", + At: now, + Category: "auth", + Action: "=HYPERLINK(\"http://evil\")", + ActorID: "+admin", + Outcome: "@evil", + Detail: jsontext.Value(`{"note":"ok"}`), + }}) + if err != nil { + t.Fatalf("writeCSV() error = %v", err) + } + records, err := csv.NewReader(&out).ReadAll() + if err != nil { + t.Fatalf("csv.ReadAll() error = %v", err) + } + if len(records) != 2 { + t.Fatalf("csv rows = %d, want 2", len(records)) + } + if records[1][4] != "'=HYPERLINK(\"http://evil\")" { + t.Fatalf("csv action cell = %q, want formula-neutralised", records[1][4]) + } + if records[1][5] != "'+admin" { + t.Fatalf("csv actor cell = %q, want formula-neutralised", records[1][5]) + } + if records[1][9] != "'@evil" { + t.Fatalf("csv outcome cell = %q, want formula-neutralised", records[1][9]) + } +} + +// TestFilterValidation guards bounds and time-range checks on audit query and +// export inputs. +func TestFilterValidation(t *testing.T) { + now := time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC) + tests := []struct { + name string + filter Filter + wantErr bool + }{ + {name: "valid defaults", filter: Filter{Limit: 100}}, + {name: "valid bounds", filter: Filter{Limit: 1000, Offset: 0, Since: now.Add(-time.Hour), Until: now}}, + {name: "limit zero", filter: Filter{Limit: 0}, wantErr: true}, + {name: "limit negative", filter: Filter{Limit: -5}, wantErr: true}, + {name: "limit over max", filter: Filter{Limit: 1001}, wantErr: true}, + {name: "negative offset", filter: Filter{Limit: 10, Offset: -1}, wantErr: true}, + {name: "since after until", filter: Filter{Limit: 10, Since: now, Until: now.Add(-time.Minute)}, wantErr: true}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + err := tc.filter.Validate() + if (err != nil) != tc.wantErr { + t.Fatalf("Validate() error = %v, wantErr = %v", err, tc.wantErr) + } + if tc.wantErr && !errors.Is(err, ErrInvalidFilter) { + t.Fatalf("Validate() error = %v, want ErrInvalidFilter", err) + } + }) + } + + m := &Module{orgID: "default", store: &fakeAuditStore{}} + if _, err := m.exportEvents(t.Context(), &exportInput{Limit: 10, Format: "xml"}); err == nil { + t.Fatal("expected error for unsupported export format") + } +} + +type stubAuth struct { + principal governance.Principal +} + +func (a stubAuth) Authenticate(ctx context.Context, _ *http.Request) (context.Context, bool, error) { + return governance.WithPrincipal(ctx, a.principal), false, nil +} + +type stubAuthz struct { + allow bool + got string +} + +func (a *stubAuthz) Allow(_ context.Context, action, kind string) error { + a.got = action + ":" + kind + if !a.allow { + return httpapi.ErrDenied + } + return nil +} + +// TestAuditRoutesRequireReadAuditPermission guards Cedar enforcement on the +// audit query and export routes and checks JSONL export output. +func TestAuditRoutesRequireReadAuditPermission(t *testing.T) { + st := &fakeAuditStore{ + rows: []store.EventRow{{ + ID: uuid.MustParse("22222222-2222-2222-2222-222222222222"), + OrgID: "default", + At: time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC), + Category: "policy", + Action: "put", + ActorID: "root", + Outcome: "allowed", + Detail: jsontext.Value(`{"id":"p1"}`), + }}, + } + m := &Module{orgID: "default", store: st, log: slog.New(slog.DiscardHandler)} + + authz := &stubAuthz{allow: false} + mux := http.NewServeMux() + api := httpapi.New(mux, "test", stubAuth{principal: governance.SharedTokenOwner()}, authz) + m.Register(api) + + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/audit/events", nil) + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("denied status = %d, want 403", rec.Code) + } + if authz.got != string(governance.ActionReadAudit)+":"+string(governance.KindAudit) { + t.Fatalf("checked permission = %q, want %s:%s", authz.got, governance.ActionReadAudit, governance.KindAudit) + } + + authz.allow = true + exportReq := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/audit/events/export?format=jsonl", nil) + exportRec := httptest.NewRecorder() + mux.ServeHTTP(exportRec, exportReq) + if exportRec.Code != http.StatusOK { + t.Fatalf("export status = %d, want 200 (%s)", exportRec.Code, exportRec.Body.String()) + } + if ct := exportRec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/x-ndjson") { + t.Fatalf("export Content-Type = %q, want application/x-ndjson", ct) + } + if !strings.Contains(exportRec.Body.String(), `"category":"policy"`) { + t.Fatalf("export body missing event: %s", exportRec.Body.String()) + } +} diff --git a/modules/audit/internal/store/store.go b/modules/audit/internal/store/store.go new file mode 100644 index 000000000..5552a6638 --- /dev/null +++ b/modules/audit/internal/store/store.go @@ -0,0 +1,95 @@ +// Package store holds the SQL persistence for append-only audit events. +package store + +import ( + "context" + "encoding/json/jsontext" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" +) + +// EventRow is one row in audit.events. +type EventRow struct { + ID uuid.UUID `db:"id"` + OrgID string `db:"org_id"` + At time.Time `db:"at"` + Category string `db:"category"` + Action string `db:"action"` + ActorID string `db:"actor_id"` + ActorKind string `db:"actor_kind"` + ResourceKind string `db:"resource_kind"` + ResourceID string `db:"resource_id"` + Outcome string `db:"outcome"` + TraceID string `db:"trace_id"` + Detail jsontext.Value `db:"detail"` +} + +// Filter narrows List queries on audit.events. +type Filter struct { + OrgID string + Category string + Action string + ActorID string + Since time.Time + Until time.Time + Limit int + Offset int +} + +// Store persists and queries audit.events. +type Store struct { + db *sqlx.DB +} + +// New returns a Store backed by db. +func New(db *sqlx.DB) *Store { + return &Store{db: db} +} + +// Insert appends row to audit.events. +func (s *Store) Insert(ctx context.Context, row EventRow) error { + if _, err := s.db.ExecContext(ctx, ` + INSERT INTO audit.events ( + id, org_id, at, category, action, actor_id, actor_kind, + resource_kind, resource_id, outcome, trace_id, detail + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`, + row.ID, row.OrgID, row.At, row.Category, row.Action, row.ActorID, + row.ActorKind, row.ResourceKind, row.ResourceID, row.Outcome, row.TraceID, row.Detail, + ); err != nil { + return fmt.Errorf("insert audit event: %w", err) + } + return nil +} + +// List returns events matching f ordered newest first. +func (s *Store) List(ctx context.Context, f Filter) ([]EventRow, error) { + var out []EventRow + if err := s.db.SelectContext(ctx, &out, ` + SELECT id, org_id, at, category, action, actor_id, actor_kind, + resource_kind, resource_id, outcome, trace_id, detail + FROM audit.events + WHERE org_id = $1 + AND ($2 = '' OR category = $2) + AND ($3 = '' OR action = $3) + AND ($4 = '' OR actor_id = $4) + AND ($5::timestamptz IS NULL OR at >= $5) + AND ($6::timestamptz IS NULL OR at < $6) + ORDER BY at DESC, id DESC + LIMIT $7 OFFSET $8`, + f.OrgID, f.Category, f.Action, f.ActorID, + nullTime(f.Since), nullTime(f.Until), f.Limit, f.Offset, + ); err != nil { + return nil, fmt.Errorf("list audit events: %w", err) + } + return out, nil +} + +func nullTime(t time.Time) *time.Time { + if t.IsZero() { + return nil + } + return &t +}