|
1 | 1 | import type { Store } from './store.js'; |
| 2 | +import { Fault } from '../core/util.js'; |
| 3 | +import { withSavepoint } from './savepoint.js'; |
2 | 4 |
|
3 | 5 | /** |
4 | 6 | * Durable audit trail of *authenticated* denials: scope, host, isolation, concurrency and quota |
5 | 7 | * refusals. Unauthenticated failures (401, invalid host/origin) and `rate_limited` are not written: |
6 | 8 | * an attacker could otherwise turn every rejected request into a database write. Bursts of the |
7 | 9 | * same denial (owner, key, code, path) within one minute are coalesced into one row whose |
8 | | - * `suppressed` field counts the repeats seen since the previous row. At most RETAIN rows are kept |
9 | | - * per owner; older rows are pruned. |
| 10 | + * `suppressed` field counts the repeats seen since the previous row. Every PRUNE_EVERY committed |
| 11 | + * records per owner (denials or operator notes), older rows beyond RETAIN are pruned. |
10 | 12 | */ |
11 | 13 | export const AUDITED_CODES = new Set([ |
12 | 14 | 'scope_denied', |
@@ -65,42 +67,39 @@ export type AuditEvent = { |
65 | 67 | }; |
66 | 68 |
|
67 | 69 | export class AuditLog { |
68 | | - private recent = new Map<string, { at: number; suppressed: number }>(); |
69 | | - private writes = new Map<string, number>(); |
70 | 70 | constructor( |
71 | 71 | private readonly store: Store, |
72 | 72 | private readonly now: () => number = Date.now, |
73 | 73 | ) { |
74 | 74 | store.db.exec(` |
75 | 75 | CREATE TABLE IF NOT EXISTS audit_events (id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT NOT NULL, time INTEGER NOT NULL, code TEXT NOT NULL, payload TEXT NOT NULL); |
76 | | - CREATE INDEX IF NOT EXISTS audit_owner ON audit_events(owner,id);`); |
| 76 | + CREATE INDEX IF NOT EXISTS audit_owner ON audit_events(owner,id); |
| 77 | + CREATE TEMP TABLE IF NOT EXISTS oaa_audit_windows(bucket TEXT PRIMARY KEY,owner TEXT NOT NULL,anchor INTEGER NOT NULL UNIQUE,at INTEGER NOT NULL,suppressed INTEGER NOT NULL); |
| 78 | + CREATE TABLE IF NOT EXISTS audit_retention_progress(owner TEXT PRIMARY KEY,n INTEGER NOT NULL);`); |
77 | 79 | } |
78 | 80 | /** Record one denial. Returns false when it was coalesced into a recent identical row. */ |
79 | 81 | record(input: AuditInput): boolean { |
80 | 82 | if (!AUDITED_CODES.has(input.code)) return false; |
81 | 83 | const now = this.now(); |
82 | 84 | const key = JSON.stringify([input.owner, input.keyId ?? null, input.code, input.path]); |
83 | | - const last = this.recent.get(key); |
84 | | - if (last && now - last.at < WINDOW_MS) { |
85 | | - last.suppressed++; |
86 | | - return false; |
87 | | - } |
88 | | - if (this.recent.size >= MAX_TRACKED) this.recent.clear(); |
89 | | - this.recent.set(key, { at: now, suppressed: 0 }); |
| 85 | + // The common repeat touches connection-local memory only. SQLite rolls the window |
| 86 | + // back with its audit receipt, including when a caller owns the surrounding transaction. |
| 87 | + const repeated = this.store |
| 88 | + .prepare('UPDATE temp.oaa_audit_windows SET suppressed=suppressed+1 WHERE bucket=? AND at>?') |
| 89 | + .run(key, now - WINDOW_MS); |
| 90 | + if (repeated.changes) return false; |
| 91 | + const last = this.store |
| 92 | + .prepare('SELECT suppressed FROM temp.oaa_audit_windows WHERE bucket=?') |
| 93 | + .get(key); |
90 | 94 | const payload = { |
91 | 95 | key_id: input.keyId ?? null, |
92 | 96 | subject: input.subject ?? null, |
93 | 97 | method: input.method, |
94 | 98 | path: input.path.slice(0, 200), |
95 | 99 | ip: input.ip ?? null, |
96 | | - suppressed: last?.suppressed ?? 0, |
| 100 | + suppressed: Number(last?.suppressed ?? 0), |
97 | 101 | }; |
98 | | - this.store |
99 | | - .prepare('INSERT INTO audit_events(owner,time,code,payload) VALUES(?,?,?,?)') |
100 | | - .run(input.owner, now, input.code, JSON.stringify(payload)); |
101 | | - const count = (this.writes.get(input.owner) ?? 0) + 1; |
102 | | - this.writes.set(input.owner, count); |
103 | | - if (count % PRUNE_EVERY === 0) this.prune(input.owner); |
| 102 | + this.append(input, now, payload, key); |
104 | 103 | return true; |
105 | 104 | } |
106 | 105 | /** |
@@ -128,18 +127,55 @@ export class AuditLog { |
128 | 127 | ...(input.detail ? { detail: input.detail.slice(0, 200) } : {}), |
129 | 128 | }), |
130 | 129 | }; |
131 | | - this.store |
132 | | - .prepare('INSERT INTO audit_events(owner,time,code,payload) VALUES(?,?,?,?)') |
133 | | - .run(input.owner, this.now(), input.code, JSON.stringify(payload)); |
| 130 | + this.append(input, this.now(), payload); |
| 131 | + } |
| 132 | + private append( |
| 133 | + input: AuditInput, |
| 134 | + now: number, |
| 135 | + payload: Record<string, unknown>, |
| 136 | + bucket?: string, |
| 137 | + ) { |
| 138 | + withSavepoint(this.store.db, () => { |
| 139 | + const row = this.store |
| 140 | + .prepare('INSERT INTO audit_events(owner,time,code,payload) VALUES(?,?,?,?)') |
| 141 | + .run(input.owner, now, input.code, JSON.stringify(payload)); |
| 142 | + if (!row.changes) |
| 143 | + throw new Fault('persistence_failed', 'The audit event could not be recorded.', 500); |
| 144 | + const id = Number(row.lastInsertRowid); |
| 145 | + if (bucket !== undefined) |
| 146 | + this.store |
| 147 | + .prepare( |
| 148 | + `INSERT INTO temp.oaa_audit_windows VALUES(?,?,?,?,0) ON CONFLICT(bucket) DO UPDATE SET anchor=excluded.anchor,at=excluded.at,suppressed=0`, |
| 149 | + ) |
| 150 | + .run(bucket, input.owner, id, now); |
| 151 | + if (id > MAX_TRACKED) |
| 152 | + this.store |
| 153 | + .prepare('DELETE FROM temp.oaa_audit_windows WHERE anchor<=?') |
| 154 | + .run(id - MAX_TRACKED); |
| 155 | + const count = this.store |
| 156 | + .prepare( |
| 157 | + 'INSERT INTO audit_retention_progress VALUES(?,1) ON CONFLICT(owner) DO UPDATE SET n=n+1 RETURNING n', |
| 158 | + ) |
| 159 | + .get(input.owner)!; |
| 160 | + if (Number(count.n) >= PRUNE_EVERY) { |
| 161 | + this.prune(input.owner); |
| 162 | + this.store.prepare('DELETE FROM audit_retention_progress WHERE owner=?').run(input.owner); |
| 163 | + } |
| 164 | + }); |
134 | 165 | } |
135 | 166 | prune(owner: string): void { |
136 | 167 | const cutoff = this.store |
137 | 168 | .prepare('SELECT id FROM audit_events WHERE owner=? ORDER BY id DESC LIMIT 1 OFFSET ?') |
138 | 169 | .get(owner, RETAIN); |
139 | 170 | if (cutoff) |
140 | | - this.store |
141 | | - .prepare('DELETE FROM audit_events WHERE owner=? AND id<=?') |
142 | | - .run(owner, Number(cutoff.id)); |
| 171 | + withSavepoint(this.store.db, () => { |
| 172 | + this.store |
| 173 | + .prepare('DELETE FROM audit_events WHERE owner=? AND id<=?') |
| 174 | + .run(owner, Number(cutoff.id)); |
| 175 | + this.store |
| 176 | + .prepare('DELETE FROM temp.oaa_audit_windows WHERE owner=? AND anchor<=?') |
| 177 | + .run(owner, Number(cutoff.id)); |
| 178 | + }); |
143 | 179 | } |
144 | 180 | /** Oldest-first page of an owner's audit rows after `after` (an event ID). */ |
145 | 181 | page(owner: string, after = 0, limit = 50): { data: AuditEvent[]; next_after: number | null } { |
|
0 commit comments