@wtfalch/keys 0.12.1 → 0.13.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.
package/README.md CHANGED
@@ -415,29 +415,6 @@ export const DELETE = platform;
415
415
  have been made, so revoke all of the organisation's keys before retrying)
416
416
  - 503 `unavailable` (no platform token configured, or under 32 characters)
417
417
 
418
- ## Adopting `./testing` (deprecated)
419
-
420
- **Deprecated.** `@wtfalch/keys/testing` still works unchanged in 0.x and is
421
- removed in **1.0.0**. Move your tests off it before then.
422
-
423
- `@wtfalch/keys/testing` (added in **0.6.0**) is an in-process Worker stub for
424
- a host's own tests, built on the package's own signing and AAD code
425
- (`encodeSigned`/`canonicalJson`/`pickSignable` from `./issued`, `encodeAad`
426
- from `./held`) rather than a host-side reimplementation of them — the
427
- problem issue #83 found: every host's `tests/keys-worker-stub.ts` had
428
- rebuilt these "checked by hand against `dist/issued/index.d.ts`".
429
-
430
- `createKeysWorkerStub<TGrant>({ now? })` returns a `WorkerClient<TGrant>`
431
- implementing the full contract (`wrap`/`unwrap`/`rewrap`/`signRow`/`resign`/
432
- `recordEviction`), plus `verifyKeys`/`verifyKeysEnv` for
433
- `createCredentialIssuer`'s `verifyKeys` option, `callCounts` per method, and
434
- `failAs(method, code, retryAfterMs?)` / `clearFailure()` to force a refusal.
435
- Every call requires `TEST_CREDENTIAL` as the bearer. `canonicalJson`,
436
- `encodeSigned` and `pickSignable` are re-exported from this entry too, for a
437
- host's own fixture code that needs to build signable bytes directly — never
438
- from `./issued` or the public root, since a host's runtime code has no
439
- reason to construct signed bytes itself.
440
-
441
418
  ## Build inputs
442
419
 
443
420
  See [build-time delivery](https://github.com/wtfalch/keys/blob/main/packages/keys/BUILD.md) for delegated build credentials, the host
@@ -4,6 +4,7 @@ import { ID_PATTERN, WORKER_ERROR_CODES, } from '../worker-contract.js';
4
4
  import { encodeAad } from './aad.js';
5
5
  import { keysHeldEntries, keysHeldVersions } from './schema.js';
6
6
  import { shredExpired } from './shred.js';
7
+ import { inTenant } from './tenant.js';
7
8
  export { encodeAad } from './aad.js';
8
9
  export { WORKER_ERROR_CODES };
9
10
  export { shredClocks, shredExpired } from './shred.js';
@@ -177,11 +178,11 @@ export function createHeldKeys(options) {
177
178
  * that would change the answer.
178
179
  */
179
180
  async function existingEntry(entry) {
180
- const [row] = await db
181
+ const [row] = await inTenant(db, entry.tenantId, (tx) => tx
181
182
  .select({ kind: keysHeldEntries.kind })
182
183
  .from(keysHeldEntries)
183
184
  .where(and(eq(keysHeldEntries.tenantId, entry.tenantId), eq(keysHeldEntries.entryId, entry.entryId)))
184
- .limit(1);
185
+ .limit(1));
185
186
  if (!row)
186
187
  return undefined;
187
188
  return { kind: row.kind ?? null };
@@ -226,7 +227,7 @@ export function createHeldKeys(options) {
226
227
  // hold up a concurrent revokeEntry or another put on the same entry.
227
228
  // Losing a version number to a failed wrap is harmless; holding a
228
229
  // Postgres lock open across a network call to the Worker is not.
229
- const version = await db.transaction(async (tx) => {
230
+ const version = await inTenant(db, entry.tenantId, async (tx) => {
230
231
  await tx
231
232
  .insert(keysHeldEntries)
232
233
  .values({
@@ -287,7 +288,7 @@ export function createHeldKeys(options) {
287
288
  });
288
289
  const auditTx = options.auditInTransaction;
289
290
  if (auditTx) {
290
- await db.transaction(async (tx) => {
291
+ await inTenant(db, entry.tenantId, async (tx) => {
291
292
  await publish(tx);
292
293
  await auditTx(tx, {
293
294
  name: 'held.put',
@@ -299,7 +300,9 @@ export function createHeldKeys(options) {
299
300
  });
300
301
  }
301
302
  else {
302
- await publish(db);
303
+ await inTenant(db, entry.tenantId, async (tx) => {
304
+ await publish(tx);
305
+ });
303
306
  }
304
307
  }
305
308
  catch (err) {
@@ -393,18 +396,18 @@ export function createHeldKeys(options) {
393
396
  const value = gcmOpen(cached.dataKey, cached.iv, cached.ciphertext, encodeAad(binding));
394
397
  return use(value);
395
398
  }
396
- const [entryRow] = await db
399
+ const [entryRow] = await inTenant(db, binding.tenantId, (tx) => tx
397
400
  .select({ revokedAt: keysHeldEntries.revokedAt, kind: keysHeldEntries.kind })
398
401
  .from(keysHeldEntries)
399
402
  .where(and(eq(keysHeldEntries.tenantId, binding.tenantId), eq(keysHeldEntries.entryId, binding.entryId)))
400
- .limit(1);
403
+ .limit(1));
401
404
  if (!entryRow)
402
405
  throw new HeldKeysError('not_found', `there is no entry ${binding.entryId}`);
403
406
  if (entryRow.revokedAt)
404
407
  throw new HeldKeysError('revoked', `entry ${binding.entryId} is revoked`);
405
408
  const kind = entryRow.kind ?? null;
406
409
  await requireKindPermission(kind, binding);
407
- const [versionRow] = await db
410
+ const [versionRow] = await inTenant(db, binding.tenantId, (tx) => tx
408
411
  .select({
409
412
  kekId: keysHeldVersions.kekId,
410
413
  wrappedKey: keysHeldVersions.wrappedKey,
@@ -413,7 +416,7 @@ export function createHeldKeys(options) {
413
416
  })
414
417
  .from(keysHeldVersions)
415
418
  .where(and(eq(keysHeldVersions.tenantId, binding.tenantId), eq(keysHeldVersions.entryId, binding.entryId), eq(keysHeldVersions.version, binding.version)))
416
- .limit(1);
419
+ .limit(1));
417
420
  if (!versionRow)
418
421
  throw new HeldKeysError('not_found', `there is no version ${binding.version}`);
419
422
  return openSelected(binding, versionRow, openingEpoch, use, kind);
@@ -426,10 +429,10 @@ export function createHeldKeys(options) {
426
429
  // One statement chooses both the entry state and the highest version row
427
430
  // visible in its snapshot. In particular, current_version is deliberately
428
431
  // absent: put reserves it before the Worker call and may never publish the
429
- // corresponding version row. When `db` is already a transaction handle,
430
- // this statement simply participates in that transaction; no nested
431
- // transaction, commit, or automatic retry is introduced here.
432
- const [selected] = await db
432
+ // corresponding version row. It runs in its own short
433
+ // transaction (a savepoint when `db` is already a transaction handle),
434
+ // which sets the tenant; no automatic retry is introduced here.
435
+ const [selected] = await inTenant(db, entry.tenantId, (tx) => tx
433
436
  .select({
434
437
  revokedAt: keysHeldEntries.revokedAt,
435
438
  kind: keysHeldEntries.kind,
@@ -443,7 +446,7 @@ export function createHeldKeys(options) {
443
446
  .leftJoin(keysHeldVersions, and(eq(keysHeldVersions.tenantId, keysHeldEntries.tenantId), eq(keysHeldVersions.entryId, keysHeldEntries.entryId)))
444
447
  .where(and(eq(keysHeldEntries.tenantId, entry.tenantId), eq(keysHeldEntries.entryId, entry.entryId)))
445
448
  .orderBy(desc(keysHeldVersions.version))
446
- .limit(1);
449
+ .limit(1));
447
450
  if (!selected)
448
451
  throw new HeldKeysError('not_found', `there is no entry ${entry.entryId}`);
449
452
  if (selected.revokedAt)
@@ -556,10 +559,7 @@ export function createHeldKeys(options) {
556
559
  });
557
560
  }
558
561
  };
559
- if (options.auditInTransaction)
560
- await db.transaction(revoke);
561
- else
562
- await revoke(db);
562
+ await inTenant(db, entry.tenantId, revoke);
563
563
  forgetEntry(entry);
564
564
  }
565
565
  async function finishMigrationCredential(entry) {
@@ -609,10 +609,10 @@ export function createHeldKeys(options) {
609
609
  // rather than re-dating it, same reasoning as revokeEntry above. A new
610
610
  // entry put() after this call is not retroactively covered; that
611
611
  // matches revokeEntry's own entry-scoped (not tenant-scoped) reach.
612
- await db
612
+ await inTenant(db, tenantId, (tx) => tx
613
613
  .update(keysHeldEntries)
614
614
  .set({ tenantArchivedAt: sql `now()` })
615
- .where(and(eq(keysHeldEntries.tenantId, tenantId), sql `${keysHeldEntries.tenantArchivedAt} is null`));
615
+ .where(and(eq(keysHeldEntries.tenantId, tenantId), sql `${keysHeldEntries.tenantArchivedAt} is null`)));
616
616
  epoch++;
617
617
  const prefix = `${tenantId} `;
618
618
  for (const [key, hit] of cache) {
@@ -3,7 +3,7 @@
3
3
  * ciphertext-with-tag`, WebCrypto's tag appended to the ciphertext itself.
4
4
  *
5
5
  * The one module both the unwrap Worker (`packages/worker/src/crypto.ts`)
6
- * and the in-process test stub (`../testing/worker-stub.ts`) import for this
6
+ * and the in-process test stub (`../test/worker-stub.ts`) import for this
7
7
  * layout, rather than each carrying its own copy. Before #86 the stub
8
8
  * reimplemented it by hand: a real risk, since a host's tests would keep
9
9
  * passing against a stub whose layout had silently drifted from what the
package/dist/held/seal.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * ciphertext-with-tag`, WebCrypto's tag appended to the ciphertext itself.
4
4
  *
5
5
  * The one module both the unwrap Worker (`packages/worker/src/crypto.ts`)
6
- * and the in-process test stub (`../testing/worker-stub.ts`) import for this
6
+ * and the in-process test stub (`../test/worker-stub.ts`) import for this
7
7
  * layout, rather than each carrying its own copy. Before #86 the stub
8
8
  * reimplemented it by hand: a real risk, since a host's tests would keep
9
9
  * passing against a stub whose layout had silently drifted from what the
@@ -0,0 +1,2 @@
1
+ import type { HeldKeysDb } from './index.js';
2
+ export declare function inTenant<T>(db: HeldKeysDb, tenantId: string, work: (tx: HeldKeysDb) => Promise<T>): Promise<T>;
@@ -0,0 +1,46 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { ID_PATTERN } from '../worker-contract.js';
3
+ /**
4
+ * Runs `work` in a short transaction whose first statement sets the
5
+ * `app.tenant_id` setting to `tenantId` (transaction-local), the setting the
6
+ * opt-in `tenant-rows` policies compare `tenant_id` with. This file is the one
7
+ * place in `src/` that names the setting.
8
+ *
9
+ * On a pool handle this opens a transaction; on a transaction handle, a
10
+ * savepoint. The setting found before is put back when `work` returns. When
11
+ * `work` throws, the transaction (or savepoint) rolls back and the setting
12
+ * reverts with it. `tenantId` is checked against `ID_PATTERN` before any SQL.
13
+ * Never call the Worker inside `work`.
14
+ */
15
+ /**
16
+ * A transaction handle has one connection, and its savepoints are one stack:
17
+ * two `inTenant` calls running at once on it would interleave their savepoints
18
+ * and settings. Calls on the same transaction handle therefore run one after
19
+ * the other. A pool handle needs no queue: each call gets its own connection.
20
+ */
21
+ const queues = new WeakMap();
22
+ function isTransaction(db) {
23
+ return typeof db.rollback === 'function';
24
+ }
25
+ export async function inTenant(db, tenantId, work) {
26
+ if (typeof tenantId !== 'string' || !ID_PATTERN.test(tenantId)) {
27
+ throw new RangeError(`inTenant: tenantId does not match ID_PATTERN: ${String(tenantId)}`);
28
+ }
29
+ if (!isTransaction(db))
30
+ return run(db, tenantId, work);
31
+ const turn = (queues.get(db) ?? Promise.resolve()).then(() => run(db, tenantId, work));
32
+ queues.set(db, turn.catch(() => undefined));
33
+ return turn;
34
+ }
35
+ function run(db, tenantId, work) {
36
+ return db.transaction(async (tx) => {
37
+ // One statement: the CTE reads the setting that was in force, set_config replaces it.
38
+ const found = await tx.execute(sql `with prev as materialized (select current_setting('app.tenant_id', true) as v)
39
+ select v as prev, set_config('app.tenant_id', ${tenantId}, true) as now from prev`);
40
+ const rows = (Array.isArray(found) ? found : found.rows);
41
+ const previous = rows[0]?.prev ?? '';
42
+ const result = await work(tx);
43
+ await tx.execute(sql `select set_config('app.tenant_id', ${previous}, true)`);
44
+ return result;
45
+ });
46
+ }
@@ -1,3 +1,4 @@
1
+ import { inTenant } from '../held/tenant.js';
1
2
  import { keysHostEvents } from './schema.js';
2
3
  /**
3
4
  * Inserts one `keys_host_events` row: this host's own append-only record of
@@ -10,7 +11,7 @@ export async function recordEvent(db, event) {
10
11
  const at = new Date(event.at);
11
12
  switch (event.name) {
12
13
  case 'key.used':
13
- await db.insert(keysHostEvents).values({
14
+ await inTenant(db, event.tenantId, (tx) => tx.insert(keysHostEvents).values({
14
15
  kind: event.name,
15
16
  requestId: event.requestId,
16
17
  credentialId: null,
@@ -18,11 +19,11 @@ export async function recordEvent(db, event) {
18
19
  entryId: event.entryId,
19
20
  version: event.version,
20
21
  at,
21
- });
22
+ }));
22
23
  return;
23
24
  case 'held.put':
24
25
  case 'held.revoked':
25
- await db.insert(keysHostEvents).values({
26
+ await inTenant(db, event.tenantId, (tx) => tx.insert(keysHostEvents).values({
26
27
  kind: event.name,
27
28
  requestId: null,
28
29
  credentialId: null,
@@ -30,7 +31,7 @@ export async function recordEvent(db, event) {
30
31
  entryId: event.entryId,
31
32
  version: event.name === 'held.put' ? event.version : null,
32
33
  at,
33
- });
34
+ }));
34
35
  return;
35
36
  case 'held.shredded':
36
37
  await db.insert(keysHostEvents).values({
@@ -0,0 +1,63 @@
1
+ -- Forced row-level security for the tables that hold a tenant's rows:
2
+ -- keys_held_entries, keys_held_versions and keys_host_events. A connection
3
+ -- sees and writes only the rows whose tenant_id equals the text in the
4
+ -- `app.tenant_id` setting (set per transaction with set_config(..., true)).
5
+ --
6
+ -- OPT-IN. This directory is not part of the held or host chains and the
7
+ -- keys-migrations binary does not copy it. A host that does not set
8
+ -- `app.tenant_id` would read nothing after applying it, so a host applies it
9
+ -- only when its code sets the setting. A host that does not apply it is
10
+ -- unchanged.
11
+ --
12
+ -- `tenant_id` here is the keys namespace text, not an authz tenant uuid. The
13
+ -- company's Archon credential is stored under tenant_id = 'company', and the
14
+ -- id is part of the sealed value's AAD (src/held/aad.ts:23), so it cannot be
15
+ -- renamed. The comparison is text to text.
16
+ --
17
+ -- A null tenant_id on keys_host_events is a global platform row: the
18
+ -- `held.shredded` row (src/host/events.ts:70) and the `credential.*` rows
19
+ -- (src/host/events.ts:81) carry no tenant. Those rows are visible to and
20
+ -- insertable by every setting. Rows with a tenant follow the setting.
21
+ --
22
+ -- keys_issued_credentials and keys_issued_rate_limit_windows get NO policy.
23
+ -- The credentials table has no tenant column (organisation_id may be null)
24
+ -- and is looked up by key_prefix or secret_hash before any tenant is known
25
+ -- (src/issued/verify.ts); the rate-limit table is keyed by credential id.
26
+ -- Both are on the host's global list. What guards them instead: the secret is
27
+ -- stored as a hash and rows are found only by hash or prefix.
28
+ --
29
+ -- The owner is a superuser and is not bound by row-level security, even with
30
+ -- FORCE. That is what lets the SECURITY DEFINER functions (keys_shred_expired,
31
+ -- the retire trigger, the publish guard) run as the owner and ignore these
32
+ -- policies. A non-superuser owner WOULD be bound by FORCE, and those functions
33
+ -- would then act on no rows, silently. Keep the owner a superuser, or do not
34
+ -- apply this directory.
35
+ --
36
+ -- Every statement is idempotent: each policy is dropped before it is created.
37
+
38
+ alter table keys_held_entries enable row level security;
39
+ alter table keys_held_entries force row level security;
40
+ drop policy if exists keys_held_entries_tenant on keys_held_entries;
41
+ create policy keys_held_entries_tenant on keys_held_entries
42
+ for all
43
+ using (tenant_id = nullif(current_setting('app.tenant_id', true), ''))
44
+ with check (tenant_id = nullif(current_setting('app.tenant_id', true), ''));
45
+
46
+ alter table keys_held_versions enable row level security;
47
+ alter table keys_held_versions force row level security;
48
+ drop policy if exists keys_held_versions_tenant on keys_held_versions;
49
+ create policy keys_held_versions_tenant on keys_held_versions
50
+ for all
51
+ using (tenant_id = nullif(current_setting('app.tenant_id', true), ''))
52
+ with check (tenant_id = nullif(current_setting('app.tenant_id', true), ''));
53
+
54
+ alter table keys_host_events enable row level security;
55
+ alter table keys_host_events force row level security;
56
+ drop policy if exists keys_host_events_select on keys_host_events;
57
+ create policy keys_host_events_select on keys_host_events
58
+ for select
59
+ using (tenant_id is null or tenant_id = nullif(current_setting('app.tenant_id', true), ''));
60
+ drop policy if exists keys_host_events_insert on keys_host_events;
61
+ create policy keys_host_events_insert on keys_host_events
62
+ for insert
63
+ with check (tenant_id is null or tenant_id = nullif(current_setting('app.tenant_id', true), ''));
@@ -17,3 +17,12 @@
17
17
  export declare const issuedMigrationsDir: string;
18
18
  export declare const heldMigrationsDir: string;
19
19
  export declare const hostMigrationsDir: string;
20
+ /**
21
+ * OPT-IN, not one of the three chains: forced row-level security on the
22
+ * tables that hold a tenant's rows. Apply it only in a host that sets
23
+ * `app.tenant_id`; otherwise every read of those tables returns no rows.
24
+ * Apply it after the held and host chains:
25
+ *
26
+ * { name: 'keys-tenant-rows', dir: tenantRowsMigrationsDir }
27
+ */
28
+ export declare const tenantRowsMigrationsDir: string;
@@ -18,3 +18,12 @@ import { fileURLToPath } from 'node:url';
18
18
  export const issuedMigrationsDir = fileURLToPath(new URL('./migrations/issued/', import.meta.url));
19
19
  export const heldMigrationsDir = fileURLToPath(new URL('./migrations/held/', import.meta.url));
20
20
  export const hostMigrationsDir = fileURLToPath(new URL('./migrations/host/', import.meta.url));
21
+ /**
22
+ * OPT-IN, not one of the three chains: forced row-level security on the
23
+ * tables that hold a tenant's rows. Apply it only in a host that sets
24
+ * `app.tenant_id`; otherwise every read of those tables returns no rows.
25
+ * Apply it after the held and host chains:
26
+ *
27
+ * { name: 'keys-tenant-rows', dir: tenantRowsMigrationsDir }
28
+ */
29
+ export const tenantRowsMigrationsDir = fileURLToPath(new URL('./migrations/tenant-rows/', import.meta.url));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wtfalch/keys",
3
- "version": "0.12.1",
3
+ "version": "0.13.0",
4
4
  "description": "The estate's own bearer keys, issued to callers and held on their behalf: two entries, issued and held, nothing stored in common.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -50,10 +50,6 @@
50
50
  "types": "./dist/host/index.d.ts",
51
51
  "default": "./dist/host/index.js"
52
52
  },
53
- "./testing": {
54
- "types": "./dist/testing/index.d.ts",
55
- "default": "./dist/testing/index.js"
56
- },
57
53
  "./service": {
58
54
  "types": "./dist/service/index.d.ts",
59
55
  "default": "./dist/service/index.js"
@@ -67,7 +63,7 @@
67
63
  "node": ">=22.0.0"
68
64
  },
69
65
  "scripts": {
70
- "build": "rm -rf dist && tsc -p tsconfig.build.json && mkdir -p dist/migrations && cp -R src/migrations/issued src/migrations/held src/migrations/host dist/migrations/",
66
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && mkdir -p dist/migrations && cp -R src/migrations/issued src/migrations/held src/migrations/host src/migrations/tenant-rows dist/migrations/",
71
67
  "prepack": "pnpm build",
72
68
  "typecheck": "tsc --noEmit",
73
69
  "test": "vitest run"
@@ -1,12 +0,0 @@
1
- /**
2
- * `./testing`: an in-process Worker stub built on the package's own signing
3
- * and AAD code, for a host's tests that need a `WorkerClient` without a
4
- * live Worker (issue #83). `canonicalJson`, `encodeSigned` and
5
- * `pickSignable` are re-exported here -- not from `./issued` or the
6
- * public root -- because they exist for building test fixtures, not for a
7
- * host's runtime code, which never needs to construct signed bytes itself.
8
- *
9
- * @deprecated `@wtfalch/keys/testing` is removed in 1.0.0. It still works
10
- * unchanged in 0.x.
11
- */
12
- export { createKeysWorkerStub, TEST_CREDENTIAL, canonicalJson, encodeSigned, pickSignable, type CreateKeysWorkerStubOptions, type KeysWorkerStub, } from './worker-stub.js';
@@ -1,12 +0,0 @@
1
- /**
2
- * `./testing`: an in-process Worker stub built on the package's own signing
3
- * and AAD code, for a host's tests that need a `WorkerClient` without a
4
- * live Worker (issue #83). `canonicalJson`, `encodeSigned` and
5
- * `pickSignable` are re-exported here -- not from `./issued` or the
6
- * public root -- because they exist for building test fixtures, not for a
7
- * host's runtime code, which never needs to construct signed bytes itself.
8
- *
9
- * @deprecated `@wtfalch/keys/testing` is removed in 1.0.0. It still works
10
- * unchanged in 0.x.
11
- */
12
- export { createKeysWorkerStub, TEST_CREDENTIAL, canonicalJson, encodeSigned, pickSignable, } from './worker-stub.js';
@@ -1,55 +0,0 @@
1
- import { canonicalJson, encodeSigned, pickSignable } from '../issued/encoding.js';
2
- import type { VerifyKeys, WorkerClient, WorkerErrorCode } from '../worker-contract.js';
3
- /**
4
- * An in-process stand-in for the unwrap Worker (`packages/worker`), for
5
- * every host test that needs a `WorkerClient<TGrant>` without a live
6
- * Worker. Implements the full contract -- `wrap`/`unwrap`/`rewrap` for
7
- * `./held`, `signRow`/`resign`/`recordEviction` for `./issued` -- with the
8
- * package's own real signing, AAD and sealing code, not a reimplementation:
9
- * it imports `encodeSigned`/`canonicalJson`/`pickSignable` from `../issued/
10
- * encoding.js`, `encodeAad` from `../held/aad.js`, and `aesGcmSeal`/
11
- * `aesGcmOpen` from `../held/seal.js` -- the same module
12
- * `packages/worker/src/crypto.ts` imports for its own AES-256-GCM layout
13
- * (#86: before this, the two copies could drift silently) -- rather than
14
- * duplicating any of them, so a signature or a sealed key this stub
15
- * produces is verified the same way a real Worker's would be -- proven by
16
- * `worker-stub.test.ts`, which runs `check()` (`../issued`) and `open()`
17
- * (`../held`) against rows this stub signed and sealed, and by
18
- * `../../../worker/src/crypto.test.ts`, which opens a value sealed through
19
- * this same module with the Worker's own re-exported `aesGcmOpen`, and the
20
- * reverse.
21
- *
22
- * This is what every host's own `tests/keys-worker-stub.ts` re-implemented
23
- * by hand (issue #83, "checked by hand against dist/issued/index.d.ts") --
24
- * see the package README's "Adopting ./testing".
25
- *
26
- * Signing uses `node:crypto`'s classic, synchronous `generateKeyPairSync`/
27
- * `sign`/`verify` rather than `webcrypto.subtle`: both produce and check
28
- * the same RFC 8032 Ed25519 signatures -- `worker-stub.test.ts` proves it
29
- * by running `../issued/verify.js`'s own `verifyIssuedRowSignature`
30
- * (which uses `webcrypto.subtle.verify`) against a signature this stub
31
- * produced -- but being synchronous, it lets `verifyKeys`/`verifyKeysEnv`
32
- * be plain properties instead of a promise a caller would have to await
33
- * before building `KEYS_VERIFY_KEYS`.
34
- */
35
- /** Every credential this stub accepts. Anything else is `credential_invalid`, exactly as a real bad bearer token would be. */
36
- export declare const TEST_CREDENTIAL = "stub-test-credential";
37
- type Method = keyof WorkerClient<unknown>;
38
- export interface CreateKeysWorkerStubOptions {
39
- /** Unix milliseconds. Defaults to `Date.now`; a test passes a fake clock to check `minter_expired`. */
40
- readonly now?: () => number;
41
- }
42
- export interface KeysWorkerStub<TGrant> extends WorkerClient<TGrant> {
43
- /** This stub's one Ed25519 public key, for `createCredentialIssuer`'s `verifyKeys` option. */
44
- readonly verifyKeys: VerifyKeys;
45
- /** The same key, base64url, in the comma-separated form `KEYS_VERIFY_KEYS` takes. */
46
- readonly verifyKeysEnv: string;
47
- /** Calls received so far, per method -- for asserting a code path called the Worker exactly once, or not at all. */
48
- readonly callCounts: Record<Method, number>;
49
- /** Every call to `method` (or `'all'`) fails with `code` until `clearFailure()`. */
50
- failAs(method: Method | 'all', code: WorkerErrorCode, retryAfterMs?: number): void;
51
- clearFailure(): void;
52
- }
53
- /** `canonicalJson`, `encodeSigned` and `pickSignable` are the package's own -- re-exported by `./testing/index.js`, not reimplemented here. */
54
- export declare function createKeysWorkerStub<TGrant = unknown>(options?: CreateKeysWorkerStubOptions): KeysWorkerStub<TGrant>;
55
- export { canonicalJson, encodeSigned, pickSignable };
@@ -1,180 +0,0 @@
1
- import { generateKeyPairSync, sign as signWithKey, verify as verifyWithKey, webcrypto, } from 'node:crypto';
2
- import { encodeAad } from '../held/aad.js';
3
- import { aesGcmOpen, aesGcmSeal } from '../held/seal.js';
4
- import { canonicalJson, encodeSigned, pickSignable } from '../issued/encoding.js';
5
- /**
6
- * An in-process stand-in for the unwrap Worker (`packages/worker`), for
7
- * every host test that needs a `WorkerClient<TGrant>` without a live
8
- * Worker. Implements the full contract -- `wrap`/`unwrap`/`rewrap` for
9
- * `./held`, `signRow`/`resign`/`recordEviction` for `./issued` -- with the
10
- * package's own real signing, AAD and sealing code, not a reimplementation:
11
- * it imports `encodeSigned`/`canonicalJson`/`pickSignable` from `../issued/
12
- * encoding.js`, `encodeAad` from `../held/aad.js`, and `aesGcmSeal`/
13
- * `aesGcmOpen` from `../held/seal.js` -- the same module
14
- * `packages/worker/src/crypto.ts` imports for its own AES-256-GCM layout
15
- * (#86: before this, the two copies could drift silently) -- rather than
16
- * duplicating any of them, so a signature or a sealed key this stub
17
- * produces is verified the same way a real Worker's would be -- proven by
18
- * `worker-stub.test.ts`, which runs `check()` (`../issued`) and `open()`
19
- * (`../held`) against rows this stub signed and sealed, and by
20
- * `../../../worker/src/crypto.test.ts`, which opens a value sealed through
21
- * this same module with the Worker's own re-exported `aesGcmOpen`, and the
22
- * reverse.
23
- *
24
- * This is what every host's own `tests/keys-worker-stub.ts` re-implemented
25
- * by hand (issue #83, "checked by hand against dist/issued/index.d.ts") --
26
- * see the package README's "Adopting ./testing".
27
- *
28
- * Signing uses `node:crypto`'s classic, synchronous `generateKeyPairSync`/
29
- * `sign`/`verify` rather than `webcrypto.subtle`: both produce and check
30
- * the same RFC 8032 Ed25519 signatures -- `worker-stub.test.ts` proves it
31
- * by running `../issued/verify.js`'s own `verifyIssuedRowSignature`
32
- * (which uses `webcrypto.subtle.verify`) against a signature this stub
33
- * produced -- but being synchronous, it lets `verifyKeys`/`verifyKeysEnv`
34
- * be plain properties instead of a promise a caller would have to await
35
- * before building `KEYS_VERIFY_KEYS`.
36
- */
37
- // ---------------------------------------------------------------------------
38
- // The stub
39
- // ---------------------------------------------------------------------------
40
- /** Every credential this stub accepts. Anything else is `credential_invalid`, exactly as a real bad bearer token would be. */
41
- export const TEST_CREDENTIAL = 'stub-test-credential';
42
- const KEK_ID = 'kek-test';
43
- const SIGN_GENERATION_ID = 'sign-test';
44
- function failure(code, retryAfterMs) {
45
- return {
46
- ok: false,
47
- error: retryAfterMs !== undefined ? { code, retryAfterMs } : { code },
48
- };
49
- }
50
- function publicKeyRawOf(key) {
51
- const jwk = key.export({ format: 'jwk' });
52
- if (!jwk.x) {
53
- throw new Error('createKeysWorkerStub: Ed25519 public key export had no JWK x coordinate');
54
- }
55
- return new Uint8Array(Buffer.from(jwk.x, 'base64url'));
56
- }
57
- /** `canonicalJson`, `encodeSigned` and `pickSignable` are the package's own -- re-exported by `./testing/index.js`, not reimplemented here. */
58
- export function createKeysWorkerStub(options = {}) {
59
- const now = options.now ?? (() => Date.now());
60
- const { publicKey, privateKey } = generateKeyPairSync('ed25519');
61
- const publicKeyRaw = publicKeyRawOf(publicKey);
62
- const kek = webcrypto.getRandomValues(new Uint8Array(32));
63
- const callCounts = {
64
- wrap: 0,
65
- unwrap: 0,
66
- rewrap: 0,
67
- signRow: 0,
68
- resign: 0,
69
- recordEviction: 0,
70
- };
71
- let forced = null;
72
- function record(method) {
73
- callCounts[method] += 1;
74
- if (forced && (forced.method === method || forced.method === 'all')) {
75
- return failure(forced.code, forced.retryAfterMs);
76
- }
77
- return null;
78
- }
79
- function signRowBytes(row) {
80
- return new Uint8Array(signWithKey(null, encodeSigned('issued-row', pickSignable(row)), privateKey));
81
- }
82
- function verifyRowSignature(row, signature) {
83
- return verifyWithKey(null, encodeSigned('issued-row', pickSignable(row)), publicKey, signature);
84
- }
85
- const client = {
86
- async wrap(req) {
87
- const forcedFailure = record('wrap');
88
- if (forcedFailure)
89
- return forcedFailure;
90
- if (req.credential !== TEST_CREDENTIAL)
91
- return failure('credential_invalid');
92
- const dataKey = webcrypto.getRandomValues(new Uint8Array(32));
93
- const wrappedKey = await aesGcmSeal(kek, dataKey, encodeAad(req.binding));
94
- return { ok: true, dataKey, wrappedKey, kekId: KEK_ID };
95
- },
96
- async unwrap(req) {
97
- const forcedFailure = record('unwrap');
98
- if (forcedFailure)
99
- return forcedFailure;
100
- if (req.credential !== TEST_CREDENTIAL)
101
- return failure('credential_invalid');
102
- if (req.kekId !== KEK_ID)
103
- return failure('unknown_generation');
104
- const dataKey = await aesGcmOpen(kek, req.wrappedKey, encodeAad(req.binding));
105
- if (!dataKey)
106
- return failure('aad_mismatch');
107
- return { ok: true, dataKey };
108
- },
109
- async rewrap(req) {
110
- const forcedFailure = record('rewrap');
111
- if (forcedFailure)
112
- return forcedFailure;
113
- if (req.credential !== TEST_CREDENTIAL)
114
- return failure('credential_invalid');
115
- if (req.kekIdOld !== KEK_ID || req.kekIdNew !== KEK_ID)
116
- return failure('unknown_generation');
117
- const aad = encodeAad(req.binding);
118
- const dataKey = await aesGcmOpen(kek, req.wrappedKey, aad);
119
- if (!dataKey)
120
- return failure('aad_mismatch');
121
- const wrappedKey = await aesGcmSeal(kek, dataKey, aad);
122
- return { ok: true, wrappedKey };
123
- },
124
- async signRow(req) {
125
- const forcedFailure = record('signRow');
126
- if (forcedFailure)
127
- return forcedFailure;
128
- if (req.credential !== TEST_CREDENTIAL)
129
- return failure('credential_invalid');
130
- const { candidate, minter } = req;
131
- if (minter) {
132
- if (!verifyRowSignature(minter.row, minter.signature)) {
133
- return failure('bad_minter_signature');
134
- }
135
- if (minter.row.expiresAt <= now())
136
- return failure('minter_expired');
137
- }
138
- // Minimal lineage check -- the mint log and resign/recordEviction
139
- // sweeps a real Worker keeps are out of this stub's scope.
140
- const expectedIssuedById = minter ? minter.row.id : null;
141
- if (candidate.issuedById !== expectedIssuedById)
142
- return failure('lineage_mismatch');
143
- return { ok: true, signature: signRowBytes(candidate), generationId: SIGN_GENERATION_ID };
144
- },
145
- async resign(req) {
146
- const forcedFailure = record('resign');
147
- if (forcedFailure)
148
- return forcedFailure;
149
- if (req.credential !== TEST_CREDENTIAL)
150
- return failure('credential_invalid');
151
- if (req.oldGenerationId !== SIGN_GENERATION_ID)
152
- return failure('unknown_generation');
153
- if (!verifyRowSignature(req.row, req.oldSignature))
154
- return failure('bad_old_signature');
155
- return { ok: true, signature: signRowBytes(req.row), generationId: SIGN_GENERATION_ID };
156
- },
157
- async recordEviction(req) {
158
- const forcedFailure = record('recordEviction');
159
- if (forcedFailure)
160
- return forcedFailure;
161
- if (req.credential !== TEST_CREDENTIAL)
162
- return failure('credential_invalid');
163
- return { ok: true, receiptId: `receipt-${req.credentialId}-${req.revokedAt}` };
164
- },
165
- };
166
- return Object.assign(client, {
167
- verifyKeys: [publicKeyRaw],
168
- verifyKeysEnv: Buffer.from(publicKeyRaw).toString('base64url'),
169
- callCounts,
170
- failAs(method, code, retryAfterMs) {
171
- forced = { method, code, retryAfterMs };
172
- },
173
- clearFailure() {
174
- forced = null;
175
- },
176
- });
177
- }
178
- // Re-exported by ./testing/index.js so a host's own fixture code can build
179
- // custom signable bytes without depending on this file's internals.
180
- export { canonicalJson, encodeSigned, pickSignable };