Repository Public
1package api23import (4 "context"5 "crypto/ed25519"6 "encoding/base64"7 "encoding/hex"8 "fmt"9 "io"10 "strconv"11 "strings"12 "sync"13 "time"1415 "github.com/google/uuid"16 "github.com/jackc/pgx/v5"1718 "clustr.spboucher.ai/mcc/internal/audit"19 "clustr.spboucher.ai/mcc/internal/httpx"20 "clustr.spboucher.ai/mcc/internal/signkey"21)2223// Audit API: read, verify, export. Nothing here can change or delete an entry24// (the table refuses it anyway).2526// Reading the audit log is itself audited — but at most once per minute and27// per session. Auditing every page would let a reader grow the log simply by28// scrolling (each read appending an entry that the next read shows), which29// buries real events; once a minute still records who looked, when, and with30// which filters first.31var auditReads = struct {32 sync.Mutex33 last map[uuid.UUID]time.Time34}{last: map[uuid.UUID]time.Time{}}3536func auditReadDue(session uuid.UUID, now time.Time) bool {37 auditReads.Lock()38 defer auditReads.Unlock()39 if t, ok := auditReads.last[session]; ok && now.Sub(t) < time.Minute {40 return false41 }42 if len(auditReads.last) > 10_000 {43 for k, t := range auditReads.last {44 if now.Sub(t) >= time.Minute {45 delete(auditReads.last, k)46 }47 }48 }49 auditReads.last[session] = now50 return true51}5253var (54 auditKeyMu sync.Mutex55 auditKeys = map[string]ed25519.PrivateKey{}56)5758// auditKey returns the export signing key (created 0600 on first use) and its id.59func (h *opsHandlers) auditKey() (ed25519.PrivateKey, string, error) {60 path := h.Cfg.SecretPath("audit-signing.key")61 auditKeyMu.Lock()62 defer auditKeyMu.Unlock()63 k, ok := auditKeys[path]64 if !ok {65 var err error66 if k, err = signkey.LoadOrCreate(path); err != nil {67 return nil, "", err68 }69 auditKeys[path] = k70 }71 return k, signkey.ID(k.Public().(ed25519.PublicKey)), nil72}7374const auditSelect = `select seq, ts, actor_kind, actor_id, actor_label, device_id, session_id, host(ip), action, target_kind, target_id, params, outcome::text,75 detail, correlation_id, prev_hash, hash from audit_log`7677func scanAudit(r pgx.Row) (AuditEntry, error) {78 var e AuditEntry79 var kind, outcome string80 var prev, hash []byte81 err := r.Scan(&e.Seq, &e.Ts, &kind, &e.ActorId, &e.ActorLabel, &e.DeviceId, &e.SessionId, &e.Ip, &e.Action, &e.TargetKind, &e.TargetId, &e.Params, &outcome,82 &e.Detail, &e.CorrelationId, &prev, &hash)83 e.ActorKind, e.Outcome = AuditEntryActorKind(kind), AuditOutcome(outcome)84 e.PrevHash, e.Hash = hex.EncodeToString(prev), hex.EncodeToString(hash)85 if e.Params == nil {86 e.Params = map[string]any{}87 }88 return e, err89}9091func (h *opsHandlers) ListAudit(ctx context.Context, req ListAuditRequestObject) (ListAuditResponseObject, error) {92 p := req.Params93 var w where94 filters := map[string]any{}95 if p.ActorId != nil {96 w.add("actor_id = ?", *p.ActorId)97 filters["actor_id"] = p.ActorId.String()98 }99 if p.Action != nil && *p.Action != "" {100 a := *p.Action101 if len(a) > 100 {102 return nil, httpx.Validation("action is too long.")103 }104 if prefix, ok := strings.CutSuffix(a, "*"); ok {105 w.add(`action like ? || '%' escape '\'`, escapeLike(prefix))106 } else {107 w.add("action = ?", a)108 }109 filters["action"] = a110 }111 if p.TargetKind != nil {112 w.add("target_kind = ?", *p.TargetKind)113 filters["target_kind"] = *p.TargetKind114 }115 if p.TargetId != nil {116 w.add("target_id = ?", *p.TargetId)117 filters["target_id"] = *p.TargetId118 }119 if p.Outcome != nil {120 w.add("outcome = ?::audit_outcome", string(*p.Outcome))121 filters["outcome"] = string(*p.Outcome)122 }123 if p.From != nil {124 w.add("ts >= ?", *p.From)125 }126 if p.To != nil {127 w.add("ts < ?", *p.To)128 }129 if p.CorrelationId != nil {130 w.add("correlation_id = ?", *p.CorrelationId)131 }132 if p.Cursor != nil && *p.Cursor != "" {133 seq, err := strconv.ParseInt(*p.Cursor, 10, 64)134 if err != nil || seq < 1 {135 return nil, httpx.Validation("Invalid cursor.")136 }137 w.add("seq < ?", seq)138 }139 limit := pageLimit(p.Limit)140 rows, err := h.Pool.Query(ctx, auditSelect+w.sql()+" order by seq desc limit "+w.arg(limit+1), w.args...)141 if err != nil {142 return nil, err143 }144 items, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (AuditEntry, error) { return scanAudit(r) })145 if err != nil {146 return nil, err147 }148 out := AuditList{Items: items}149 if len(items) > limit {150 out.Items, out.NextCursor = items[:limit], ptr(strconv.FormatInt(items[limit-1].Seq, 10))151 }152 if out.Items == nil {153 out.Items = []AuditEntry{}154 }155 if sess := principalFrom(ctx).Session; auditReadDue(sess.ID, time.Now()) {156 if err := h.audit(ctx, h.Pool, "audit.read", "", "", audit.Success, "", filters); err != nil {157 return nil, err158 }159 }160 return ListAudit200JSONResponse{Body: out}, nil161}162163func (h *opsHandlers) VerifyAudit(ctx context.Context, req VerifyAuditRequestObject) (VerifyAuditResponseObject, error) {164 from := int64(1)165 if req.Params.FromSeq != nil {166 from = *req.Params.FromSeq167 }168 res, err := audit.VerifyFrom(ctx, h.Pool, from)169 if err != nil {170 return nil, err171 }172 out := AuditVerification{Ok: res.OK, CheckedEntries: res.Entries, VerifiedAt: nowUTC()}173 if res.Entries > 0 {174 out.FirstSeq, out.LastSeq = &res.FirstSeq, &res.LastSeq175 out.HeadHash = ptr(hex.EncodeToString(res.HeadHash))176 }177 if !res.OK {178 out.FirstBrokenSeq, out.Reason = &res.BrokenSeq, &res.Reason179 }180 if key, id, err := h.auditKey(); err == nil {181 out.ExportKeyId = &id182 out.ExportPublicKey = ptr(base64.StdEncoding.EncodeToString(key.Public().(ed25519.PublicKey)))183 }184 if err := h.audit(ctx, h.Pool, "audit.verify", "", "", audit.Success, "", map[string]any{"ok": res.OK, "entries": res.Entries}); err != nil {185 return nil, err186 }187 return VerifyAudit200JSONResponse{Body: out}, nil188}189190const maxExportSpan = 366 * 24 * time.Hour191192// ExportAudit streams a signed export (format: internal/audit/export.go). The193// permission audit.export and the step-up are enforced by the contract policy.194func (h *opsHandlers) ExportAudit(ctx context.Context, req ExportAuditRequestObject) (ExportAuditResponseObject, error) {195 from, to := req.Params.From.UTC(), req.Params.To.UTC()196 if !to.After(from) || to.Sub(from) > maxExportSpan {197 return nil, httpx.Validation("The range must be positive and at most 366 days.")198 }199 key, keyID, err := h.auditKey()200 if err != nil {201 return nil, err202 }203 // The export is recorded BEFORE it is produced: no export without a trace.204 if err := h.audit(ctx, h.Pool, "audit.export", "", "", audit.Success, "", map[string]any{"from": from, "to": to, "key_id": keyID}); err != nil {205 return nil, err206 }207 // One stable snapshot for the announced head hash and for the stream.208 tx, err := h.Pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})209 if err != nil {210 return nil, err211 }212 head, err := audit.Head(ctx, tx, from, to)213 if err != nil {214 tx.Rollback(ctx)215 return nil, err216 }217 pr, pw := io.Pipe()218 go func() {219 defer tx.Rollback(context.WithoutCancel(ctx))220 _, err := audit.WriteExport(ctx, tx, pw, from, to, key, keyID, nowUTC())221 pw.CloseWithError(err) // on error the file ends without a manifest: it cannot verify222 }()223 name := fmt.Sprintf(`attachment; filename="mcc-audit-%s-%s.jsonl"`, from.Format("20060102T150405Z"), to.Format("20060102T150405Z"))224 return ExportAudit200ApplicationxNdjsonResponse{Body: pr, Headers: ExportAudit200ResponseHeaders{ContentDisposition: &name,225 XMCCAuditHeadHash: &head, XMCCAuditSignature: ptr(audit.SignHead(key, keyID, head))}}, nil226}227