Skip to content

Commit 74e82d5

Browse files
author
hzq
committed
Keep audit coalescing and retention consistent with committed events
Roll back the in-memory denial window with its audit row. Share a durable per-owner pruning cadence with operator actions while repeated denials leave the main database untouched.
1 parent 769a790 commit 74e82d5

5 files changed

Lines changed: 205 additions & 30 deletions

File tree

‎docs/protocol.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,8 @@ A caller can send its own model-provider key in the `X-OAA-Provider-Key` request
145145
The gateway persistently records events where an **authenticated** request is rejected. The recorded error codes are: `scope_denied`, `admin_host_denied`, `isolation_required`, `concurrency_limit`, `subject_concurrency_limit`, `key_concurrency_limit`, `run_quota_exceeded`, `token_quota_exceeded`.
146146

147147
- Each record contains the time, error code, key ID, subject, HTTP method, path, and the client IP (with `trustProxy`, the first hop of `X-Forwarded-For`).
148-
- Rejections with the same owner, key, error code, and path are written as one record within 60 seconds; the `suppressed` field of the next record gives the number merged in between. This count is kept in process memory and is lost on gateway restart.
149-
- At most 10,000 records are kept per owner; older ones are deleted.
148+
- Rejections with the same owner, key, error code, and path are coalesced for 60 seconds. The next record's `suppressed` count is connection-local and resets on restart. Repeats do not write to the main database. A failed or rolled-back insert is not grounds to suppress the next denial; if storage is unavailable the original rejection still stands.
149+
- Every 100 recorded events per owner (including operator actions), the oldest rows beyond 10,000 are deleted. This maintenance count survives restart; up to 99 more rows may accumulate between passes.
150150

151151
**Not recorded**: unauthenticated failures (401, `invalid_host`, `origin_denied`) and `rate_limited`. Otherwise every rejected request would become a database write, which hands an attacker an amplifier. That traffic should be rate limited and logged at the edge.
152152

‎docs/zh-CN/protocol.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,8 @@ srt 后端的边界与局限:
147147
网关会持久记录**已鉴权**请求被拒绝的事件,记录的错误码有:`scope_denied`、`admin_host_denied`、`isolation_required`、`concurrency_limit`、`subject_concurrency_limit`、`key_concurrency_limit`、`run_quota_exceeded`、`token_quota_exceeded`。
148148

149149
- 每条记录包含:时间、错误码、密钥 ID、subject、HTTP 方法、路径,以及客户端 IP(`trustProxy` 时取 `X-Forwarded-For` 的第一跳)。
150-
- 同一 owner、同一密钥、同一错误码、同一路径的拒绝,在 60 秒内只写一条;下一条记录的 `suppressed` 字段给出期间被合并的次数。这个次数保存在进程内存里,网关重启会丢失。
151-
- 每个 owner 最多保留 10,000 条,更早的会被删除。
150+
- 同一 owner、密钥、错误码和路径的拒绝在 60 秒内合并。下一条的 `suppressed` 给出合并次数;计数只在当前连接有效,重启会清零。重复拒绝不写主数据库。一条审计写入失败或回滚,不会让下一次拒绝被误判为已有记录;审计不可写也不改变原来的拒绝响应。
151+
- 每个 owner 每成功记录 100 条事件(包括运营者操作)便清理一次,保留最新 10,000 条。清理进度跨重启保留;两次清理之间可暂时多出最多 99 条。
152152

153153
**不记录**的情况:未鉴权的失败(401、`invalid_host`、`origin_denied`)和 `rate_limited`。否则每个被拒绝的请求都会变成一次数据库写入,等于给攻击者一个放大手段。这类流量应该在边缘层限流和记录。
154154

‎src/store/audit.ts‎

Lines changed: 61 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
import type { Store } from './store.js';
2+
import { Fault } from '../core/util.js';
3+
import { withSavepoint } from './savepoint.js';
24

35
/**
46
* Durable audit trail of *authenticated* denials: scope, host, isolation, concurrency and quota
57
* refusals. Unauthenticated failures (401, invalid host/origin) and `rate_limited` are not written:
68
* an attacker could otherwise turn every rejected request into a database write. Bursts of the
79
* 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.
1012
*/
1113
export const AUDITED_CODES = new Set([
1214
'scope_denied',
@@ -65,42 +67,39 @@ export type AuditEvent = {
6567
};
6668

6769
export class AuditLog {
68-
private recent = new Map<string, { at: number; suppressed: number }>();
69-
private writes = new Map<string, number>();
7070
constructor(
7171
private readonly store: Store,
7272
private readonly now: () => number = Date.now,
7373
) {
7474
store.db.exec(`
7575
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);`);
7779
}
7880
/** Record one denial. Returns false when it was coalesced into a recent identical row. */
7981
record(input: AuditInput): boolean {
8082
if (!AUDITED_CODES.has(input.code)) return false;
8183
const now = this.now();
8284
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);
9094
const payload = {
9195
key_id: input.keyId ?? null,
9296
subject: input.subject ?? null,
9397
method: input.method,
9498
path: input.path.slice(0, 200),
9599
ip: input.ip ?? null,
96-
suppressed: last?.suppressed ?? 0,
100+
suppressed: Number(last?.suppressed ?? 0),
97101
};
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);
104103
return true;
105104
}
106105
/**
@@ -128,18 +127,55 @@ export class AuditLog {
128127
...(input.detail ? { detail: input.detail.slice(0, 200) } : {}),
129128
}),
130129
};
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+
});
134165
}
135166
prune(owner: string): void {
136167
const cutoff = this.store
137168
.prepare('SELECT id FROM audit_events WHERE owner=? ORDER BY id DESC LIMIT 1 OFFSET ?')
138169
.get(owner, RETAIN);
139170
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+
});
143179
}
144180
/** Oldest-first page of an owner's audit rows after `after` (an event ID). */
145181
page(owner: string, after = 0, limit = 50): { data: AuditEvent[]; next_after: number | null } {

‎src/store/savepoint.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@ export function withSavepoint<T>(db: DatabaseSync, change: () => T): T {
88
db.exec('RELEASE oaa_change');
99
return result;
1010
} catch (error) {
11-
db.exec('ROLLBACK TO oaa_change; RELEASE oaa_change');
11+
// SQLite may already have rolled back the whole transaction (for example, SQLITE_FULL).
12+
if (db.isTransaction) db.exec('ROLLBACK TO oaa_change; RELEASE oaa_change');
1213
throw error;
1314
}
1415
}

‎test/audit-recovery.test.ts‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
import assert from 'node:assert/strict';
2+
import test from 'node:test';
3+
import { DatabaseSync } from 'node:sqlite';
4+
import { mkdtempSync, rmSync } from 'node:fs';
5+
import os from 'node:os';
6+
import path from 'node:path';
7+
import { AuditLog } from '../src/store/audit.js';
8+
import { Store } from '../src/store/store.js';
9+
10+
const denial = {
11+
owner: 'fixture',
12+
keyId: 'key',
13+
code: 'scope_denied',
14+
method: 'POST',
15+
path: '/fixture',
16+
};
17+
function fixture() {
18+
const root = mkdtempSync(path.join(os.tmpdir(), 'oaa-audit-recovery-')),
19+
store = new Store(root);
20+
let time = 1000000;
21+
return {
22+
store,
23+
log: new AuditLog(store, () => time),
24+
next: () => (time += 60000),
25+
close: () => {
26+
store.close();
27+
rmSync(root, { recursive: true, force: true });
28+
},
29+
};
30+
}
31+
for (const mode of ['ABORT', 'ROLLBACK', 'IGNORE'])
32+
test(`audit: ${mode} cannot create a phantom suppression window`, () => {
33+
const { store, log, next, close } = fixture();
34+
const deny = () =>
35+
store.db.exec(
36+
`CREATE TEMP TRIGGER refuse BEFORE INSERT ON audit_events BEGIN SELECT RAISE(${mode}${mode === 'IGNORE' ? '' : ",'fixture audit failure'"}); END`,
37+
);
38+
try {
39+
deny();
40+
assert.throws(() => log.record(denial));
41+
assert.equal(log.page('fixture').data.length, 0);
42+
store.db.exec('DROP TRIGGER refuse');
43+
assert.equal(log.record(denial), true);
44+
assert.equal(log.record(denial), false);
45+
assert.equal(log.record(denial), false);
46+
next();
47+
deny();
48+
assert.throws(() => log.record(denial));
49+
store.db.exec('DROP TRIGGER refuse');
50+
assert.equal(log.record(denial), true);
51+
assert.deepEqual(
52+
log.page('fixture').data.map((r) => r.suppressed),
53+
[0, 2],
54+
);
55+
} finally {
56+
close();
57+
}
58+
});
59+
test('audit: rolling back the caller transaction restores the old window and its true repeat count', () => {
60+
const { store, log, next, close } = fixture();
61+
try {
62+
log.record(denial);
63+
log.record(denial);
64+
next();
65+
store.db.exec('BEGIN IMMEDIATE');
66+
assert.equal(log.record(denial), true);
67+
assert.equal(log.record(denial), false);
68+
assert.equal(log.record({ ...denial, path: '/never-committed' }), true);
69+
store.db.exec('ROLLBACK');
70+
assert.equal(
71+
log.record({ ...denial, path: '/never-committed' }),
72+
true,
73+
'no receipt survived the rollback',
74+
);
75+
assert.equal(log.record(denial), true);
76+
assert.deepEqual(
77+
log
78+
.page('fixture')
79+
.data.filter((e) => e.path === '/fixture')
80+
.map((e) => e.suppressed),
81+
[0, 1],
82+
);
83+
} finally {
84+
close();
85+
}
86+
});
87+
test('audit: repeats need no main writer and do not change the on-disk database', () => {
88+
const { store, log, next, close } = fixture(),
89+
other = new DatabaseSync(path.join(store.root, 'state.sqlite'));
90+
try {
91+
assert.equal(log.record(denial), true);
92+
store.db.exec('PRAGMA busy_timeout=0');
93+
const version = () => other.prepare('PRAGMA data_version').get()!.data_version;
94+
const before = version();
95+
other.exec('BEGIN IMMEDIATE');
96+
for (let i = 0; i < 100; i++) assert.equal(log.record(denial), false);
97+
assert.throws(() => log.record({ ...denial, path: '/new' }), { code: 'ERR_SQLITE_ERROR' });
98+
other.exec('ROLLBACK');
99+
assert.equal(version(), before);
100+
assert.equal(log.record({ ...denial, path: '/new' }), true);
101+
next();
102+
log.record(denial);
103+
assert.equal(log.page('fixture').data.at(-1)?.suppressed, 100);
104+
} finally {
105+
other.close();
106+
close();
107+
}
108+
});
109+
test('audit: operator notes count toward retention across restart and a pruned denial no longer suppresses', () => {
110+
const root = mkdtempSync(path.join(os.tmpdir(), 'oaa-audit-cadence-'));
111+
let store = new Store(root),
112+
log = new AuditLog(store, () => 1000000);
113+
try {
114+
log.note({ ...denial, owner: 'other', code: 'platform_setup', detail: 'fixture' });
115+
store.db.exec('BEGIN IMMEDIATE');
116+
for (let i = 0; i < 51; i++)
117+
log.note({ ...denial, path: '/setup/' + i, code: 'platform_setup', detail: 'fixture' });
118+
store.db.exec('COMMIT');
119+
store.close();
120+
store = new Store(root);
121+
log = new AuditLog(store, () => 1000000);
122+
log.record(denial);
123+
store.db.exec('BEGIN IMMEDIATE');
124+
for (let i = 51; i < 10099; i++)
125+
log.note({ ...denial, path: '/setup/' + i, code: 'platform_setup', detail: 'fixture' });
126+
store.db.exec('COMMIT');
127+
assert.equal(
128+
store.prepare('SELECT count(*) AS n FROM audit_events WHERE owner=?').get('fixture')!.n,
129+
10000,
130+
);
131+
assert.equal(log.page('fixture', 0, 1).data[0]?.path, '/setup/99');
132+
assert.equal(log.page('other').data.length, 1);
133+
assert.equal(log.record(denial), true);
134+
} finally {
135+
store.close();
136+
rmSync(root, { recursive: true, force: true });
137+
}
138+
});

0 commit comments

Comments
 (0)