265 lines
8.4 KiB
Go
265 lines
8.4 KiB
Go
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())
|
|
}
|
|
}
|