@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.
Files changed (68) hide show
  1. package/README.md +244 -27
  2. package/dist/held/index.d.ts +116 -6
  3. package/dist/held/index.js +259 -37
  4. package/dist/held/schema.d.ts +17 -0
  5. package/dist/held/schema.js +12 -0
  6. package/dist/held/seal.d.ts +1 -1
  7. package/dist/held/seal.js +1 -1
  8. package/dist/held/shred.d.ts +6 -0
  9. package/dist/held/shred.js +6 -0
  10. package/dist/held/tenant.d.ts +2 -0
  11. package/dist/held/tenant.js +46 -0
  12. package/dist/held-edge/index.d.ts +17 -2
  13. package/dist/held-edge/index.js +51 -9
  14. package/dist/host/audit-endpoint.js +2 -8
  15. package/dist/host/company-registrar-keys.d.ts +13 -0
  16. package/dist/host/company-registrar-keys.js +6 -8
  17. package/dist/host/events.d.ts +19 -3
  18. package/dist/host/events.js +56 -20
  19. package/dist/host/index.d.ts +9 -2
  20. package/dist/host/index.js +9 -2
  21. package/dist/host/native-build.d.ts +126 -0
  22. package/dist/host/native-build.js +322 -0
  23. package/dist/host/registrar.d.ts +10 -4
  24. package/dist/host/registrar.js +64 -42
  25. package/dist/host/rotation-sweep.d.ts +56 -0
  26. package/dist/host/rotation-sweep.js +89 -0
  27. package/dist/issued/encoding.d.ts +4 -0
  28. package/dist/issued/encoding.js +22 -0
  29. package/dist/issued/index.d.ts +148 -7
  30. package/dist/issued/index.js +320 -34
  31. package/dist/issued/resign.d.ts +16 -0
  32. package/dist/issued/resign.js +55 -2
  33. package/dist/issued/tables.d.ts +38 -0
  34. package/dist/issued/tables.js +6 -0
  35. package/dist/issued/verify.d.ts +14 -3
  36. package/dist/issued/verify.js +10 -3
  37. package/dist/migrations/held/0004_keys_archived_publish_guard.sql +46 -0
  38. package/dist/migrations/held/0005_keys_held_migration_credential.sql +216 -0
  39. package/dist/migrations/held/0006_keys_held_entries_guard.sql +54 -0
  40. package/dist/migrations/host/0002_keys_host_held_events.sql +29 -0
  41. package/dist/migrations/issued/0007_keys_purpose.sql +68 -0
  42. package/dist/migrations/issued/0008_keys_idempotency_scope.sql +23 -0
  43. package/dist/migrations/tenant-rows/0001_keys_tenant_rows.sql +63 -0
  44. package/dist/migrations-dir.d.ts +9 -0
  45. package/dist/migrations-dir.js +9 -0
  46. package/dist/service/body.d.ts +21 -0
  47. package/dist/service/body.js +128 -0
  48. package/dist/service/errors.d.ts +24 -0
  49. package/dist/service/errors.js +89 -0
  50. package/dist/service/handler.d.ts +35 -0
  51. package/dist/service/handler.js +328 -0
  52. package/dist/service/index.d.ts +7 -0
  53. package/dist/service/index.js +7 -0
  54. package/dist/service/policy.d.ts +130 -0
  55. package/dist/service/policy.js +123 -0
  56. package/dist/service/timeout.d.ts +6 -0
  57. package/dist/service/timeout.js +34 -0
  58. package/dist/webhooks.d.ts +40 -17
  59. package/dist/webhooks.js +70 -26
  60. package/dist/worker-contract.d.ts +43 -6
  61. package/dist/worker-contract.js +37 -0
  62. package/dist/worker.d.ts +1 -1
  63. package/dist/worker.js +7 -28
  64. package/package.json +21 -7
  65. package/dist/testing/index.d.ts +0 -9
  66. package/dist/testing/index.js +0 -9
  67. package/dist/testing/worker-stub.d.ts +0 -55
  68. package/dist/testing/worker-stub.js +0 -180
@@ -23,6 +23,10 @@ import { bigint, jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core';
23
23
  * `keys_issued_guard()` trigger is what keeps it trustworthy: set
24
24
  * once at `issue()`, immutable for the row's life.
25
25
  *
26
+ * `purpose` and `organisationId` (`0007_keys_purpose.sql`) are unsigned too, and
27
+ * `null` on an older row means unknown. `keys_issued_guard()` lets each move
28
+ * from `null` to a value once and never change after that.
29
+ *
26
30
  * `lastUsedAt`/`useCount` (#46, `0003_keys_usage.sql`) are the one pair on
27
31
  * this row that is NOT set-once: `check()` writes both on every successful
28
32
  * verification, so -- unlike `environment` -- `keys_issued_guard()` leaves
@@ -41,6 +45,8 @@ export const keysIssuedCredentials = pgTable('keys_issued_credentials', {
41
45
  signingGenerationId: text('signing_generation_id').notNull(),
42
46
  idempotencyKey: text('idempotency_key'),
43
47
  environment: text('environment').notNull(),
48
+ purpose: text('purpose'),
49
+ organisationId: text('organisation_id'),
44
50
  createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
45
51
  revokedAt: timestamp('revoked_at', { withTimezone: true }),
46
52
  lastUsedAt: timestamp('last_used_at', { withTimezone: true }),
@@ -1,8 +1,19 @@
1
1
  import type { SignableRow, VerifyKeys } from '../worker-contract.js';
2
+ export interface IssuedRowGenerationLabel {
3
+ /** The row's `signing_generation_id`. */
4
+ readonly rowGenerationId: string;
5
+ /** The generation the `previous` key belongs to. */
6
+ readonly previousGenerationId: string;
7
+ }
2
8
  /**
3
9
  * Verifies `signature` over `encodeSigned('issued-row', pickSignable(row))`
4
10
  * against `verifyKeys`: `current` first, then `previous` if present. A row
5
- * signed under either key checks — that is what lets a Worker signing-key
6
- * rotation happen without re-signing every row before `previous` is dropped.
11
+ * signed under either key checks, so a Worker signing-key rotation does not
12
+ * need every row re-signed before `previous` is dropped.
13
+ *
14
+ * With `label`, `previous` is tried only for a row whose `rowGenerationId`
15
+ * equals `previousGenerationId`; a row with any other label that verifies
16
+ * only under `previous` is refused. Without it, both keys are tried for every
17
+ * row (deprecated, removed at 1.0.0).
7
18
  */
8
- export declare function verifyIssuedRowSignature<TGrant>(row: SignableRow<TGrant>, signature: Uint8Array, verifyKeys: VerifyKeys): Promise<boolean>;
19
+ export declare function verifyIssuedRowSignature<TGrant>(row: SignableRow<TGrant>, signature: Uint8Array, verifyKeys: VerifyKeys, label?: IssuedRowGenerationLabel): Promise<boolean>;
@@ -17,14 +17,21 @@ async function verifyEd25519(publicKey, signature, data) {
17
17
  /**
18
18
  * Verifies `signature` over `encodeSigned('issued-row', pickSignable(row))`
19
19
  * against `verifyKeys`: `current` first, then `previous` if present. A row
20
- * signed under either key checks — that is what lets a Worker signing-key
21
- * rotation happen without re-signing every row before `previous` is dropped.
20
+ * signed under either key checks, so a Worker signing-key rotation does not
21
+ * need every row re-signed before `previous` is dropped.
22
+ *
23
+ * With `label`, `previous` is tried only for a row whose `rowGenerationId`
24
+ * equals `previousGenerationId`; a row with any other label that verifies
25
+ * only under `previous` is refused. Without it, both keys are tried for every
26
+ * row (deprecated, removed at 1.0.0).
22
27
  */
23
- export async function verifyIssuedRowSignature(row, signature, verifyKeys) {
28
+ export async function verifyIssuedRowSignature(row, signature, verifyKeys, label) {
24
29
  const data = encodeSigned('issued-row', pickSignable(row));
25
30
  const [current, previous] = verifyKeys;
26
31
  if (await verifyEd25519(current, signature, data))
27
32
  return true;
33
+ if (label && label.rowGenerationId !== label.previousGenerationId)
34
+ return false;
28
35
  if (previous && (await verifyEd25519(previous, signature, data)))
29
36
  return true;
30
37
  return false;
@@ -0,0 +1,46 @@
1
+ -- Closes the archive race: an archiveTenant() that commits after put()'s
2
+ -- reservation but before its insert used to publish a version anyway,
3
+ -- because the publish guard (0003) checked revoked_at only. The shred sweep
4
+ -- would then count that version on the tenant's archive clock.
5
+ --
6
+ -- Copies 0003's keys_held_versions_publish_guard: same SECURITY DEFINER, same
7
+ -- pinned search_path (the first statement builds it, `set search_path from
8
+ -- current` records it), same `for update` on the entry row, which is what
9
+ -- makes an archive that is still in flight finish first and be seen here.
10
+ -- The one change is that tenant_archived_at refuses the insert too, with its
11
+ -- own message so put() can name the cause.
12
+ --
13
+ -- Safe on live rows at container start: `create or replace function` rewrites
14
+ -- one catalog row and scans no table. The trigger
15
+ -- keys_held_versions_publish (0003) keeps pointing at the function by name,
16
+ -- so it is not dropped or recreated. No existing row is read or changed, so
17
+ -- rows already published, the shred sweep (keys_shred_expired) and
18
+ -- keys_held_versions_retire_predecessors behave as before. During a rolling
19
+ -- deploy an older process still refuses the insert; it just reports a plain
20
+ -- database error instead of 'revoked'.
21
+ select set_config('search_path', quote_ident(current_schema()) || ', pg_catalog, pg_temp', true);
22
+
23
+ create or replace function keys_held_versions_publish_guard() returns trigger
24
+ language plpgsql
25
+ security definer
26
+ set search_path from current
27
+ as $$
28
+ declare
29
+ revoked timestamptz;
30
+ archived timestamptz;
31
+ begin
32
+ select revoked_at, tenant_archived_at into revoked, archived from keys_held_entries
33
+ where tenant_id = new.tenant_id and entry_id = new.entry_id for update;
34
+ if revoked is not null then
35
+ raise exception 'held entry is revoked';
36
+ end if;
37
+ if archived is not null then
38
+ raise exception 'held tenant is archived';
39
+ end if;
40
+ if exists (select 1 from keys_held_versions
41
+ where tenant_id = new.tenant_id and entry_id = new.entry_id and version > new.version) then
42
+ new.retired_at := clock_timestamp();
43
+ end if;
44
+ return new;
45
+ end
46
+ $$;
@@ -0,0 +1,216 @@
1
+ -- @wtfalch/keys ./held: a migration-credential kind for keys_held_entries
2
+ -- (#110). Mirrors src/held/schema.ts's `kind` column.
3
+ --
4
+ -- A migration credential (one per provider and customer tenant: a sealed copy
5
+ -- of a Google service account key or a Microsoft app secret) reads every
6
+ -- mailbox of every open grant, so it is destroyed as soon as it is superseded
7
+ -- or revoked, not after the ordinary 30-day shred delay.
8
+ --
9
+ -- keys_shred_delay_days() takes the entry's kind (default null, so the old
10
+ -- zero-argument call still works and means 30) and returns 0 for
11
+ -- 'migration_credential'. keys_shred_expired() stays the one sweep and still
12
+ -- takes no row-selecting argument (#225's refutation rejected a targeted
13
+ -- shred function). Only how long it waits once a clock has started now
14
+ -- depends on the entry's kind.
15
+ --
16
+ -- Copies 0003: keys_shred_expired, keys_held_versions_guard and
17
+ -- keys_held_entries_clock_guard are 0003's bodies with the delay call changed
18
+ -- (guard, sweep) or one check added (clock guard: `kind` may not change once
19
+ -- set, so a runtime-role UPDATE cannot turn a migration credential back into
20
+ -- an ordinary entry). Same SECURITY DEFINER and pinned search_path as 0003.
21
+ --
22
+ -- Safe on live rows at container start: add column if not exists with a null
23
+ -- default rewrites no rows; the CHECK is satisfied by every existing row
24
+ -- (kind is null) and is validated by the same statement; the rest is create
25
+ -- or replace of functions, no table scan. Existing entries keep kind null, so
26
+ -- the delay stays 30 for them. During a rolling deploy an older process
27
+ -- neither reads nor writes `kind`, so its entries stay ordinary.
28
+ select set_config('search_path', quote_ident(current_schema()) || ', pg_catalog, pg_temp', true);
29
+
30
+ alter table keys_held_entries
31
+ add column if not exists kind text;
32
+
33
+ alter table keys_held_entries
34
+ drop constraint if exists keys_held_entries_kind_check;
35
+ alter table keys_held_entries
36
+ add constraint keys_held_entries_kind_check
37
+ check (kind is null or kind = 'migration_credential');
38
+
39
+ -- One function, not an overload: the zero-argument version is dropped and the
40
+ -- same name returns with a defaulted argument, so `keys_shred_delay_days()`
41
+ -- still resolves. It reads no table, so it stays unpinned like the original.
42
+ drop function if exists keys_shred_delay_days();
43
+ create or replace function keys_shred_delay_days(kind text default null) returns integer
44
+ language sql immutable as $$
45
+ select case when kind = 'migration_credential' then 0 else 30 end;
46
+ $$;
47
+
48
+ create or replace function keys_shred_expired()
49
+ returns integer
50
+ language plpgsql
51
+ security definer
52
+ set search_path from current
53
+ as $$
54
+ declare
55
+ shredded integer;
56
+ begin
57
+ update keys_held_versions kv
58
+ set wrapped_key = null
59
+ from keys_held_entries ke
60
+ where kv.tenant_id = ke.tenant_id
61
+ and kv.entry_id = ke.entry_id
62
+ and kv.wrapped_key is not null
63
+ and (
64
+ (kv.retired_at is not null
65
+ and now() >= kv.retired_at + (keys_shred_delay_days(ke.kind) || ' days')::interval)
66
+ or (ke.revoked_at is not null
67
+ and now() >= ke.revoked_at + (keys_shred_delay_days(ke.kind) || ' days')::interval)
68
+ or (ke.tenant_archived_at is not null
69
+ and now() >= ke.tenant_archived_at + (keys_shred_delay_days(ke.kind) || ' days')::interval)
70
+ );
71
+ get diagnostics shredded = row_count;
72
+ return shredded;
73
+ end
74
+ $$;
75
+ revoke all on function keys_shred_expired() from public;
76
+
77
+ create or replace function keys_held_versions_guard() returns trigger
78
+ language plpgsql
79
+ set search_path from current
80
+ as $$
81
+ declare
82
+ is_rewrap boolean;
83
+ is_retire boolean;
84
+ is_shred boolean;
85
+ entry_kind text;
86
+ begin
87
+ if tg_op = 'INSERT' then
88
+ -- Nothing that inserts a row -- put(), or keys_held_versions_retire_predecessors
89
+ -- below, which never inserts -- ever does so with retired_at set; this
90
+ -- guards a raw INSERT bypassing that, the same way the UPDATE branch
91
+ -- below guards a raw UPDATE.
92
+ if new.retired_at is not null then
93
+ new.retired_at := clock_timestamp();
94
+ end if;
95
+ return new;
96
+ elsif tg_op = 'DELETE' then
97
+ raise exception 'keys_held_versions is append-only: delete refused';
98
+ elsif tg_op = 'TRUNCATE' then
99
+ raise exception 'keys_held_versions is append-only: truncate refused';
100
+ elsif tg_op = 'UPDATE' then
101
+ -- Stamp: retired_at moving from NULL to non-null is forced to now(),
102
+ -- whatever the caller sent. Must run before the shape checks below, so
103
+ -- is_retire/is_shred see the real value, not a forged one.
104
+ if old.retired_at is null and new.retired_at is not null then
105
+ new.retired_at := clock_timestamp();
106
+ end if;
107
+ -- Once set, retired_at is fixed: no re-dating, no clearing.
108
+ if old.retired_at is not null and new.retired_at is distinct from old.retired_at then
109
+ raise exception 'keys_held_versions is append-only: retired_at may not be re-dated or cleared once set';
110
+ end if;
111
+
112
+ if new.tenant_id is distinct from old.tenant_id
113
+ or new.entry_id is distinct from old.entry_id
114
+ or new.version is distinct from old.version
115
+ or new.iv is distinct from old.iv
116
+ or new.ciphertext is distinct from old.ciphertext
117
+ or new.created_at is distinct from old.created_at
118
+ then
119
+ raise exception 'keys_held_versions is append-only: tenant_id, entry_id, version, iv, ciphertext and created_at may never change';
120
+ end if;
121
+
122
+ -- rewrap: an operator sweep (#217), run with an operator database
123
+ -- handle -- see 0002's file header, item 3. The data key moves to a new
124
+ -- kek generation; wrapped_key and kek_id change together, retired_at
125
+ -- untouched either way.
126
+ is_rewrap := old.wrapped_key is not null
127
+ and new.wrapped_key is not null
128
+ and new.wrapped_key is distinct from old.wrapped_key
129
+ and new.kek_id is distinct from old.kek_id
130
+ and new.retired_at is not distinct from old.retired_at;
131
+
132
+ -- retire: keys_held_versions_retire_predecessors, below, the only
133
+ -- thing that performs this write now. retired_at moves from NULL to a
134
+ -- value (now stamped, above), once, with nothing else about the row
135
+ -- changing.
136
+ is_retire := old.retired_at is null
137
+ and new.retired_at is not null
138
+ and new.wrapped_key is not distinct from old.wrapped_key
139
+ and new.kek_id is not distinct from old.kek_id;
140
+
141
+ -- shred (keys_shred_expired(), or an operator's own ordinary UPDATE
142
+ -- with the same shape -- the trigger cannot and does not distinguish
143
+ -- the two): the shape alone is not enough -- this row's own stored
144
+ -- clocks, which can no longer be forged (0002's file header), must
145
+ -- already show this entry's kind's own keys_shred_delay_days()
146
+ -- elapsed -- zero for a migration credential, so a clock that just
147
+ -- started already qualifies; 30 for everything else, exactly as
148
+ -- before this migration.
149
+ select ke.kind into entry_kind from keys_held_entries ke
150
+ where ke.tenant_id = new.tenant_id and ke.entry_id = new.entry_id;
151
+
152
+ is_shred := old.wrapped_key is not null
153
+ and new.wrapped_key is null
154
+ and new.kek_id is not distinct from old.kek_id
155
+ and new.retired_at is not distinct from old.retired_at
156
+ and (
157
+ (new.retired_at is not null
158
+ and now() >= new.retired_at + (keys_shred_delay_days(entry_kind) || ' days')::interval)
159
+ or (
160
+ exists (
161
+ select 1 from keys_held_entries ke
162
+ where ke.tenant_id = new.tenant_id
163
+ and ke.entry_id = new.entry_id
164
+ and (
165
+ (ke.revoked_at is not null
166
+ and now() >= ke.revoked_at + (keys_shred_delay_days(ke.kind) || ' days')::interval)
167
+ or (ke.tenant_archived_at is not null
168
+ and now() >= ke.tenant_archived_at + (keys_shred_delay_days(ke.kind) || ' days')::interval)
169
+ )
170
+ )
171
+ )
172
+ );
173
+
174
+ if not (is_rewrap or is_retire or is_shred) then
175
+ raise exception 'keys_held_versions is append-only: an update must be exactly a rewrap (wrapped_key and kek_id together), a retire (retired_at NULL to non-null, once), or a shred of a row genuinely eligible for its kind''s shred delay -- refused, including un-retiring, un-shredding, shredding early, and any change to ciphertext or iv';
176
+ end if;
177
+ end if;
178
+ return new;
179
+ end
180
+ $$;
181
+
182
+ create or replace function keys_held_entries_clock_guard() returns trigger
183
+ language plpgsql
184
+ set search_path from current
185
+ as $$
186
+ begin
187
+ if tg_op = 'INSERT' then
188
+ if new.revoked_at is not null then
189
+ new.revoked_at := clock_timestamp();
190
+ end if;
191
+ if new.tenant_archived_at is not null then
192
+ new.tenant_archived_at := clock_timestamp();
193
+ end if;
194
+ return new;
195
+ elsif tg_op = 'UPDATE' then
196
+ if old.revoked_at is null and new.revoked_at is not null then
197
+ new.revoked_at := clock_timestamp();
198
+ end if;
199
+ if old.revoked_at is not null and new.revoked_at is distinct from old.revoked_at then
200
+ raise exception 'keys_held_entries: revoked_at may not be re-dated or cleared once set';
201
+ end if;
202
+
203
+ if old.tenant_archived_at is null and new.tenant_archived_at is not null then
204
+ new.tenant_archived_at := clock_timestamp();
205
+ end if;
206
+ if old.tenant_archived_at is not null and new.tenant_archived_at is distinct from old.tenant_archived_at then
207
+ raise exception 'keys_held_entries: tenant_archived_at may not be re-dated or cleared once set';
208
+ end if;
209
+
210
+ if new.kind is distinct from old.kind then
211
+ raise exception 'keys_held_entries: kind may not change once set';
212
+ end if;
213
+ end if;
214
+ return new;
215
+ end
216
+ $$;
@@ -0,0 +1,54 @@
1
+ -- The entries table keeps what it learned (A10, from the phase 3 finding).
2
+ -- An entry is never deleted or truncated, and current_version never falls.
3
+ -- Additive; do not edit copied migrations. Safe while the previous version
4
+ -- runs: no code in any released version deletes an entry or lowers its
5
+ -- counter, so the triggers refuse only what nothing legitimate does.
6
+ --
7
+ -- Why: an entry with no version row could be deleted by the runtime role (the
8
+ -- foreign key only protects an entry that has a version). A later put() then
9
+ -- recreated it with no revoked_at, no tenant_archived_at and a null kind. And
10
+ -- an UPDATE could lower current_version, so the next put() reserved a number
11
+ -- that already exists and failed on the primary key.
12
+ --
13
+ -- Nothing deletes an entry: erasure, archive and shred only stamp
14
+ -- tenant_archived_at, revoked_at and null the wrapped key on the versions
15
+ -- table (0002, 0003). So no SECURITY DEFINER path is needed, and the guard
16
+ -- refuses every role. A test that needs a clean table drops the schema.
17
+ -- Truncate is refused the same way, even for a role that holds the privilege.
18
+ --
19
+ -- The functions pin their search_path to the schema this file runs in,
20
+ -- followed by pg_catalog, with pg_temp last. The first statement builds that
21
+ -- path for this transaction; `set search_path from current` records it on
22
+ -- each function. The host lists the table under `noDelete` in
23
+ -- `ensureRuntimeRole` (README) as well, so the privilege is gone too.
24
+ select set_config('search_path', quote_ident(current_schema()) || ', pg_catalog, pg_temp', true);
25
+
26
+ create or replace function keys_held_entries_no_delete() returns trigger
27
+ language plpgsql
28
+ set search_path from current
29
+ as $$
30
+ begin
31
+ raise exception 'keys_held_entries: delete and truncate refused';
32
+ end
33
+ $$;
34
+ drop trigger if exists keys_held_entries_no_delete on keys_held_entries;
35
+ create trigger keys_held_entries_no_delete before delete on keys_held_entries
36
+ for each row execute function keys_held_entries_no_delete();
37
+ drop trigger if exists keys_held_entries_no_truncate on keys_held_entries;
38
+ create trigger keys_held_entries_no_truncate before truncate on keys_held_entries
39
+ for each statement execute function keys_held_entries_no_delete();
40
+
41
+ create or replace function keys_held_entries_counter_guard() returns trigger
42
+ language plpgsql
43
+ set search_path from current
44
+ as $$
45
+ begin
46
+ if new.current_version < old.current_version then
47
+ raise exception 'keys_held_entries: current_version may not fall';
48
+ end if;
49
+ return new;
50
+ end
51
+ $$;
52
+ drop trigger if exists keys_held_entries_counter_guard on keys_held_entries;
53
+ create trigger keys_held_entries_counter_guard before update on keys_held_entries
54
+ for each row execute function keys_held_entries_counter_guard();
@@ -0,0 +1,29 @@
1
+ -- @wtfalch/keys: host/0002 widens the kind check on keys_host_events for ./service.
2
+ --
3
+ -- Adds three kinds, one per held mutation the service makes: held.put (a new
4
+ -- version was sealed), held.revoked (an entry was revoked) and held.shredded
5
+ -- (the shred sweep ran). Nothing is removed, so every existing row still passes
6
+ -- and a host that never calls ./service is unaffected.
7
+ --
8
+ -- Safe on a live table, with one cost. The new check is added NOT VALID, which
9
+ -- does not scan the table, then validated. Validation alone would let reads and
10
+ -- writes continue, but the host applies this file in one transaction, and the
11
+ -- drop and the add take an exclusive lock that is held until it commits. So
12
+ -- writes to keys_host_events wait for the scan of its rows. Applying this twice is safe: the drop
13
+ -- is "if exists" and the add replaces it.
14
+ --
15
+ -- auditEndpoint still returns only the three request-bearing kinds, so
16
+ -- reconcile's closed list is unchanged and a held event row never reaches it.
17
+ --
18
+ -- Applied by the host's own migrate script after the host copies this file
19
+ -- into its own migrations directory as the next number (keys-migrations),
20
+ -- never edited there.
21
+
22
+ alter table keys_host_events drop constraint if exists keys_host_events_kind_check;
23
+ alter table keys_host_events
24
+ add constraint keys_host_events_kind_check
25
+ check (kind in (
26
+ 'key.used', 'credential.minted', 'credential.rotated', 'credential.revoked',
27
+ 'held.put', 'held.revoked', 'held.shredded'
28
+ )) not valid;
29
+ alter table keys_host_events validate constraint keys_host_events_kind_check;
@@ -0,0 +1,68 @@
1
+ -- A credential's purpose and organisation: ordinary, company_root or
2
+ -- platform_master, plus the organisation a company key belongs to. Additive;
3
+ -- do not edit copied migrations.
4
+ --
5
+ -- Copies 0002_keys_environment.sql (a new unsigned column and a check
6
+ -- constraint, guarded to run twice) and 0006_keys_issued_guard.sql (the guard
7
+ -- function body, with the search_path pinned the same way).
8
+ --
9
+ -- Neither column is part of what the Worker signs, so every existing
10
+ -- signature stays valid and no Worker deploy or resign is needed. A person who
11
+ -- can write the database can change them; keys_issued_guard() below refuses an
12
+ -- UPDATE that changes a value once it is set.
13
+ --
14
+ -- Existing rows keep `null`, which means "unknown purpose". Nothing guesses it
15
+ -- from a name, a grant or a missing minter; operator code moves a row out of
16
+ -- `null` once, through classify().
17
+ --
18
+ -- Safe on live rows at container start. Both columns are nullable with no
19
+ -- default, so adding them rewrites nothing. The check constraint is added
20
+ -- after the columns and only ever sees `null`. `create or replace function`
21
+ -- swaps the guard in one step and the existing triggers keep pointing at it by
22
+ -- name, so no write is refused between the two statements. A container still
23
+ -- running the previous version inserts rows without these columns (they stay
24
+ -- `null`) and never updates them, so it keeps working.
25
+ select set_config('search_path', quote_ident(current_schema()) || ', pg_catalog, pg_temp', true);
26
+
27
+ alter table keys_issued_credentials add column if not exists purpose text;
28
+ alter table keys_issued_credentials add column if not exists organisation_id text;
29
+
30
+ do $$
31
+ begin
32
+ if not exists (
33
+ select 1 from pg_constraint
34
+ where conname = 'keys_issued_credentials_purpose_check'
35
+ and conrelid = 'keys_issued_credentials'::regclass
36
+ ) then
37
+ alter table keys_issued_credentials
38
+ add constraint keys_issued_credentials_purpose_check
39
+ check (purpose is null or purpose in ('ordinary', 'company_root', 'platform_master'));
40
+ end if;
41
+ end
42
+ $$;
43
+
44
+ create or replace function keys_issued_guard() returns trigger
45
+ language plpgsql
46
+ set search_path from current
47
+ as $$
48
+ begin
49
+ if tg_op in ('DELETE', 'TRUNCATE') then
50
+ raise exception 'keys_issued_credentials: delete and truncate refused';
51
+ end if;
52
+ if tg_op = 'UPDATE' then
53
+ if new.id is distinct from old.id or new.issued_by_id is distinct from old.issued_by_id
54
+ or new.key_prefix is distinct from old.key_prefix
55
+ or new.environment is distinct from old.environment then
56
+ raise exception 'keys_issued_credentials: identity, lineage and environment are immutable';
57
+ end if;
58
+ if (old.purpose is not null and new.purpose is distinct from old.purpose)
59
+ or (old.organisation_id is not null and new.organisation_id is distinct from old.organisation_id) then
60
+ raise exception 'keys_issued_credentials: purpose and organisation are set once';
61
+ end if;
62
+ if old.revoked_at is not null and new.revoked_at is distinct from old.revoked_at then
63
+ raise exception 'keys_issued_credentials: revocation is permanent';
64
+ end if;
65
+ end if;
66
+ return new;
67
+ end
68
+ $$;
@@ -0,0 +1,23 @@
1
+ -- An idempotency key belongs to the credential that minted it: the unique
2
+ -- index moves from (idempotency_key) to (coalesce(issued_by_id, ''),
3
+ -- idempotency_key). Additive; do not edit copied migrations.
4
+ --
5
+ -- Copies 0001_keys_issued.sql's partial unique index on the same column, and
6
+ -- its "if not exists" guard so the file runs twice.
7
+ --
8
+ -- Safe on live rows at container start. The new index is looser than the old
9
+ -- one (it adds a column to the key), so every set of rows the old index
10
+ -- allowed the new one allows too, and building it cannot fail on existing
11
+ -- data. That includes rows whose key was renamed to `<key>:superseded:<id>`
12
+ -- by the registrar's old freeStaleSlot: those keys are already unique and
13
+ -- stay as they are. The new index is built before the old one is dropped, so
14
+ -- there is no moment without a uniqueness guard. A container still running the
15
+ -- previous version looks a key up on its own and treats a unique violation as
16
+ -- a replay, which both indexes still raise for the same minter. The build
17
+ -- blocks writes to this table for as long as it takes, which is short for a
18
+ -- table of credentials.
19
+ create unique index if not exists keys_issued_credentials_idempotency_scope_idx
20
+ on keys_issued_credentials ((coalesce(issued_by_id, '')), idempotency_key)
21
+ where idempotency_key is not null;
22
+
23
+ drop index if exists keys_issued_credentials_idempotency_key_idx;
@@ -0,0 +1,63 @@
1
+ -- Forced row-level security for the tables that hold a tenant's rows:
2
+ -- keys_held_entries, keys_held_versions and keys_host_events. A connection
3
+ -- sees and writes only the rows whose tenant_id equals the text in the
4
+ -- `app.tenant_id` setting (set per transaction with set_config(..., true)).
5
+ --
6
+ -- OPT-IN. This directory is not part of the held or host chains and the
7
+ -- keys-migrations binary does not copy it. A host that does not set
8
+ -- `app.tenant_id` would read nothing after applying it, so a host applies it
9
+ -- only when its code sets the setting. A host that does not apply it is
10
+ -- unchanged.
11
+ --
12
+ -- `tenant_id` here is the keys namespace text, not an authz tenant uuid. The
13
+ -- company's Archon credential is stored under tenant_id = 'company', and the
14
+ -- id is part of the sealed value's AAD (src/held/aad.ts:23), so it cannot be
15
+ -- renamed. The comparison is text to text.
16
+ --
17
+ -- A null tenant_id on keys_host_events is a global platform row: the
18
+ -- `held.shredded` row (src/host/events.ts:70) and the `credential.*` rows
19
+ -- (src/host/events.ts:81) carry no tenant. Those rows are visible to and
20
+ -- insertable by every setting. Rows with a tenant follow the setting.
21
+ --
22
+ -- keys_issued_credentials and keys_issued_rate_limit_windows get NO policy.
23
+ -- The credentials table has no tenant column (organisation_id may be null)
24
+ -- and is looked up by key_prefix or secret_hash before any tenant is known
25
+ -- (src/issued/verify.ts); the rate-limit table is keyed by credential id.
26
+ -- Both are on the host's global list. What guards them instead: the secret is
27
+ -- stored as a hash and rows are found only by hash or prefix.
28
+ --
29
+ -- The owner is a superuser and is not bound by row-level security, even with
30
+ -- FORCE. That is what lets the SECURITY DEFINER functions (keys_shred_expired,
31
+ -- the retire trigger, the publish guard) run as the owner and ignore these
32
+ -- policies. A non-superuser owner WOULD be bound by FORCE, and those functions
33
+ -- would then act on no rows, silently. Keep the owner a superuser, or do not
34
+ -- apply this directory.
35
+ --
36
+ -- Every statement is idempotent: each policy is dropped before it is created.
37
+
38
+ alter table keys_held_entries enable row level security;
39
+ alter table keys_held_entries force row level security;
40
+ drop policy if exists keys_held_entries_tenant on keys_held_entries;
41
+ create policy keys_held_entries_tenant on keys_held_entries
42
+ for all
43
+ using (tenant_id = nullif(current_setting('app.tenant_id', true), ''))
44
+ with check (tenant_id = nullif(current_setting('app.tenant_id', true), ''));
45
+
46
+ alter table keys_held_versions enable row level security;
47
+ alter table keys_held_versions force row level security;
48
+ drop policy if exists keys_held_versions_tenant on keys_held_versions;
49
+ create policy keys_held_versions_tenant on keys_held_versions
50
+ for all
51
+ using (tenant_id = nullif(current_setting('app.tenant_id', true), ''))
52
+ with check (tenant_id = nullif(current_setting('app.tenant_id', true), ''));
53
+
54
+ alter table keys_host_events enable row level security;
55
+ alter table keys_host_events force row level security;
56
+ drop policy if exists keys_host_events_select on keys_host_events;
57
+ create policy keys_host_events_select on keys_host_events
58
+ for select
59
+ using (tenant_id is null or tenant_id = nullif(current_setting('app.tenant_id', true), ''));
60
+ drop policy if exists keys_host_events_insert on keys_host_events;
61
+ create policy keys_host_events_insert on keys_host_events
62
+ for insert
63
+ with check (tenant_id is null or tenant_id = nullif(current_setting('app.tenant_id', true), ''));
@@ -17,3 +17,12 @@
17
17
  export declare const issuedMigrationsDir: string;
18
18
  export declare const heldMigrationsDir: string;
19
19
  export declare const hostMigrationsDir: string;
20
+ /**
21
+ * OPT-IN, not one of the three chains: forced row-level security on the
22
+ * tables that hold a tenant's rows. Apply it only in a host that sets
23
+ * `app.tenant_id`; otherwise every read of those tables returns no rows.
24
+ * Apply it after the held and host chains:
25
+ *
26
+ * { name: 'keys-tenant-rows', dir: tenantRowsMigrationsDir }
27
+ */
28
+ export declare const tenantRowsMigrationsDir: string;
@@ -18,3 +18,12 @@ import { fileURLToPath } from 'node:url';
18
18
  export const issuedMigrationsDir = fileURLToPath(new URL('./migrations/issued/', import.meta.url));
19
19
  export const heldMigrationsDir = fileURLToPath(new URL('./migrations/held/', import.meta.url));
20
20
  export const hostMigrationsDir = fileURLToPath(new URL('./migrations/host/', import.meta.url));
21
+ /**
22
+ * OPT-IN, not one of the three chains: forced row-level security on the
23
+ * tables that hold a tenant's rows. Apply it only in a host that sets
24
+ * `app.tenant_id`; otherwise every read of those tables returns no rows.
25
+ * Apply it after the held and host chains:
26
+ *
27
+ * { name: 'keys-tenant-rows', dir: tenantRowsMigrationsDir }
28
+ */
29
+ export const tenantRowsMigrationsDir = fileURLToPath(new URL('./migrations/tenant-rows/', import.meta.url));
@@ -0,0 +1,21 @@
1
+ export declare const MAX_BODY_BYTES: number;
2
+ export declare const MAX_GRANTS = 64;
3
+ export declare const MAX_GRANT_BYTES: number;
4
+ export type Fields = Readonly<Record<string, unknown>>;
5
+ /** The body of a request, read up to `MAX_BODY_BYTES` and no further. Anything but a JSON object is `invalid_request`. */
6
+ export declare function readObjectBody(request: Request): Promise<Fields>;
7
+ /** The query string as fields. A repeated name is `invalid_request`. */
8
+ export declare function queryFields(url: URL): Fields;
9
+ /** Refuses a field outside `allowed`: a caller cannot send `purpose`, and a typo is not silently dropped. */
10
+ export declare function onlyFields(fields: Fields, allowed: readonly string[]): void;
11
+ export declare function idField(fields: Fields, name: string): string;
12
+ export declare function optionalIdField(fields: Fields, name: string): string | null;
13
+ export declare function secretField(fields: Fields, name: string): string;
14
+ export declare function textField(fields: Fields, name: string): string;
15
+ export declare function optionalKeyField(fields: Fields, name: string): string | undefined;
16
+ export declare function numberField(fields: Fields, name: string): number;
17
+ export declare function graceField(fields: Fields, name: string): number;
18
+ export declare function optionalBooleanField(fields: Fields, name: string): boolean | undefined;
19
+ export declare function optionalEnvironmentField(fields: Fields, name: string): 'live' | 'test' | undefined;
20
+ /** At most `MAX_GRANTS` entries, each at most `MAX_GRANT_BYTES` of JSON. What a grant means is the host's. */
21
+ export declare function grantsField(fields: Fields, name: string): readonly unknown[];