@coffre/conformance 0.15.0 → 0.16.0

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.
@@ -1,25 +1,19 @@
1
1
  // A sign-in row written by the database's owner mints nothing: a chosen
2
2
  // token, an account binding, an approval or an edited generation is refused
3
- // where it is used, and reported.
3
+ // where it is used, and the signer names the row in its alert.
4
4
  import { createHash, randomBytes, randomUUID } from 'node:crypto';
5
5
 
6
6
  import { Browser } from '../browser.ts';
7
7
  import { using } from '../database.ts';
8
8
  import type { Deployment } from '../harness.ts';
9
9
  import { defaultGitHubAccount } from '../idp/people.ts';
10
- import { expect, until } from '../report.ts';
10
+ import { expect } from '../report.ts';
11
11
  import { member } from './members.ts';
12
12
  import { signIn, type People } from './people.ts';
13
- import { insertRow, query, restoreRow } from './storage.ts';
13
+ import { alerted, insertRow, query, restoreRow } from './storage.ts';
14
14
 
15
15
  const hash = (value: string) => createHash('sha256').update(value).digest();
16
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
17
  /** Knowing the database password and a chosen token must not mint a credential. */
24
18
  export async function forgedCredential(deployment: Deployment, people: People): Promise<string> {
25
19
  const person = await member(deployment, people, 'forged-credential');
@@ -32,7 +26,7 @@ export async function forgedCredential(deployment: Deployment, people: People):
32
26
  try {
33
27
  const response = await fetch(`${deployment.origin}/api/me`, { headers: { authorization: `Bearer ${token}` } });
34
28
  expect(response.status === 401, 'an owner-forged credential authenticated', await response.text());
35
- await reported(deployment, forged.id);
29
+ await alerted(deployment, 'credentials', forged.id);
36
30
  } finally {
37
31
  await query(sql, 'DELETE FROM credentials WHERE id = $1', [forged.id]);
38
32
  }
@@ -55,7 +49,7 @@ export async function forgedIdentity(deployment: Deployment, people: People): Pr
55
49
  // The callback can answer a sanitized server error for a row it cannot authenticate.
56
50
  await signIn(deployment, browser, email).catch(() => {});
57
51
  expect((await browser.fetch('/api/me')).status === 401, 'an owner-forged identity minted a session');
58
- await reported(deployment, forged.id);
52
+ await alerted(deployment, 'identities', forged.id);
59
53
  } finally {
60
54
  await query(sql, 'DELETE FROM credentials WHERE identity_id = $1', [forged.id]);
61
55
  await query(sql, 'DELETE FROM identities WHERE id = $1', [forged.id]);
@@ -75,32 +69,41 @@ export function pollDevice(deployment: Deployment, code: string): Promise<Respon
75
69
  return fetch(`${deployment.origin}/api/auth/device/token`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ device_code: code }) });
76
70
  }
77
71
 
78
- /** An authentic pending row, changed to approved around the app, grants nothing. */
72
+ /**
73
+ * An authentic pending row, changed to approved around the vault, grants
74
+ * nothing: its MAC is the pending row's. Edited under the MAC it had, it is
75
+ * refused, not named in the signer's alert, whose minute's check compares
76
+ * MACs (docs/design/0.16.md, "What it promises" and "How long the log
77
+ * is kept").
78
+ */
79
79
  export async function forgedApproval(deployment: Deployment, people: People): Promise<string> {
80
80
  const person = await member(deployment, people, 'forged-approval');
81
81
  const device = await startDevice(deployment);
82
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]);
83
+ const [row] = await query(sql, 'SELECT * FROM device_logins WHERE user_code = $1', [device.user_code]);
84
+ const [standing] = await query<{ generation: number }>(sql, 'SELECT generation FROM principals WHERE id = $1', [person.member]);
85
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]);
86
+ await query(sql, `UPDATE device_logins SET decision = 'approved', decided_at = $1, principal = $2, generation = $3 WHERE id = $4`,
87
+ [new Date(), person.member, standing.generation, row.id]);
88
88
  try {
89
89
  const response = await pollDevice(deployment, device.device_code);
90
90
  const body = await response.text();
91
91
  expect(!response.ok && !body.includes('access_token'), 'an owner-forged approval minted a session', body);
92
- await reported(deployment, String(row.id));
93
92
  } finally {
94
- await query(sql, 'DELETE FROM device_authorizations WHERE id = $1', [row.id]);
93
+ await query(sql, 'DELETE FROM device_logins WHERE id = $1', [row.id]);
95
94
  }
96
95
  });
97
96
  const control = await startDevice(deployment);
98
97
  await person.api.deviceLogins.decide(control.user_code, true);
99
98
  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';
99
+ return 'an owner-edited device approval grants nothing; a genuine approval works';
101
100
  }
102
101
 
103
- /** Changing an old credential's generation cannot bring its chosen token back. */
102
+ /**
103
+ * Changing an old credential's generation cannot bring its chosen token
104
+ * back: its MAC covers the generation it was issued under. Like any row
105
+ * edited under the MAC it had, it is refused, not alerted on (as above).
106
+ */
104
107
  export async function editedGeneration(deployment: Deployment, people: People): Promise<string> {
105
108
  const principal = 'token:generation-mac';
106
109
  const { admin } = people;
@@ -114,17 +117,16 @@ export async function editedGeneration(deployment: Deployment, people: People):
114
117
  await admin.api.members.add(principal);
115
118
  await admin.api.access.set(principal, { 'conformance/dev': 'viewer' });
116
119
  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]);
120
+ const [standing] = await query<{ generation: number }>(sql, 'SELECT generation FROM principals WHERE id = $1', [principal]);
118
121
  await restoreRow(sql, 'credentials', { ...old, generation: standing.generation }, 'id');
119
122
  try {
120
123
  const response = await fetch(`${deployment.origin}/api/me`, { headers: { authorization: `Bearer ${issued.token}` } });
121
124
  expect(response.status === 401, 'editing the credential generation revived the token', await response.text());
122
- await reported(deployment, String(old.id));
123
125
  } finally {
124
126
  await restoreRow(sql, 'credentials', current, 'id');
125
127
  }
126
128
  });
127
129
  const fresh = await admin.api.tokens.issue(principal, { expiresInDays: 1 });
128
130
  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';
131
+ return 'an old token with its generation edited to the current membership is refused';
130
132
  }
@@ -1,18 +1,18 @@
1
1
  // SQL around coffre, as the database's owner: what the checks read, change
2
- // and put back behind its back, on Postgres or SQLite alike.
2
+ // and put back behind its back.
3
3
  import type { Sql } from '../database.ts';
4
- import { expect } from '../report.ts';
4
+ import type { Deployment } from '../harness.ts';
5
+ import { expect, until } from '../report.ts';
5
6
 
6
7
  export const TABLES = [
7
- 'projects', 'environments', 'secrets', 'secret_versions', 'vault_members', 'vault_grants',
8
- 'audit_log', 'audit_chain_head', 'identities', 'credentials', 'device_authorizations',
8
+ 'projects', 'environments', 'secrets', 'secret_versions', 'principals', 'grants',
9
+ 'log_pending', 'log', 'log_head', 'identities', 'credentials', 'device_logins',
9
10
  ] as const;
10
11
 
11
12
  /** Inspect every table, including any a deployment added. Missing shared tables fail. */
12
13
  export async function tables(sql: Sql): Promise<string[]> {
13
- const rows = await sql.query<{ name: string }>(sql.engine === 'postgres'
14
- ? `SELECT table_name AS name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE'`
15
- : `SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`);
14
+ const rows = await sql.query<{ name: string }>(
15
+ `SELECT table_name AS name FROM information_schema.tables WHERE table_schema = $1 AND table_type = 'BASE TABLE'`, [sql.schema]);
16
16
  const names = rows.map((row) => row.name);
17
17
  const missing = TABLES.filter((name) => !names.includes(name));
18
18
  expect(missing.length === 0, 'shared tables could not be inspected', missing);
@@ -28,7 +28,7 @@ export async function scanTables(sql: Sql, names: string[], look: (where: string
28
28
  for (const name of names) {
29
29
  for (const row of await sql.query(`SELECT * FROM ${quoted(name)}`)) {
30
30
  for (const value of Object.values(row)) {
31
- look(`the database's ${name} table`, value instanceof Uint8Array ? value : typeof value === 'bigint' ? String(value) : JSON.stringify(value) ?? '');
31
+ look(`the database's ${name} table`, value instanceof Uint8Array ? value : JSON.stringify(value) ?? '');
32
32
  }
33
33
  }
34
34
  }
@@ -36,7 +36,7 @@ export async function scanTables(sql: Sql, names: string[], look: (where: string
36
36
 
37
37
  /** Parameters use one spelling in the checks, whatever the database. */
38
38
  export function query<Row = Record<string, unknown>>(sql: Sql, statement: string, params: unknown[] = []): Promise<Row[]> {
39
- return sql.query<Row>(sql.engine === 'sqlite' ? statement.replace(/\$\d+/g, '?') : statement, params);
39
+ return sql.query<Row>(statement, params);
40
40
  }
41
41
 
42
42
  /** Insert a saved or forged row as it is, but for its generated columns. */
@@ -66,86 +66,47 @@ export async function transaction<T>(sql: Sql, work: () => Promise<T>): Promise<
66
66
  }
67
67
  }
68
68
 
69
- /**
70
- * `work` with the audit log's append-only triggers lifted, as only its owner
71
- * can: Postgres disables them for the session, SQLite drops them and makes
72
- * them again after.
73
- */
74
- export async function appendOnlyLifted<T>(sql: Sql, work: () => Promise<T>): Promise<T> {
75
- if (sql.engine === 'postgres') {
76
- await sql.exec('ALTER TABLE audit_log DISABLE TRIGGER USER');
77
- try {
78
- return await work();
79
- } finally {
80
- await sql.exec('ALTER TABLE audit_log ENABLE TRIGGER USER');
81
- }
82
- }
83
- const triggers = await sql.query<{ name: string; sql: string }>(
84
- `SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND tbl_name = 'audit_log'`,
85
- );
86
- for (const trigger of triggers) await sql.exec(`DROP TRIGGER ${trigger.name}`);
87
- try {
88
- return await work();
89
- } finally {
90
- for (const trigger of triggers) await sql.exec(trigger.sql);
91
- }
92
- }
93
-
94
69
  export const LOG_REFUSAL = 'coffre-conformance: the log refuses writes';
95
70
 
96
71
  /**
97
- * `work` with a log refusing appends, as a full disk or a lost connection
98
- * would, without changing the deployment's code: a trigger, dropped after.
99
- * 0.14's, `audit_log`, of one action or all; or 0.15's uses, `log_uses`.
100
- *
101
- * On Postgres, each statement first locks the table itself, as every reader
102
- * does: `log_uses` is partitioned by day, and a trigger on it is one on each
103
- * day, which `DROP TRIGGER` locks newest first, while a query reading several
104
- * days locks them oldest first. A use, or the reads' projector, holding one
105
- * day and waiting on the next deadlocked with the drop (seen in CI; 15 in 50
106
- * drops against uses and the projector, none in 2,703 with the table locked
107
- * first).
72
+ * `work` with the log refusing appends, of one action or all, as a full
73
+ * disk or a lost connection would, without changing the deployment's code:
74
+ * a trigger on `log_pending`, where the vault appends each entry, dropped
75
+ * after.
108
76
  */
109
- export async function logRefuses<T>(sql: Sql, work: () => Promise<T>, action?: string, table: 'audit_log' | 'log_uses' = 'audit_log'): Promise<T> {
110
- const when = action === undefined ? '' : ` WHEN (NEW.action = '${action}')`;
111
- const create = sql.engine === 'postgres'
112
- ? `LOCK TABLE ${table} IN SHARE ROW EXCLUSIVE MODE;
113
- CREATE FUNCTION conformance_refuse() RETURNS trigger LANGUAGE plpgsql AS $$
114
- BEGIN RAISE EXCEPTION '${LOG_REFUSAL}'; END $$;
115
- CREATE TRIGGER conformance_refuse BEFORE INSERT ON ${table} FOR EACH ROW${when} EXECUTE FUNCTION conformance_refuse();`
116
- : `CREATE TRIGGER conformance_refuse BEFORE INSERT ON ${table}${when}
117
- BEGIN SELECT RAISE(ABORT, '${LOG_REFUSAL}'); END;`;
118
- await sql.exec(create);
77
+ export async function logRefuses<T>(sql: Sql, work: () => Promise<T>, action?: string): Promise<T> {
78
+ const when = action === undefined ? '' : ` WHEN ((NEW.body::jsonb)->>'action' = '${action}')`;
79
+ await sql.exec(`CREATE FUNCTION conformance_refuse() RETURNS trigger LANGUAGE plpgsql AS $$
80
+ BEGIN RAISE EXCEPTION '${LOG_REFUSAL}'; END $$;
81
+ CREATE TRIGGER conformance_refuse BEFORE INSERT ON log_pending FOR EACH ROW${when} EXECUTE FUNCTION conformance_refuse();`);
119
82
  try {
120
83
  return await work();
121
84
  } finally {
122
- await sql.exec(sql.engine === 'postgres'
123
- ? `LOCK TABLE ${table} IN ACCESS EXCLUSIVE MODE; DROP TRIGGER conformance_refuse ON ${table}; DROP FUNCTION conformance_refuse();`
124
- : 'DROP TRIGGER conformance_refuse;');
85
+ await sql.exec('DROP TRIGGER conformance_refuse ON log_pending; DROP FUNCTION conformance_refuse();');
125
86
  }
126
87
  }
127
88
 
128
- /** The log's fields in the order its format (`coffre.audit.v2`) encodes them. */
129
- const ENTRY_FIELDS = [
130
- 'seq', 'author', 'key_id', 'occurred_at', 'actor', 'action', 'decision', 'code', 'subject_principal', 'project_id',
131
- 'environment_id', 'secret_id', 'secret_version_id', 'operation_id', 'request_id', 'source_ip', 'related_seq', 'metadata',
132
- ] as const;
89
+ /** A log entry's body as the vault writes it (`Entry` in @coffre/vault): the fields the checks read. */
90
+ export type Body = {
91
+ action: string;
92
+ actor: string | null;
93
+ request: string | null;
94
+ objects: string[];
95
+ detail: Record<string, unknown>;
96
+ };
97
+
98
+ /** Every entry, signed (`log`) or waiting to be (`log_pending`), oldest first, read in one statement. */
99
+ export async function logBodies(sql: Sql): Promise<Body[]> {
100
+ const rows = await sql.query<{ body: string }>('SELECT body FROM (SELECT seq, 0 AS waiting, body FROM log UNION ALL SELECT id, 1, body FROM log_pending) entries ORDER BY waiting, seq');
101
+ return rows.map((row) => JSON.parse(row.body) as Body);
102
+ }
133
103
 
134
104
  /**
135
- * An entry's fields as its MAC and hash cover them, written here from the
136
- * format rather than taken from coffre, so a check does not trust the code
137
- * it checks: each field length-prefixed in order, null as length -1.
105
+ * Wait for the signer's alert naming a row (`nameOf` in @coffre/vault:
106
+ * its table and key), in the processes' output, where a deployment with no
107
+ * `alert` of its own sends it. Its check runs each minute.
138
108
  */
139
- export function entryFields(row: Record<string, unknown>): Buffer {
140
- return Buffer.concat(ENTRY_FIELDS.flatMap((field) => {
141
- const header = Buffer.alloc(4);
142
- const value = row[field];
143
- if (value === null || value === undefined) {
144
- header.writeInt32BE(-1);
145
- return [header];
146
- }
147
- const bytes = Buffer.from(String(value));
148
- header.writeInt32BE(bytes.length);
149
- return [header, bytes];
150
- }));
109
+ export async function alerted(deployment: Deployment, table: string, ...key: unknown[]): Promise<void> {
110
+ const named = `- row ${JSON.stringify([table, ...key])}:`;
111
+ await until(`the signer's alert naming ${named}`, async () => deployment.output().includes(named), 150);
151
112
  }
@@ -1,26 +1,35 @@
1
- // Health: up, and ready only once the scheduled job has beaten and the
2
- // vault has checkpointed it. What else anyone on the network sees, its
3
- // headers among it, `coffre verify instance` checks, here as anywhere.
1
+ // Health: up, and ready once migrated; a fresh deployment, only once its
2
+ // vault has adopted the database and its signer signed the first entry.
3
+ // What else anyone on the network sees, its headers among it, `coffre
4
+ // verify instance` checks, here as anywhere.
4
5
  import { clientFiles, serverCodeIn } from '../bundle.ts';
5
6
  import type { Deployment } from '../harness.ts';
6
7
  import type { Person } from './people.ts';
7
8
  import { expect, until } from '../report.ts';
8
9
 
10
+ /**
11
+ * A fresh deployment is not ready until its vault has adopted the database
12
+ * and the signer has signed its first entry, what the app learns from the
13
+ * vault's `about` (docs/design/0.16.md, "Readiness"). 0.14 asked the same of
14
+ * its heartbeat and checkpoint, which 0.16 drops. Run first, while the
15
+ * deployment is still fresh.
16
+ */
17
+ export async function readyOnceAdopted(deployment: Deployment): Promise<string> {
18
+ const { origin } = deployment;
19
+ if (!deployment.fresh) return 'not a fresh deployment: its database was adopted before the suite';
20
+ const early = await fetch(`${origin}/readyz`);
21
+ const body = await early.text();
22
+ expect(early.status === 503, `/readyz answered ${early.status} before the vault adopted the database`, body);
23
+ await until('/readyz', async () => (await fetch(`${origin}/readyz`)).ok, 90);
24
+ return '/readyz red until the vault adopted the database and signed its first entry, then green';
25
+ }
26
+
9
27
  export async function health(deployment: Deployment): Promise<string> {
10
28
  const { origin } = deployment;
11
29
  const live = await fetch(`${origin}/livez`);
12
30
  expect(live.ok, `/livez answered ${live.status}`);
13
- // Readiness follows the audit heartbeat and the vault's checkpoint of it,
14
- // which only the scheduled job writes: not ready until it has run.
15
- if (deployment.beforeFirstBeat) {
16
- const early = await fetch(`${origin}/readyz`);
17
- expect(early.status === 503, `/readyz answered ${early.status} before any heartbeat`, await early.text());
18
- await deployment.scheduled();
19
- }
20
31
  await until('/readyz', async () => (await fetch(`${origin}/readyz`)).ok, 20);
21
- const ready = (await (await fetch(`${origin}/readyz`)).json()) as { checkpointed?: unknown };
22
- expect(ready.checkpointed === true, '/readyz passed without a checkpoint covering the heartbeat', ready);
23
- return deployment.beforeFirstBeat ? '/livez, and /readyz only once the heartbeat ran and was checkpointed' : '/livez and /readyz';
32
+ return '/livez and /readyz';
24
33
  }
25
34
 
26
35
  /** The headers coffre sets on everything it answers, but the policy, whose nonce is each response's own. */
@@ -15,10 +15,9 @@ import type { AuditEntryView } from '@coffre/client';
15
15
  import { bearer } from '../browser.ts';
16
16
  import type { Deployment } from '../harness.ts';
17
17
  import { GITHUB_RUN } from '../idp/index.ts';
18
- import { expect, Skip } from '../report.ts';
18
+ import { expect, Skip, until, PUBLISHED_SECONDS } from '../report.ts';
19
19
  import { Cli } from './cli.ts';
20
20
  import { DEV, type Canaries, type Person } from './people.ts';
21
- import { listed } from './audit.ts';
22
21
 
23
22
  /** The service the runs sign in as: a viewer on dev. */
24
23
  export const RUNNER = 'token:conformance-run';
@@ -92,16 +91,17 @@ export async function runSignsIn(deployment: Deployment, admin: Person, canaries
92
91
  const { values } = await bearer(deployment.origin, token).secrets.reveal(`${DEV}/API_KEY`);
93
92
  expect(values.API_KEY === canaries[`${DEV}/API_KEY`], 'the credential did not read the value as the service');
94
93
 
95
- // The read listed once sealed and projected, a tick or two on (T166).
94
+ // The signer moves what the vault wrote into the log within its minute.
96
95
  let entries: AuditEntryView[] = [];
96
+ const exchangedIn = () => entries.find((entry) => entry.action === 'token.exchange');
97
97
  const readIn = () => entries.find((entry) => entry.author === 'vault' && entry.action === 'secret.read' && entry.key === 'API_KEY');
98
- await listed(async () => ((entries = (await admin.api.audit.list({ actor: RUNNER, detail: '1', sealed: '1' })).entries), readIn() !== undefined));
99
- const exchanged = entries.find((entry) => entry.action === 'token.exchange');
100
- const read = readIn();
98
+ await until('the exchange and the read in the log', async () => {
99
+ ({ entries } = await admin.api.audit.list({ actor: RUNNER, detail: '1' }));
100
+ return exchangedIn() !== undefined && readIn() !== undefined;
101
+ }, PUBLISHED_SECONDS).catch(() => undefined);
102
+ const [exchanged, read] = [exchangedIn(), readIn()];
101
103
  expect(exchanged !== undefined && read !== undefined, 'the exchange or the read is not in the log', entries.map((entry) => entry.action));
102
- const credentialId = exchanged.metadata.credentialId;
103
- expect(typeof credentialId === 'string', 'the exchange did not log its credential', exchanged.metadata);
104
- expect(read.metadata.credentialId === credentialId, "the vault's entry for the read does not name the credential", read.metadata);
104
+ expect(typeof exchanged.metadata.credential === 'string', 'the exchange did not log its credential', exchanged.metadata);
105
105
  expect(
106
106
  read.run?.exchangeSeq === exchanged.seq && read.run.claims.run_id === GITHUB_RUN.run_id && read.run.claims.repository === GITHUB_RUN.repository,
107
107
  'the read does not lead to its run',
@@ -138,7 +138,7 @@ export async function runsRefused(deployment: Deployment, admin: Person): Promis
138
138
  ['from a pull request', await mint(deployment, { event_name: 'pull_request', ref: 'refs/pull/1/merge', base_ref: 'main', workflow_ref: GITHUB_RUN.workflow_ref.replace(/@.*/, '@refs/pull/1/merge'), sub: 'repo:acme/api:pull_request' }), 'no_match'],
139
139
  ['from another repository', await mint(deployment, { repository_id: '1', repository: 'acme/fork' }), 'no_match'],
140
140
  ] as const;
141
- const before = (await admin.api.audit.list({ actor: RUNNER, detail: '1', sealed: '1' })).entries.filter((entry) => entry.action === 'token.exchange').length;
141
+ const from = Date.now();
142
142
  for (const [what, token, reason] of cases) {
143
143
  const answer = await exchange(deployment, token);
144
144
  expect(answer.status === 401 && answer.reason === reason, `a token ${what} was not refused as ${reason}`, shown(answer));
@@ -146,8 +146,16 @@ export async function runsRefused(deployment: Deployment, admin: Person): Promis
146
146
  }
147
147
  const stranger = await exchange(deployment, await mint(deployment), 'token:conformance-nobody');
148
148
  expect(stranger.status === 401 && stranger.reason === 'no_match', 'a token was taken for a service no binding names', shown(stranger));
149
- const after = (await admin.api.audit.list({ actor: RUNNER, detail: '1', sealed: '1' })).entries.filter((entry) => entry.action === 'token.exchange').length;
150
- expect(after === before, `${after - before} refused exchanges were logged as exchanges`);
149
+ // The signer moves entries into the log in order: once an exchange taken after the refusals is in, any refusal logged would be too.
150
+ const to = Date.now();
151
+ expect((await exchange(deployment, await mint(deployment))).status === 200, 'a fresh token was refused');
152
+ let exchanges: AuditEntryView[] = [];
153
+ await until('an exchange taken after the refusals in the log', async () => {
154
+ exchanges = (await admin.api.audit.list({ actor: RUNNER, detail: '1' })).entries.filter((entry) => entry.action === 'token.exchange');
155
+ return exchanges.some((entry) => Date.parse(entry.occurredAt) >= to);
156
+ }, PUBLISHED_SECONDS);
157
+ const logged = exchanges.filter((entry) => Date.parse(entry.occurredAt) >= from && Date.parse(entry.occurredAt) < to).length;
158
+ expect(logged === 0, `${logged} refused exchanges were logged as exchanges`);
151
159
  return `${cases.length + 1} refused, each for its reason, none saying what the binding expects, none logged: ${cases.map(([what]) => what).join(', ')}, for another service`;
152
160
  }
153
161
 
@@ -199,7 +207,9 @@ export async function keysUploaded(deployment: Deployment, admin: Person, canari
199
207
  const { keys } = (await (await fetch(deployment.idp.workloads.jwksUrl)).json()) as { keys: Record<string, unknown>[] };
200
208
  const claims = { sub: POD_ACCOUNT.sub, 'kubernetes.io.serviceaccount.uid': POD_ACCOUNT.uid };
201
209
  const made = await admin.api.bindings.create(POD, { profile: 'custom', issuer: CLUSTER, claims, jwks: { keys }, label: 'conformance pod' });
202
- expect(made.binding.keys?.length === 2 && /^sha256:/.test(made.binding.jwksUri), 'the binding does not show the keys uploaded with it', made.binding);
210
+ // The answer names the binding made; its keys are in the service's list of bindings.
211
+ const listed = (await admin.api.bindings.list(POD)).bindings.find((binding) => binding.id === made.binding.id);
212
+ expect(listed?.keys?.length === 2 && /^sha256:/.test(listed.jwksUri), 'the binding does not show the keys uploaded with it', { made, listed });
203
213
  const now = Math.floor(Date.now() / 1000);
204
214
  const pod = (alg: 'RS256' | 'ES256', uid = POD_ACCOUNT.uid, times: Record<string, number> = {}) =>
205
215
  mint(deployment, { iss: CLUSTER, sub: POD_ACCOUNT.sub, 'kubernetes.io': { namespace: 'ci', serviceaccount: { name: 'deploy', uid } }, ...times }, { alg });
@@ -210,8 +220,9 @@ export async function keysUploaded(deployment: Deployment, admin: Person, canari
210
220
  expect(values.API_KEY === canaries[`${DEV}/API_KEY`], 'the credential did not read the value as the service');
211
221
  const other = await exchange(deployment, await pod('RS256', 'another-uid'), POD);
212
222
  expect(other.status === 401 && other.reason === 'no_match', 'a token of another service account under the same name was taken', shown(other));
223
+ // 0.16 says `too_old` where 0.14.7 said `too_long`: a token past its time, either way (docs/design/0.16.md, "Operations").
213
224
  const long = await exchange(deployment, await pod('RS256', POD_ACCOUNT.uid, { iat: now, nbf: now, exp: now + 3601 }), POD);
214
- expect(long.status === 401 && long.reason === 'too_long', 'a token that lives past the hour was taken', shown(long));
225
+ expect(long.status === 401 && long.reason === 'too_old', 'a token that lives past the hour was taken', shown(long));
215
226
 
216
227
  await admin.api.bindings.replaceKeys(POD, { issuer: CLUSTER, jwks: { keys: keys.filter((key) => key.alg === 'ES256') } });
217
228
  const dropped = await exchange(deployment, await pod('RS256'), POD);
@@ -221,17 +232,21 @@ export async function keysUploaded(deployment: Deployment, admin: Person, canari
221
232
  return `${POD} trusts ${CLUSTER} by its uploaded keys: a pod's token taken by its account's UID; another UID, and a token living past the hour, refused; the RS256 key replaced away, its tokens refused and ES256's taken`;
222
233
  }
223
234
 
224
- /** Removing the binding ends the credentials it issued at once, and the next run gets none. */
235
+ /**
236
+ * Removing the binding ends the credentials it issued within the vault's
237
+ * memory of who they are, 2 seconds (docs/design/0.16.md, D218), and the
238
+ * next run gets none at once.
239
+ */
225
240
  export async function runUnbound(deployment: Deployment, admin: Person, bindingId: string, credential: string): Promise<string> {
226
241
  const me = (token: string) => fetch(`${deployment.origin}/api/me`, { headers: { authorization: `Bearer ${token}` } }).then((response) => response.status);
227
242
  expect((await me(credential)) === 200, 'the credential did not work before its binding was removed');
228
243
  await admin.api.bindings.remove(RUNNER, bindingId);
229
- expect((await me(credential)) === 401, 'the credential still worked once its binding was removed');
244
+ await until('the credential refused once its binding was removed', async () => (await me(credential)) === 401, 5);
230
245
  const next = await exchange(deployment, await mint(deployment));
231
246
  expect(next.status === 401 && next.reason === 'no_match', 'a run was let in once its binding was removed', shown(next));
232
247
  const { bindings } = await admin.api.bindings.list(RUNNER);
233
248
  expect(bindings.length === 0, 'the removed binding is still listed', bindings);
234
- return 'its credential refused at once, and the next run refused as no binding matching';
249
+ return 'its credential refused within the vault\'s memory, and the next run refused as no binding matching';
235
250
  }
236
251
 
237
252
  /**
package/src/database.ts CHANGED
@@ -1,52 +1,31 @@
1
1
  // SQL on a deployment's shared database, as whoever holds its
2
- // password or its file: what the checks use to go around coffre, to see
3
- // what it wrote, and to break what it must notice.
4
- import { DatabaseSync } from 'node:sqlite';
5
-
2
+ // password: what the checks use to go around coffre, to see what it
3
+ // wrote, and to break what it must notice.
6
4
  import { postgresSession } from '@coffre/db/connect';
7
5
 
8
6
  export type Sql = {
9
- readonly engine: 'postgres' | 'sqlite';
10
- /** One statement, with `$1`-style parameters on Postgres and `?` on SQLite. */
7
+ /** The schema coffre's tables are in: `public` in a deployment. */
8
+ readonly schema: string;
9
+ /** One statement, with `$1`-style parameters. */
11
10
  query<Row = Record<string, unknown>>(statement: string, params?: unknown[]): Promise<Row[]>;
12
11
  /** Any number of statements, no parameters. */
13
12
  exec(statements: string): Promise<void>;
14
13
  close(): Promise<void>;
15
14
  };
16
15
 
17
- export async function postgres(url: string): Promise<Sql> {
16
+ export async function postgres(url: string, schema = 'public'): Promise<Sql> {
18
17
  // One session, as a check's transaction needs: lost, its statements fail rather than run on a new connection, unheld.
19
18
  const client = postgresSession(url);
20
19
  // Connected now, as the harness expects a database it can reach.
21
20
  await client.unsafe('SELECT 1');
22
21
  return {
23
- engine: 'postgres',
22
+ schema,
24
23
  query: async <Row>(statement: string, params: unknown[] = []) => [...await client.unsafe(statement, params as never[])] as Row[],
25
24
  exec: async (statements) => void (await client.unsafe(statements)),
26
25
  close: () => client.end(),
27
26
  };
28
27
  }
29
28
 
30
- /**
31
- * A SQLite file, perhaps open in another process: it waits out their locks.
32
- * An integer past 2^53, as 0.15's log numbers are, reads as a bigint; any other, as a number.
33
- */
34
- export function sqlite(file: string): Sql {
35
- const db = new DatabaseSync(file, { timeout: 5000 });
36
- const exact = (value: unknown) => (typeof value === 'bigint' && value <= BigInt(Number.MAX_SAFE_INTEGER) && value >= BigInt(Number.MIN_SAFE_INTEGER) ? Number(value) : value);
37
- return {
38
- engine: 'sqlite',
39
- query: async <Row>(statement: string, params: unknown[] = []) => {
40
- const prepared = db.prepare(statement);
41
- prepared.setReadBigInts(true);
42
- const rows = prepared.all(...(params as never[])) as Record<string, unknown>[];
43
- return rows.map((row) => Object.fromEntries(Object.entries(row).map(([name, value]) => [name, exact(value)]))) as Row[];
44
- },
45
- exec: async (statements) => db.exec(statements),
46
- close: async () => db.close(),
47
- };
48
- }
49
-
50
29
  export async function using<T>(open: Sql | Promise<Sql>, use: (sql: Sql) => Promise<T>): Promise<T> {
51
30
  const sql = await open;
52
31
  try {