@wtfalch/keys 0.4.2 → 0.7.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 +160 -5
- package/dist/bin/copy.d.ts +8 -4
- package/dist/bin/copy.js +8 -4
- package/dist/bin/migrations.js +21 -7
- package/dist/held/schema.js +1 -1
- package/dist/held/seal.d.ts +22 -0
- package/dist/held/seal.js +48 -0
- package/dist/held/shred.d.ts +1 -1
- package/dist/held/shred.js +1 -1
- package/dist/held-edge/index.d.ts +50 -0
- package/dist/held-edge/index.js +175 -0
- package/dist/host/audit-endpoint.d.ts +15 -0
- package/dist/host/audit-endpoint.js +117 -0
- package/dist/host/events.d.ts +26 -0
- package/dist/host/events.js +31 -0
- package/dist/host/index.d.ts +11 -0
- package/dist/host/index.js +11 -0
- package/dist/host/schema.d.ts +153 -0
- package/dist/host/schema.js +20 -0
- package/dist/issued/index.js +2 -2
- package/dist/issued/ratelimit.d.ts +1 -1
- package/dist/issued/ratelimit.js +1 -1
- package/dist/issued/resign.js +1 -1
- package/dist/issued/tables.d.ts +4 -4
- package/dist/issued/tables.js +4 -4
- package/dist/migrations/{0003_keys_shred.sql → held/0002_keys_shred.sql} +26 -31
- package/dist/migrations/{0004_keys_security.sql → held/0003_keys_security.sql} +36 -70
- package/dist/migrations/host/0001_keys_host_events.sql +73 -0
- package/dist/migrations/issued/0002_keys_environment.sql +29 -0
- package/dist/migrations/{0006_keys_usage.sql → issued/0003_keys_usage.sql} +3 -2
- package/dist/migrations/{0008_keys_environment_default.sql → issued/0005_keys_environment_default.sql} +1 -1
- package/dist/migrations/issued/0006_keys_issued_guard.sql +47 -0
- package/dist/migrations-dir.d.ts +19 -0
- package/dist/migrations-dir.js +20 -0
- package/dist/testing/index.d.ts +9 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/worker-stub.d.ts +55 -0
- package/dist/testing/worker-stub.js +180 -0
- package/package.json +21 -4
- package/dist/migrations/0005_keys_environment.sql +0 -52
- package/dist/migrations/0009_keys_issued_guard.sql +0 -46
- /package/dist/migrations/{0002_keys_held.sql → held/0001_keys_held.sql} +0 -0
- /package/dist/migrations/{0001_keys_issued.sql → issued/0001_keys_issued.sql} +0 -0
- /package/dist/migrations/{0007_keys_rate_limit.sql → issued/0004_keys_rate_limit.sql} +0 -0
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { and, asc, gte, inArray, isNotNull, lt } from 'drizzle-orm';
|
|
3
|
+
import { keysHostEvents } from './schema.js';
|
|
4
|
+
/**
|
|
5
|
+
* `GET /v1/keys/audit` -- the per-host read-only endpoint
|
|
6
|
+
* `packages/reconcile` pulls from (`../../reconcile/README.md`'s "Host
|
|
7
|
+
* audit contract", and that package's `hosts.ts`/`types.ts` for the exact
|
|
8
|
+
* wire shape this must return). Every host that adopts `./host` ships the
|
|
9
|
+
* same response shape, so `packages/reconcile` never has to special-case
|
|
10
|
+
* one host's endpoint against another's -- this is exactly the copy that
|
|
11
|
+
* issue #83 found drifting between `files`, `ai`, `integrations` and
|
|
12
|
+
* `boule` (one of the four copies dropped the target fields the contract
|
|
13
|
+
* requires; the drift is silent until reconciliation starts flagging false
|
|
14
|
+
* `host_row_unmatched` findings).
|
|
15
|
+
*
|
|
16
|
+
* Fails closed throughout: a misconfigured token refuses to serve at all
|
|
17
|
+
* (503) rather than falling back to "accept anything", an unrecognised or
|
|
18
|
+
* malformed request is refused before it ever reaches the database (400),
|
|
19
|
+
* and a window matching more rows than this endpoint will ever return is
|
|
20
|
+
* refused outright (413) rather than silently truncated -- a dropped row
|
|
21
|
+
* here would look identical to a real reconciliation finding on the other
|
|
22
|
+
* side (`packages/reconcile/README.md`'s own fails-closed rule for the
|
|
23
|
+
* client half of this contract).
|
|
24
|
+
*/
|
|
25
|
+
const REQUEST_BEARING_KINDS = ['key.used', 'credential.minted', 'credential.rotated'];
|
|
26
|
+
/** No signs, no exponents, at most 16 digits -- deliberately narrower than "whatever `Number()` accepts". */
|
|
27
|
+
const INTEGER_PATTERN = /^\d{1,16}$/;
|
|
28
|
+
const THIRTY_ONE_DAYS_MS = 31 * 24 * 60 * 60 * 1000;
|
|
29
|
+
/** A dropped row would look like a real reconciliation finding; refuse the whole window instead of truncating it. */
|
|
30
|
+
const MAX_ROWS = 50_000;
|
|
31
|
+
const BEARER_PATTERN = /^Bearer ([^\s]+)$/;
|
|
32
|
+
function jsonResponse(body, status) {
|
|
33
|
+
return Response.json(body, { status, headers: { 'cache-control': 'no-store' } });
|
|
34
|
+
}
|
|
35
|
+
const unavailable = () => jsonResponse({ error: { code: 'unavailable' } }, 503);
|
|
36
|
+
const unauthorized = () => jsonResponse({ error: { code: 'unauthorized' } }, 401);
|
|
37
|
+
const badRequest = () => jsonResponse({ error: { code: 'bad_request' } }, 400);
|
|
38
|
+
const windowTooLarge = () => jsonResponse({ error: { code: 'window_too_large' } }, 413);
|
|
39
|
+
const methodNotAllowed = () => jsonResponse({ error: { code: 'method_not_allowed' } }, 405);
|
|
40
|
+
/** Constant-time regardless of length: both sides are always a 32-byte SHA-256 digest, so `timingSafeEqual` never throws on a length mismatch here. */
|
|
41
|
+
function tokensMatch(presented, configured) {
|
|
42
|
+
const a = createHash('sha256').update(presented, 'utf8').digest();
|
|
43
|
+
const b = createHash('sha256').update(configured, 'utf8').digest();
|
|
44
|
+
return timingSafeEqual(a, b);
|
|
45
|
+
}
|
|
46
|
+
/** `Number(bigint)` past this silently rounds, which would let `since`/`until` collapse together after conversion even though the `bigint` comparison above said they didn't. 16 digits alone doesn't rule that out, so bound it explicitly too. */
|
|
47
|
+
const MAX_SAFE_WINDOW_PARAM = BigInt(Number.MAX_SAFE_INTEGER);
|
|
48
|
+
/** A decimal-integer query param, or `null` for anything else -- absent, empty, signed, fractional, exponential, over 16 digits, or past `Number.MAX_SAFE_INTEGER`. */
|
|
49
|
+
function parseWindowParam(raw) {
|
|
50
|
+
if (raw === null || !INTEGER_PATTERN.test(raw))
|
|
51
|
+
return null;
|
|
52
|
+
const value = BigInt(raw);
|
|
53
|
+
return value <= MAX_SAFE_WINDOW_PARAM ? value : null;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* `auditEndpoint({ db, token })` returns a fetch-shaped handler
|
|
57
|
+
* (`(request: Request) => Promise<Response>`) -- wire it directly as a
|
|
58
|
+
* route: `export const GET = auditEndpoint({ db, token:
|
|
59
|
+
* process.env.KEYS_AUDIT_TOKEN });`. Deps are read once, at handler
|
|
60
|
+
* construction; nothing here is re-read per request.
|
|
61
|
+
*/
|
|
62
|
+
export function auditEndpoint(options) {
|
|
63
|
+
const { db, token } = options;
|
|
64
|
+
return async function handleKeysAudit(request) {
|
|
65
|
+
if (request.method !== 'GET')
|
|
66
|
+
return methodNotAllowed();
|
|
67
|
+
// A misconfigured host must not serve, regardless of what the caller presents.
|
|
68
|
+
if (!token || token.length < 32)
|
|
69
|
+
return unavailable();
|
|
70
|
+
const match = BEARER_PATTERN.exec(request.headers.get('authorization') ?? '');
|
|
71
|
+
if (!match?.[1] || !tokensMatch(match[1], token))
|
|
72
|
+
return unauthorized();
|
|
73
|
+
const url = new URL(request.url);
|
|
74
|
+
const since = parseWindowParam(url.searchParams.get('since'));
|
|
75
|
+
const until = parseWindowParam(url.searchParams.get('until'));
|
|
76
|
+
if (since === null ||
|
|
77
|
+
until === null ||
|
|
78
|
+
since >= until ||
|
|
79
|
+
until - since > BigInt(THIRTY_ONE_DAYS_MS)) {
|
|
80
|
+
return badRequest();
|
|
81
|
+
}
|
|
82
|
+
const sinceMs = Number(since);
|
|
83
|
+
const untilMs = Number(until);
|
|
84
|
+
const rows = await db
|
|
85
|
+
.select({
|
|
86
|
+
kind: keysHostEvents.kind,
|
|
87
|
+
requestId: keysHostEvents.requestId,
|
|
88
|
+
credentialId: keysHostEvents.credentialId,
|
|
89
|
+
tenantId: keysHostEvents.tenantId,
|
|
90
|
+
entryId: keysHostEvents.entryId,
|
|
91
|
+
version: keysHostEvents.version,
|
|
92
|
+
at: keysHostEvents.at,
|
|
93
|
+
})
|
|
94
|
+
.from(keysHostEvents)
|
|
95
|
+
.where(and(inArray(keysHostEvents.kind, [...REQUEST_BEARING_KINDS]), isNotNull(keysHostEvents.requestId), gte(keysHostEvents.at, new Date(sinceMs)), lt(keysHostEvents.at, new Date(untilMs))))
|
|
96
|
+
.orderBy(asc(keysHostEvents.at), asc(keysHostEvents.id))
|
|
97
|
+
.limit(MAX_ROWS + 1);
|
|
98
|
+
if (rows.length > MAX_ROWS)
|
|
99
|
+
return windowTooLarge();
|
|
100
|
+
const body = rows.map((row) => {
|
|
101
|
+
// `at` is timestamptz (microsecond storage); every row here was
|
|
102
|
+
// written from a unix-ms `Date`, so its fraction is already an exact
|
|
103
|
+
// multiple of one millisecond -- floor explicitly anyway rather than
|
|
104
|
+
// trust that.
|
|
105
|
+
const common = {
|
|
106
|
+
kind: row.kind,
|
|
107
|
+
requestId: row.requestId,
|
|
108
|
+
at: Math.floor(row.at.getTime()),
|
|
109
|
+
};
|
|
110
|
+
if (row.kind === 'key.used') {
|
|
111
|
+
return { ...common, tenantId: row.tenantId, entryId: row.entryId, version: row.version };
|
|
112
|
+
}
|
|
113
|
+
return { ...common, credentialId: row.credentialId };
|
|
114
|
+
});
|
|
115
|
+
return jsonResponse(body, 200);
|
|
116
|
+
};
|
|
117
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { KeyUsedEvent } from '../held/index.js';
|
|
2
|
+
import type { Db } from '../issued/index.js';
|
|
3
|
+
import type { AuditEvent } from '../issued/index.js';
|
|
4
|
+
/**
|
|
5
|
+
* Every event `./issued`'s `AuditCallback` or `./held`'s `audit` option can
|
|
6
|
+
* hand `recordEvent` -- the exact union `CreateCredentialIssuerOptions.audit`
|
|
7
|
+
* (`AuditEvent`, discriminated by `name`: `'credential.minted' |
|
|
8
|
+
* 'credential.rotated' | 'credential.revoked'`) and `CreateHeldKeysOptions.audit`
|
|
9
|
+
* (`KeyUsedEvent`, `name: 'key.used'`) can ever produce, between them.
|
|
10
|
+
*
|
|
11
|
+
* `recordEvent`'s own parameter is this union, wider than either option
|
|
12
|
+
* alone expects, so `(event) => recordEvent(db, event)` type-checks as both
|
|
13
|
+
* an `AuditCallback` and a held `audit` callback -- a function that accepts
|
|
14
|
+
* more than an option asks for is assignable wherever that option is asked
|
|
15
|
+
* for (TypeScript's ordinary parameter contravariance), with no cast on
|
|
16
|
+
* either side.
|
|
17
|
+
*/
|
|
18
|
+
export type HostEvent = AuditEvent | KeyUsedEvent;
|
|
19
|
+
/**
|
|
20
|
+
* Inserts one `keys_host_events` row: this host's own append-only record of
|
|
21
|
+
* what `@wtfalch/keys` did on its behalf. Takes a drizzle handle rather than
|
|
22
|
+
* assuming a module-level `db`, so a script built on its own handle can call
|
|
23
|
+
* it without pulling in a host's database module, and a test can point it at
|
|
24
|
+
* a disposable one.
|
|
25
|
+
*/
|
|
26
|
+
export declare function recordEvent(db: Db, event: HostEvent): Promise<void>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { keysHostEvents } from './schema.js';
|
|
2
|
+
/**
|
|
3
|
+
* Inserts one `keys_host_events` row: this host's own append-only record of
|
|
4
|
+
* what `@wtfalch/keys` did on its behalf. Takes a drizzle handle rather than
|
|
5
|
+
* assuming a module-level `db`, so a script built on its own handle can call
|
|
6
|
+
* it without pulling in a host's database module, and a test can point it at
|
|
7
|
+
* a disposable one.
|
|
8
|
+
*/
|
|
9
|
+
export async function recordEvent(db, event) {
|
|
10
|
+
if (event.name === 'key.used') {
|
|
11
|
+
await db.insert(keysHostEvents).values({
|
|
12
|
+
kind: event.name,
|
|
13
|
+
requestId: event.requestId,
|
|
14
|
+
credentialId: null,
|
|
15
|
+
tenantId: event.tenantId,
|
|
16
|
+
entryId: event.entryId,
|
|
17
|
+
version: event.version,
|
|
18
|
+
at: new Date(event.at),
|
|
19
|
+
});
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
await db.insert(keysHostEvents).values({
|
|
23
|
+
kind: event.name,
|
|
24
|
+
requestId: event.requestId ?? null,
|
|
25
|
+
credentialId: event.credentialId,
|
|
26
|
+
tenantId: null,
|
|
27
|
+
entryId: null,
|
|
28
|
+
version: null,
|
|
29
|
+
at: new Date(event.at),
|
|
30
|
+
});
|
|
31
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `./host`: the pieces of a keys host that #83 found hand-copied into
|
|
3
|
+
* every consumer (`files`, `ai`, `integrations`, `boule`) -- the event
|
|
4
|
+
* table `./issued` and `./held`'s `audit` options write to, and the
|
|
5
|
+
* read-only endpoint `packages/reconcile` pulls from. See the package
|
|
6
|
+
* README's "Adopting ./host" for how an existing host swaps its own copy
|
|
7
|
+
* for this one with no behaviour change.
|
|
8
|
+
*/
|
|
9
|
+
export { auditEndpoint, type AuditEndpointOptions } from './audit-endpoint.js';
|
|
10
|
+
export { recordEvent, type HostEvent } from './events.js';
|
|
11
|
+
export { keysHostEvents, type KeysHostEventRow } from './schema.js';
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `./host`: the pieces of a keys host that #83 found hand-copied into
|
|
3
|
+
* every consumer (`files`, `ai`, `integrations`, `boule`) -- the event
|
|
4
|
+
* table `./issued` and `./held`'s `audit` options write to, and the
|
|
5
|
+
* read-only endpoint `packages/reconcile` pulls from. See the package
|
|
6
|
+
* README's "Adopting ./host" for how an existing host swaps its own copy
|
|
7
|
+
* for this one with no behaviour change.
|
|
8
|
+
*/
|
|
9
|
+
export { auditEndpoint } from './audit-endpoint.js';
|
|
10
|
+
export { recordEvent } from './events.js';
|
|
11
|
+
export { keysHostEvents } from './schema.js';
|
|
@@ -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)]);
|
package/dist/issued/index.js
CHANGED
|
@@ -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
|
|
51
|
+
select id from keys_issued_credentials where id = ${id}
|
|
52
52
|
union
|
|
53
53
|
select c.id
|
|
54
|
-
from
|
|
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`, `
|
|
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.
|
package/dist/issued/ratelimit.js
CHANGED
|
@@ -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`, `
|
|
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.
|
package/dist/issued/resign.js
CHANGED
|
@@ -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
|
|
165
|
+
from keys_issued_credentials
|
|
166
166
|
where signing_generation_id = ${generationId}
|
|
167
167
|
`);
|
|
168
168
|
const rows = Array.isArray(result)
|
package/dist/issued/tables.d.ts
CHANGED
|
@@ -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`. `
|
|
22
|
-
*
|
|
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, `
|
|
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.
|
package/dist/issued/tables.js
CHANGED
|
@@ -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`. `
|
|
23
|
-
*
|
|
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, `
|
|
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
|
|
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,
|
|
110
|
-
--
|
|
111
|
-
--
|
|
112
|
-
-- and
|
|
113
|
-
--
|
|
114
|
-
--
|
|
115
|
-
-- on
|
|
116
|
-
--
|
|
117
|
-
--
|
|
118
|
-
--
|
|
119
|
-
--
|
|
120
|
-
--
|
|
121
|
-
--
|
|
122
|
-
--
|
|
123
|
-
--
|
|
124
|
-
--
|
|
125
|
-
--
|
|
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
|
|
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
|
|
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
|
-
$$;
|