@coffre/conformance 0.14.7 → 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);
@@ -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,77 +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 the audit log refusing appends, of one action or all, as a
98
- * full disk or a lost connection would, without changing the deployment's
99
- * code: a trigger, dropped after.
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.
100
76
  */
101
77
  export async function logRefuses<T>(sql: Sql, work: () => Promise<T>, action?: string): Promise<T> {
102
- const when = action === undefined ? '' : ` WHEN (NEW.action = '${action}')`;
103
- const create = sql.engine === 'postgres'
104
- ? `CREATE FUNCTION conformance_refuse() RETURNS trigger LANGUAGE plpgsql AS $$
105
- BEGIN RAISE EXCEPTION '${LOG_REFUSAL}'; END $$;
106
- CREATE TRIGGER conformance_refuse BEFORE INSERT ON audit_log FOR EACH ROW${when} EXECUTE FUNCTION conformance_refuse();`
107
- : `CREATE TRIGGER conformance_refuse BEFORE INSERT ON audit_log${when}
108
- BEGIN SELECT RAISE(ABORT, '${LOG_REFUSAL}'); END;`;
109
- await sql.exec(create);
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();`);
110
82
  try {
111
83
  return await work();
112
84
  } finally {
113
- await sql.exec(sql.engine === 'postgres'
114
- ? 'DROP TRIGGER conformance_refuse ON audit_log; DROP FUNCTION conformance_refuse();'
115
- : 'DROP TRIGGER conformance_refuse;');
85
+ await sql.exec('DROP TRIGGER conformance_refuse ON log_pending; DROP FUNCTION conformance_refuse();');
116
86
  }
117
87
  }
118
88
 
119
- /** The log's fields in the order its format (`coffre.audit.v2`) encodes them. */
120
- const ENTRY_FIELDS = [
121
- 'seq', 'author', 'key_id', 'occurred_at', 'actor', 'action', 'decision', 'code', 'subject_principal', 'project_id',
122
- 'environment_id', 'secret_id', 'secret_version_id', 'operation_id', 'request_id', 'source_ip', 'related_seq', 'metadata',
123
- ] 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
+ }
124
103
 
125
104
  /**
126
- * An entry's fields as its MAC and hash cover them, written here from the
127
- * format rather than taken from coffre, so a check does not trust the code
128
- * 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.
129
108
  */
130
- export function entryFields(row: Record<string, unknown>): Buffer {
131
- return Buffer.concat(ENTRY_FIELDS.flatMap((field) => {
132
- const header = Buffer.alloc(4);
133
- const value = row[field];
134
- if (value === null || value === undefined) {
135
- header.writeInt32BE(-1);
136
- return [header];
137
- }
138
- const bytes = Buffer.from(String(value));
139
- header.writeInt32BE(bytes.length);
140
- return [header, bytes];
141
- }));
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);
142
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. */
@@ -10,10 +10,12 @@
10
10
  import { existsSync } from 'node:fs';
11
11
  import { join } from 'node:path';
12
12
 
13
+ import type { AuditEntryView } from '@coffre/client';
14
+
13
15
  import { bearer } from '../browser.ts';
14
16
  import type { Deployment } from '../harness.ts';
15
17
  import { GITHUB_RUN } from '../idp/index.ts';
16
- import { expect, Skip } from '../report.ts';
18
+ import { expect, Skip, until, PUBLISHED_SECONDS } from '../report.ts';
17
19
  import { Cli } from './cli.ts';
18
20
  import { DEV, type Canaries, type Person } from './people.ts';
19
21
 
@@ -89,13 +91,17 @@ export async function runSignsIn(deployment: Deployment, admin: Person, canaries
89
91
  const { values } = await bearer(deployment.origin, token).secrets.reveal(`${DEV}/API_KEY`);
90
92
  expect(values.API_KEY === canaries[`${DEV}/API_KEY`], 'the credential did not read the value as the service');
91
93
 
92
- const { entries } = await admin.api.audit.list({ actor: RUNNER, detail: '1' });
93
- const exchanged = entries.find((entry) => entry.action === 'token.exchange');
94
- const read = entries.find((entry) => entry.author === 'vault' && entry.action === 'secret.read' && entry.key === 'API_KEY');
94
+ // The signer moves what the vault wrote into the log within its minute.
95
+ let entries: AuditEntryView[] = [];
96
+ const exchangedIn = () => entries.find((entry) => entry.action === 'token.exchange');
97
+ const readIn = () => entries.find((entry) => entry.author === 'vault' && entry.action === 'secret.read' && entry.key === 'API_KEY');
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()];
95
103
  expect(exchanged !== undefined && read !== undefined, 'the exchange or the read is not in the log', entries.map((entry) => entry.action));
96
- const credentialId = exchanged.metadata.credentialId;
97
- expect(typeof credentialId === 'string', 'the exchange did not log its credential', exchanged.metadata);
98
- 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);
99
105
  expect(
100
106
  read.run?.exchangeSeq === exchanged.seq && read.run.claims.run_id === GITHUB_RUN.run_id && read.run.claims.repository === GITHUB_RUN.repository,
101
107
  'the read does not lead to its run',
@@ -132,7 +138,7 @@ export async function runsRefused(deployment: Deployment, admin: Person): Promis
132
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'],
133
139
  ['from another repository', await mint(deployment, { repository_id: '1', repository: 'acme/fork' }), 'no_match'],
134
140
  ] as const;
135
- const before = (await admin.api.audit.list({ actor: RUNNER, detail: '1' })).entries.filter((entry) => entry.action === 'token.exchange').length;
141
+ const from = Date.now();
136
142
  for (const [what, token, reason] of cases) {
137
143
  const answer = await exchange(deployment, token);
138
144
  expect(answer.status === 401 && answer.reason === reason, `a token ${what} was not refused as ${reason}`, shown(answer));
@@ -140,8 +146,16 @@ export async function runsRefused(deployment: Deployment, admin: Person): Promis
140
146
  }
141
147
  const stranger = await exchange(deployment, await mint(deployment), 'token:conformance-nobody');
142
148
  expect(stranger.status === 401 && stranger.reason === 'no_match', 'a token was taken for a service no binding names', shown(stranger));
143
- const after = (await admin.api.audit.list({ actor: RUNNER, detail: '1' })).entries.filter((entry) => entry.action === 'token.exchange').length;
144
- 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`);
145
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`;
146
160
  }
147
161
 
@@ -193,7 +207,9 @@ export async function keysUploaded(deployment: Deployment, admin: Person, canari
193
207
  const { keys } = (await (await fetch(deployment.idp.workloads.jwksUrl)).json()) as { keys: Record<string, unknown>[] };
194
208
  const claims = { sub: POD_ACCOUNT.sub, 'kubernetes.io.serviceaccount.uid': POD_ACCOUNT.uid };
195
209
  const made = await admin.api.bindings.create(POD, { profile: 'custom', issuer: CLUSTER, claims, jwks: { keys }, label: 'conformance pod' });
196
- 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 });
197
213
  const now = Math.floor(Date.now() / 1000);
198
214
  const pod = (alg: 'RS256' | 'ES256', uid = POD_ACCOUNT.uid, times: Record<string, number> = {}) =>
199
215
  mint(deployment, { iss: CLUSTER, sub: POD_ACCOUNT.sub, 'kubernetes.io': { namespace: 'ci', serviceaccount: { name: 'deploy', uid } }, ...times }, { alg });
@@ -204,8 +220,9 @@ export async function keysUploaded(deployment: Deployment, admin: Person, canari
204
220
  expect(values.API_KEY === canaries[`${DEV}/API_KEY`], 'the credential did not read the value as the service');
205
221
  const other = await exchange(deployment, await pod('RS256', 'another-uid'), POD);
206
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").
207
224
  const long = await exchange(deployment, await pod('RS256', POD_ACCOUNT.uid, { iat: now, nbf: now, exp: now + 3601 }), POD);
208
- 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));
209
226
 
210
227
  await admin.api.bindings.replaceKeys(POD, { issuer: CLUSTER, jwks: { keys: keys.filter((key) => key.alg === 'ES256') } });
211
228
  const dropped = await exchange(deployment, await pod('RS256'), POD);
@@ -215,17 +232,21 @@ export async function keysUploaded(deployment: Deployment, admin: Person, canari
215
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`;
216
233
  }
217
234
 
218
- /** 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
+ */
219
240
  export async function runUnbound(deployment: Deployment, admin: Person, bindingId: string, credential: string): Promise<string> {
220
241
  const me = (token: string) => fetch(`${deployment.origin}/api/me`, { headers: { authorization: `Bearer ${token}` } }).then((response) => response.status);
221
242
  expect((await me(credential)) === 200, 'the credential did not work before its binding was removed');
222
243
  await admin.api.bindings.remove(RUNNER, bindingId);
223
- 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);
224
245
  const next = await exchange(deployment, await mint(deployment));
225
246
  expect(next.status === 401 && next.reason === 'no_match', 'a run was let in once its binding was removed', shown(next));
226
247
  const { bindings } = await admin.api.bindings.list(RUNNER);
227
248
  expect(bindings.length === 0, 'the removed binding is still listed', bindings);
228
- 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';
229
250
  }
230
251
 
231
252
  /**
package/src/database.ts CHANGED
@@ -1,43 +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
-
6
- import pg from 'pg';
7
- import { postgresConnection } from '@coffre/db/connect';
2
+ // password: what the checks use to go around coffre, to see what it
3
+ // wrote, and to break what it must notice.
4
+ import { postgresSession } from '@coffre/db/connect';
8
5
 
9
6
  export type Sql = {
10
- readonly engine: 'postgres' | 'sqlite';
11
- /** 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. */
12
10
  query<Row = Record<string, unknown>>(statement: string, params?: unknown[]): Promise<Row[]>;
13
11
  /** Any number of statements, no parameters. */
14
12
  exec(statements: string): Promise<void>;
15
13
  close(): Promise<void>;
16
14
  };
17
15
 
18
- export async function postgres(url: string): Promise<Sql> {
19
- const client = new pg.Client(postgresConnection(url));
20
- await client.connect();
16
+ export async function postgres(url: string, schema = 'public'): Promise<Sql> {
17
+ // One session, as a check's transaction needs: lost, its statements fail rather than run on a new connection, unheld.
18
+ const client = postgresSession(url);
19
+ // Connected now, as the harness expects a database it can reach.
20
+ await client.unsafe('SELECT 1');
21
21
  return {
22
- engine: 'postgres',
23
- query: async <Row>(statement: string, params: unknown[] = []) => (await client.query(statement, params)).rows as Row[],
24
- exec: async (statements) => void (await client.query(statements)),
22
+ schema,
23
+ query: async <Row>(statement: string, params: unknown[] = []) => [...await client.unsafe(statement, params as never[])] as Row[],
24
+ exec: async (statements) => void (await client.unsafe(statements)),
25
25
  close: () => client.end(),
26
26
  };
27
27
  }
28
28
 
29
- /** A SQLite file, perhaps open in another process: it waits out their locks. */
30
- export function sqlite(file: string): Sql {
31
- const db = new DatabaseSync(file, { timeout: 5000 });
32
- return {
33
- engine: 'sqlite',
34
- query: async <Row>(statement: string, params: unknown[] = []) =>
35
- db.prepare(statement).all(...(params as never[])) as Row[],
36
- exec: async (statements) => db.exec(statements),
37
- close: async () => db.close(),
38
- };
39
- }
40
-
41
29
  export async function using<T>(open: Sql | Promise<Sql>, use: (sql: Sql) => Promise<T>): Promise<T> {
42
30
  const sql = await open;
43
31
  try {