@wtfalch/keys 0.8.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +248 -8
  2. package/dist/held/index.d.ts +116 -6
  3. package/dist/held/index.js +247 -25
  4. package/dist/held/schema.d.ts +17 -0
  5. package/dist/held/schema.js +12 -0
  6. package/dist/held/shred.d.ts +6 -0
  7. package/dist/held/shred.js +6 -0
  8. package/dist/held-edge/index.d.ts +17 -2
  9. package/dist/held-edge/index.js +51 -9
  10. package/dist/host/audit-endpoint.js +2 -8
  11. package/dist/host/company-registrar-keys.d.ts +13 -0
  12. package/dist/host/company-registrar-keys.js +6 -8
  13. package/dist/host/events.d.ts +19 -3
  14. package/dist/host/events.js +55 -20
  15. package/dist/host/index.d.ts +9 -2
  16. package/dist/host/index.js +9 -2
  17. package/dist/host/native-build.d.ts +126 -0
  18. package/dist/host/native-build.js +322 -0
  19. package/dist/host/registrar.d.ts +10 -4
  20. package/dist/host/registrar.js +64 -42
  21. package/dist/host/rotation-sweep.d.ts +56 -0
  22. package/dist/host/rotation-sweep.js +89 -0
  23. package/dist/issued/encoding.d.ts +4 -0
  24. package/dist/issued/encoding.js +22 -0
  25. package/dist/issued/index.d.ts +148 -7
  26. package/dist/issued/index.js +320 -34
  27. package/dist/issued/resign.d.ts +16 -0
  28. package/dist/issued/resign.js +55 -2
  29. package/dist/issued/tables.d.ts +38 -0
  30. package/dist/issued/tables.js +6 -0
  31. package/dist/issued/verify.d.ts +14 -3
  32. package/dist/issued/verify.js +10 -3
  33. package/dist/migrations/held/0004_keys_archived_publish_guard.sql +46 -0
  34. package/dist/migrations/held/0005_keys_held_migration_credential.sql +216 -0
  35. package/dist/migrations/held/0006_keys_held_entries_guard.sql +54 -0
  36. package/dist/migrations/host/0002_keys_host_held_events.sql +29 -0
  37. package/dist/migrations/issued/0007_keys_purpose.sql +68 -0
  38. package/dist/migrations/issued/0008_keys_idempotency_scope.sql +23 -0
  39. package/dist/service/body.d.ts +21 -0
  40. package/dist/service/body.js +128 -0
  41. package/dist/service/errors.d.ts +24 -0
  42. package/dist/service/errors.js +89 -0
  43. package/dist/service/handler.d.ts +35 -0
  44. package/dist/service/handler.js +328 -0
  45. package/dist/service/index.d.ts +7 -0
  46. package/dist/service/index.js +7 -0
  47. package/dist/service/policy.d.ts +130 -0
  48. package/dist/service/policy.js +123 -0
  49. package/dist/service/timeout.d.ts +6 -0
  50. package/dist/service/timeout.js +34 -0
  51. package/dist/testing/index.d.ts +3 -0
  52. package/dist/testing/index.js +3 -0
  53. package/dist/webhooks.d.ts +40 -17
  54. package/dist/webhooks.js +70 -26
  55. package/dist/worker-contract.d.ts +43 -6
  56. package/dist/worker-contract.js +37 -0
  57. package/dist/worker.d.ts +1 -1
  58. package/dist/worker.js +7 -28
  59. package/package.json +21 -3
package/README.md CHANGED
@@ -76,13 +76,13 @@ Why each list is what it is, read from the triggers in the SQL:
76
76
  | --- | --- | --- | --- |
77
77
  | `keys_issued_credentials` | select, insert, update | `noDelete` | Revoke, rotate and usage stamps are updates; `keys_issued_guard` refuses delete and truncate whatever the role holds |
78
78
  | `keys_issued_rate_limit_windows` | select, insert, update, delete | none | An upsert counter; no guard, nothing to protect |
79
- | `keys_held_entries` | select, insert, update, delete | none | Revoke and archive stamp clocks the guard fixes once set. The code never deletes, but nothing in the SQL refuses it either (unchanged from 0.4) |
79
+ | `keys_held_entries` | select, insert, update | `noDelete` | Revoke and archive stamp clocks the guard fixes once set. From `held/0006`, a trigger refuses delete and truncate whatever the role holds, and refuses an update that lowers `current_version`. Before 0006 a row with no version could be deleted and `put()` then recreated it un-revoked |
80
80
  | `keys_held_versions` | select, insert | `appendOnly` | Retire and shred run in `SECURITY DEFINER` code. The guard would allow a rewrap from an `UPDATE`, but a runtime role that can update can write garbage as a rewrap, so rewrap needs an operator handle |
81
81
  | `keys_host_events` | select, insert | `appendOnly` | Every update, delete and truncate is refused by its guard |
82
82
  | `keys_shred_expired()` | execute | `grants` | The only way the runtime role shreds; it takes no target |
83
83
 
84
84
  Call `assertRuntimeRole(db, { appendOnly: ['svc.keys_held_versions',
85
- 'svc.keys_host_events'], noDelete: ['svc.keys_issued_credentials'] })` at boot.
85
+ 'svc.keys_host_events'], noDelete: ['svc.keys_issued_credentials', 'svc.keys_held_entries'] })` at boot.
86
86
 
87
87
  A host that cannot call `runMigrationSources` can copy the files instead:
88
88
  `keys-migrations <dir> issued held host` (name only the chains it uses). It
@@ -119,17 +119,35 @@ Held keys use active cache expiry (60 seconds by default) and retain at most 256
119
119
 
120
120
  Every issued credential carries a built-in `environment`, `'live'` or `'test'` (default `'live'`), passed on `issue()` and reported by `check()` and `lineageOf()`. A credential can only mint a child in its own environment — `issue()` returns `{ ok: false, reason: 'environment_mismatch' }` otherwise. The issued chain's `0002_keys_environment.sql` and `0005_keys_environment_default.sql` apply in the same run: without it, containers still on 0.2.1 or older cannot issue keys between the migration and their redeploy.
121
121
 
122
+ ## Credential purpose
123
+
124
+ Every issued credential has a `purpose`: `'ordinary'` (an app or user key; the default), `'company_root'` or `'platform_master'`. `issue()` takes `purpose` and `organisationId` for trusted server code only; a host never fills them from a customer's request. A child (`minter` set) can only be `'ordinary'`, takes its minter's organisation, and may not name another: `purpose_not_allowed` and `organisation_mismatch` are refused before the Worker signs. `check()`, `lineageOf()` and `CredentialLink` report both fields.
125
+
126
+ - `revokeForCompany(id, { cascade?, organisationId? })` is what company key management calls. It runs under the lifecycle lock and returns `{ ok: true, revoked }`, or `{ ok: false, reason: 'protected_credential' | 'purpose_unknown' }` and changes nothing when the target, or any live row its cascade reaches, is a company root, a platform master or of unknown purpose. With `organisationId`, it also refuses with `protected_credential` when a live row of the cascade belongs to another organisation or to none. A company rolls its root with `rotate()`, which keeps the row, its grants and its descendants. `revoke(id)` stays the trusted path for platform teardown.
127
+ - A row older than 0.10.0 has `purpose: null`: unknown. Nothing guesses it from a name, a grant or a missing minter. `classify(id, { purpose, organisationId? })` is for operator code: it moves `null` to a value once, and a second call answers `already_classified`. Until a row is classified, `revokeForCompany` leaves it alone.
128
+ - Neither column is signed, so every signature stays valid and no Worker deploy or resign is needed. A person who can write the database can change them; `keys_issued_guard()` only makes each settable once. Apply the issued chain's `0007_keys_purpose.sql`; it is safe while the previous version is still running.
129
+
122
130
  ## Issued-key usage tracking
123
131
 
124
- Every successful `check()` stamps `lastUsedAt` and increments `useCount` on the credential's row — read them off `KeysIssuedCredentialRow` directly (an admin UI's own query, not a new `check()` return field). The write is best-effort: it never turns a genuine secret into a refusal, and a revoked, expired, tampered or wrong-secret check never bumps it. It comes from the issued chain's `0003_keys_usage.sql`.
132
+ Every successful `check()` stamps `lastUsedAt` and increments `useCount` on the credential's row — read them off the row, typed by `KeysIssuedCredentialRow` (exported from `./issued`; an admin UI's own query, not a new `check()` return field). The write is best-effort: it never turns a genuine secret into a refusal, and a revoked, expired, tampered or wrong-secret check never bumps it. It comes from the issued chain's `0003_keys_usage.sql`.
125
133
 
126
134
  ## Per-issued-key rate limits
127
135
 
128
- `CreateCredentialIssuerOptions.rateLimiter` (optional) is consulted on every `check()`, keyed by the credential's own `id` — spent on every attempt against a known credential, matched secret or not, so an unlimited number of wrong guesses can't get around it. Refused as `{ ok: false, reason: 'rate_limited', retryAfterMs }`. `createPostgresRateLimiter({ db, limitPerWindow, windowMs? })` is a ready-made fixed-window limiter backed by the host's own Postgres (the issued chain's `0004_keys_rate_limit.sql`); bring your own `RateLimiter` for anything else (Redis, D1, …). Omit it and `check()` behaves exactly as before this existed — this was previously only enforced on the host's own service credential (`packages/worker/src/ratelimit.ts`), never on an individual end-user issued key.
136
+ `CreateCredentialIssuerOptions.rateLimiter` (optional) is consulted on every `check()`, keyed by the credential's own `id` — spent on every attempt against a known credential, matched secret or not, so an unlimited number of wrong guesses can't get around it. A well-formed key that matches no row is charged to one shared `unknown-key` bucket instead (`unknown-key:<organisationId>` when `check()` is given an `organisationId`), so a flood of guesses is limited too; a known credential's traffic never reaches that bucket. Refused as `{ ok: false, reason: 'rate_limited', retryAfterMs }`. `createPostgresRateLimiter({ db, limitPerWindow, windowMs? })` is a ready-made fixed-window limiter backed by the host's own Postgres (the issued chain's `0004_keys_rate_limit.sql`); bring your own `RateLimiter` for anything else (Redis, D1, …). Omit it and `check()` behaves exactly as before this existed — this was previously only enforced on the host's own service credential (`packages/worker/src/ratelimit.ts`), never on an individual end-user issued key.
137
+
138
+ ## Idempotency keys
139
+
140
+ An `idempotencyKey` belongs to the credential that minted it: the unique index is `(coalesce(issued_by_id, ''), idempotency_key)` (`0008_keys_idempotency_scope.sql`). A replay with the same minter compares `grants`, `environment` and `purpose` (`expiresAt` is not compared, because a retry computes it again) and answers `idempotency_conflict` on a difference. A replay of a revoked or an expired row answers `idempotent_row_revoked` or `idempotent_row_expired`, not `ok`. A replay under another minter is a different credential. A mint that loses a race on the index answers from the row that won.
141
+
142
+ `replaceStale: true` is for trusted code. When the key is held by a stale row (revoked or expired) of the same minter, `issue()` renames the old key to `<key>:superseded:<id>` inside its own transaction and mints a new credential. The old row stays. If the insert fails, the rename is rolled back with it. A live row is still a replay.
143
+
144
+ ## Child expiry
145
+
146
+ `issue()` refuses a child whose `expiresAt` is later than its minter's with `expires_after_minter`, before the Worker is called. Equal is allowed. A host that mints children should still choose an expiry at or below the parent's.
129
147
 
130
148
  ## Outbound webhooks
131
149
 
132
- `@wtfalch/keys/webhooks`'s `createWebhookDispatcher({ url, secret? })` returns a function that POSTs a lifecycle event as JSON — a drop-in for `./issued`'s `audit` option (`credential.minted` / `.rotated` / `.revoked`) or `./held`'s (`key.used`). With `secret`, the body is HMAC-SHA256-signed into an `X-Keys-Signature` header; the receiver checks it with `verifyWebhookSignature(body, signature, secret)`. Delivery is fire-and-forget and best-effort — a subscriber outage never fails the call that produced the event, it only calls `onDeliveryError`.
150
+ `@wtfalch/keys/webhooks`'s `createWebhookDispatcher({ url, secret? })` returns a function that POSTs a lifecycle event as JSON — a drop-in for `./issued`'s `audit` option (`credential.minted` / `.rotated` / `.revoked`) or `./held`'s (`key.used`). It returns at once and delivers outside the caller's path, with a 5-second timeout (`AbortSignal.timeout`, which does not keep the process alive). With `secret`, each delivery carries `x-keys-timestamp` (Unix milliseconds) and `x-keys-signature`, the HMAC-SHA256 of `<timestamp>.<body>`; the receiver checks them with `verifyWebhookSignature(body, signature, secret, { timestamp, toleranceMs? })`, which refuses a timestamp more than 5 minutes (default) from its own clock. Without `timestamp`, `verifyWebhookSignature` still checks the old body-only form; that form is deprecated and cannot refuse a replay. Delivery is best-effort and not retried — a subscriber outage never fails the call that produced the event, it only calls `onDeliveryError`, and a throw from `onDeliveryError` is logged by name and swallowed.
133
151
 
134
152
  ## Worker transport
135
153
 
@@ -154,8 +172,11 @@ const plaintext = await openHeld({ worker, credential, tenantId, entryId, sealed
154
172
 
155
173
  - `worker` is any `WorkerClient` (only `wrap` and `unwrap` are used); `credential` is the serialized bearer credential the custody Worker checks. Pass `timeoutMs` (default 10 s) to bound each Worker call.
156
174
  - `version` is chosen and incremented by the caller. Opening with the wrong tenant, entry or version fails (`aad_mismatch` from the Worker, `unseal_failed` locally).
175
+ - `openHeld` reads the version from the stored record, so someone who can write the caller's storage can swap in the same entry's older sealed record and it opens. Pass `expectedVersion` where the storage writer cannot reach it (kept elsewhere, or in a better-guarded store); a different version throws `version_mismatch` before any Worker call.
176
+ - `plaintext` must be well-formed UTF-16. A lone surrogate throws `bad_request`, because the encoder would turn it into U+FFFD and the value would open as a different string.
157
177
  - `tenantId` and `entryId` must match `/^[A-Za-z0-9_-]{1,128}$/`; a bad id throws `HeldEdgeError('bad_request')` before any network call.
158
- - Errors are `HeldEdgeError` with a `code`: the Worker's own code, `bad_request`, `unseal_failed` or `timeout`. A message never carries the plaintext, a key, or the Worker's free-text message.
178
+ - Errors are `HeldEdgeError` with a `code`: the Worker's own code, `bad_request`, `unseal_failed`, `timeout`, `transport` (the Worker call threw or rejected; the cause is dropped, as it can carry the credential) or `version_mismatch`. The list is `HELD_EDGE_ERROR_CODES`. A message never carries the plaintext, a key, or the Worker's free-text message. A data key from a call that settles after the timeout is zeroed.
179
+ - Within one host, `/v1/held/unwrap` has no per-tenant grant: any caller holding that host's credential and a sealed blob can unwrap it. Never share a host id between one app and another.
159
180
  - `createWorkerClient` (`./worker`) uses `Buffer`: on a Worker, enable `nodejs_compat` for it, or inject your own `WorkerClient`. `./held-edge` itself needs neither.
160
181
 
161
182
  ## Adopting `./host`
@@ -175,6 +196,9 @@ pulls from.
175
196
  either option alone, so `(event) => recordEvent(db, event)` type-checks
176
197
  directly as both `CreateCredentialIssuerOptions.audit` and
177
198
  `CreateHeldKeysOptions.audit` — no adapter, no cast.
199
+ - `recordEventInTransaction(tx, event)` is `recordEvent` for
200
+ `CreateCredentialIssuerOptions.auditInTransaction`: the event row commits
201
+ with the change, or neither does. See "Audit after commit" below.
178
202
  - `auditEndpoint({ db, token })` returns a fetch-shaped handler
179
203
  (`(request: Request) => Promise<Response>`). Wire it directly as a route,
180
204
  e.g. in Next.js: `export const GET = auditEndpoint({ db, token:
@@ -189,6 +213,86 @@ pulls from.
189
213
  no behaviour change and no data migration: the table name, every column
190
214
  and the response shape are identical field for field.
191
215
 
216
+ ## Adopting `./service`
217
+
218
+ `@wtfalch/keys/service` is the HTTP half of the keys tables, for a company data
219
+ service to mount. The contract is C7 in
220
+ [`docs/contracts.md`](https://github.com/wtfalch/keys/blob/main/docs/contracts.md).
221
+ The handler holds no credential of its own and never reads a token: the host
222
+ verifies the caller and passes the result in.
223
+
224
+ ```ts
225
+ import { createKeysHandler, policyModule } from '@wtfalch/keys/service';
226
+
227
+ const keys = createKeysHandler({
228
+ db, // the runtime role's connection
229
+ principal: async (request) => resolveCaller(request), // null is 401
230
+ worker, // a WorkerClient; every call is bounded by workerTimeoutMs (default 5 s)
231
+ credential, // this host's Worker-signed service credential
232
+ verifyKeys,
233
+ prefix: 'files_live_',
234
+ auditToken: process.env.KEYS_AUDIT_TOKEN,
235
+ basePath: '/keys', // the mount path; default ''
236
+ });
237
+ ```
238
+
239
+ - `@wtfalch/authz` 0.18.0 is a peer of this entry only, and only for types.
240
+ `policyModule` is the catalogue module for the eight permissions
241
+ (`keys:issue`, `keys:verify`, `keys:rotate`, `keys:revoke`, `keys:lineage`,
242
+ `keys:put`, `keys:held-revoke`, `keys:shred`). `keys:shred` is not offered.
243
+ - Every route runs in one order: principal, a bounded body (64 KiB, a JSON
244
+ object), authorization on the scoping id alone, the remaining fields, then
245
+ the library. A caller without the permission gets `403` whatever else the
246
+ body holds, so a refusal never shows the shape of a request. A missing or
247
+ malformed scoping id (`organisationId`, `tenantId`) is `400`, because
248
+ authorization has nothing to ask about.
249
+ - A field the route does not name is `400`. `purpose` is one: an issued
250
+ credential through this route is always `ordinary`, and carries the
251
+ `organisationId` of the authorized request.
252
+ - A row of another organisation, or with none, answers exactly as a missing
253
+ row does, for `rotate`, `revoke`, `lineage` and `verify`, and as a missing
254
+ minter for `issue`. `verify` hands the organisation to `check`, so such a row
255
+ is charged to that organisation's `unknown-key:<organisationId>` limit like a key nobody holds.
256
+ - `revoke` calls `revokeForCompany`. A `company_root`, a `platform_master` or
257
+ a row of unknown purpose in the cascade is `409 conflict` and changes
258
+ nothing. The trusted `revoke` is not reachable.
259
+ - The idempotency key is stored as `<organisationId>:<key>`. A root's key is
260
+ unique across the whole table, so without this one organisation's key would
261
+ answer another's request.
262
+ - `issue` answers `201` with the secret, and `200` with `secret: null` on a
263
+ replay of the same request.
264
+ - Every library refusal goes through `toServiceError`, which maps a closed
265
+ table (`REFUSAL_CODES`). The message is the refusal's name and nothing else.
266
+ Anything the caller cannot fix, and anything about the Worker, is
267
+ `unavailable` with one fixed log line that names a class and never a
268
+ message. A test fails when a refusal union gains a member without a row.
269
+ - Held routes: `put` (`keys:put`, answers the new `version`), `revoke`
270
+ (`keys:held-revoke`, answers `{ revoked: true }`) and `shred` (`keys:shred`,
271
+ platform-wide, no body, answers `{ shredded }`). `tenantId` plays the part
272
+ `organisationId` plays above. No route opens a value, and a held value is in
273
+ no answer, error or log line. An entry of a gated kind answers `403`.
274
+ - Audit: each `issue`, `rotate`, `revoke`, `put`, `revoke` of an entry and
275
+ `shred` writes one `keys_host_events` row. `verify` and `lineage` change
276
+ nothing and write no row. `GET <basePath>/v1/keys/audit` is `auditEndpoint`,
277
+ unchanged, on its own bearer, and returns the same three kinds as before.
278
+ - Where the audit row lands. Apply `host/0002` first: it adds the kinds
279
+ `held.put`, `held.revoked` and `held.shredded` to the table's check, additively
280
+ and without a long lock. Then every change is in one transaction with its row,
281
+ so a failed audit write undoes the change and the caller gets `unavailable`.
282
+ `issue`, `rotate` and `revoke` use `auditInTransaction`. `put` takes the new
283
+ `CreateHeldKeysOptions.auditInTransaction`: the insert of the version and its
284
+ row commit together. What `put` cannot join is the step before: it reserves
285
+ the version number in its own short transaction and calls the Worker outside
286
+ any lock. A `put` that fails after that (the Worker refuses or hangs, or the
287
+ audit write fails) publishes nothing and writes no row, but the number it
288
+ reserved stays used, so the next version skips it. `revoke` of an entry writes
289
+ its row only when it revoked something: an entry already revoked, or one that
290
+ never existed, answers `{ revoked: true }` and changes nothing. `shred` runs
291
+ the sweep and writes its row in one transaction, also when nothing was eligible.
292
+ - Not routes: rewrap and resign. They need an operator handle and the sweep
293
+ credential, which do not belong in a serving process; run them through
294
+ `runRotationSweep`.
295
+
192
296
  ## Per-company registrar
193
297
 
194
298
  `createRegistrar`/`registrarEndpoint` from `./host` (added for #119) let a
@@ -221,7 +325,27 @@ export const DELETE = registrarEndpoint(options);
221
325
  returns the same `id` with `secret: null`, never a second credential.
222
326
  - `DELETE` on the same path revokes it. Revoking a name the caller never
223
327
  registered — or one only a different company registered — is
224
- `app_not_found` either way; the caller cannot tell the two apart.
328
+ `app_not_found` either way; the caller cannot tell the two apart. It goes
329
+ through `revokeForCompany`, so an app whose purpose is still unknown
330
+ (minted before 0.10.0, not yet classified) answers `purpose_unknown` and is
331
+ left as it is.
332
+ - An app is named `registrar:<organisationId>:<appName>`; a company key with no
333
+ organisation (minted before 0.10.0) uses its own credential id there, as
334
+ before. A second live key of the same organisation asking for a name that a
335
+ different key holds gets `app_held_by_another_key` (409). A key that is not a
336
+ registrar, or is revoked, reads as `company_key_invalid`; `company_key_not_a_registrar`
337
+ is no longer returned and goes at 1.0.0.
338
+ - An app ends with its company key when the key has less life left than
339
+ `appTtlMs`. Revoking a company key revokes its apps (the cascade); company
340
+ key management cannot remove the key itself, only roll it.
341
+ - The Worker refuses a child credential that holds a grant its minter lacks
342
+ (`minter_exceeded`). `createCompanyRegistrarKeys` and
343
+ `platformRegistrarEndpoint` therefore take `appGrants`, and mint the company
344
+ key holding `[registrarGrant, ...appGrants]`, so the apps it registers pass.
345
+ `isRegistrarGrant` stays the only thing that marks a registrar. A company key
346
+ minted before `appGrants` existed holds only the registrar grant, and its
347
+ apps are refused until it is rolled: mint a new key with `appGrants`, then
348
+ revoke the old one.
225
349
  - Scoping is the existing parent/child lineage, not a lookup a caller's
226
350
  input could widen: every app this registrar mints is a child of the
227
351
  company credential that minted it, and every lookup is filtered by that
@@ -291,7 +415,10 @@ export const DELETE = platform;
291
415
  have been made, so revoke all of the organisation's keys before retrying)
292
416
  - 503 `unavailable` (no platform token configured, or under 32 characters)
293
417
 
294
- ## Adopting `./testing`
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.
295
422
 
296
423
  `@wtfalch/keys/testing` (added in **0.6.0**) is an in-process Worker stub for
297
424
  a host's own tests, built on the package's own signing and AAD code
@@ -318,6 +445,34 @@ endpoint boundary, required BuildKit mounts, explicit bootstrap delivery and
318
445
  output/image-layer canary checks. `@wtfalch/keys/build` exports the delivery
319
446
  helpers; `keys-build` and `keys-build-scan` are the executable entries.
320
447
 
448
+ ## What shredding guarantees
449
+
450
+ Shredding sets one column, `keys_held_versions.wrapped_key`, to null. After
451
+ that, nothing in the live database can open the version, and `open` answers
452
+ `not_found`. It does not reach copies. A backup or replica taken before the
453
+ shred still holds the wrapped data key and the ciphertext, and both stay
454
+ openable for as long as the key-encryption key that wrapped the data key
455
+ lives. So destruction is complete only when the last backup that held the
456
+ row has expired, or the key-encryption key is destroyed, whichever comes
457
+ first. With the ordinary 30-day shred delay and a 30-day backup retention, a
458
+ version that became eligible on day 0 is gone from the live table on day 30
459
+ or the next sweep after it, and gone from every backup on day 60 or later.
460
+ Plan for day 60 or later, not day 30. A migration credential shreds at once
461
+ in the live table, but its backups follow the same rule.
462
+
463
+ ## Lifecycle lock
464
+
465
+ `createCredentialIssuer` serialises issuance, rotation and cascade
466
+ revocation with one database-wide advisory lock, `pg_advisory_xact_lock(1801812339, 1)`.
467
+ The key does not name a schema, so every issuer in a database queues behind
468
+ the same lock, including issuers in different schemas that share the
469
+ database. The lock is held for one short transaction and never across a
470
+ Worker call, so the cost is a short queue, not a deadlock. The key is left
471
+ as it is on purpose: every issuer process must use the same key for mutual
472
+ exclusion, and a key that names the schema would make an old and a new
473
+ process lock different keys during a rolling deploy. Put issuers whose
474
+ throughput matters in separate databases.
475
+
321
476
  ## Current held values
322
477
 
323
478
  `held.openCurrent({ tenantId, entryId }, use)` selects the highest successfully
@@ -325,9 +480,94 @@ sealed version once, then opens that binding. Pending or failed reservations do
325
480
  not hide the preceding value. The existing `held.open(binding, use)` remains the
326
481
  version-pinned operation. See the [selection and cache contract](https://github.com/wtfalch/keys/blob/main/packages/keys/src/held/open-current.md).
327
482
 
483
+ ## The migration-credential kind
484
+
485
+ A migration credential (a Google service account key, or a Microsoft app
486
+ secret -- one of ours per provider, approved by the customer's admin; see
487
+ [estate's migration-in proposal](https://github.com/wtfalch/estate/blob/main/proposals/migration-in.md),
488
+ "Mail: where it runs, what the owner sees") reads every mailbox of every open
489
+ grant for its provider, so it is held with tighter custody than an ordinary
490
+ held key:
491
+
492
+ - `held.put(entry, value, { kind: MIGRATION_CREDENTIAL_KIND })` seals it under
493
+ this kind, once, at the entry's first `put`. The stored kind wins over any
494
+ `kind` a later `put` passes, and the database refuses an `UPDATE` that
495
+ changes it. Each customer tenant holds its own sealed copy (one entry per
496
+ tenant), so one customer's Finish touches only that tenant's entry.
497
+ - `createHeldKeys`'s `checkKindPermission` option is required, not optional,
498
+ for this kind: `put`, `open`, `openCurrent` and `revokeEntry` on a
499
+ migration-credential entry refuse with `forbidden` when it is not supplied,
500
+ rather than behaving like an ordinary held key. This is where a host wires
501
+ its own `@wtfalch/authz` check in.
502
+ - Every `open`/`openCurrent` call writes its own audit row: a migration
503
+ credential's version is never placed in the accepted-key cache, so the
504
+ cache-hit path that otherwise skips a second audit (ADR 0019) never applies
505
+ to it.
506
+ - `held.finishMigrationCredential(entry)` is "delete at Finish": it revokes
507
+ the entry, then sweeps with the existing shred path (`shredExpired`,
508
+ `shred.ts`) so the version it just made eligible is destroyed in the same
509
+ call. `held.rotateMigrationCredential(entry, value)` seals a new version the
510
+ same way `put` does, then sweeps the same way, so the version it just
511
+ superseded is destroyed at once too. Both rely on this kind's shred delay
512
+ being zero days rather than the estate's ordinary 30
513
+ (`migrations/held/0005_keys_held_migration_credential.sql`) -- an ordinary
514
+ entry's old version still stays openable after a rotation, exactly as
515
+ before. The sweep is the host-wide one, so its count includes any other
516
+ version that was already due. If the process dies between the write and
517
+ the sweep, the old bytes stay until the host's next `shredExpired` run:
518
+ a revoked entry is already refused by `open`, but a superseded version
519
+ stays openable by its explicit version until then. Run the sweep on a
520
+ timer as well. Shredding nulls the `wrapped_key` column only; backups that
521
+ hold the old row stay unwrappable while the key-encryption key lives (see
522
+ "What shredding guarantees").
523
+
524
+ ## Rotation sweep
525
+
526
+ `runRotationSweep` from `./host` moves a host onto a new key generation. It rewraps every non-shredded version, re-signs every credential row, and returns a report with both remaining counts. A host runs it from its migrate container with `KEYS_SWEEP_CREDENTIAL`, an operator handle for `./held`, and the signing migrator. The operator passes the report to `rotate-host.mjs promote --report <file>`, which refuses unless both counts are 0 and the Worker's own log agrees. `packages/worker/README.md` has the rotation order.
527
+
328
528
  ## Signing generation migration
329
529
 
330
530
  `createSigningGenerationMigrator` from `@wtfalch/keys/issued` provides bounded,
331
531
  resumable operator batches that preserve existing bearer secrets. Follow the
332
532
  [signing migration runbook](https://github.com/wtfalch/keys/blob/main/packages/keys/src/issued/SIGNING_GENERATION_MIGRATION.md)
333
533
  for verification, concurrency and retirement requirements.
534
+
535
+ ### Signing generations
536
+
537
+ A row's `signing_generation_id` is its label. It is not signed. Pass
538
+ `previousGenerationId` to `createCredentialIssuer` next to a `previous` key in
539
+ `verifyKeys`, and `check()` and `rotate()` accept the `previous` key only for a
540
+ row carrying that label. A row that verifies only under `previous` with any
541
+ other label is `signature_invalid`. Leave it unset and both keys are tried for
542
+ every row, as before; that is deprecated, and 1.0.0 requires
543
+ `previousGenerationId` whenever `previous` is passed.
544
+
545
+ `migrator.retirementCheck(previousGenerationId)` returns
546
+ `{ retirable, blocking }`: `blocking` is how many live rows (not revoked, not
547
+ expired) carry that label and would stop verifying if `previous` were dropped.
548
+ `retirable` is true only at 0. It is a count at one moment; a writer still
549
+ signing under the old generation can add rows after it.
550
+
551
+ **Rollback is not prevented.** A row has no monotonic counter, so someone who
552
+ can write the database can restore an older row with its older signature, and
553
+ with it a rotated-out secret. Keys detects tampering; it does not detect
554
+ rollback.
555
+
556
+ ## Audit after commit
557
+
558
+ `createCredentialIssuer`'s `audit` runs after the write has committed. A throw
559
+ from it no longer reaches the caller: it goes to `onAuditError(event, error)`,
560
+ or, if that is unset, one line `keys: audit failed for <event name>: <error
561
+ name>` is logged. The one-time secret is always returned, and every remaining
562
+ `credential.revoked` event is still emitted. What plain `audit` cannot do: a
563
+ process killed between the commit and the call leaves no event, and nothing
564
+ re-emits it.
565
+
566
+ `auditInTransaction(tx, event)` runs inside the transaction that makes the
567
+ change, for hosts that keep events in the same database. The event and the
568
+ change land together; a throw aborts the write (nothing is stored, and the
569
+ call throws), so a kill between commit and audit cannot lose an event. Use
570
+ `recordEventInTransaction` from `@wtfalch/keys/host`. If both options are set,
571
+ each event is recorded twice. `./held`'s `audit` stays as it is: it runs before
572
+ `use` gets the value and there is no write to commit, so a throw refuses the
573
+ use rather than losing an event.
@@ -1,10 +1,20 @@
1
1
  import type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';
2
- import { type KeyBinding, type SerializedCredential, type WorkerClient, type WorkerError, type WorkerErrorCode } from '../worker-contract.js';
2
+ import { type KeyBinding, type SerializedCredential, WORKER_ERROR_CODES, type WorkerClient, type WorkerError, type WorkerErrorCode } from '../worker-contract.js';
3
3
  export { encodeAad } from './aad.js';
4
4
  export type { KeyBinding, WorkerClient, WorkerError, WorkerErrorCode } from '../worker-contract.js';
5
+ export { WORKER_ERROR_CODES };
5
6
  export type { KeysHeldEntryRow, KeysHeldVersionRow } from './schema.js';
6
7
  export { shredClocks, shredExpired } from './shred.js';
7
8
  export type { ShredClock, ShredClockReason } from './shred.js';
9
+ /**
10
+ * The one held-entry kind this package itself knows about (#110). `null`
11
+ * (the default) is an ordinary held key. `migrations/held/0005_keys_held_migration_credential.sql`'s
12
+ * CHECK is the actual enforcement; this constant is so a host spells the
13
+ * same string everywhere rather than retyping it.
14
+ */
15
+ export declare const MIGRATION_CREDENTIAL_KIND: "migration_credential";
16
+ /** `keys_held_entries.kind`: `null` for an ordinary held key. */
17
+ export type HeldEntryKind = typeof MIGRATION_CREDENTIAL_KIND | null;
8
18
  /**
9
19
  * `./held`: the ciphertext half of a held key, in the host's own database
10
20
  * (#216), plus the 60-second data-key cache and the callback-shaped `open`
@@ -22,7 +32,11 @@ export type HeldKeysDb = PgDatabase<PgQueryResultHKT, any, any>;
22
32
  * local codes are refusals this package makes itself, never sent by a
23
33
  * Worker.
24
34
  */
25
- export type HeldKeysErrorCode = WorkerErrorCode | 'not_found' | 'revoked' | 'unseal_failed' | 'disposed' | 'invalidated';
35
+ export type HeldKeysErrorCode = WorkerErrorCode | 'not_found' | 'revoked' | 'unseal_failed' | 'disposed' | 'invalidated'
36
+ /** A `put`, `open`, `openCurrent` or `revokeEntry` on a gated-kind entry with no `checkKindPermission` wired, or that callback's own refusal. */
37
+ | 'forbidden';
38
+ /** Every member of `HeldKeysErrorCode`. Adding one is a major change after 1.0.0. */
39
+ export declare const HELD_KEYS_ERROR_CODES: readonly ["credential_invalid", "credential_expired", "credential_revoked", "grant_missing", "rate_limited", "bad_request", "aad_mismatch", "unknown_generation", "bad_minter_signature", "minter_expired", "minter_revoked", "minter_exceeded", "lineage_mismatch", "bad_old_signature", "unlogged_row", "not_in_lineage", "unreachable", "not_found", "revoked", "unseal_failed", "disposed", "invalidated", "forbidden"];
26
40
  /**
27
41
  * Thrown by `put`, `open` and `rewrap`. Never carries a value or a key --
28
42
  * only what a caller can act on: which entry, which code, and (for
@@ -49,6 +63,23 @@ export interface KeyUsedEvent {
49
63
  /** Unix milliseconds. */
50
64
  readonly at: number;
51
65
  }
66
+ /**
67
+ * What `auditInTransaction` receives: one per change `put` and `revokeEntry` make. `held.put` is
68
+ * written only when a version was published, `held.revoked` only when the call revoked the entry.
69
+ * Neither carries a value.
70
+ */
71
+ export type HeldMutationEvent = {
72
+ readonly name: 'held.put';
73
+ readonly tenantId: string;
74
+ readonly entryId: string;
75
+ readonly version: number;
76
+ readonly at: number;
77
+ } | {
78
+ readonly name: 'held.revoked';
79
+ readonly tenantId: string;
80
+ readonly entryId: string;
81
+ readonly at: number;
82
+ };
52
83
  export interface HeldEntryRef {
53
84
  readonly tenantId: string;
54
85
  readonly entryId: string;
@@ -66,16 +97,50 @@ export interface CreateHeldKeysOptions {
66
97
  readonly worker: Pick<WorkerClient, 'wrap' | 'unwrap' | 'rewrap'>;
67
98
  readonly credential: SerializedCredential;
68
99
  readonly audit: (event: KeyUsedEvent) => void | Promise<void>;
100
+ /**
101
+ * Runs inside the transaction that makes a `put` publish its version or a `revokeEntry` revoke
102
+ * its entry, for hosts that keep events in the same database as `db`. The event and the change
103
+ * land together, and a throw undoes the change. Pass `recordEvent` from `./host`. A `put` that
104
+ * fails earlier (the Worker refuses, say) has published nothing and writes no event, though the
105
+ * version number it reserved stays used. A `revokeEntry` on an entry that does not exist or is
106
+ * already revoked changes nothing and writes none.
107
+ */
108
+ readonly auditInTransaction?: (tx: HeldKeysDb, event: HeldMutationEvent) => void | Promise<void>;
69
109
  /** Seconds before active cache eviction and key zeroing. Default 60 (#224). 0 disables caching. */
70
110
  readonly cacheSeconds?: number;
71
111
  /** Maximum cached versions. Default 256. Zero disables caching. */
72
112
  readonly maxCacheEntries?: number;
73
113
  /** Unix milliseconds. Defaults to `Date.now`; tests pass a fake clock to move it without waiting. */
74
114
  readonly now?: () => number;
115
+ /**
116
+ * Called before `put`, `open`, `openCurrent` or `revokeEntry` touches an
117
+ * entry whose `kind` (stored, or -- for a brand-new entry -- about to be
118
+ * stored) is not `null` -- `MIGRATION_CREDENTIAL_KIND` today. Throw to
119
+ * refuse. This package owns no authentication or authorisation of its
120
+ * own (README); this hook is where a host wires its own `@wtfalch/authz`
121
+ * check in for a gated kind specifically, and it is required, not
122
+ * optional, for that kind: a gated-kind entry is refused with
123
+ * `'forbidden'` when this option is not supplied at all, rather than
124
+ * silently behaving like an ordinary held key. An ordinary entry
125
+ * (`kind` is `null`) never calls this.
126
+ */
127
+ readonly checkKindPermission?: (context: {
128
+ readonly kind: Exclude<HeldEntryKind, null>;
129
+ readonly tenantId: string;
130
+ readonly entryId: string;
131
+ }) => void | Promise<void>;
75
132
  }
76
133
  export interface HeldKeys {
77
- /** Seals a new version under `entry`, creating the entry on its first call. */
78
- put(entry: HeldEntryRef, value: string): Promise<{
134
+ /**
135
+ * Seals a new version under `entry`, creating the entry on its first
136
+ * call. `putOptions.kind`, given on that first call only, is what
137
+ * `checkKindPermission` and every later call see as this entry's kind --
138
+ * a later `put` on the same entry ignores a different `kind` passed to
139
+ * it; kind is set once, like `revokedAt` and `tenantArchivedAt`.
140
+ */
141
+ put(entry: HeldEntryRef, value: string, putOptions?: {
142
+ readonly kind?: HeldEntryKind;
143
+ }): Promise<{
79
144
  readonly version: number;
80
145
  }>;
81
146
  /**
@@ -120,7 +185,18 @@ export interface HeldKeys {
120
185
  rewrap(options: {
121
186
  readonly kekIdOld: string;
122
187
  readonly kekIdNew: string;
123
- }): Promise<void>;
188
+ }): Promise<{
189
+ readonly rewrapped: number;
190
+ }>;
191
+ /**
192
+ * How many versions that still hold a wrapped key sit under a key id other
193
+ * than `kekId`. Counted from the stored `kek_id` values, so a version under
194
+ * an id nobody named still counts. A shredded version holds no key and is
195
+ * not counted.
196
+ */
197
+ countNotUnder(kekId: string): Promise<number>;
198
+ /** The distinct key ids that versions holding a wrapped key sit under. */
199
+ kekIdsInUse(): Promise<string[]>;
124
200
  /**
125
201
  * Marks an entry revoked. This process's own cache is cleared at once, so
126
202
  * its next `open` for this entry is a database read and refuses. A
@@ -140,10 +216,44 @@ export interface HeldKeys {
140
216
  * the mark lives on `keys_held_entries.tenant_archived_at` per entry,
141
217
  * rather than on a row it doesn't own. It is one of the three inputs
142
218
  * `keys_shred_expired()` (#232) reads to start a version's 30-day shred
143
- * clock; it does not by itself refuse `open` -- whether a departed
219
+ * clock. The shred nulls the live `wrapped_key` only: backups taken
220
+ * before it stay unwrappable while the key-encryption key lives, so
221
+ * destruction is day 60 or later, not day 30. It does not by itself refuse `open` -- whether a departed
144
222
  * tenant's calls are refused is `@wtfalch/authz`'s decision, not this
145
223
  * package's.
146
224
  */
147
225
  archiveTenant(tenantId: string): Promise<void>;
226
+ /**
227
+ * `MIGRATION_CREDENTIAL_KIND` entries only (#110): revokes `entry`
228
+ * (`revokeEntry`, so `checkKindPermission` runs and the cache clears the
229
+ * same way), then sweeps with the existing shred path (`shredExpired`,
230
+ * `shred.ts`) so the version it just made eligible is destroyed in this
231
+ * same call -- a migration credential's shred delay is zero days
232
+ * (`migrations/held/0005_keys_held_migration_credential.sql`), not the
233
+ * estate's ordinary 30. Refuses `bad_request` for an entry whose stored
234
+ * `kind` is not `MIGRATION_CREDENTIAL_KIND` (`null` included), and
235
+ * `not_found` for one that does not exist. Returns how many versions the
236
+ * sweep shredded host-wide -- including, but not limited to, this one --
237
+ * since `shredExpired` takes no row-targeting argument by design.
238
+ */
239
+ finishMigrationCredential(entry: HeldEntryRef): Promise<{
240
+ readonly shredded: number;
241
+ }>;
242
+ /**
243
+ * `MIGRATION_CREDENTIAL_KIND` entries only: seals `value` as a new
244
+ * version (`put`, so `checkKindPermission` runs), then sweeps the same
245
+ * way `finishMigrationCredential` does, so the version it just
246
+ * superseded is destroyed in this same call rather than kept openable by
247
+ * its explicit `{ tenantId, entryId, version }` the way an ordinary
248
+ * rotated entry's old version stays (`held.test.ts`: "a rotated entry
249
+ * advances the version and the old one stays openable" -- that guarantee
250
+ * is for `kind: null` only). Creates the entry, with this kind, on a
251
+ * first call for an `entry` that does not exist yet. Refuses
252
+ * `bad_request` for an entry whose stored kind is not
253
+ * `MIGRATION_CREDENTIAL_KIND`.
254
+ */
255
+ rotateMigrationCredential(entry: HeldEntryRef, value: string): Promise<{
256
+ readonly version: number;
257
+ }>;
148
258
  }
149
259
  export declare function createHeldKeys(options: CreateHeldKeysOptions): HeldKeys;