@coffre/conformance 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,167 @@
1
+ // Who holds what is the vault's record: an access change is its entry or
2
+ // nothing, and a member row or grant written around it is refused at use.
3
+ import { CoffreError } from '@coffre/client';
4
+
5
+ import { Browser } from '../browser.ts';
6
+ import { using } from '../database.ts';
7
+ import type { Deployment } from '../harness.ts';
8
+ import { expect, Skip, until } from '../report.ts';
9
+ import { DEV, PROD, signIn, type People, type Person } from './people.ts';
10
+ import { insertRow, logRefuses, query, restoreRow } from './storage.ts';
11
+
12
+ export async function member(deployment: Deployment, { admin }: People, name: string): Promise<Person> {
13
+ const email = `${name}@conformance.example`;
14
+ const principal = `user:${email}`;
15
+ await admin.api.members.add(principal);
16
+ await admin.api.access.set(principal, { [DEV]: 'viewer' });
17
+ const browser = new Browser(deployment.origin);
18
+ expect((await signIn(deployment, browser, email)).ok, 'the fixture member could not sign in');
19
+ return { email, member: principal, browser, api: browser.client() };
20
+ }
21
+
22
+ /** The row is refused at use, not only when someone explicitly verifies the log. */
23
+ export async function memberTampering(deployment: Deployment, people: People, kind: 'grant' | 'member' | 'stale'): Promise<string> {
24
+ const person = await member(deployment, people, `tamper-${kind}`);
25
+ const { admin } = people;
26
+ const path = kind === 'grant' ? PROD : DEV;
27
+ const protectedValues = Object.values((await admin.api.secrets.reveal(path)).values);
28
+ await using(deployment.database(), async (sql) => {
29
+ const [before] = await query(sql, 'SELECT * FROM vault_members WHERE principal = $1', [person.member]);
30
+ const grants = await query(sql, 'SELECT * FROM vault_grants WHERE principal = $1', [person.member]);
31
+ expect(before !== undefined && grants.length === 1, 'the fixture has no member row and grant');
32
+ let restored = before;
33
+ let held = grants;
34
+ if (kind === 'stale') {
35
+ await admin.api.access.set(person.member, { [DEV]: 'developer' });
36
+ [restored] = await query(sql, 'SELECT * FROM vault_members WHERE principal = $1', [person.member]);
37
+ held = await query(sql, 'SELECT * FROM vault_grants WHERE principal = $1', [person.member]);
38
+ await restoreRow(sql, 'vault_members', before, 'principal');
39
+ await query(sql, 'UPDATE vault_grants SET role = $1, granted_at = $2, granted_by = $3 WHERE principal = $4',
40
+ [grants[0].role, grants[0].granted_at, grants[0].granted_by, person.member]);
41
+ } else if (kind === 'member') {
42
+ await query(sql, 'UPDATE vault_members SET owner = $1 WHERE principal = $2', [sql.engine === 'sqlite' ? 1 : true, person.member]);
43
+ } else {
44
+ const [place] = await query<{ id: string }>(sql, `SELECT e.id FROM environments e JOIN projects p ON p.id = e.project_id
45
+ WHERE p.slug = 'conformance' AND e.slug = 'prod'`);
46
+ expect(place !== undefined, 'no prod environment to forge a grant on');
47
+ await query(sql, `INSERT INTO vault_grants (principal, environment_id, role, granted_at, granted_by) VALUES ($1, $2, 'viewer', $3, $4)`,
48
+ [person.member, place.id, Date.now(), person.member]);
49
+ }
50
+ try {
51
+ const response = await person.browser.send('POST', '/api/reveals', { path });
52
+ const text = await response.text();
53
+ expect(response.status === 401 && (JSON.parse(text) as { error: string }).error === 'unauthenticated', 'the tampered credential was not refused', text);
54
+ expect(!protectedValues.some((value) => text.includes(value)), 'the tampered refusal carried a value', text);
55
+ const reports = await query(sql, `SELECT seq FROM audit_log WHERE author = 'vault' AND action = 'vault.tampered'
56
+ AND subject_principal = $1 AND code = $2`, [person.member, kind === 'stale' ? 'stale' : 'mac']);
57
+ expect(reports.length > 0, 'the tampering was not logged at use', reports);
58
+ expect((await admin.api.members.get(person.member)).status === 'tampered', 'the refused member is not marked tampered');
59
+ const verified = await admin.api.audit.verify();
60
+ expect(!verified.ok && verified.author === 'vault' && verified.failedAtSeq === null, 'the tampered member verifies', verified);
61
+ } finally {
62
+ await restoreRow(sql, 'vault_members', restored, 'principal');
63
+ await query(sql, 'DELETE FROM vault_grants WHERE principal = $1', [person.member]);
64
+ for (const grant of held) await insertRow(sql, 'vault_grants', grant);
65
+ }
66
+ });
67
+ expect((await person.api.secrets.reveal(DEV)).values.API_KEY !== undefined, 'restoring the member did not restore legitimate use');
68
+ expect((await admin.api.audit.verify()).ok, 'the restored member did not verify');
69
+ return `${kind === 'stale' ? 'a genuine older member row, put back,' : `a forged ${kind}`} refused at use as tampered, logged, then restored`;
70
+ }
71
+
72
+ /** Access changes have one author, the vault that commits the changed rows. */
73
+ export async function accessAuthorship(deployment: Deployment, people: People): Promise<string> {
74
+ const person = await member(deployment, people, 'access-actions');
75
+ const { admin } = people;
76
+ await admin.api.access.set(person.member, { [DEV]: null });
77
+ await admin.api.members.remove(person.member);
78
+ await admin.api.members.add(person.member);
79
+ await using(deployment.database(), async (sql) => {
80
+ const access = await sql.query<{ author: string; action: string; subject_principal: string }>(`SELECT author, action, subject_principal FROM audit_log
81
+ WHERE decision = 'allow' AND (action LIKE 'access.%' OR action LIKE 'member.%' OR action LIKE 'directory.%' OR action LIKE 'grant.%' OR action LIKE 'principal.%')`);
82
+ expect(access.length > 0 && access.every((entry) => entry.author === 'vault'), 'an access change was written by the app', access.filter((entry) => entry.author !== 'vault'));
83
+ const actions = access.filter((entry) => entry.subject_principal === person.member).map((entry) => entry.action);
84
+ for (const action of ['member.add', 'member.remove', 'member.restore', 'access.grant', 'access.revoke']) {
85
+ expect(actions.includes(action), `${action} left no vault entry`, actions);
86
+ }
87
+ });
88
+ return 'admission, grant, revoke, removal and re-admission are only vault entries';
89
+ }
90
+
91
+ /** A failure to append may not commit an access change. */
92
+ export async function noAuditNoAccess(deployment: Deployment, people: People): Promise<string> {
93
+ const person = await member(deployment, people, 'no-audit');
94
+ const { admin } = people;
95
+ await using(deployment.database(), async (sql) => {
96
+ const snapshot = async () => ({
97
+ members: await sql.query('SELECT * FROM vault_members ORDER BY principal'),
98
+ grants: await sql.query('SELECT * FROM vault_grants ORDER BY principal, project_id, environment_id'),
99
+ });
100
+ const before = await snapshot();
101
+ await logRefuses(sql, async () => {
102
+ for (const change of [
103
+ () => admin.api.access.set(person.member, { [DEV]: 'developer' }),
104
+ () => admin.api.members.remove(person.member),
105
+ () => admin.api.members.add('user:no-audit-new@conformance.example'),
106
+ ]) {
107
+ const outcome = await change().then(() => true, () => false);
108
+ expect(!outcome, 'an access change succeeded while the log refused writes');
109
+ expect(JSON.stringify(await snapshot()) === JSON.stringify(before), 'an access change committed without its entry');
110
+ }
111
+ });
112
+ });
113
+ expect((await person.api.secrets.reveal(DEV)).values.API_KEY !== undefined, 'legitimate reads did not recover');
114
+ return 'grant, removal and admission commit nothing while the log refuses their entries';
115
+ }
116
+
117
+ /** Hold the head after the vault checked a member, then forge a grant before it seals them. */
118
+ export async function sealingRace(deployment: Deployment, people: People): Promise<string> {
119
+ if (deployment.vaultRuntime === null) throw new Skip('SQLite prevents a write beside a decision; the vault suite covers review R2 on Postgres');
120
+ const [login] = await using(deployment.vaultRuntime(), (sql) => sql.query<{ name: string }>('SELECT current_user AS name'));
121
+ const person = await member(deployment, people, 'seal-race');
122
+ const { admin } = people;
123
+ try {
124
+ await using(deployment.database(), (holder) => using(deployment.database(), async (sql) => {
125
+ const [place] = await query<{ id: string }>(sql, `SELECT e.id FROM environments e JOIN projects p ON p.id = e.project_id
126
+ WHERE p.slug = 'conformance' AND e.slug = 'prod'`);
127
+ const [head] = await sql.query<{ next_seq: string | number }>('SELECT next_seq FROM audit_chain_head');
128
+ const [owner] = await holder.query<{ pid: number }>('SELECT pg_backend_pid() AS pid');
129
+ expect(place !== undefined, 'no prod environment for the sealing race');
130
+ await holder.exec('BEGIN');
131
+ let pending;
132
+ try {
133
+ await holder.query('SELECT 1 FROM audit_chain_head FOR UPDATE');
134
+ pending = admin.api.access.set(person.member, { [DEV]: 'developer' }).then(
135
+ (value) => ({ value }), (error: unknown) => ({ error }),
136
+ );
137
+ // The blocking PID proves where the request stopped; no sleep guesses the window.
138
+ await until('the vault decision waiting on our head', async () => {
139
+ const waiting = await query(sql, `SELECT pid FROM pg_stat_activity WHERE datname = current_database()
140
+ AND usename = $1 AND $2 = ANY(pg_blocking_pids(pid))`, [login.name, owner.pid]);
141
+ return waiting.length > 0;
142
+ }, 10);
143
+ await query(sql, `INSERT INTO vault_grants (principal, environment_id, role, granted_at, granted_by)
144
+ VALUES ($1, $2, 'viewer', $3, $4)`, [person.member, place.id, Date.now(), person.member]);
145
+ } finally {
146
+ await holder.exec('ROLLBACK');
147
+ if (pending !== undefined) await pending;
148
+ }
149
+ expect(pending !== undefined, 'the access decision was not started');
150
+ const result = await pending;
151
+ expect('error' in result && result.error instanceof CoffreError && result.error.status === 403
152
+ && result.error.code === 'vault_refused' && result.error.reason === 'tampered',
153
+ 'a grant inserted during the decision was not refused as tampered', result);
154
+ const reports = await query(sql, `SELECT seq FROM audit_log WHERE author = 'vault' AND action = 'vault.tampered'
155
+ AND subject_principal = $1 AND code = 'mac' AND seq >= $2`, [person.member, head.next_seq]);
156
+ expect(reports.length > 0, 'the grant inserted during the decision was not reported', reports);
157
+ const response = await person.browser.send('POST', '/api/reveals', { path: PROD });
158
+ const body = await response.json() as { error: string };
159
+ expect(response.status === 401 && body.error === 'unauthenticated', 'the forged grant let its member read', body);
160
+ }));
161
+ } finally {
162
+ // Removal recovers this disposable member even if a broken build sealed the forged grant.
163
+ await admin.api.members.remove(person.member);
164
+ }
165
+ expect((await admin.api.audit.verify()).ok, 'the log did not verify after recovering the sealing-race member');
166
+ return 'a grant inserted while the vault waited on the head was refused as tampered and logged; removal recovered the member';
167
+ }
@@ -0,0 +1,186 @@
1
+ // Who the checks act as, and the project they act on. Each value set here
2
+ // is a canary: random, and never to be seen again outside a reveal.
3
+ import { randomBytes } from 'node:crypto';
4
+
5
+ import type { CoffreClient } from '@coffre/client';
6
+
7
+ import { bearer, Browser } from '../browser.ts';
8
+ import type { Deployment } from '../harness.ts';
9
+ import { expect } from '../report.ts';
10
+
11
+ export const PROJECT = 'conformance';
12
+ export const DEV = `${PROJECT}/dev`;
13
+ export const PROD = `${PROJECT}/prod`;
14
+ export const BULK = `${PROJECT}/bulk`;
15
+ export const SERVICE = 'token:conformance-ci';
16
+ /** Where the live checks' token reads, as an operator would set it up. */
17
+ export const LIVE = `${PROJECT}/live`;
18
+ export const LIVE_SERVICE = 'token:conformance-live';
19
+
20
+ export type Person = { email: string; member: string; browser: Browser; api: CoffreClient };
21
+
22
+ export type People = {
23
+ admin: Person;
24
+ /** A viewer on dev, and nothing else. */
25
+ reader: Person;
26
+ /** A developer on dev, signed in in a browser and in the CLI; offboarded along the way. */
27
+ leaver: Person & { cli: CoffreClient; cliToken: string };
28
+ /** A service, viewer on dev, with a token; offboarded along the way. */
29
+ service: { member: string; token: string; api: CoffreClient };
30
+ /** Never admitted. */
31
+ stranger: { email: string; browser: Browser };
32
+ /** A viewer on bulk, where there are more values than the bulk limit allows at once. */
33
+ bulk: Person;
34
+ };
35
+
36
+ /** Every value set, by `project/environment/KEY`. */
37
+ export type Canaries = Record<string, string>;
38
+
39
+ export function canary(): string {
40
+ return `coffre-canary-${randomBytes(12).toString('hex')}`;
41
+ }
42
+
43
+ /**
44
+ * Sign in the way a browser does: to the stand-in GitHub, which asks for no
45
+ * password, and back. The error is the one coffre sent the browser back to
46
+ * /login with.
47
+ */
48
+ export async function signIn(
49
+ deployment: Deployment,
50
+ browser: Browser,
51
+ email: string,
52
+ ): Promise<{ ok: true } | { ok: false; error: string }> {
53
+ const leave = await browser.fetch('/auth/signin/github');
54
+ const authorize = new URL(leave.headers.get('location') ?? '', deployment.origin);
55
+ expect(
56
+ leave.status === 302 && authorize.origin === deployment.idp.origin,
57
+ 'sign-in did not send the browser to GitHub',
58
+ `${leave.status} ${leave.headers.get('location')}`,
59
+ );
60
+ const form = new URLSearchParams(authorize.searchParams);
61
+ form.set('email', email);
62
+ const approve = await fetch(authorize.origin + authorize.pathname, { method: 'POST', body: form, redirect: 'manual' });
63
+ const callback = approve.headers.get('location') ?? '';
64
+ expect(
65
+ approve.status === 302 && callback.startsWith(`${deployment.origin}/auth/callback/github?`),
66
+ 'GitHub did not send the browser back',
67
+ callback,
68
+ );
69
+ const back = await browser.fetch(callback);
70
+ expect(back.status === 302 || back.status === 303, `the callback answered ${back.status}`, await back.text());
71
+ const error = new URL(back.headers.get('location') ?? '/', deployment.origin).searchParams.get('error');
72
+ return error === null ? { ok: true } : { ok: false, error };
73
+ }
74
+
75
+ export async function signInAdmin(deployment: Deployment) {
76
+ const browser = new Browser(deployment.origin);
77
+ const signed = await signIn(deployment, browser, deployment.rootAdmin);
78
+ expect(signed.ok, `the root admin was refused: ${'error' in signed ? signed.error : ''}`);
79
+ const api = browser.client();
80
+ const me = await api.me();
81
+ expect(me.principal.id === deployment.rootAdmin && me.isRootAdmin, 'signed in as someone else', me);
82
+ const admin: Person = { email: deployment.rootAdmin, member: `user:${deployment.rootAdmin}`, browser, api };
83
+ return { detail: `${admin.email}, root admin, through GitHub`, value: admin };
84
+ }
85
+
86
+ export async function setUp(admin: Person) {
87
+ await admin.api.projects.create(PROJECT, { name: 'Conformance' });
88
+ for (const [path, name] of [
89
+ [DEV, 'Development'],
90
+ [PROD, 'Production'],
91
+ [BULK, 'Bulk'],
92
+ ] as const) {
93
+ await admin.api.environments.create(path, { name });
94
+ }
95
+ const canaries: Canaries = {
96
+ [`${DEV}/API_KEY`]: canary(),
97
+ [`${DEV}/DATABASE_URL`]: canary(),
98
+ [`${PROD}/API_KEY`]: canary(),
99
+ };
100
+ for (const path of [DEV, PROD]) await admin.api.secrets.set(path, valuesIn(canaries, path));
101
+ return { detail: `${PROJECT}: dev and prod, ${Object.keys(canaries).length} values, and bulk`, value: canaries };
102
+ }
103
+
104
+ /**
105
+ * What `probe --token` asks an operator for: an environment holding one
106
+ * canary, and a service that reads it there and audits the project. Its
107
+ * value joins the others, for the scans that follow.
108
+ */
109
+ export async function setUpLive(admin: Person, canaries: Canaries) {
110
+ await admin.api.environments.create(LIVE, { name: 'Live' });
111
+ const value = canary();
112
+ await admin.api.secrets.set(LIVE, { CANARY: value });
113
+ canaries[`${LIVE}/CANARY`] = value;
114
+ await admin.api.members.add(LIVE_SERVICE);
115
+ await admin.api.access.set(LIVE_SERVICE, { [LIVE]: 'viewer', [PROJECT]: 'auditor' });
116
+ const { token } = await admin.api.tokens.issue(LIVE_SERVICE, { label: 'conformance live', expiresInDays: 1 });
117
+ return {
118
+ detail: `${LIVE}/CANARY, and ${LIVE_SERVICE}: viewer there, auditor on ${PROJECT}`,
119
+ value: { token, canary: { project: PROJECT, environment: 'live', key: 'CANARY', value } },
120
+ };
121
+ }
122
+
123
+ /** The canaries in one environment, by key. */
124
+ export function valuesIn(canaries: Canaries, environment: string): Record<string, string> {
125
+ return Object.fromEntries(
126
+ Object.entries(canaries)
127
+ .filter(([path]) => path.startsWith(`${environment}/`))
128
+ .map(([path, value]) => [path.slice(environment.length + 1), value]),
129
+ );
130
+ }
131
+
132
+ export async function personas(deployment: Deployment, admin: Person) {
133
+ async function person(name: string, access: Record<string, 'viewer' | 'developer'>): Promise<Person> {
134
+ const email = `${name}@conformance.example`;
135
+ const member = `user:${email}`;
136
+ await admin.api.members.add(member);
137
+ await admin.api.access.set(member, access);
138
+ const browser = new Browser(deployment.origin);
139
+ const signed = await signIn(deployment, browser, email);
140
+ expect(signed.ok, `${email} was refused: ${'error' in signed ? signed.error : ''}`);
141
+ return { email, member, browser, api: browser.client() };
142
+ }
143
+
144
+ const reader = await person('reader', { [DEV]: 'viewer' });
145
+ const leaver = await person('leaver', { [DEV]: 'developer' });
146
+ const bulk = await person('bulk', { [BULK]: 'viewer' });
147
+
148
+ await admin.api.members.add(SERVICE);
149
+ await admin.api.access.set(SERVICE, { [DEV]: 'viewer' });
150
+ const issued = await admin.api.tokens.issue(SERVICE, { label: 'conformance', expiresInDays: 1 });
151
+ const cliToken = await deviceLogin(deployment, leaver.browser);
152
+
153
+ const people: People = {
154
+ admin,
155
+ reader,
156
+ leaver: { ...leaver, cli: bearer(deployment.origin, cliToken), cliToken },
157
+ service: { member: SERVICE, token: issued.token, api: bearer(deployment.origin, issued.token) },
158
+ stranger: { email: 'stranger@conformance.example', browser: new Browser(deployment.origin) },
159
+ bulk,
160
+ };
161
+ return {
162
+ detail: 'a reader, a leaver in a browser and the CLI, a bulk reader, a service with a token, and a stranger',
163
+ value: people,
164
+ };
165
+ }
166
+
167
+ /** `coffre login`: a device code, approved in a signed-in browser, for a CLI session. */
168
+ async function deviceLogin(deployment: Deployment, browser: Browser): Promise<string> {
169
+ const json = { 'content-type': 'application/json' };
170
+ const started = await fetch(`${deployment.origin}/api/auth/device`, {
171
+ method: 'POST',
172
+ headers: json,
173
+ body: JSON.stringify({ client_label: 'coffre-conformance' }),
174
+ });
175
+ expect(started.ok, `the device login did not start: ${started.status}`, await started.clone().text());
176
+ const device = (await started.json()) as { device_code: string; user_code: string };
177
+ await browser.client().deviceLogins.decide(device.user_code, true);
178
+ const polled = await fetch(`${deployment.origin}/api/auth/device/token`, {
179
+ method: 'POST',
180
+ headers: json,
181
+ body: JSON.stringify({ device_code: device.device_code }),
182
+ });
183
+ const session = (await polled.json()) as { access_token?: string };
184
+ expect(polled.ok && session.access_token, `the approved device login gave no token: ${polled.status}`, session);
185
+ return session.access_token;
186
+ }
@@ -0,0 +1,93 @@
1
+ // Readiness needs both halves of the Cron's work: a recent heartbeat, and a
2
+ // checkpoint the vault signed over it. Either missing turns /readyz red.
3
+ import { using } from '../database.ts';
4
+ import type { Deployment } from '../harness.ts';
5
+ import { expect, until } from '../report.ts';
6
+ import { appendOnlyLifted, insertRow, logRefuses, query, transaction } from './storage.ts';
7
+ import type { People } from './people.ts';
8
+
9
+ async function red(deployment: Deployment): Promise<void> {
10
+ await until('readiness red', async () => (await fetch(`${deployment.origin}/readyz`)).status === 503, 10);
11
+ const body = await (await fetch(`${deployment.origin}/readyz`)).json() as { ok: boolean; checkpointed: boolean };
12
+ expect(body.ok === false && body.checkpointed === false, 'readiness did not report the missing checkpoint', body);
13
+ }
14
+
15
+ export async function refusedCheckpoint(deployment: Deployment): Promise<string> {
16
+ expect((await fetch(`${deployment.origin}/readyz`)).ok, 'readiness is not green before the checkpoint refusal');
17
+ await using(deployment.database(), (sql) => logRefuses(sql, async () => {
18
+ const [before] = await sql.query<{ seq: number | string }>("SELECT seq FROM audit_log WHERE action = 'audit.heartbeat' ORDER BY seq DESC LIMIT 1");
19
+ await deployment.scheduled({ allowFailure: true });
20
+ await until('the new heartbeat', async () => {
21
+ const [after] = await sql.query<{ seq: number | string }>("SELECT seq FROM audit_log WHERE action = 'audit.heartbeat' ORDER BY seq DESC LIMIT 1");
22
+ return BigInt(after.seq) > BigInt(before.seq);
23
+ }, 10);
24
+ await red(deployment);
25
+ }, 'audit.checkpoint'));
26
+ await deployment.scheduled();
27
+ await until('readiness recovered', async () => (await fetch(`${deployment.origin}/readyz`)).ok, 20);
28
+ return 'a committed heartbeat with a refused checkpoint turns readiness red, then recovers';
29
+ }
30
+
31
+ export async function missingCheckpoint(deployment: Deployment): Promise<string> {
32
+ expect((await fetch(`${deployment.origin}/readyz`)).ok, 'readiness is not green before removing checkpoints');
33
+ await using(deployment.database(), (sql) => appendOnlyLifted(sql, async () => {
34
+ const rows = await sql.query("SELECT * FROM audit_log WHERE action = 'audit.checkpoint' ORDER BY seq");
35
+ expect(rows.length > 0, 'no checkpoints to remove');
36
+ await sql.exec("DELETE FROM audit_log WHERE action = 'audit.checkpoint'");
37
+ try {
38
+ await red(deployment);
39
+ } finally {
40
+ for (const row of rows) await insertRow(sql, 'audit_log', row);
41
+ }
42
+ }));
43
+ await until('readiness recovered', async () => (await fetch(`${deployment.origin}/readyz`)).ok, 20);
44
+ return 'a recent heartbeat without a checkpoint is red; restoring the checkpoint recovers';
45
+ }
46
+
47
+ /** A hole before the latest signed prefix must stop the next scheduled checkpoint. */
48
+ export async function middleCut(deployment: Deployment, { admin }: People): Promise<string> {
49
+ expect((await fetch(`${deployment.origin}/readyz`)).ok, 'readiness is not green before the middle cut');
50
+ let seq = 0;
51
+ await using(deployment.database(), async (sql) => {
52
+ const [head] = await sql.query<{ next_seq: string | number }>('SELECT next_seq FROM audit_chain_head');
53
+ const [latest] = await sql.query<{ seq: string | number; metadata: string }>(
54
+ "SELECT seq, metadata FROM audit_log WHERE author = 'vault' AND action = 'audit.checkpoint' AND decision = 'allow' ORDER BY seq DESC LIMIT 1",
55
+ );
56
+ expect(latest !== undefined, 'no signed prefix to cut from');
57
+ const signed = JSON.parse(latest.metadata) as { seq: number };
58
+ // An old heartbeat and its checkpoint carry no access change or linked write.
59
+ const [heartbeat] = await query<{ seq: string | number }>(sql, `SELECT h.seq FROM audit_log h JOIN audit_log c ON c.seq = h.seq + 1
60
+ WHERE h.action = 'audit.heartbeat' AND h.seq > 0 AND c.author = 'vault' AND c.action = 'audit.checkpoint'
61
+ AND c.decision = 'allow' AND c.seq < $1 AND NOT EXISTS
62
+ (SELECT 1 FROM audit_log linked WHERE linked.related_seq IN (h.seq, c.seq)) ORDER BY h.seq LIMIT 1`, [signed.seq]);
63
+ expect(heartbeat !== undefined, 'no older heartbeat and checkpoint to cut');
64
+ seq = Number(heartbeat.seq);
65
+ const kept = await query(sql, 'SELECT * FROM audit_log WHERE seq >= $1 AND seq <= $2 ORDER BY seq', [seq, seq + 1]);
66
+ expect(kept.length === 2, 'the middle cut needs two adjacent entries');
67
+ await appendOnlyLifted(sql, async () => {
68
+ await query(sql, 'DELETE FROM audit_log WHERE seq >= $1 AND seq <= $2', [seq, seq + 1]);
69
+ try {
70
+ // Do not call full verification first: the scheduled job must find the hole itself.
71
+ await deployment.scheduled({ allowFailure: true });
72
+ let checkpoint: { decision: string; code: string | null; metadata: string } | undefined;
73
+ await until('the checkpoint after the cut', async () => {
74
+ [checkpoint] = await query(sql, `SELECT decision, code, metadata FROM audit_log
75
+ WHERE author = 'vault' AND action = 'audit.checkpoint' AND seq >= $1 ORDER BY seq LIMIT 1`, [head.next_seq]);
76
+ return checkpoint !== undefined;
77
+ }, 10);
78
+ expect(checkpoint?.decision === 'deny' && checkpoint.code === 'log_broken', 'the checkpoint signed over a middle cut', checkpoint);
79
+ const detail = JSON.parse(checkpoint.metadata) as { reason: string };
80
+ expect(detail.reason.includes(`sequence gap: expected seq ${seq}`), 'the checkpoint did not name the middle gap', detail);
81
+ await red(deployment);
82
+ } finally {
83
+ await transaction(sql, async () => {
84
+ for (const row of kept) await insertRow(sql, 'audit_log', row);
85
+ });
86
+ }
87
+ });
88
+ });
89
+ await deployment.scheduled();
90
+ await until('readiness recovered after the middle cut', async () => (await fetch(`${deployment.origin}/readyz`)).ok, 20);
91
+ expect((await admin.api.audit.verify()).ok, 'the restored middle cut did not verify');
92
+ return `entries ${seq} and ${seq + 1}, before the latest signed prefix, cut: checkpoint log_broken, readiness red; restored and recovered`;
93
+ }
@@ -0,0 +1,130 @@
1
+ // A sign-in row written by the database's owner mints nothing: a chosen
2
+ // token, an account binding, an approval or an edited generation is refused
3
+ // where it is used, and reported.
4
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
5
+
6
+ import { Browser } from '../browser.ts';
7
+ import { using } from '../database.ts';
8
+ import type { Deployment } from '../harness.ts';
9
+ import { defaultGitHubAccount } from '../idp/people.ts';
10
+ import { expect, until } from '../report.ts';
11
+ import { member } from './members.ts';
12
+ import { signIn, type People } from './people.ts';
13
+ import { insertRow, query, restoreRow } from './storage.ts';
14
+
15
+ const hash = (value: string) => createHash('sha256').update(value).digest();
16
+
17
+ // Wrangler can forward console output after the HTTP refusal arrives.
18
+ async function reported(deployment: Deployment, id: string): Promise<void> {
19
+ const event = new RegExp(`auth_row_tampered[^}]*${id}`);
20
+ await until(`the sign-in row failure report for ${id}`, async () => event.test(deployment.output()), 10);
21
+ }
22
+
23
+ /** Knowing the database password and a chosen token must not mint a credential. */
24
+ export async function forgedCredential(deployment: Deployment, people: People): Promise<string> {
25
+ const person = await member(deployment, people, 'forged-credential');
26
+ const token = `coffre_cli_${randomBytes(32).toString('base64url')}`;
27
+ await using(deployment.database(), async (sql) => {
28
+ const [row] = await query(sql, 'SELECT * FROM credentials WHERE principal = $1 AND revoked_at IS NULL LIMIT 1', [person.member]);
29
+ expect(row !== undefined, 'no genuine credential to copy');
30
+ const forged = { ...row, id: randomUUID(), kind: 'cli', token_hash: hash(token), identity_id: null };
31
+ await insertRow(sql, 'credentials', forged);
32
+ try {
33
+ const response = await fetch(`${deployment.origin}/api/me`, { headers: { authorization: `Bearer ${token}` } });
34
+ expect(response.status === 401, 'an owner-forged credential authenticated', await response.text());
35
+ await reported(deployment, forged.id);
36
+ } finally {
37
+ await query(sql, 'DELETE FROM credentials WHERE id = $1', [forged.id]);
38
+ }
39
+ });
40
+ expect((await person.api.me()).principal.id === person.email, 'the genuine credential stopped working');
41
+ return 'a chosen token in an owner-inserted credential cannot authenticate, and is reported';
42
+ }
43
+
44
+ /** An account binding inserted by the owner must not sign someone in as a member. */
45
+ export async function forgedIdentity(deployment: Deployment, people: People): Promise<string> {
46
+ const person = await member(deployment, people, 'forged-identity');
47
+ const email = 'identity-forger@conformance.example';
48
+ const browser = new Browser(deployment.origin);
49
+ await using(deployment.database(), async (sql) => {
50
+ const [row] = await query(sql, 'SELECT * FROM identities WHERE principal = $1 AND revoked_at IS NULL LIMIT 1', [person.member]);
51
+ expect(row !== undefined, 'no genuine identity to copy');
52
+ const forged = { ...row, id: randomUUID(), subject: String(defaultGitHubAccount(email).id) };
53
+ await insertRow(sql, 'identities', forged);
54
+ try {
55
+ // The callback can answer a sanitized server error for a row it cannot authenticate.
56
+ await signIn(deployment, browser, email).catch(() => {});
57
+ expect((await browser.fetch('/api/me')).status === 401, 'an owner-forged identity minted a session');
58
+ await reported(deployment, forged.id);
59
+ } finally {
60
+ await query(sql, 'DELETE FROM credentials WHERE identity_id = $1', [forged.id]);
61
+ await query(sql, 'DELETE FROM identities WHERE id = $1', [forged.id]);
62
+ }
63
+ });
64
+ expect((await person.api.me()).principal.id === person.email, 'the genuine identity stopped working');
65
+ return 'an owner-inserted account binding cannot mint a session, and is reported';
66
+ }
67
+
68
+ export async function startDevice(deployment: Deployment): Promise<{ device_code: string; user_code: string }> {
69
+ const response = await fetch(`${deployment.origin}/api/auth/device`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
70
+ expect(response.ok, 'the device fixture did not start', await response.clone().text());
71
+ return response.json();
72
+ }
73
+
74
+ export function pollDevice(deployment: Deployment, code: string): Promise<Response> {
75
+ return fetch(`${deployment.origin}/api/auth/device/token`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ device_code: code }) });
76
+ }
77
+
78
+ /** An authentic pending row, changed to approved around the app, grants nothing. */
79
+ export async function forgedApproval(deployment: Deployment, people: People): Promise<string> {
80
+ const person = await member(deployment, people, 'forged-approval');
81
+ const device = await startDevice(deployment);
82
+ await using(deployment.database(), async (sql) => {
83
+ const [row] = await query(sql, 'SELECT * FROM device_authorizations WHERE user_code = $1', [device.user_code]);
84
+ const [standing] = await query<{ generation: number }>(sql, 'SELECT generation FROM vault_members WHERE principal = $1', [person.member]);
85
+ expect(row !== undefined, 'no device row to forge');
86
+ await query(sql, `UPDATE device_authorizations SET decision = 'approved', decided_at = $1, principal = $2, generation = $3 WHERE id = $4`,
87
+ [sql.engine === 'sqlite' ? Date.now() : new Date(), person.member, standing.generation, row.id]);
88
+ try {
89
+ const response = await pollDevice(deployment, device.device_code);
90
+ const body = await response.text();
91
+ expect(!response.ok && !body.includes('access_token'), 'an owner-forged approval minted a session', body);
92
+ await reported(deployment, String(row.id));
93
+ } finally {
94
+ await query(sql, 'DELETE FROM device_authorizations WHERE id = $1', [row.id]);
95
+ }
96
+ });
97
+ const control = await startDevice(deployment);
98
+ await person.api.deviceLogins.decide(control.user_code, true);
99
+ expect((await pollDevice(deployment, control.device_code)).ok, 'a genuine approval no longer works');
100
+ return 'an owner-edited device approval grants nothing and is reported; a genuine approval works';
101
+ }
102
+
103
+ /** Changing an old credential's generation cannot bring its chosen token back. */
104
+ export async function editedGeneration(deployment: Deployment, people: People): Promise<string> {
105
+ const principal = 'token:generation-mac';
106
+ const { admin } = people;
107
+ await admin.api.members.add(principal);
108
+ await admin.api.access.set(principal, { 'conformance/dev': 'viewer' });
109
+ const issued = await admin.api.tokens.issue(principal, { expiresInDays: 1 });
110
+ await using(deployment.database(), async (sql) => {
111
+ const [old] = await query(sql, 'SELECT * FROM credentials WHERE token_hash = $1', [hash(issued.token)]);
112
+ expect(old !== undefined, 'no old token row to save');
113
+ await admin.api.members.remove(principal);
114
+ await admin.api.members.add(principal);
115
+ await admin.api.access.set(principal, { 'conformance/dev': 'viewer' });
116
+ const [current] = await query(sql, 'SELECT * FROM credentials WHERE id = $1', [old.id]);
117
+ const [standing] = await query<{ generation: number }>(sql, 'SELECT generation FROM vault_members WHERE principal = $1', [principal]);
118
+ await restoreRow(sql, 'credentials', { ...old, generation: standing.generation }, 'id');
119
+ try {
120
+ const response = await fetch(`${deployment.origin}/api/me`, { headers: { authorization: `Bearer ${issued.token}` } });
121
+ expect(response.status === 401, 'editing the credential generation revived the token', await response.text());
122
+ await reported(deployment, String(old.id));
123
+ } finally {
124
+ await restoreRow(sql, 'credentials', current, 'id');
125
+ }
126
+ });
127
+ const fresh = await admin.api.tokens.issue(principal, { expiresInDays: 1 });
128
+ expect((await fetch(`${deployment.origin}/api/me`, { headers: { authorization: `Bearer ${fresh.token}` } })).ok, 'a newly issued token does not work');
129
+ return 'an old token with its generation edited to the current membership is refused and reported';
130
+ }