@wtfalch/keys 0.7.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.
- package/README.md +349 -7
- package/dist/held/index.d.ts +116 -6
- package/dist/held/index.js +247 -25
- package/dist/held/schema.d.ts +17 -0
- package/dist/held/schema.js +12 -0
- package/dist/held/shred.d.ts +6 -0
- package/dist/held/shred.js +6 -0
- package/dist/held-edge/index.d.ts +17 -2
- package/dist/held-edge/index.js +51 -9
- package/dist/host/audit-endpoint.js +2 -8
- package/dist/host/company-registrar-keys.d.ts +106 -0
- package/dist/host/company-registrar-keys.js +211 -0
- package/dist/host/events.d.ts +19 -3
- package/dist/host/events.js +55 -20
- package/dist/host/index.d.ts +15 -1
- package/dist/host/index.js +15 -1
- package/dist/host/native-build.d.ts +126 -0
- package/dist/host/native-build.js +322 -0
- package/dist/host/registrar.d.ts +87 -0
- package/dist/host/registrar.js +284 -0
- package/dist/host/rotation-sweep.d.ts +56 -0
- package/dist/host/rotation-sweep.js +89 -0
- package/dist/issued/encoding.d.ts +4 -0
- package/dist/issued/encoding.js +22 -0
- package/dist/issued/index.d.ts +148 -7
- package/dist/issued/index.js +320 -34
- package/dist/issued/resign.d.ts +16 -0
- package/dist/issued/resign.js +55 -2
- package/dist/issued/tables.d.ts +38 -0
- package/dist/issued/tables.js +6 -0
- package/dist/issued/verify.d.ts +14 -3
- package/dist/issued/verify.js +10 -3
- package/dist/migrations/held/0004_keys_archived_publish_guard.sql +46 -0
- package/dist/migrations/held/0005_keys_held_migration_credential.sql +216 -0
- package/dist/migrations/held/0006_keys_held_entries_guard.sql +54 -0
- package/dist/migrations/host/0002_keys_host_held_events.sql +29 -0
- package/dist/migrations/issued/0007_keys_purpose.sql +68 -0
- package/dist/migrations/issued/0008_keys_idempotency_scope.sql +23 -0
- package/dist/service/body.d.ts +21 -0
- package/dist/service/body.js +128 -0
- package/dist/service/errors.d.ts +24 -0
- package/dist/service/errors.js +89 -0
- package/dist/service/handler.d.ts +35 -0
- package/dist/service/handler.js +328 -0
- package/dist/service/index.d.ts +7 -0
- package/dist/service/index.js +7 -0
- package/dist/service/policy.d.ts +130 -0
- package/dist/service/policy.js +123 -0
- package/dist/service/timeout.d.ts +6 -0
- package/dist/service/timeout.js +34 -0
- package/dist/testing/index.d.ts +3 -0
- package/dist/testing/index.js +3 -0
- package/dist/webhooks.d.ts +40 -17
- package/dist/webhooks.js +70 -26
- package/dist/worker-contract.d.ts +43 -6
- package/dist/worker-contract.js +37 -0
- package/dist/worker.d.ts +1 -1
- package/dist/worker.js +7 -28
- package/package.json +21 -3
package/dist/held/index.js
CHANGED
|
@@ -1,13 +1,32 @@
|
|
|
1
1
|
import { createCipheriv, createDecipheriv, randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
-
import { and, desc, eq, sql } from 'drizzle-orm';
|
|
3
|
-
import { ID_PATTERN, } from '../worker-contract.js';
|
|
2
|
+
import { and, desc, eq, isNotNull, ne, sql } from 'drizzle-orm';
|
|
3
|
+
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
|
+
import { shredExpired } from './shred.js';
|
|
6
7
|
export { encodeAad } from './aad.js';
|
|
8
|
+
export { WORKER_ERROR_CODES };
|
|
7
9
|
export { shredClocks, shredExpired } from './shred.js';
|
|
10
|
+
/**
|
|
11
|
+
* The one held-entry kind this package itself knows about (#110). `null`
|
|
12
|
+
* (the default) is an ordinary held key. `migrations/held/0005_keys_held_migration_credential.sql`'s
|
|
13
|
+
* CHECK is the actual enforcement; this constant is so a host spells the
|
|
14
|
+
* same string everywhere rather than retyping it.
|
|
15
|
+
*/
|
|
16
|
+
export const MIGRATION_CREDENTIAL_KIND = 'migration_credential';
|
|
8
17
|
const IV_BYTES = 12;
|
|
9
18
|
const TAG_BYTES = 16;
|
|
10
19
|
const ALGORITHM = 'aes-256-gcm';
|
|
20
|
+
/** Every member of `HeldKeysErrorCode`. Adding one is a major change after 1.0.0. */
|
|
21
|
+
export const HELD_KEYS_ERROR_CODES = [
|
|
22
|
+
...WORKER_ERROR_CODES,
|
|
23
|
+
'not_found',
|
|
24
|
+
'revoked',
|
|
25
|
+
'unseal_failed',
|
|
26
|
+
'disposed',
|
|
27
|
+
'invalidated',
|
|
28
|
+
'forbidden',
|
|
29
|
+
];
|
|
11
30
|
/**
|
|
12
31
|
* Thrown by `put`, `open` and `rewrap`. Never carries a value or a key --
|
|
13
32
|
* only what a caller can act on: which entry, which code, and (for
|
|
@@ -148,10 +167,59 @@ export function createHeldKeys(options) {
|
|
|
148
167
|
evict(key, hit);
|
|
149
168
|
}
|
|
150
169
|
}
|
|
151
|
-
|
|
170
|
+
/**
|
|
171
|
+
* `undefined` when `entry` does not exist yet -- distinct from an
|
|
172
|
+
* existing entry whose own stored `kind` is `null` (an ordinary held
|
|
173
|
+
* key), which a caller must not treat the same way `put`'s own
|
|
174
|
+
* `onConflictDoNothing` would make the opposite mistake look harmless.
|
|
175
|
+
* No lock: kind is set once at an entry's creation and never changes, so
|
|
176
|
+
* reading it outside `put`'s own transaction cannot race with anything
|
|
177
|
+
* that would change the answer.
|
|
178
|
+
*/
|
|
179
|
+
async function existingEntry(entry) {
|
|
180
|
+
const [row] = await db
|
|
181
|
+
.select({ kind: keysHeldEntries.kind })
|
|
182
|
+
.from(keysHeldEntries)
|
|
183
|
+
.where(and(eq(keysHeldEntries.tenantId, entry.tenantId), eq(keysHeldEntries.entryId, entry.entryId)))
|
|
184
|
+
.limit(1);
|
|
185
|
+
if (!row)
|
|
186
|
+
return undefined;
|
|
187
|
+
return { kind: row.kind ?? null };
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Run before `put`, `open`, `openCurrent` and `revokeEntry` touch an
|
|
191
|
+
* entry whose effective kind -- the stored one, or, for a brand-new
|
|
192
|
+
* entry, the one about to be stored -- is not `null`. Fail-closed: a
|
|
193
|
+
* gated kind with no `checkKindPermission` wired refuses rather than
|
|
194
|
+
* behaving like an ordinary held key. Called outside any transaction and
|
|
195
|
+
* before any row lock is taken, so a slow or network-backed permission
|
|
196
|
+
* check never holds a Postgres lock open, the same reason `put`'s own
|
|
197
|
+
* Worker call runs after its transaction commits.
|
|
198
|
+
*/
|
|
199
|
+
async function requireKindPermission(kind, entry) {
|
|
200
|
+
if (kind === null)
|
|
201
|
+
return;
|
|
202
|
+
if (!options.checkKindPermission) {
|
|
203
|
+
throw new HeldKeysError('forbidden', `entry ${entry.entryId} is kind ${kind}, which has no checkKindPermission wired`);
|
|
204
|
+
}
|
|
205
|
+
await options.checkKindPermission({ kind, tenantId: entry.tenantId, entryId: entry.entryId });
|
|
206
|
+
}
|
|
207
|
+
async function put(entry, value, putOptions) {
|
|
152
208
|
requireActive();
|
|
153
209
|
requireId(entry.tenantId, 'tenantId');
|
|
154
210
|
requireId(entry.entryId, 'entryId');
|
|
211
|
+
// Kind is set once, at creation: an existing entry's own stored kind
|
|
212
|
+
// always wins over a different kind passed here, the same way a
|
|
213
|
+
// second put() cannot un-revoke or un-archive one -- including an
|
|
214
|
+
// existing *ordinary* entry (kind null), which must not fall through
|
|
215
|
+
// to a `kind` option a caller passes by mistake on a later put.
|
|
216
|
+
const requestedKind = putOptions?.kind ?? null;
|
|
217
|
+
if (requestedKind !== null && requestedKind !== MIGRATION_CREDENTIAL_KIND) {
|
|
218
|
+
throw new HeldKeysError('bad_request', 'kind is not a known held entry kind');
|
|
219
|
+
}
|
|
220
|
+
const existing = await existingEntry(entry);
|
|
221
|
+
const effectiveKind = existing ? existing.kind : requestedKind;
|
|
222
|
+
await requireKindPermission(effectiveKind, entry);
|
|
155
223
|
// Reserve the next version number under a row lock, and nothing else:
|
|
156
224
|
// the lock is released the instant this short transaction commits, so a
|
|
157
225
|
// slow or unreachable Worker (the next step, outside any lock) cannot
|
|
@@ -161,20 +229,37 @@ export function createHeldKeys(options) {
|
|
|
161
229
|
const version = await db.transaction(async (tx) => {
|
|
162
230
|
await tx
|
|
163
231
|
.insert(keysHeldEntries)
|
|
164
|
-
.values({
|
|
232
|
+
.values({
|
|
233
|
+
tenantId: entry.tenantId,
|
|
234
|
+
entryId: entry.entryId,
|
|
235
|
+
currentVersion: 0,
|
|
236
|
+
kind: effectiveKind,
|
|
237
|
+
})
|
|
165
238
|
.onConflictDoNothing();
|
|
166
239
|
const [row] = await tx
|
|
167
240
|
.select({
|
|
168
241
|
currentVersion: keysHeldEntries.currentVersion,
|
|
242
|
+
kind: keysHeldEntries.kind,
|
|
169
243
|
revokedAt: keysHeldEntries.revokedAt,
|
|
244
|
+
tenantArchivedAt: keysHeldEntries.tenantArchivedAt,
|
|
170
245
|
})
|
|
171
246
|
.from(keysHeldEntries)
|
|
172
247
|
.where(and(eq(keysHeldEntries.tenantId, entry.tenantId), eq(keysHeldEntries.entryId, entry.entryId)))
|
|
173
248
|
.for('update');
|
|
174
249
|
if (!row)
|
|
175
250
|
throw new HeldKeysError('not_found', 'the entry vanished mid-transaction');
|
|
251
|
+
// Another put created the entry between the permission check above and
|
|
252
|
+
// this insert: the permission check named the wrong kind. Refuse rather
|
|
253
|
+
// than add a version under a kind nobody was checked for.
|
|
254
|
+
if ((row.kind ?? null) !== effectiveKind) {
|
|
255
|
+
throw new HeldKeysError('bad_request', `entry ${entry.entryId} was created with another kind`);
|
|
256
|
+
}
|
|
176
257
|
if (row.revokedAt)
|
|
177
258
|
throw new HeldKeysError('revoked', `entry ${entry.entryId} is revoked`);
|
|
259
|
+
// The shred sweep would count a new version on the tenant's archive clock.
|
|
260
|
+
if (row.tenantArchivedAt) {
|
|
261
|
+
throw new HeldKeysError('revoked', `tenant ${entry.tenantId} is archived`);
|
|
262
|
+
}
|
|
178
263
|
const next = row.currentVersion + 1;
|
|
179
264
|
await tx
|
|
180
265
|
.update(keysHeldEntries)
|
|
@@ -190,15 +275,44 @@ export function createHeldKeys(options) {
|
|
|
190
275
|
try {
|
|
191
276
|
const aad = encodeAad(binding);
|
|
192
277
|
const sealed = gcmSeal(dataKey, Buffer.from(value, 'utf8'), aad);
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
278
|
+
try {
|
|
279
|
+
const publish = (handle) => handle.insert(keysHeldVersions).values({
|
|
280
|
+
tenantId: entry.tenantId,
|
|
281
|
+
entryId: entry.entryId,
|
|
282
|
+
version,
|
|
283
|
+
kekId: result.kekId,
|
|
284
|
+
wrappedKey: Buffer.from(result.wrappedKey),
|
|
285
|
+
iv: sealed.iv,
|
|
286
|
+
ciphertext: sealed.ciphertext,
|
|
287
|
+
});
|
|
288
|
+
const auditTx = options.auditInTransaction;
|
|
289
|
+
if (auditTx) {
|
|
290
|
+
await db.transaction(async (tx) => {
|
|
291
|
+
await publish(tx);
|
|
292
|
+
await auditTx(tx, {
|
|
293
|
+
name: 'held.put',
|
|
294
|
+
tenantId: entry.tenantId,
|
|
295
|
+
entryId: entry.entryId,
|
|
296
|
+
version,
|
|
297
|
+
at: now(),
|
|
298
|
+
});
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
else {
|
|
302
|
+
await publish(db);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
catch (err) {
|
|
306
|
+
// keys_held_versions_publish_guard refuses the insert of a revoked entry
|
|
307
|
+
// or an archived tenant's entry.
|
|
308
|
+
if (isGuardError(err, 'held entry is revoked')) {
|
|
309
|
+
throw new HeldKeysError('revoked', `entry ${entry.entryId} is revoked`);
|
|
310
|
+
}
|
|
311
|
+
if (isGuardError(err, 'held tenant is archived')) {
|
|
312
|
+
throw new HeldKeysError('revoked', `tenant ${entry.tenantId} is archived`);
|
|
313
|
+
}
|
|
314
|
+
throw err;
|
|
315
|
+
}
|
|
202
316
|
// Retiring the version this one supersedes is a side effect of the
|
|
203
317
|
// INSERT above, not a second write here: keys_held_versions_retire_predecessors
|
|
204
318
|
// (#232's migration), an AFTER INSERT, SECURITY DEFINER trigger, sets
|
|
@@ -221,7 +335,7 @@ export function createHeldKeys(options) {
|
|
|
221
335
|
forgetEntry(entry);
|
|
222
336
|
return { version };
|
|
223
337
|
}
|
|
224
|
-
async function openSelected(binding, versionRow, openingEpoch, use) {
|
|
338
|
+
async function openSelected(binding, versionRow, openingEpoch, use, kind) {
|
|
225
339
|
if (versionRow.wrappedKey === null) {
|
|
226
340
|
throw new HeldKeysError('not_found', `version ${binding.version} has been shredded`);
|
|
227
341
|
}
|
|
@@ -253,7 +367,14 @@ export function createHeldKeys(options) {
|
|
|
253
367
|
requireActive();
|
|
254
368
|
if (epoch !== openingEpoch)
|
|
255
369
|
throw new HeldKeysError('invalidated');
|
|
256
|
-
|
|
370
|
+
// A gated kind is never remembered: #110 wants one audit row for
|
|
371
|
+
// every single use ("each use... so there is one audit row for each
|
|
372
|
+
// use"), and the accepted-key cache's whole point is to let a later
|
|
373
|
+
// call skip the audit above (ADR 0019) -- so a gated entry is simply
|
|
374
|
+
// never placed in it, which also means it can never satisfy a cache
|
|
375
|
+
// hit later in this process.
|
|
376
|
+
if (kind === null)
|
|
377
|
+
remember(binding, dataKey, versionRow.iv, versionRow.ciphertext, until);
|
|
257
378
|
dataKey.fill(0);
|
|
258
379
|
return use(value);
|
|
259
380
|
}
|
|
@@ -273,7 +394,7 @@ export function createHeldKeys(options) {
|
|
|
273
394
|
return use(value);
|
|
274
395
|
}
|
|
275
396
|
const [entryRow] = await db
|
|
276
|
-
.select({ revokedAt: keysHeldEntries.revokedAt })
|
|
397
|
+
.select({ revokedAt: keysHeldEntries.revokedAt, kind: keysHeldEntries.kind })
|
|
277
398
|
.from(keysHeldEntries)
|
|
278
399
|
.where(and(eq(keysHeldEntries.tenantId, binding.tenantId), eq(keysHeldEntries.entryId, binding.entryId)))
|
|
279
400
|
.limit(1);
|
|
@@ -281,6 +402,8 @@ export function createHeldKeys(options) {
|
|
|
281
402
|
throw new HeldKeysError('not_found', `there is no entry ${binding.entryId}`);
|
|
282
403
|
if (entryRow.revokedAt)
|
|
283
404
|
throw new HeldKeysError('revoked', `entry ${binding.entryId} is revoked`);
|
|
405
|
+
const kind = entryRow.kind ?? null;
|
|
406
|
+
await requireKindPermission(kind, binding);
|
|
284
407
|
const [versionRow] = await db
|
|
285
408
|
.select({
|
|
286
409
|
kekId: keysHeldVersions.kekId,
|
|
@@ -293,7 +416,7 @@ export function createHeldKeys(options) {
|
|
|
293
416
|
.limit(1);
|
|
294
417
|
if (!versionRow)
|
|
295
418
|
throw new HeldKeysError('not_found', `there is no version ${binding.version}`);
|
|
296
|
-
return openSelected(binding, versionRow, openingEpoch, use);
|
|
419
|
+
return openSelected(binding, versionRow, openingEpoch, use, kind);
|
|
297
420
|
}
|
|
298
421
|
async function openCurrent(entry, use) {
|
|
299
422
|
requireActive();
|
|
@@ -309,6 +432,7 @@ export function createHeldKeys(options) {
|
|
|
309
432
|
const [selected] = await db
|
|
310
433
|
.select({
|
|
311
434
|
revokedAt: keysHeldEntries.revokedAt,
|
|
435
|
+
kind: keysHeldEntries.kind,
|
|
312
436
|
version: keysHeldVersions.version,
|
|
313
437
|
kekId: keysHeldVersions.kekId,
|
|
314
438
|
wrappedKey: keysHeldVersions.wrappedKey,
|
|
@@ -324,6 +448,8 @@ export function createHeldKeys(options) {
|
|
|
324
448
|
throw new HeldKeysError('not_found', `there is no entry ${entry.entryId}`);
|
|
325
449
|
if (selected.revokedAt)
|
|
326
450
|
throw new HeldKeysError('revoked', `entry ${entry.entryId} is revoked`);
|
|
451
|
+
const kind = selected.kind ?? null;
|
|
452
|
+
await requireKindPermission(kind, entry);
|
|
327
453
|
if (selected.version === null ||
|
|
328
454
|
selected.kekId === null ||
|
|
329
455
|
selected.iv === null ||
|
|
@@ -345,7 +471,7 @@ export function createHeldKeys(options) {
|
|
|
345
471
|
const value = gcmOpen(cached.dataKey, cached.iv, cached.ciphertext, encodeAad(binding));
|
|
346
472
|
return use(value);
|
|
347
473
|
}
|
|
348
|
-
return openSelected(binding, versionRow, openingEpoch, use);
|
|
474
|
+
return openSelected(binding, versionRow, openingEpoch, use, kind);
|
|
349
475
|
}
|
|
350
476
|
async function rewrap(rewrapOptions) {
|
|
351
477
|
requireActive();
|
|
@@ -361,6 +487,7 @@ export function createHeldKeys(options) {
|
|
|
361
487
|
})
|
|
362
488
|
.from(keysHeldVersions)
|
|
363
489
|
.where(and(eq(keysHeldVersions.kekId, kekIdOld), sql `${keysHeldVersions.wrappedKey} is not null`));
|
|
490
|
+
let rewrapped = 0;
|
|
364
491
|
for (const row of rows) {
|
|
365
492
|
if (row.wrappedKey === null)
|
|
366
493
|
continue; // shredded between the read above and this row; nothing to rewrap
|
|
@@ -379,26 +506,101 @@ export function createHeldKeys(options) {
|
|
|
379
506
|
});
|
|
380
507
|
if (!result.ok)
|
|
381
508
|
throw HeldKeysError.fromWorker(result.error);
|
|
382
|
-
await db
|
|
509
|
+
const updated = await db
|
|
383
510
|
.update(keysHeldVersions)
|
|
384
511
|
.set({ kekId: kekIdNew, wrappedKey: Buffer.from(result.wrappedKey) })
|
|
385
|
-
.where(and(eq(keysHeldVersions.tenantId, binding.tenantId), eq(keysHeldVersions.entryId, binding.entryId), eq(keysHeldVersions.version, binding.version), eq(keysHeldVersions.kekId, kekIdOld), eq(keysHeldVersions.wrappedKey, row.wrappedKey)))
|
|
512
|
+
.where(and(eq(keysHeldVersions.tenantId, binding.tenantId), eq(keysHeldVersions.entryId, binding.entryId), eq(keysHeldVersions.version, binding.version), eq(keysHeldVersions.kekId, kekIdOld), eq(keysHeldVersions.wrappedKey, row.wrappedKey)))
|
|
513
|
+
.returning({ version: keysHeldVersions.version });
|
|
514
|
+
rewrapped += updated.length;
|
|
386
515
|
}
|
|
516
|
+
return { rewrapped };
|
|
517
|
+
}
|
|
518
|
+
async function countNotUnder(kekId) {
|
|
519
|
+
requireActive();
|
|
520
|
+
requireId(kekId, 'kekId');
|
|
521
|
+
const [row] = await db
|
|
522
|
+
.select({ n: sql `count(*)::integer` })
|
|
523
|
+
.from(keysHeldVersions)
|
|
524
|
+
.where(and(isNotNull(keysHeldVersions.wrappedKey), ne(keysHeldVersions.kekId, kekId)));
|
|
525
|
+
return Number(row?.n ?? 0);
|
|
526
|
+
}
|
|
527
|
+
async function kekIdsInUse() {
|
|
528
|
+
requireActive();
|
|
529
|
+
const rows = await db
|
|
530
|
+
.selectDistinct({ kekId: keysHeldVersions.kekId })
|
|
531
|
+
.from(keysHeldVersions)
|
|
532
|
+
.where(isNotNull(keysHeldVersions.wrappedKey));
|
|
533
|
+
return rows.map((r) => r.kekId).sort();
|
|
387
534
|
}
|
|
388
535
|
async function revokeEntry(entry) {
|
|
389
536
|
requireActive();
|
|
390
537
|
requireId(entry.tenantId, 'tenantId');
|
|
391
538
|
requireId(entry.entryId, 'entryId');
|
|
539
|
+
await requireKindPermission((await existingEntry(entry))?.kind ?? null, entry);
|
|
392
540
|
// The `revoked_at is null` guard makes a second call a no-op rather than
|
|
393
541
|
// re-dating the revocation: an operator investigating an incident wants
|
|
394
542
|
// the first time this entry went dark, not the last time someone called
|
|
395
543
|
// revokeEntry on an already-revoked one.
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
544
|
+
const revoke = async (handle) => {
|
|
545
|
+
const rows = await handle
|
|
546
|
+
.update(keysHeldEntries)
|
|
547
|
+
.set({ revokedAt: sql `now()` })
|
|
548
|
+
.where(and(eq(keysHeldEntries.tenantId, entry.tenantId), eq(keysHeldEntries.entryId, entry.entryId), sql `${keysHeldEntries.revokedAt} is null`))
|
|
549
|
+
.returning({ entryId: keysHeldEntries.entryId });
|
|
550
|
+
if (rows.length > 0) {
|
|
551
|
+
await options.auditInTransaction?.(handle, {
|
|
552
|
+
name: 'held.revoked',
|
|
553
|
+
tenantId: entry.tenantId,
|
|
554
|
+
entryId: entry.entryId,
|
|
555
|
+
at: now(),
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
if (options.auditInTransaction)
|
|
560
|
+
await db.transaction(revoke);
|
|
561
|
+
else
|
|
562
|
+
await revoke(db);
|
|
400
563
|
forgetEntry(entry);
|
|
401
564
|
}
|
|
565
|
+
async function finishMigrationCredential(entry) {
|
|
566
|
+
requireActive();
|
|
567
|
+
requireId(entry.tenantId, 'tenantId');
|
|
568
|
+
requireId(entry.entryId, 'entryId');
|
|
569
|
+
const existing = await existingEntry(entry);
|
|
570
|
+
if (!existing) {
|
|
571
|
+
throw new HeldKeysError('not_found', `there is no entry ${entry.entryId}`);
|
|
572
|
+
}
|
|
573
|
+
if (existing.kind !== MIGRATION_CREDENTIAL_KIND) {
|
|
574
|
+
throw new HeldKeysError('bad_request', `entry ${entry.entryId} is kind ${existing.kind}, not ${MIGRATION_CREDENTIAL_KIND}`);
|
|
575
|
+
}
|
|
576
|
+
// revokeEntry runs the permission check itself (requireKindPermission),
|
|
577
|
+
// clears this process's cache, and is already a no-op on a second call.
|
|
578
|
+
await revokeEntry(entry);
|
|
579
|
+
// The existing shred path (shred.ts): this entry's kind carries a
|
|
580
|
+
// zero-day delay (0005's migration), so the version revokeEntry's
|
|
581
|
+
// write just made eligible is swept in this same call rather than
|
|
582
|
+
// kept around for the estate's ordinary 30 days.
|
|
583
|
+
const shredded = await shredExpired(db);
|
|
584
|
+
return { shredded };
|
|
585
|
+
}
|
|
586
|
+
async function rotateMigrationCredential(entry, value) {
|
|
587
|
+
requireActive();
|
|
588
|
+
requireId(entry.tenantId, 'tenantId');
|
|
589
|
+
requireId(entry.entryId, 'entryId');
|
|
590
|
+
const existing = await existingEntry(entry);
|
|
591
|
+
if (existing && existing.kind !== MIGRATION_CREDENTIAL_KIND) {
|
|
592
|
+
throw new HeldKeysError('bad_request', `entry ${entry.entryId} is kind ${existing.kind}, not ${MIGRATION_CREDENTIAL_KIND}`);
|
|
593
|
+
}
|
|
594
|
+
// put runs the permission check itself. On a first call for an entry
|
|
595
|
+
// that does not exist yet, this is what creates it with this kind.
|
|
596
|
+
const result = await put(entry, value, { kind: MIGRATION_CREDENTIAL_KIND });
|
|
597
|
+
// The version put() just retired (the entry's previous current one, if
|
|
598
|
+
// any) carries the same zero-day delay, so it is destroyed in this
|
|
599
|
+
// same call rather than staying openable the way an ordinary rotated
|
|
600
|
+
// entry's old version does.
|
|
601
|
+
await shredExpired(db);
|
|
602
|
+
return result;
|
|
603
|
+
}
|
|
402
604
|
async function archiveTenant(tenantId) {
|
|
403
605
|
requireActive();
|
|
404
606
|
requireId(tenantId, 'tenantId');
|
|
@@ -418,5 +620,25 @@ export function createHeldKeys(options) {
|
|
|
418
620
|
evict(key, hit);
|
|
419
621
|
}
|
|
420
622
|
}
|
|
421
|
-
return {
|
|
623
|
+
return {
|
|
624
|
+
put,
|
|
625
|
+
open,
|
|
626
|
+
openCurrent,
|
|
627
|
+
forget,
|
|
628
|
+
dispose,
|
|
629
|
+
rewrap,
|
|
630
|
+
countNotUnder,
|
|
631
|
+
kekIdsInUse,
|
|
632
|
+
revokeEntry,
|
|
633
|
+
archiveTenant,
|
|
634
|
+
finishMigrationCredential,
|
|
635
|
+
rotateMigrationCredential,
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
function isGuardError(err, message) {
|
|
639
|
+
if (!err || typeof err !== 'object')
|
|
640
|
+
return false;
|
|
641
|
+
const e = err;
|
|
642
|
+
return ((e.code === 'P0001' && e.message === message) ||
|
|
643
|
+
(e.cause !== err && isGuardError(e.cause, message)));
|
|
422
644
|
}
|
package/dist/held/schema.d.ts
CHANGED
|
@@ -87,6 +87,23 @@ export declare const keysHeldEntries: import("drizzle-orm/pg-core").PgTableWithC
|
|
|
87
87
|
identity: undefined;
|
|
88
88
|
generated: undefined;
|
|
89
89
|
}, {}, {}>;
|
|
90
|
+
kind: import("drizzle-orm/pg-core").PgColumn<{
|
|
91
|
+
name: "kind";
|
|
92
|
+
tableName: "keys_held_entries";
|
|
93
|
+
dataType: "string";
|
|
94
|
+
columnType: "PgText";
|
|
95
|
+
data: string;
|
|
96
|
+
driverParam: string;
|
|
97
|
+
notNull: false;
|
|
98
|
+
hasDefault: false;
|
|
99
|
+
isPrimaryKey: false;
|
|
100
|
+
isAutoincrement: false;
|
|
101
|
+
hasRuntimeDefault: false;
|
|
102
|
+
enumValues: [string, ...string[]];
|
|
103
|
+
baseColumn: never;
|
|
104
|
+
identity: undefined;
|
|
105
|
+
generated: undefined;
|
|
106
|
+
}, {}, {}>;
|
|
90
107
|
createdAt: import("drizzle-orm/pg-core").PgColumn<{
|
|
91
108
|
name: "created_at";
|
|
92
109
|
tableName: "keys_held_entries";
|
package/dist/held/schema.js
CHANGED
|
@@ -24,6 +24,18 @@ export const keysHeldEntries = pgTable('keys_held_entries', {
|
|
|
24
24
|
* per entry, rather than on a row this package doesn't own.
|
|
25
25
|
*/
|
|
26
26
|
tenantArchivedAt: timestamp('tenant_archived_at', { withTimezone: true }),
|
|
27
|
+
/**
|
|
28
|
+
* `null` for an ordinary held key, or `MIGRATION_CREDENTIAL_KIND`
|
|
29
|
+
* (#110): set once, at the entry's first `put`, never changed after --
|
|
30
|
+
* `migrations/held/0005_keys_held_migration_credential.sql`'s CHECK
|
|
31
|
+
* only widens by adding a kind, so a stray write to any other value is
|
|
32
|
+
* refused at the database, not just by this package's own code. A
|
|
33
|
+
* migration credential reads every mailbox of every open grant for its
|
|
34
|
+
* provider, so it carries a zero-day shred delay instead of the
|
|
35
|
+
* estate's ordinary 30 (same migration's `keys_shred_delay_days`) and a
|
|
36
|
+
* required permission check (`./index.ts`'s `checkKindPermission`).
|
|
37
|
+
*/
|
|
38
|
+
kind: text('kind'),
|
|
27
39
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
|
28
40
|
}, (table) => [primaryKey({ columns: [table.tenantId, table.entryId] })]);
|
|
29
41
|
/** Append-only in spirit: nothing here updates a row except `current_version`, `revoked_at` and, from #232 on, `wrapped_key`. */
|
package/dist/held/shred.d.ts
CHANGED
|
@@ -5,6 +5,12 @@ import type { HeldKeysDb } from './index.js';
|
|
|
5
5
|
* no row-targeting argument itself, matching the function: the function
|
|
6
6
|
* decides eligibility on its own from `retired_at`, `revoked_at` and
|
|
7
7
|
* `tenant_archived_at`, never from anything this caller supplies.
|
|
8
|
+
*
|
|
9
|
+
* A shred nulls the `wrapped_key` column of the live row and nothing else.
|
|
10
|
+
* A backup or replica taken earlier still holds the wrapped key, which
|
|
11
|
+
* stays unwrappable while the key-encryption key lives, so a version is
|
|
12
|
+
* gone from every copy only after the last such backup expires: day 60 or
|
|
13
|
+
* later for the 30-day delay, not day 30.
|
|
8
14
|
*/
|
|
9
15
|
export declare function shredExpired(db: HeldKeysDb): Promise<number>;
|
|
10
16
|
/** Which of #232's three shred-eligibility clocks a version's is. */
|
package/dist/held/shred.js
CHANGED
|
@@ -6,6 +6,12 @@ import { keysHeldEntries, keysHeldVersions } from './schema.js';
|
|
|
6
6
|
* no row-targeting argument itself, matching the function: the function
|
|
7
7
|
* decides eligibility on its own from `retired_at`, `revoked_at` and
|
|
8
8
|
* `tenant_archived_at`, never from anything this caller supplies.
|
|
9
|
+
*
|
|
10
|
+
* A shred nulls the `wrapped_key` column of the live row and nothing else.
|
|
11
|
+
* A backup or replica taken earlier still holds the wrapped key, which
|
|
12
|
+
* stays unwrappable while the key-encryption key lives, so a version is
|
|
13
|
+
* gone from every copy only after the last such backup expires: day 60 or
|
|
14
|
+
* later for the 30-day delay, not day 30.
|
|
9
15
|
*/
|
|
10
16
|
export async function shredExpired(db) {
|
|
11
17
|
const result = await db.execute(sql `select keys_shred_expired() as n`);
|
|
@@ -24,8 +24,15 @@ export interface SealedHeld {
|
|
|
24
24
|
ct: string;
|
|
25
25
|
version: number;
|
|
26
26
|
}
|
|
27
|
-
/**
|
|
28
|
-
|
|
27
|
+
/**
|
|
28
|
+
* Local refusals plus the Worker's own code, verbatim. Never carries a value or a key.
|
|
29
|
+
* `transport`: the Worker call threw or rejected. `version_mismatch`: the sealed
|
|
30
|
+
* record's version is not the `expectedVersion` the caller pinned.
|
|
31
|
+
* Closed list: `HELD_EDGE_ERROR_CODES`.
|
|
32
|
+
*/
|
|
33
|
+
export type HeldEdgeErrorCode = WorkerErrorCode | 'bad_request' | 'unseal_failed' | 'timeout' | 'transport' | 'version_mismatch';
|
|
34
|
+
/** Every member of `HeldEdgeErrorCode`. Adding one is a major change after 1.0.0. */
|
|
35
|
+
export declare const HELD_EDGE_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", "bad_request", "unseal_failed", "timeout", "transport", "version_mismatch"];
|
|
29
36
|
export declare class HeldEdgeError extends Error {
|
|
30
37
|
readonly code: HeldEdgeErrorCode;
|
|
31
38
|
constructor(code: HeldEdgeErrorCode, message?: string);
|
|
@@ -45,6 +52,14 @@ export interface SealHeldOptions extends CallOptions {
|
|
|
45
52
|
}
|
|
46
53
|
export interface OpenHeldOptions extends CallOptions {
|
|
47
54
|
readonly sealed: SealedHeld;
|
|
55
|
+
/**
|
|
56
|
+
* The version the caller expects. Without it the version is read from `sealed`, so
|
|
57
|
+
* anyone who can write the caller's storage can swap in the same entry's older
|
|
58
|
+
* sealed record and have it open. Pin it wherever the storage writer cannot reach
|
|
59
|
+
* (a version kept in a separate, better-guarded place). A different version is
|
|
60
|
+
* refused as `version_mismatch` before any Worker call.
|
|
61
|
+
*/
|
|
62
|
+
readonly expectedVersion?: number;
|
|
48
63
|
}
|
|
49
64
|
export declare function sealHeld(o: SealHeldOptions): Promise<SealedHeld>;
|
|
50
65
|
export declare function openHeld(o: OpenHeldOptions): Promise<string>;
|
package/dist/held-edge/index.js
CHANGED
|
@@ -12,13 +12,22 @@ import { encodeAad } from '../held/aad.js';
|
|
|
12
12
|
* and constants from `../worker-contract.ts`. The `WorkerClient` is injected
|
|
13
13
|
* (`createWorkerClient` from `../worker` needs `nodejs_compat`).
|
|
14
14
|
*/
|
|
15
|
-
import { ID_PATTERN, } from '../worker-contract.js';
|
|
15
|
+
import { ID_PATTERN, WORKER_ERROR_CODES, } from '../worker-contract.js';
|
|
16
16
|
export { encodeAad } from '../held/aad.js';
|
|
17
17
|
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
18
18
|
const IV_BYTES = 12;
|
|
19
19
|
const DATA_KEY_BYTES = 32;
|
|
20
20
|
const WRAPPED_KEY_BYTES = 60;
|
|
21
21
|
const TAG_BYTES = 16;
|
|
22
|
+
/** Every member of `HeldEdgeErrorCode`. Adding one is a major change after 1.0.0. */
|
|
23
|
+
export const HELD_EDGE_ERROR_CODES = [
|
|
24
|
+
...WORKER_ERROR_CODES,
|
|
25
|
+
'bad_request',
|
|
26
|
+
'unseal_failed',
|
|
27
|
+
'timeout',
|
|
28
|
+
'transport',
|
|
29
|
+
'version_mismatch',
|
|
30
|
+
];
|
|
22
31
|
export class HeldEdgeError extends Error {
|
|
23
32
|
code;
|
|
24
33
|
constructor(code, message) {
|
|
@@ -69,14 +78,34 @@ function checkTimeout(timeoutMs) {
|
|
|
69
78
|
}
|
|
70
79
|
return ms;
|
|
71
80
|
}
|
|
72
|
-
|
|
81
|
+
function zeroKey(result) {
|
|
82
|
+
if (result?.ok && result.dataKey instanceof Uint8Array)
|
|
83
|
+
result.dataKey.fill(0);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Races the Worker call against a timer; the timer is always cleared. A call that
|
|
87
|
+
* settles after the timeout has its data key zeroed. A throw or rejection from the
|
|
88
|
+
* Worker call becomes `transport`; the cause is dropped, as it can carry the request.
|
|
89
|
+
*/
|
|
73
90
|
async function withTimeout(call, ms) {
|
|
74
91
|
let timer;
|
|
75
|
-
const
|
|
76
|
-
|
|
92
|
+
const timedOut = Symbol('timeout');
|
|
93
|
+
const timeout = new Promise((resolve) => {
|
|
94
|
+
timer = setTimeout(() => resolve(timedOut), ms);
|
|
77
95
|
});
|
|
96
|
+
const started = (async () => call())();
|
|
78
97
|
try {
|
|
79
|
-
|
|
98
|
+
const winner = await Promise.race([started, timeout]);
|
|
99
|
+
if (winner === timedOut) {
|
|
100
|
+
started.then(zeroKey, () => undefined);
|
|
101
|
+
throw new HeldEdgeError('timeout', 'custody Worker timed out');
|
|
102
|
+
}
|
|
103
|
+
return winner;
|
|
104
|
+
}
|
|
105
|
+
catch (e) {
|
|
106
|
+
if (e instanceof HeldEdgeError)
|
|
107
|
+
throw e;
|
|
108
|
+
throw new HeldEdgeError('transport', 'custody Worker call failed');
|
|
80
109
|
}
|
|
81
110
|
finally {
|
|
82
111
|
clearTimeout(timer);
|
|
@@ -87,8 +116,11 @@ function fromWorker(code) {
|
|
|
87
116
|
return new HeldEdgeError(code, `custody Worker refused: ${code}`);
|
|
88
117
|
}
|
|
89
118
|
async function importDataKey(dataKey, usage) {
|
|
90
|
-
if (dataKey.length !== DATA_KEY_BYTES)
|
|
91
|
-
throw
|
|
119
|
+
if (dataKey.length !== DATA_KEY_BYTES) {
|
|
120
|
+
throw usage === 'encrypt'
|
|
121
|
+
? new HeldEdgeError('bad_request', 'custody worker returned a data key of the wrong length')
|
|
122
|
+
: new HeldEdgeError('unseal_failed');
|
|
123
|
+
}
|
|
92
124
|
return crypto.subtle.importKey('raw', dataKey, { name: 'AES-GCM' }, false, [usage]);
|
|
93
125
|
}
|
|
94
126
|
export async function sealHeld(o) {
|
|
@@ -97,10 +129,14 @@ export async function sealHeld(o) {
|
|
|
97
129
|
if (typeof o.plaintext !== 'string') {
|
|
98
130
|
throw new HeldEdgeError('bad_request', 'plaintext must be a string');
|
|
99
131
|
}
|
|
132
|
+
// TextEncoder turns a lone surrogate into U+FFFD, so the value would open as a different string.
|
|
133
|
+
if (!o.plaintext.isWellFormed()) {
|
|
134
|
+
throw new HeldEdgeError('bad_request', 'plaintext is not well-formed UTF-16');
|
|
135
|
+
}
|
|
100
136
|
const ms = checkTimeout(o.timeoutMs);
|
|
101
137
|
const binding = { tenantId: o.tenantId, entryId: o.entryId, version: o.version };
|
|
102
138
|
const aad = encodeAad(binding);
|
|
103
|
-
const result = await withTimeout(o.worker.wrap({ requestId: crypto.randomUUID(), credential: o.credential, binding }), ms);
|
|
139
|
+
const result = await withTimeout(() => o.worker.wrap({ requestId: crypto.randomUUID(), credential: o.credential, binding }), ms);
|
|
104
140
|
if (!result.ok)
|
|
105
141
|
throw fromWorker(result.error.code);
|
|
106
142
|
const dataKey = result.dataKey;
|
|
@@ -132,6 +168,12 @@ export async function openHeld(o) {
|
|
|
132
168
|
throw new HeldEdgeError('bad_request', 'sealed is not a v1 SealedHeld');
|
|
133
169
|
}
|
|
134
170
|
checkVersion(s.version);
|
|
171
|
+
if (o.expectedVersion !== undefined) {
|
|
172
|
+
checkVersion(o.expectedVersion);
|
|
173
|
+
if (s.version !== o.expectedVersion) {
|
|
174
|
+
throw new HeldEdgeError('version_mismatch', 'sealed.version is not the expected version');
|
|
175
|
+
}
|
|
176
|
+
}
|
|
135
177
|
if (typeof s.kekId !== 'string' || !ID_PATTERN.test(s.kekId)) {
|
|
136
178
|
throw new HeldEdgeError('bad_request', 'sealed.kekId does not match the id pattern');
|
|
137
179
|
}
|
|
@@ -147,7 +189,7 @@ export async function openHeld(o) {
|
|
|
147
189
|
const ms = checkTimeout(o.timeoutMs);
|
|
148
190
|
const binding = { tenantId: o.tenantId, entryId: o.entryId, version: s.version };
|
|
149
191
|
const aad = encodeAad(binding);
|
|
150
|
-
const result = await withTimeout(o.worker.unwrap({
|
|
192
|
+
const result = await withTimeout(() => o.worker.unwrap({
|
|
151
193
|
requestId: crypto.randomUUID(),
|
|
152
194
|
credential: o.credential,
|
|
153
195
|
kekId: s.kekId,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { safeEqual } from '@wtfalch/utils/crypto';
|
|
2
2
|
import { and, asc, gte, inArray, isNotNull, lt } from 'drizzle-orm';
|
|
3
3
|
import { keysHostEvents } from './schema.js';
|
|
4
4
|
/**
|
|
@@ -37,12 +37,6 @@ const unauthorized = () => jsonResponse({ error: { code: 'unauthorized' } }, 401
|
|
|
37
37
|
const badRequest = () => jsonResponse({ error: { code: 'bad_request' } }, 400);
|
|
38
38
|
const windowTooLarge = () => jsonResponse({ error: { code: 'window_too_large' } }, 413);
|
|
39
39
|
const methodNotAllowed = () => jsonResponse({ error: { code: 'method_not_allowed' } }, 405);
|
|
40
|
-
/** Constant-time regardless of length: both sides are always a 32-byte SHA-256 digest, so `timingSafeEqual` never throws on a length mismatch here. */
|
|
41
|
-
function tokensMatch(presented, configured) {
|
|
42
|
-
const a = createHash('sha256').update(presented, 'utf8').digest();
|
|
43
|
-
const b = createHash('sha256').update(configured, 'utf8').digest();
|
|
44
|
-
return timingSafeEqual(a, b);
|
|
45
|
-
}
|
|
46
40
|
/** `Number(bigint)` past this silently rounds, which would let `since`/`until` collapse together after conversion even though the `bigint` comparison above said they didn't. 16 digits alone doesn't rule that out, so bound it explicitly too. */
|
|
47
41
|
const MAX_SAFE_WINDOW_PARAM = BigInt(Number.MAX_SAFE_INTEGER);
|
|
48
42
|
/** A decimal-integer query param, or `null` for anything else -- absent, empty, signed, fractional, exponential, over 16 digits, or past `Number.MAX_SAFE_INTEGER`. */
|
|
@@ -68,7 +62,7 @@ export function auditEndpoint(options) {
|
|
|
68
62
|
if (!token || token.length < 32)
|
|
69
63
|
return unavailable();
|
|
70
64
|
const match = BEARER_PATTERN.exec(request.headers.get('authorization') ?? '');
|
|
71
|
-
if (!match?.[1] || !
|
|
65
|
+
if (!match?.[1] || !safeEqual(match[1], token))
|
|
72
66
|
return unauthorized();
|
|
73
67
|
const url = new URL(request.url);
|
|
74
68
|
const since = parseWindowParam(url.searchParams.get('since'));
|