@wtfalch/keys 0.8.0 → 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 +244 -27
- package/dist/held/index.d.ts +116 -6
- package/dist/held/index.js +259 -37
- package/dist/held/schema.d.ts +17 -0
- package/dist/held/schema.js +12 -0
- package/dist/held/seal.d.ts +1 -1
- package/dist/held/seal.js +1 -1
- package/dist/held/shred.d.ts +6 -0
- package/dist/held/shred.js +6 -0
- package/dist/held/tenant.d.ts +2 -0
- package/dist/held/tenant.js +46 -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 +13 -0
- package/dist/host/company-registrar-keys.js +6 -8
- package/dist/host/events.d.ts +19 -3
- package/dist/host/events.js +56 -20
- package/dist/host/index.d.ts +9 -2
- package/dist/host/index.js +9 -2
- package/dist/host/native-build.d.ts +126 -0
- package/dist/host/native-build.js +322 -0
- package/dist/host/registrar.d.ts +10 -4
- package/dist/host/registrar.js +64 -42
- 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/migrations/tenant-rows/0001_keys_tenant_rows.sql +63 -0
- package/dist/migrations-dir.d.ts +9 -0
- package/dist/migrations-dir.js +9 -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/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 -7
- package/dist/testing/index.d.ts +0 -9
- package/dist/testing/index.js +0 -9
- package/dist/testing/worker-stub.d.ts +0 -55
- package/dist/testing/worker-stub.js +0 -180
package/dist/held/index.js
CHANGED
|
@@ -1,13 +1,33 @@
|
|
|
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';
|
|
7
|
+
import { inTenant } from './tenant.js';
|
|
6
8
|
export { encodeAad } from './aad.js';
|
|
9
|
+
export { WORKER_ERROR_CODES };
|
|
7
10
|
export { shredClocks, shredExpired } from './shred.js';
|
|
11
|
+
/**
|
|
12
|
+
* The one held-entry kind this package itself knows about (#110). `null`
|
|
13
|
+
* (the default) is an ordinary held key. `migrations/held/0005_keys_held_migration_credential.sql`'s
|
|
14
|
+
* CHECK is the actual enforcement; this constant is so a host spells the
|
|
15
|
+
* same string everywhere rather than retyping it.
|
|
16
|
+
*/
|
|
17
|
+
export const MIGRATION_CREDENTIAL_KIND = 'migration_credential';
|
|
8
18
|
const IV_BYTES = 12;
|
|
9
19
|
const TAG_BYTES = 16;
|
|
10
20
|
const ALGORITHM = 'aes-256-gcm';
|
|
21
|
+
/** Every member of `HeldKeysErrorCode`. Adding one is a major change after 1.0.0. */
|
|
22
|
+
export const HELD_KEYS_ERROR_CODES = [
|
|
23
|
+
...WORKER_ERROR_CODES,
|
|
24
|
+
'not_found',
|
|
25
|
+
'revoked',
|
|
26
|
+
'unseal_failed',
|
|
27
|
+
'disposed',
|
|
28
|
+
'invalidated',
|
|
29
|
+
'forbidden',
|
|
30
|
+
];
|
|
11
31
|
/**
|
|
12
32
|
* Thrown by `put`, `open` and `rewrap`. Never carries a value or a key --
|
|
13
33
|
* only what a caller can act on: which entry, which code, and (for
|
|
@@ -148,33 +168,99 @@ export function createHeldKeys(options) {
|
|
|
148
168
|
evict(key, hit);
|
|
149
169
|
}
|
|
150
170
|
}
|
|
151
|
-
|
|
171
|
+
/**
|
|
172
|
+
* `undefined` when `entry` does not exist yet -- distinct from an
|
|
173
|
+
* existing entry whose own stored `kind` is `null` (an ordinary held
|
|
174
|
+
* key), which a caller must not treat the same way `put`'s own
|
|
175
|
+
* `onConflictDoNothing` would make the opposite mistake look harmless.
|
|
176
|
+
* No lock: kind is set once at an entry's creation and never changes, so
|
|
177
|
+
* reading it outside `put`'s own transaction cannot race with anything
|
|
178
|
+
* that would change the answer.
|
|
179
|
+
*/
|
|
180
|
+
async function existingEntry(entry) {
|
|
181
|
+
const [row] = await inTenant(db, entry.tenantId, (tx) => tx
|
|
182
|
+
.select({ kind: keysHeldEntries.kind })
|
|
183
|
+
.from(keysHeldEntries)
|
|
184
|
+
.where(and(eq(keysHeldEntries.tenantId, entry.tenantId), eq(keysHeldEntries.entryId, entry.entryId)))
|
|
185
|
+
.limit(1));
|
|
186
|
+
if (!row)
|
|
187
|
+
return undefined;
|
|
188
|
+
return { kind: row.kind ?? null };
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Run before `put`, `open`, `openCurrent` and `revokeEntry` touch an
|
|
192
|
+
* entry whose effective kind -- the stored one, or, for a brand-new
|
|
193
|
+
* entry, the one about to be stored -- is not `null`. Fail-closed: a
|
|
194
|
+
* gated kind with no `checkKindPermission` wired refuses rather than
|
|
195
|
+
* behaving like an ordinary held key. Called outside any transaction and
|
|
196
|
+
* before any row lock is taken, so a slow or network-backed permission
|
|
197
|
+
* check never holds a Postgres lock open, the same reason `put`'s own
|
|
198
|
+
* Worker call runs after its transaction commits.
|
|
199
|
+
*/
|
|
200
|
+
async function requireKindPermission(kind, entry) {
|
|
201
|
+
if (kind === null)
|
|
202
|
+
return;
|
|
203
|
+
if (!options.checkKindPermission) {
|
|
204
|
+
throw new HeldKeysError('forbidden', `entry ${entry.entryId} is kind ${kind}, which has no checkKindPermission wired`);
|
|
205
|
+
}
|
|
206
|
+
await options.checkKindPermission({ kind, tenantId: entry.tenantId, entryId: entry.entryId });
|
|
207
|
+
}
|
|
208
|
+
async function put(entry, value, putOptions) {
|
|
152
209
|
requireActive();
|
|
153
210
|
requireId(entry.tenantId, 'tenantId');
|
|
154
211
|
requireId(entry.entryId, 'entryId');
|
|
212
|
+
// Kind is set once, at creation: an existing entry's own stored kind
|
|
213
|
+
// always wins over a different kind passed here, the same way a
|
|
214
|
+
// second put() cannot un-revoke or un-archive one -- including an
|
|
215
|
+
// existing *ordinary* entry (kind null), which must not fall through
|
|
216
|
+
// to a `kind` option a caller passes by mistake on a later put.
|
|
217
|
+
const requestedKind = putOptions?.kind ?? null;
|
|
218
|
+
if (requestedKind !== null && requestedKind !== MIGRATION_CREDENTIAL_KIND) {
|
|
219
|
+
throw new HeldKeysError('bad_request', 'kind is not a known held entry kind');
|
|
220
|
+
}
|
|
221
|
+
const existing = await existingEntry(entry);
|
|
222
|
+
const effectiveKind = existing ? existing.kind : requestedKind;
|
|
223
|
+
await requireKindPermission(effectiveKind, entry);
|
|
155
224
|
// Reserve the next version number under a row lock, and nothing else:
|
|
156
225
|
// the lock is released the instant this short transaction commits, so a
|
|
157
226
|
// slow or unreachable Worker (the next step, outside any lock) cannot
|
|
158
227
|
// hold up a concurrent revokeEntry or another put on the same entry.
|
|
159
228
|
// Losing a version number to a failed wrap is harmless; holding a
|
|
160
229
|
// Postgres lock open across a network call to the Worker is not.
|
|
161
|
-
const version = await db.
|
|
230
|
+
const version = await inTenant(db, entry.tenantId, async (tx) => {
|
|
162
231
|
await tx
|
|
163
232
|
.insert(keysHeldEntries)
|
|
164
|
-
.values({
|
|
233
|
+
.values({
|
|
234
|
+
tenantId: entry.tenantId,
|
|
235
|
+
entryId: entry.entryId,
|
|
236
|
+
currentVersion: 0,
|
|
237
|
+
kind: effectiveKind,
|
|
238
|
+
})
|
|
165
239
|
.onConflictDoNothing();
|
|
166
240
|
const [row] = await tx
|
|
167
241
|
.select({
|
|
168
242
|
currentVersion: keysHeldEntries.currentVersion,
|
|
243
|
+
kind: keysHeldEntries.kind,
|
|
169
244
|
revokedAt: keysHeldEntries.revokedAt,
|
|
245
|
+
tenantArchivedAt: keysHeldEntries.tenantArchivedAt,
|
|
170
246
|
})
|
|
171
247
|
.from(keysHeldEntries)
|
|
172
248
|
.where(and(eq(keysHeldEntries.tenantId, entry.tenantId), eq(keysHeldEntries.entryId, entry.entryId)))
|
|
173
249
|
.for('update');
|
|
174
250
|
if (!row)
|
|
175
251
|
throw new HeldKeysError('not_found', 'the entry vanished mid-transaction');
|
|
252
|
+
// Another put created the entry between the permission check above and
|
|
253
|
+
// this insert: the permission check named the wrong kind. Refuse rather
|
|
254
|
+
// than add a version under a kind nobody was checked for.
|
|
255
|
+
if ((row.kind ?? null) !== effectiveKind) {
|
|
256
|
+
throw new HeldKeysError('bad_request', `entry ${entry.entryId} was created with another kind`);
|
|
257
|
+
}
|
|
176
258
|
if (row.revokedAt)
|
|
177
259
|
throw new HeldKeysError('revoked', `entry ${entry.entryId} is revoked`);
|
|
260
|
+
// The shred sweep would count a new version on the tenant's archive clock.
|
|
261
|
+
if (row.tenantArchivedAt) {
|
|
262
|
+
throw new HeldKeysError('revoked', `tenant ${entry.tenantId} is archived`);
|
|
263
|
+
}
|
|
178
264
|
const next = row.currentVersion + 1;
|
|
179
265
|
await tx
|
|
180
266
|
.update(keysHeldEntries)
|
|
@@ -190,15 +276,46 @@ export function createHeldKeys(options) {
|
|
|
190
276
|
try {
|
|
191
277
|
const aad = encodeAad(binding);
|
|
192
278
|
const sealed = gcmSeal(dataKey, Buffer.from(value, 'utf8'), aad);
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
279
|
+
try {
|
|
280
|
+
const publish = (handle) => handle.insert(keysHeldVersions).values({
|
|
281
|
+
tenantId: entry.tenantId,
|
|
282
|
+
entryId: entry.entryId,
|
|
283
|
+
version,
|
|
284
|
+
kekId: result.kekId,
|
|
285
|
+
wrappedKey: Buffer.from(result.wrappedKey),
|
|
286
|
+
iv: sealed.iv,
|
|
287
|
+
ciphertext: sealed.ciphertext,
|
|
288
|
+
});
|
|
289
|
+
const auditTx = options.auditInTransaction;
|
|
290
|
+
if (auditTx) {
|
|
291
|
+
await inTenant(db, entry.tenantId, async (tx) => {
|
|
292
|
+
await publish(tx);
|
|
293
|
+
await auditTx(tx, {
|
|
294
|
+
name: 'held.put',
|
|
295
|
+
tenantId: entry.tenantId,
|
|
296
|
+
entryId: entry.entryId,
|
|
297
|
+
version,
|
|
298
|
+
at: now(),
|
|
299
|
+
});
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
else {
|
|
303
|
+
await inTenant(db, entry.tenantId, async (tx) => {
|
|
304
|
+
await publish(tx);
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
catch (err) {
|
|
309
|
+
// keys_held_versions_publish_guard refuses the insert of a revoked entry
|
|
310
|
+
// or an archived tenant's entry.
|
|
311
|
+
if (isGuardError(err, 'held entry is revoked')) {
|
|
312
|
+
throw new HeldKeysError('revoked', `entry ${entry.entryId} is revoked`);
|
|
313
|
+
}
|
|
314
|
+
if (isGuardError(err, 'held tenant is archived')) {
|
|
315
|
+
throw new HeldKeysError('revoked', `tenant ${entry.tenantId} is archived`);
|
|
316
|
+
}
|
|
317
|
+
throw err;
|
|
318
|
+
}
|
|
202
319
|
// Retiring the version this one supersedes is a side effect of the
|
|
203
320
|
// INSERT above, not a second write here: keys_held_versions_retire_predecessors
|
|
204
321
|
// (#232's migration), an AFTER INSERT, SECURITY DEFINER trigger, sets
|
|
@@ -221,7 +338,7 @@ export function createHeldKeys(options) {
|
|
|
221
338
|
forgetEntry(entry);
|
|
222
339
|
return { version };
|
|
223
340
|
}
|
|
224
|
-
async function openSelected(binding, versionRow, openingEpoch, use) {
|
|
341
|
+
async function openSelected(binding, versionRow, openingEpoch, use, kind) {
|
|
225
342
|
if (versionRow.wrappedKey === null) {
|
|
226
343
|
throw new HeldKeysError('not_found', `version ${binding.version} has been shredded`);
|
|
227
344
|
}
|
|
@@ -253,7 +370,14 @@ export function createHeldKeys(options) {
|
|
|
253
370
|
requireActive();
|
|
254
371
|
if (epoch !== openingEpoch)
|
|
255
372
|
throw new HeldKeysError('invalidated');
|
|
256
|
-
|
|
373
|
+
// A gated kind is never remembered: #110 wants one audit row for
|
|
374
|
+
// every single use ("each use... so there is one audit row for each
|
|
375
|
+
// use"), and the accepted-key cache's whole point is to let a later
|
|
376
|
+
// call skip the audit above (ADR 0019) -- so a gated entry is simply
|
|
377
|
+
// never placed in it, which also means it can never satisfy a cache
|
|
378
|
+
// hit later in this process.
|
|
379
|
+
if (kind === null)
|
|
380
|
+
remember(binding, dataKey, versionRow.iv, versionRow.ciphertext, until);
|
|
257
381
|
dataKey.fill(0);
|
|
258
382
|
return use(value);
|
|
259
383
|
}
|
|
@@ -272,16 +396,18 @@ export function createHeldKeys(options) {
|
|
|
272
396
|
const value = gcmOpen(cached.dataKey, cached.iv, cached.ciphertext, encodeAad(binding));
|
|
273
397
|
return use(value);
|
|
274
398
|
}
|
|
275
|
-
const [entryRow] = await db
|
|
276
|
-
.select({ revokedAt: keysHeldEntries.revokedAt })
|
|
399
|
+
const [entryRow] = await inTenant(db, binding.tenantId, (tx) => tx
|
|
400
|
+
.select({ revokedAt: keysHeldEntries.revokedAt, kind: keysHeldEntries.kind })
|
|
277
401
|
.from(keysHeldEntries)
|
|
278
402
|
.where(and(eq(keysHeldEntries.tenantId, binding.tenantId), eq(keysHeldEntries.entryId, binding.entryId)))
|
|
279
|
-
.limit(1);
|
|
403
|
+
.limit(1));
|
|
280
404
|
if (!entryRow)
|
|
281
405
|
throw new HeldKeysError('not_found', `there is no entry ${binding.entryId}`);
|
|
282
406
|
if (entryRow.revokedAt)
|
|
283
407
|
throw new HeldKeysError('revoked', `entry ${binding.entryId} is revoked`);
|
|
284
|
-
const
|
|
408
|
+
const kind = entryRow.kind ?? null;
|
|
409
|
+
await requireKindPermission(kind, binding);
|
|
410
|
+
const [versionRow] = await inTenant(db, binding.tenantId, (tx) => tx
|
|
285
411
|
.select({
|
|
286
412
|
kekId: keysHeldVersions.kekId,
|
|
287
413
|
wrappedKey: keysHeldVersions.wrappedKey,
|
|
@@ -290,10 +416,10 @@ export function createHeldKeys(options) {
|
|
|
290
416
|
})
|
|
291
417
|
.from(keysHeldVersions)
|
|
292
418
|
.where(and(eq(keysHeldVersions.tenantId, binding.tenantId), eq(keysHeldVersions.entryId, binding.entryId), eq(keysHeldVersions.version, binding.version)))
|
|
293
|
-
.limit(1);
|
|
419
|
+
.limit(1));
|
|
294
420
|
if (!versionRow)
|
|
295
421
|
throw new HeldKeysError('not_found', `there is no version ${binding.version}`);
|
|
296
|
-
return openSelected(binding, versionRow, openingEpoch, use);
|
|
422
|
+
return openSelected(binding, versionRow, openingEpoch, use, kind);
|
|
297
423
|
}
|
|
298
424
|
async function openCurrent(entry, use) {
|
|
299
425
|
requireActive();
|
|
@@ -303,12 +429,13 @@ export function createHeldKeys(options) {
|
|
|
303
429
|
// One statement chooses both the entry state and the highest version row
|
|
304
430
|
// visible in its snapshot. In particular, current_version is deliberately
|
|
305
431
|
// absent: put reserves it before the Worker call and may never publish the
|
|
306
|
-
// corresponding version row.
|
|
307
|
-
//
|
|
308
|
-
//
|
|
309
|
-
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
|
|
310
436
|
.select({
|
|
311
437
|
revokedAt: keysHeldEntries.revokedAt,
|
|
438
|
+
kind: keysHeldEntries.kind,
|
|
312
439
|
version: keysHeldVersions.version,
|
|
313
440
|
kekId: keysHeldVersions.kekId,
|
|
314
441
|
wrappedKey: keysHeldVersions.wrappedKey,
|
|
@@ -319,11 +446,13 @@ export function createHeldKeys(options) {
|
|
|
319
446
|
.leftJoin(keysHeldVersions, and(eq(keysHeldVersions.tenantId, keysHeldEntries.tenantId), eq(keysHeldVersions.entryId, keysHeldEntries.entryId)))
|
|
320
447
|
.where(and(eq(keysHeldEntries.tenantId, entry.tenantId), eq(keysHeldEntries.entryId, entry.entryId)))
|
|
321
448
|
.orderBy(desc(keysHeldVersions.version))
|
|
322
|
-
.limit(1);
|
|
449
|
+
.limit(1));
|
|
323
450
|
if (!selected)
|
|
324
451
|
throw new HeldKeysError('not_found', `there is no entry ${entry.entryId}`);
|
|
325
452
|
if (selected.revokedAt)
|
|
326
453
|
throw new HeldKeysError('revoked', `entry ${entry.entryId} is revoked`);
|
|
454
|
+
const kind = selected.kind ?? null;
|
|
455
|
+
await requireKindPermission(kind, entry);
|
|
327
456
|
if (selected.version === null ||
|
|
328
457
|
selected.kekId === null ||
|
|
329
458
|
selected.iv === null ||
|
|
@@ -345,7 +474,7 @@ export function createHeldKeys(options) {
|
|
|
345
474
|
const value = gcmOpen(cached.dataKey, cached.iv, cached.ciphertext, encodeAad(binding));
|
|
346
475
|
return use(value);
|
|
347
476
|
}
|
|
348
|
-
return openSelected(binding, versionRow, openingEpoch, use);
|
|
477
|
+
return openSelected(binding, versionRow, openingEpoch, use, kind);
|
|
349
478
|
}
|
|
350
479
|
async function rewrap(rewrapOptions) {
|
|
351
480
|
requireActive();
|
|
@@ -361,6 +490,7 @@ export function createHeldKeys(options) {
|
|
|
361
490
|
})
|
|
362
491
|
.from(keysHeldVersions)
|
|
363
492
|
.where(and(eq(keysHeldVersions.kekId, kekIdOld), sql `${keysHeldVersions.wrappedKey} is not null`));
|
|
493
|
+
let rewrapped = 0;
|
|
364
494
|
for (const row of rows) {
|
|
365
495
|
if (row.wrappedKey === null)
|
|
366
496
|
continue; // shredded between the read above and this row; nothing to rewrap
|
|
@@ -379,26 +509,98 @@ export function createHeldKeys(options) {
|
|
|
379
509
|
});
|
|
380
510
|
if (!result.ok)
|
|
381
511
|
throw HeldKeysError.fromWorker(result.error);
|
|
382
|
-
await db
|
|
512
|
+
const updated = await db
|
|
383
513
|
.update(keysHeldVersions)
|
|
384
514
|
.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)))
|
|
515
|
+
.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)))
|
|
516
|
+
.returning({ version: keysHeldVersions.version });
|
|
517
|
+
rewrapped += updated.length;
|
|
386
518
|
}
|
|
519
|
+
return { rewrapped };
|
|
520
|
+
}
|
|
521
|
+
async function countNotUnder(kekId) {
|
|
522
|
+
requireActive();
|
|
523
|
+
requireId(kekId, 'kekId');
|
|
524
|
+
const [row] = await db
|
|
525
|
+
.select({ n: sql `count(*)::integer` })
|
|
526
|
+
.from(keysHeldVersions)
|
|
527
|
+
.where(and(isNotNull(keysHeldVersions.wrappedKey), ne(keysHeldVersions.kekId, kekId)));
|
|
528
|
+
return Number(row?.n ?? 0);
|
|
529
|
+
}
|
|
530
|
+
async function kekIdsInUse() {
|
|
531
|
+
requireActive();
|
|
532
|
+
const rows = await db
|
|
533
|
+
.selectDistinct({ kekId: keysHeldVersions.kekId })
|
|
534
|
+
.from(keysHeldVersions)
|
|
535
|
+
.where(isNotNull(keysHeldVersions.wrappedKey));
|
|
536
|
+
return rows.map((r) => r.kekId).sort();
|
|
387
537
|
}
|
|
388
538
|
async function revokeEntry(entry) {
|
|
389
539
|
requireActive();
|
|
390
540
|
requireId(entry.tenantId, 'tenantId');
|
|
391
541
|
requireId(entry.entryId, 'entryId');
|
|
542
|
+
await requireKindPermission((await existingEntry(entry))?.kind ?? null, entry);
|
|
392
543
|
// The `revoked_at is null` guard makes a second call a no-op rather than
|
|
393
544
|
// re-dating the revocation: an operator investigating an incident wants
|
|
394
545
|
// the first time this entry went dark, not the last time someone called
|
|
395
546
|
// revokeEntry on an already-revoked one.
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
547
|
+
const revoke = async (handle) => {
|
|
548
|
+
const rows = await handle
|
|
549
|
+
.update(keysHeldEntries)
|
|
550
|
+
.set({ revokedAt: sql `now()` })
|
|
551
|
+
.where(and(eq(keysHeldEntries.tenantId, entry.tenantId), eq(keysHeldEntries.entryId, entry.entryId), sql `${keysHeldEntries.revokedAt} is null`))
|
|
552
|
+
.returning({ entryId: keysHeldEntries.entryId });
|
|
553
|
+
if (rows.length > 0) {
|
|
554
|
+
await options.auditInTransaction?.(handle, {
|
|
555
|
+
name: 'held.revoked',
|
|
556
|
+
tenantId: entry.tenantId,
|
|
557
|
+
entryId: entry.entryId,
|
|
558
|
+
at: now(),
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
await inTenant(db, entry.tenantId, revoke);
|
|
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');
|
|
@@ -407,10 +609,10 @@ export function createHeldKeys(options) {
|
|
|
407
609
|
// rather than re-dating it, same reasoning as revokeEntry above. A new
|
|
408
610
|
// entry put() after this call is not retroactively covered; that
|
|
409
611
|
// matches revokeEntry's own entry-scoped (not tenant-scoped) reach.
|
|
410
|
-
await db
|
|
612
|
+
await inTenant(db, tenantId, (tx) => tx
|
|
411
613
|
.update(keysHeldEntries)
|
|
412
614
|
.set({ tenantArchivedAt: sql `now()` })
|
|
413
|
-
.where(and(eq(keysHeldEntries.tenantId, tenantId), sql `${keysHeldEntries.tenantArchivedAt} is null`));
|
|
615
|
+
.where(and(eq(keysHeldEntries.tenantId, tenantId), sql `${keysHeldEntries.tenantArchivedAt} is null`)));
|
|
414
616
|
epoch++;
|
|
415
617
|
const prefix = `${tenantId} `;
|
|
416
618
|
for (const [key, hit] of cache) {
|
|
@@ -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/seal.d.ts
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 (`../
|
|
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 (`../
|
|
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/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`);
|
|
@@ -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
|
+
}
|
|
@@ -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>;
|