@wtfalch/keys 0.4.1 → 0.6.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 (41) hide show
  1. package/README.md +143 -5
  2. package/dist/bin/copy.d.ts +8 -4
  3. package/dist/bin/copy.js +8 -4
  4. package/dist/bin/migrations.js +21 -7
  5. package/dist/held/schema.js +1 -1
  6. package/dist/held/seal.d.ts +22 -0
  7. package/dist/held/seal.js +48 -0
  8. package/dist/held/shred.d.ts +1 -1
  9. package/dist/held/shred.js +1 -1
  10. package/dist/host/audit-endpoint.d.ts +15 -0
  11. package/dist/host/audit-endpoint.js +117 -0
  12. package/dist/host/events.d.ts +26 -0
  13. package/dist/host/events.js +31 -0
  14. package/dist/host/index.d.ts +11 -0
  15. package/dist/host/index.js +11 -0
  16. package/dist/host/schema.d.ts +153 -0
  17. package/dist/host/schema.js +20 -0
  18. package/dist/issued/index.js +2 -2
  19. package/dist/issued/ratelimit.d.ts +1 -1
  20. package/dist/issued/ratelimit.js +1 -1
  21. package/dist/issued/resign.js +1 -1
  22. package/dist/issued/tables.d.ts +4 -4
  23. package/dist/issued/tables.js +4 -4
  24. package/dist/migrations/{0003_keys_shred.sql → held/0002_keys_shred.sql} +26 -31
  25. package/dist/migrations/{0004_keys_security.sql → held/0003_keys_security.sql} +36 -70
  26. package/dist/migrations/host/0001_keys_host_events.sql +73 -0
  27. package/dist/migrations/issued/0002_keys_environment.sql +29 -0
  28. package/dist/migrations/{0006_keys_usage.sql → issued/0003_keys_usage.sql} +3 -2
  29. package/dist/migrations/{0008_keys_environment_default.sql → issued/0005_keys_environment_default.sql} +1 -1
  30. package/dist/migrations/issued/0006_keys_issued_guard.sql +47 -0
  31. package/dist/migrations-dir.d.ts +19 -0
  32. package/dist/migrations-dir.js +20 -0
  33. package/dist/testing/index.d.ts +9 -0
  34. package/dist/testing/index.js +9 -0
  35. package/dist/testing/worker-stub.d.ts +55 -0
  36. package/dist/testing/worker-stub.js +180 -0
  37. package/package.json +17 -4
  38. package/dist/migrations/0005_keys_environment.sql +0 -52
  39. /package/dist/migrations/{0002_keys_held.sql → held/0001_keys_held.sql} +0 -0
  40. /package/dist/migrations/{0001_keys_issued.sql → issued/0001_keys_issued.sql} +0 -0
  41. /package/dist/migrations/{0007_keys_rate_limit.sql → issued/0004_keys_rate_limit.sql} +0 -0
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Mirrors `../migrations/host/0001_keys_host_events.sql`, which is the source of
3
+ * truth: the SQL carries the CHECK and the append-only guard trigger that
4
+ * drizzle's table builder does not generate. Column-for-column identical to
5
+ * every host's own hand-written copy of this table (checked against
6
+ * `files`, `ai` and `integrations`'s `apps/host/src/lib/keys/schema.ts`), so
7
+ * a host with pre-existing rows can point this module at its existing table
8
+ * with no data migration.
9
+ */
10
+ export declare const keysHostEvents: import("drizzle-orm/pg-core").PgTableWithColumns<{
11
+ name: "keys_host_events";
12
+ schema: undefined;
13
+ columns: {
14
+ id: import("drizzle-orm/pg-core").PgColumn<{
15
+ name: "id";
16
+ tableName: "keys_host_events";
17
+ dataType: "number";
18
+ columnType: "PgBigInt53";
19
+ data: number;
20
+ driverParam: string | number;
21
+ notNull: true;
22
+ hasDefault: true;
23
+ isPrimaryKey: true;
24
+ isAutoincrement: false;
25
+ hasRuntimeDefault: false;
26
+ enumValues: undefined;
27
+ baseColumn: never;
28
+ identity: "always";
29
+ generated: undefined;
30
+ }, {}, {}>;
31
+ kind: import("drizzle-orm/pg-core").PgColumn<{
32
+ name: "kind";
33
+ tableName: "keys_host_events";
34
+ dataType: "string";
35
+ columnType: "PgText";
36
+ data: string;
37
+ driverParam: string;
38
+ notNull: true;
39
+ hasDefault: false;
40
+ isPrimaryKey: false;
41
+ isAutoincrement: false;
42
+ hasRuntimeDefault: false;
43
+ enumValues: [string, ...string[]];
44
+ baseColumn: never;
45
+ identity: undefined;
46
+ generated: undefined;
47
+ }, {}, {}>;
48
+ requestId: import("drizzle-orm/pg-core").PgColumn<{
49
+ name: "request_id";
50
+ tableName: "keys_host_events";
51
+ dataType: "string";
52
+ columnType: "PgText";
53
+ data: string;
54
+ driverParam: string;
55
+ notNull: false;
56
+ hasDefault: false;
57
+ isPrimaryKey: false;
58
+ isAutoincrement: false;
59
+ hasRuntimeDefault: false;
60
+ enumValues: [string, ...string[]];
61
+ baseColumn: never;
62
+ identity: undefined;
63
+ generated: undefined;
64
+ }, {}, {}>;
65
+ credentialId: import("drizzle-orm/pg-core").PgColumn<{
66
+ name: "credential_id";
67
+ tableName: "keys_host_events";
68
+ dataType: "string";
69
+ columnType: "PgText";
70
+ data: string;
71
+ driverParam: string;
72
+ notNull: false;
73
+ hasDefault: false;
74
+ isPrimaryKey: false;
75
+ isAutoincrement: false;
76
+ hasRuntimeDefault: false;
77
+ enumValues: [string, ...string[]];
78
+ baseColumn: never;
79
+ identity: undefined;
80
+ generated: undefined;
81
+ }, {}, {}>;
82
+ tenantId: import("drizzle-orm/pg-core").PgColumn<{
83
+ name: "tenant_id";
84
+ tableName: "keys_host_events";
85
+ dataType: "string";
86
+ columnType: "PgText";
87
+ data: string;
88
+ driverParam: string;
89
+ notNull: false;
90
+ hasDefault: false;
91
+ isPrimaryKey: false;
92
+ isAutoincrement: false;
93
+ hasRuntimeDefault: false;
94
+ enumValues: [string, ...string[]];
95
+ baseColumn: never;
96
+ identity: undefined;
97
+ generated: undefined;
98
+ }, {}, {}>;
99
+ entryId: import("drizzle-orm/pg-core").PgColumn<{
100
+ name: "entry_id";
101
+ tableName: "keys_host_events";
102
+ dataType: "string";
103
+ columnType: "PgText";
104
+ data: string;
105
+ driverParam: string;
106
+ notNull: false;
107
+ hasDefault: false;
108
+ isPrimaryKey: false;
109
+ isAutoincrement: false;
110
+ hasRuntimeDefault: false;
111
+ enumValues: [string, ...string[]];
112
+ baseColumn: never;
113
+ identity: undefined;
114
+ generated: undefined;
115
+ }, {}, {}>;
116
+ version: import("drizzle-orm/pg-core").PgColumn<{
117
+ name: "version";
118
+ tableName: "keys_host_events";
119
+ dataType: "number";
120
+ columnType: "PgInteger";
121
+ data: number;
122
+ driverParam: string | number;
123
+ notNull: false;
124
+ hasDefault: false;
125
+ isPrimaryKey: false;
126
+ isAutoincrement: false;
127
+ hasRuntimeDefault: false;
128
+ enumValues: undefined;
129
+ baseColumn: never;
130
+ identity: undefined;
131
+ generated: undefined;
132
+ }, {}, {}>;
133
+ at: import("drizzle-orm/pg-core").PgColumn<{
134
+ name: "at";
135
+ tableName: "keys_host_events";
136
+ dataType: "date";
137
+ columnType: "PgTimestamp";
138
+ data: Date;
139
+ driverParam: string;
140
+ notNull: true;
141
+ hasDefault: true;
142
+ isPrimaryKey: false;
143
+ isAutoincrement: false;
144
+ hasRuntimeDefault: false;
145
+ enumValues: undefined;
146
+ baseColumn: never;
147
+ identity: undefined;
148
+ generated: undefined;
149
+ }, {}, {}>;
150
+ };
151
+ dialect: "pg";
152
+ }>;
153
+ export type KeysHostEventRow = typeof keysHostEvents.$inferSelect;
@@ -0,0 +1,20 @@
1
+ import { bigint, index, integer, pgTable, text, timestamp } from 'drizzle-orm/pg-core';
2
+ /**
3
+ * Mirrors `../migrations/host/0001_keys_host_events.sql`, which is the source of
4
+ * truth: the SQL carries the CHECK and the append-only guard trigger that
5
+ * drizzle's table builder does not generate. Column-for-column identical to
6
+ * every host's own hand-written copy of this table (checked against
7
+ * `files`, `ai` and `integrations`'s `apps/host/src/lib/keys/schema.ts`), so
8
+ * a host with pre-existing rows can point this module at its existing table
9
+ * with no data migration.
10
+ */
11
+ export const keysHostEvents = pgTable('keys_host_events', {
12
+ id: bigint('id', { mode: 'number' }).generatedAlwaysAsIdentity().primaryKey(),
13
+ kind: text('kind').notNull(),
14
+ requestId: text('request_id'),
15
+ credentialId: text('credential_id'),
16
+ tenantId: text('tenant_id'),
17
+ entryId: text('entry_id'),
18
+ version: integer('version'),
19
+ at: timestamp('at', { withTimezone: true }).notNull().defaultNow(),
20
+ }, (t) => [index('keys_host_events_at_idx').on(t.at)]);
@@ -48,10 +48,10 @@ export function createCredentialIssuer(options) {
48
48
  async function subtreeIds(id, handle) {
49
49
  const result = await handle.execute(sql `
50
50
  with recursive descendants as (
51
- select id from public.keys_issued_credentials where id = ${id}
51
+ select id from keys_issued_credentials where id = ${id}
52
52
  union
53
53
  select c.id
54
- from public.keys_issued_credentials c
54
+ from keys_issued_credentials c
55
55
  join descendants d on c.issued_by_id = d.id
56
56
  )
57
57
  select id from descendants
@@ -26,7 +26,7 @@ export interface CreatePostgresRateLimiterOptions {
26
26
  }
27
27
  /**
28
28
  * A fixed-window counter in the host's own Postgres, one bounded row per
29
- * credential (`keys_issued_rate_limit_windows`, `0007_keys_rate_limit.sql`),
29
+ * credential (`keys_issued_rate_limit_windows`, `0004_keys_rate_limit.sql`),
30
30
  * atomically reset each window by a single upsert -- the same shape
31
31
  * `packages/worker/src/ratelimit.ts`'s D1 `host_rate_limit_windows` uses, a
32
32
  * level down: keyed by the end user's credential id, not the host's.
@@ -6,7 +6,7 @@ function rowsOf(result) {
6
6
  }
7
7
  /**
8
8
  * A fixed-window counter in the host's own Postgres, one bounded row per
9
- * credential (`keys_issued_rate_limit_windows`, `0007_keys_rate_limit.sql`),
9
+ * credential (`keys_issued_rate_limit_windows`, `0004_keys_rate_limit.sql`),
10
10
  * atomically reset each window by a single upsert -- the same shape
11
11
  * `packages/worker/src/ratelimit.ts`'s D1 `host_rate_limit_windows` uses, a
12
12
  * level down: keyed by the end user's credential id, not the host's.
@@ -162,7 +162,7 @@ export function createSigningGenerationMigrator(options) {
162
162
  throw new TypeError('generationId must match ID_PATTERN');
163
163
  const result = await db.execute(sql `
164
164
  select count(*)::integer as count
165
- from public.keys_issued_credentials
165
+ from keys_issued_credentials
166
166
  where signing_generation_id = ${generationId}
167
167
  `);
168
168
  const rows = Array.isArray(result)
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `keys_issued_credentials`, mirrored from `../migrations/0001_keys_issued.sql`,
2
+ * `keys_issued_credentials`, mirrored from `../migrations/issued/0001_keys_issued.sql`,
3
3
  * which is the source of truth: the SQL carries the CHECKs, the self-referencing
4
4
  * foreign key and the partial unique indexes that drizzle-kit does not generate.
5
5
  *
@@ -18,11 +18,11 @@
18
18
  * runs is the one in the SQL migration.
19
19
  *
20
20
  * `environment` (#47) is not part of `SignableRow` -- unsigned metadata, same
21
- * footing as `idempotencyKey`/`createdAt`. `0005_keys_environment.sql`'s
22
- * extended `keys_issued_guard()` trigger is what keeps it trustworthy: set
21
+ * footing as `idempotencyKey`/`createdAt`. `0006_keys_issued_guard.sql`'s
22
+ * `keys_issued_guard()` trigger is what keeps it trustworthy: set
23
23
  * once at `issue()`, immutable for the row's life.
24
24
  *
25
- * `lastUsedAt`/`useCount` (#46, `0006_keys_usage.sql`) are the one pair on
25
+ * `lastUsedAt`/`useCount` (#46, `0003_keys_usage.sql`) are the one pair on
26
26
  * this row that is NOT set-once: `check()` writes both on every successful
27
27
  * verification, so -- unlike `environment` -- `keys_issued_guard()` leaves
28
28
  * them out of its immutable-columns check.
@@ -1,6 +1,6 @@
1
1
  import { bigint, jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core';
2
2
  /**
3
- * `keys_issued_credentials`, mirrored from `../migrations/0001_keys_issued.sql`,
3
+ * `keys_issued_credentials`, mirrored from `../migrations/issued/0001_keys_issued.sql`,
4
4
  * which is the source of truth: the SQL carries the CHECKs, the self-referencing
5
5
  * foreign key and the partial unique indexes that drizzle-kit does not generate.
6
6
  *
@@ -19,11 +19,11 @@ import { bigint, jsonb, pgTable, text, timestamp } from 'drizzle-orm/pg-core';
19
19
  * runs is the one in the SQL migration.
20
20
  *
21
21
  * `environment` (#47) is not part of `SignableRow` -- unsigned metadata, same
22
- * footing as `idempotencyKey`/`createdAt`. `0005_keys_environment.sql`'s
23
- * extended `keys_issued_guard()` trigger is what keeps it trustworthy: set
22
+ * footing as `idempotencyKey`/`createdAt`. `0006_keys_issued_guard.sql`'s
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
- * `lastUsedAt`/`useCount` (#46, `0006_keys_usage.sql`) are the one pair on
26
+ * `lastUsedAt`/`useCount` (#46, `0003_keys_usage.sql`) are the one pair on
27
27
  * this row that is NOT set-once: `check()` writes both on every successful
28
28
  * verification, so -- unlike `environment` -- `keys_issued_guard()` leaves
29
29
  * them out of its immutable-columns check.
@@ -4,7 +4,7 @@
4
4
  -- Applied by the host's own migrate script after this file is copied into
5
5
  -- its drizzle/ directory as the next number (keys-migrations); never edited
6
6
  -- there. Every statement is idempotent. Purely additive: adds one column,
7
- -- four functions, six triggers, one revoke and one grant. Nothing here
7
+ -- four functions and six triggers. Nothing here
8
8
  -- drops or renames anything 0002 created.
9
9
  --
10
10
  -- What "eligible" means (app-template #225, revised answer): a
@@ -106,23 +106,29 @@
106
106
  -- operator is trusted with the privilege; the shape check just keeps a
107
107
  -- fumbled UPDATE from doing something else instead.
108
108
  --
109
- -- Grants, following @wtfalch/audit's pattern (src/migrations/0001_audit.sql):
110
- -- a host names its runtime role <database>_rt, and the DO block below is a
111
- -- no-op if that role doesn't exist -- the functions and triggers still exist
112
- -- and still protect the tables either way. The runtime role keeps its
113
- -- ordinary default SELECT and INSERT on keys_held_versions (put and open
114
- -- need them; nothing else does now) and its ordinary SELECT, INSERT, UPDATE
115
- -- on keys_held_entries (revokeEntry, archiveTenant, and the shred guard's
116
- -- own eligibility lookup all need them) -- this migration does not touch
117
- -- keys_held_entries' grants at all. UPDATE, DELETE and TRUNCATE on
118
- -- keys_held_versions are revoked from the runtime role: #225's revised
119
- -- answer keeps a shredded row (permanent but unreadable, matching ADR 0019
120
- -- and audit rows), so DELETE/TRUNCATE were never legitimate; UPDATE is
121
- -- revoked because every legitimate write to this table -- retire, shred --
122
- -- now runs through a SECURITY DEFINER function rather than the runtime
123
- -- role's own privilege, and the one write that still needs ordinary UPDATE
124
- -- (rewrap) is an operator's job, not the runtime role's (item 3). The
125
- -- runtime role gets EXECUTE on keys_shred_expired(), nothing wider.
109
+ -- Grants are the host's, not this file's: the runtime role is made by the
110
+ -- host's `ensureRuntimeRole` (README), which this file never calls. The
111
+ -- runtime role keeps its ordinary SELECT and INSERT on keys_held_versions
112
+ -- (put and open need them; nothing else does now) and its ordinary SELECT,
113
+ -- INSERT, UPDATE on keys_held_entries (revokeEntry, archiveTenant, and the
114
+ -- shred guard's own eligibility lookup all need them). UPDATE, DELETE and
115
+ -- TRUNCATE on keys_held_versions are revoked from the runtime role (the
116
+ -- host lists the table under `appendOnly`): #225's revised answer keeps a
117
+ -- shredded row (permanent but unreadable, matching ADR 0019 and audit
118
+ -- rows), so DELETE/TRUNCATE were never legitimate; UPDATE is revoked because
119
+ -- every legitimate write to this table -- retire, shred -- now runs through
120
+ -- a SECURITY DEFINER function rather than the runtime role's own privilege,
121
+ -- and the one write that still needs ordinary UPDATE (rewrap) is an
122
+ -- operator's job, not the runtime role's (item 3). The runtime role gets
123
+ -- EXECUTE on keys_shred_expired() (the host passes it under `grants`),
124
+ -- nothing wider.
125
+ --
126
+ -- Every function here pins its search_path to the schema this file runs in,
127
+ -- followed by pg_catalog, with pg_temp last, so a caller-owned temporary
128
+ -- relation cannot shadow one of this schema's. The first statement builds
129
+ -- that path for this transaction; `set search_path from current` then
130
+ -- records it on each function.
131
+ select set_config('search_path', quote_ident(current_schema()) || ', pg_catalog, pg_temp', true);
126
132
 
127
133
  alter table keys_held_entries
128
134
  add column if not exists tenant_archived_at timestamptz;
@@ -139,7 +145,7 @@ create or replace function keys_shred_expired()
139
145
  returns integer
140
146
  language plpgsql
141
147
  security definer
142
- set search_path = pg_catalog, public
148
+ set search_path from current
143
149
  as $$
144
150
  declare
145
151
  shredded integer;
@@ -289,7 +295,7 @@ create trigger keys_held_versions_no_truncate
289
295
  create or replace function keys_held_versions_retire_predecessors() returns trigger
290
296
  language plpgsql
291
297
  security definer
292
- set search_path = pg_catalog, public
298
+ set search_path from current
293
299
  as $$
294
300
  begin
295
301
  update keys_held_versions
@@ -348,14 +354,3 @@ drop trigger if exists keys_held_entries_clock_guard_update on keys_held_entries
348
354
  create trigger keys_held_entries_clock_guard_update
349
355
  before update on keys_held_entries
350
356
  for each row execute function keys_held_entries_clock_guard();
351
-
352
- do $$
353
- declare
354
- rt text := current_database() || '_rt';
355
- begin
356
- if exists (select 1 from pg_roles where rolname = rt) then
357
- execute format('revoke update, delete, truncate on keys_held_versions from %I', rt);
358
- execute format('grant execute on function keys_shred_expired() to %I', rt);
359
- end if;
360
- end
361
- $$;
@@ -1,38 +1,44 @@
1
1
  -- Security review K01/K07. Additive upgrade; do not edit copied migrations.
2
- -- Explicit relation qualification defeats caller-owned temporary relations.
3
- -- The runtime role must not own these objects or have CREATE on public.
4
- create or replace function public.keys_shred_expired()
2
+ -- Explicit relation qualification defeats caller-owned temporary relations:
3
+ -- every function here pins its search_path to the schema this file runs in,
4
+ -- followed by pg_catalog, with pg_temp last. The first statement builds that
5
+ -- path for this transaction; `set search_path from current` then records it
6
+ -- on each function. The runtime role must not own these objects or have
7
+ -- CREATE on the schema; the host's `ensureRuntimeRole` never grants it.
8
+ select set_config('search_path', quote_ident(current_schema()) || ', pg_catalog, pg_temp', true);
9
+
10
+ create or replace function keys_shred_expired()
5
11
  returns integer
6
12
  language plpgsql
7
13
  security definer
8
- set search_path = pg_catalog, public, pg_temp
14
+ set search_path from current
9
15
  as $$
10
16
  declare
11
17
  shredded integer;
12
18
  begin
13
- update public.keys_held_versions kv
19
+ update keys_held_versions kv
14
20
  set wrapped_key = null
15
- from public.keys_held_entries ke
21
+ from keys_held_entries ke
16
22
  where kv.tenant_id = ke.tenant_id
17
23
  and kv.entry_id = ke.entry_id
18
24
  and kv.wrapped_key is not null
19
25
  and (
20
26
  (kv.retired_at is not null
21
- and now() >= kv.retired_at + (public.keys_shred_delay_days() || ' days')::interval)
27
+ and now() >= kv.retired_at + (keys_shred_delay_days() || ' days')::interval)
22
28
  or (ke.revoked_at is not null
23
- and now() >= ke.revoked_at + (public.keys_shred_delay_days() || ' days')::interval)
29
+ and now() >= ke.revoked_at + (keys_shred_delay_days() || ' days')::interval)
24
30
  or (ke.tenant_archived_at is not null
25
- and now() >= ke.tenant_archived_at + (public.keys_shred_delay_days() || ' days')::interval)
31
+ and now() >= ke.tenant_archived_at + (keys_shred_delay_days() || ' days')::interval)
26
32
  );
27
33
  get diagnostics shredded = row_count;
28
34
  return shredded;
29
35
  end
30
36
  $$;
31
- revoke all on function public.keys_shred_expired() from public;
37
+ revoke all on function keys_shred_expired() from public;
32
38
 
33
- create or replace function public.keys_held_versions_guard() returns trigger
39
+ create or replace function keys_held_versions_guard() returns trigger
34
40
  language plpgsql
35
- set search_path = pg_catalog, public, pg_temp
41
+ set search_path from current
36
42
  as $$
37
43
  declare
38
44
  is_rewrap boolean;
@@ -101,7 +107,7 @@ begin
101
107
  -- with the same shape -- the trigger cannot and does not distinguish
102
108
  -- the two): the shape alone is not enough -- this row's own stored
103
109
  -- clocks, which can no longer be forged (see the file header), must
104
- -- already show public.keys_shred_delay_days() elapsed, the same predicate
110
+ -- already show keys_shred_delay_days() elapsed, the same predicate
105
111
  -- keys_shred_expired()'s WHERE clause applies.
106
112
  is_shred := old.wrapped_key is not null
107
113
  and new.wrapped_key is null
@@ -109,22 +115,22 @@ begin
109
115
  and new.retired_at is not distinct from old.retired_at
110
116
  and (
111
117
  (new.retired_at is not null
112
- and now() >= new.retired_at + (public.keys_shred_delay_days() || ' days')::interval)
118
+ and now() >= new.retired_at + (keys_shred_delay_days() || ' days')::interval)
113
119
  or exists (
114
- select 1 from public.keys_held_entries ke
120
+ select 1 from keys_held_entries ke
115
121
  where ke.tenant_id = new.tenant_id
116
122
  and ke.entry_id = new.entry_id
117
123
  and (
118
124
  (ke.revoked_at is not null
119
- and now() >= ke.revoked_at + (public.keys_shred_delay_days() || ' days')::interval)
125
+ and now() >= ke.revoked_at + (keys_shred_delay_days() || ' days')::interval)
120
126
  or (ke.tenant_archived_at is not null
121
- and now() >= ke.tenant_archived_at + (public.keys_shred_delay_days() || ' days')::interval)
127
+ and now() >= ke.tenant_archived_at + (keys_shred_delay_days() || ' days')::interval)
122
128
  )
123
129
  )
124
130
  );
125
131
 
126
132
  if not (is_rewrap or is_retire or is_shred) then
127
- 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 public.keys_shred_delay_days() -- refused, including un-retiring, un-shredding, shredding early, and any change to ciphertext or iv';
133
+ 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 keys_shred_delay_days() -- refused, including un-retiring, un-shredding, shredding early, and any change to ciphertext or iv';
128
134
  end if;
129
135
  end if;
130
136
  return new;
@@ -134,37 +140,37 @@ $$;
134
140
  -- Serialize publication before INSERT takes a snapshot of other versions.
135
141
  -- Reservations may finish out of order; current_version remains the reservation
136
142
  -- counter, not a promise that that version was successfully published.
137
- create or replace function public.keys_held_versions_publish_guard() returns trigger
143
+ create or replace function keys_held_versions_publish_guard() returns trigger
138
144
  language plpgsql
139
145
  security definer
140
- set search_path = pg_catalog, public, pg_temp
146
+ set search_path from current
141
147
  as $$
142
148
  declare
143
149
  revoked timestamptz;
144
150
  begin
145
- select revoked_at into revoked from public.keys_held_entries
151
+ select revoked_at into revoked from keys_held_entries
146
152
  where tenant_id = new.tenant_id and entry_id = new.entry_id for update;
147
153
  if revoked is not null then
148
154
  raise exception 'held entry is revoked';
149
155
  end if;
150
- if exists (select 1 from public.keys_held_versions
156
+ if exists (select 1 from keys_held_versions
151
157
  where tenant_id = new.tenant_id and entry_id = new.entry_id and version > new.version) then
152
158
  new.retired_at := clock_timestamp();
153
159
  end if;
154
160
  return new;
155
161
  end
156
162
  $$;
157
- drop trigger if exists keys_held_versions_publish on public.keys_held_versions;
158
- create trigger keys_held_versions_publish before insert on public.keys_held_versions
159
- for each row execute function public.keys_held_versions_publish_guard();
163
+ drop trigger if exists keys_held_versions_publish on keys_held_versions;
164
+ create trigger keys_held_versions_publish before insert on keys_held_versions
165
+ for each row execute function keys_held_versions_publish_guard();
160
166
 
161
- create or replace function public.keys_held_versions_retire_predecessors() returns trigger
167
+ create or replace function keys_held_versions_retire_predecessors() returns trigger
162
168
  language plpgsql
163
169
  security definer
164
- set search_path = pg_catalog, public, pg_temp
170
+ set search_path from current
165
171
  as $$
166
172
  begin
167
- update public.keys_held_versions set retired_at = clock_timestamp()
173
+ update keys_held_versions set retired_at = clock_timestamp()
168
174
  where tenant_id = new.tenant_id and entry_id = new.entry_id
169
175
  and version < new.version and retired_at is null;
170
176
  return null;
@@ -173,9 +179,9 @@ $$;
173
179
 
174
180
  -- A transaction's start time is caller-controlled by holding it open. Stamp
175
181
  -- clocks at the actual write, so long transactions cannot backdate eligibility.
176
- create or replace function public.keys_held_entries_clock_guard() returns trigger
182
+ create or replace function keys_held_entries_clock_guard() returns trigger
177
183
  language plpgsql
178
- set search_path = pg_catalog, public, pg_temp
184
+ set search_path from current
179
185
  as $$
180
186
  begin
181
187
  if tg_op = 'INSERT' then
@@ -204,43 +210,3 @@ begin
204
210
  return new;
205
211
  end
206
212
  $$;
207
-
208
- -- K03: keep issued revocations irreversible under ordinary table privileges.
209
- -- Retaining IDs also prevents deleting and reinserting a revoked signed row.
210
- create or replace function public.keys_issued_guard() returns trigger
211
- language plpgsql
212
- set search_path = pg_catalog, public, pg_temp
213
- as $$
214
- begin
215
- if tg_op in ('DELETE', 'TRUNCATE') then
216
- raise exception 'keys_issued_credentials: delete and truncate refused';
217
- end if;
218
- if tg_op = 'UPDATE' then
219
- if new.id is distinct from old.id or new.issued_by_id is distinct from old.issued_by_id
220
- or new.key_prefix is distinct from old.key_prefix then
221
- raise exception 'keys_issued_credentials: identity and lineage are immutable';
222
- end if;
223
- if old.revoked_at is not null and new.revoked_at is distinct from old.revoked_at then
224
- raise exception 'keys_issued_credentials: revocation is permanent';
225
- end if;
226
- end if;
227
- return new;
228
- end
229
- $$;
230
- drop trigger if exists keys_issued_guard_update on public.keys_issued_credentials;
231
- create trigger keys_issued_guard_update before update or delete on public.keys_issued_credentials
232
- for each row execute function public.keys_issued_guard();
233
- drop trigger if exists keys_issued_guard_truncate on public.keys_issued_credentials;
234
- create trigger keys_issued_guard_truncate before truncate on public.keys_issued_credentials
235
- for each statement execute function public.keys_issued_guard();
236
-
237
- do $$
238
- declare rt text := current_database() || '_rt';
239
- begin
240
- revoke create on schema public from public;
241
- if exists (select 1 from pg_roles where rolname = rt) then
242
- execute format('revoke create on schema public from %I', rt);
243
- execute format('revoke delete, truncate on public.keys_issued_credentials from %I', rt);
244
- end if;
245
- end
246
- $$;
@@ -0,0 +1,73 @@
1
+ -- @wtfalch/keys: the ./host entry's event table. Mirrors src/host/schema.ts.
2
+ --
3
+ -- One row per thing @wtfalch/keys did for this host: a caller key
4
+ -- authenticating (key.used, ./held's KeyUsedEvent) or this host minting,
5
+ -- rotating or revoking one of its own issued credentials (credential.minted /
6
+ -- .rotated / .revoked, ./issued's AuditEvent). Not audit_events -- a host
7
+ -- picking this table over its own audit ledger is the host's call, made
8
+ -- for the same reasons every existing host copy of this table already
9
+ -- recorded (a core `credential.*` namespace a host's own audit vocabulary
10
+ -- may refuse, and a held-key `key.used` row carrying no tenant Access to
11
+ -- sign an audit_events row with). Which columns apply depends on kind: a
12
+ -- key.used row carries request_id, tenant_id, entry_id and version; a
13
+ -- credential.* row carries request_id (absent on credential.revoked, which
14
+ -- never calls the Worker) and credential_id; all four are nullable for that
15
+ -- reason.
16
+ --
17
+ -- `./host`'s `auditEndpoint` reads only the three kinds that carry a
18
+ -- request_id (`key.used`, `credential.minted`, `credential.rotated`) --
19
+ -- `packages/reconcile`'s own contract (`packages/reconcile/README.md`,
20
+ -- "Host audit contract"): `credential.revoked` has no Worker call to pair
21
+ -- against and is excluded there, not here -- this table still records it,
22
+ -- for a host's own audit trail.
23
+ --
24
+ -- Append-only via the guard trigger below: every UPDATE, DELETE and
25
+ -- TRUNCATE is refused outright -- this table has no in-place edit, so
26
+ -- there is no narrower shape to allow. The trigger is the first wall; the
27
+ -- second is the host listing this table under `appendOnly` in
28
+ -- `ensureRuntimeRole` (README), which leaves its runtime role INSERT and
29
+ -- SELECT only. Roles stay host-owned: this migration owns none.
30
+ --
31
+ -- Applied by the host's own migrate script after the host copies this file
32
+ -- into its own migrations directory as the next number (keys-migrations);
33
+ -- never edited there. Every statement is idempotent.
34
+
35
+ create table if not exists keys_host_events (
36
+ id bigint generated always as identity primary key,
37
+ kind text not null,
38
+ request_id text,
39
+ credential_id text,
40
+ tenant_id text,
41
+ entry_id text,
42
+ version integer,
43
+ at timestamptz not null default now(),
44
+ constraint keys_host_events_kind_check
45
+ check (kind in ('key.used', 'credential.minted', 'credential.rotated', 'credential.revoked'))
46
+ );
47
+ create index if not exists keys_host_events_at_idx on keys_host_events (at);
48
+
49
+ create or replace function keys_host_events_guard() returns trigger
50
+ language plpgsql as $$
51
+ begin
52
+ if tg_op = 'UPDATE' then
53
+ raise exception 'keys_host_events is append-only: update refused';
54
+ elsif tg_op = 'DELETE' then
55
+ raise exception 'keys_host_events is append-only: delete refused';
56
+ elsif tg_op = 'TRUNCATE' then
57
+ raise exception 'keys_host_events is append-only: truncate refused';
58
+ end if;
59
+ return null;
60
+ end
61
+ $$;
62
+ drop trigger if exists keys_host_events_no_update on keys_host_events;
63
+ create trigger keys_host_events_no_update
64
+ before update on keys_host_events
65
+ for each row execute function keys_host_events_guard();
66
+ drop trigger if exists keys_host_events_no_delete on keys_host_events;
67
+ create trigger keys_host_events_no_delete
68
+ before delete on keys_host_events
69
+ for each row execute function keys_host_events_guard();
70
+ drop trigger if exists keys_host_events_no_truncate on keys_host_events;
71
+ create trigger keys_host_events_no_truncate
72
+ before truncate on keys_host_events
73
+ for each statement execute function keys_host_events_guard();
@@ -0,0 +1,29 @@
1
+ -- #47: a built-in `environment` on every issued credential, so a host's
2
+ -- sandbox/live split is a structured field rather than a convention the host
3
+ -- invents on top of `key_prefix`. Additive; do not edit copied migrations.
4
+ --
5
+ -- Not part of SignableRow (worker-contract.ts): the Worker's signature never
6
+ -- covers it, same footing as idempotency_key and created_at. What keeps it
7
+ -- trustworthy despite that is keys_issued_guard() (0006_keys_issued_guard.sql),
8
+ -- which refuses any UPDATE that changes it -- set once at issue(), for that row's life.
9
+ --
10
+ -- Backfilled 'live' on existing rows: every row minted before this migration
11
+ -- was minted under a single, unqualified prefix, which today's default
12
+ -- environment ('live') matches.
13
+ alter table keys_issued_credentials
14
+ add column if not exists environment text not null default 'live';
15
+ alter table keys_issued_credentials alter column environment drop default;
16
+
17
+ do $$
18
+ begin
19
+ if not exists (
20
+ select 1 from pg_constraint
21
+ where conname = 'keys_issued_credentials_environment_check'
22
+ and conrelid = 'keys_issued_credentials'::regclass
23
+ ) then
24
+ alter table keys_issued_credentials
25
+ add constraint keys_issued_credentials_environment_check
26
+ check (environment in ('live', 'test'));
27
+ end if;
28
+ end
29
+ $$;