@coffre/db 0.10.1 → 0.11.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/dist/connect.d.ts +1 -1
- package/dist/{database-DBtn3jqp.d.ts → database-Dh4W2pAj.d.ts} +1 -1
- package/dist/dialect.d.ts +7 -1
- package/dist/dialect.js +10 -1
- package/dist/grants.d.ts +12 -5
- package/dist/grants.js +13 -8
- package/dist/hyperdrive.d.ts +9 -2
- package/dist/hyperdrive.js +16 -2
- package/dist/index.d.ts +2 -2
- package/dist/log.d.ts +65 -3
- package/dist/log.js +26 -14
- package/dist/migrations/postgres/0015_workload_access.sql +43 -0
- package/dist/migrations/postgres/0016_spent_tokens.sql +12 -0
- package/dist/migrations/postgres/meta/0015_snapshot.json +3256 -0
- package/dist/migrations/postgres/meta/0016_snapshot.json +3256 -0
- package/dist/migrations/postgres/meta/_journal.json +14 -0
- package/dist/migrations/sqlite/0015_workload_access.sql +70 -0
- package/dist/migrations/sqlite/meta/0015_snapshot.json +2959 -0
- package/dist/migrations/sqlite/meta/_journal.json +7 -0
- package/dist/portable.d.ts +2 -2
- package/dist/{schema-NBVA9q-s.d.ts → schema-DG2t57Kf.d.ts} +327 -2
- package/dist/schema-sqlite.d.ts +346 -1
- package/dist/schema-sqlite.js +53 -5
- package/dist/schema-version.d.ts +1 -1
- package/dist/schema-version.js +21 -0
- package/dist/schema.d.ts +2 -2
- package/dist/schema.js +54 -5
- package/package.json +2 -2
- package/src/dialect.ts +10 -0
- package/src/grants.ts +18 -9
- package/src/hyperdrive.ts +16 -2
- package/src/log.ts +35 -10
- package/src/migrations/postgres/0015_workload_access.sql +43 -0
- package/src/migrations/postgres/0016_spent_tokens.sql +12 -0
- package/src/migrations/postgres/meta/0015_snapshot.json +3256 -0
- package/src/migrations/postgres/meta/0016_snapshot.json +3256 -0
- package/src/migrations/postgres/meta/_journal.json +14 -0
- package/src/migrations/sqlite/0015_workload_access.sql +70 -0
- package/src/migrations/sqlite/meta/0015_snapshot.json +2959 -0
- package/src/migrations/sqlite/meta/_journal.json +7 -0
- package/src/schema.sqlite.ts +73 -2
- package/src/schema.ts +73 -2
package/src/grants.ts
CHANGED
|
@@ -205,35 +205,44 @@ export async function everyProjectPreview(db: Queryable, at: number): Promise<Ev
|
|
|
205
205
|
});
|
|
206
206
|
}
|
|
207
207
|
|
|
208
|
-
/**
|
|
209
|
-
|
|
208
|
+
/**
|
|
209
|
+
* A service token or trust binding whose scope this release has not sealed
|
|
210
|
+
* yet: none of its own, as 0.4 made it (`scope` null), or one that does not
|
|
211
|
+
* say where it reads sensitive values, as a release before 0.11 made it. By
|
|
212
|
+
* whom it was issued, `createdBy`, a person's email.
|
|
213
|
+
*/
|
|
214
|
+
export type Unsealed = { kind: 'token' | 'binding'; id: string; principal: string; createdBy: string; scope: string | null };
|
|
210
215
|
|
|
211
216
|
/**
|
|
212
217
|
* The live service tokens and trust bindings of active service accounts
|
|
213
|
-
*
|
|
214
|
-
*
|
|
215
|
-
*
|
|
218
|
+
* whose scope is not sealed yet (`Unsealed`): what the app seals once a
|
|
219
|
+
* process (`sealScopes`), and what `coffre migrate` says it will. A
|
|
220
|
+
* credential a binding issued carries its binding's.
|
|
216
221
|
*/
|
|
217
222
|
export async function unsealedCredentials(db: Queryable, at: Date): Promise<Unsealed[]> {
|
|
218
223
|
const { credentials, serviceBindings, vaultMembers } = tablesOf(db);
|
|
224
|
+
// Every scope this release writes for a service says, at each place it names, whether it reads the sensitive values
|
|
225
|
+
// there; one that names none, sealed while its account held nothing, is sealed (`unsealedScope` in @coffre/server).
|
|
226
|
+
const unsealed = (scope: typeof credentials.scope | typeof serviceBindings.scope) =>
|
|
227
|
+
or(isNull(scope), and(like(scope, '%"projectId"%'), sql`${scope} NOT LIKE '%"sensitive":%'`));
|
|
219
228
|
const [tokens, bindings] = await Promise.all([
|
|
220
229
|
db
|
|
221
|
-
.select({ id: credentials.id, principal: credentials.principal })
|
|
230
|
+
.select({ id: credentials.id, principal: credentials.principal, createdBy: credentials.createdBy, scope: credentials.scope })
|
|
222
231
|
.from(credentials)
|
|
223
232
|
.innerJoin(vaultMembers, and(eq(vaultMembers.principal, credentials.principal), eq(vaultMembers.generation, credentials.generation)))
|
|
224
233
|
.where(and(
|
|
225
234
|
eq(credentials.kind, 'service'),
|
|
226
|
-
|
|
235
|
+
unsealed(credentials.scope),
|
|
227
236
|
sql`${credentials.createdBy} NOT LIKE 'binding:%'`,
|
|
228
237
|
isNull(credentials.revokedAt),
|
|
229
238
|
gt(credentials.expiresAt, at),
|
|
230
239
|
eq(vaultMembers.status, 'active'),
|
|
231
240
|
)),
|
|
232
241
|
db
|
|
233
|
-
.select({ id: serviceBindings.id, principal: serviceBindings.principal })
|
|
242
|
+
.select({ id: serviceBindings.id, principal: serviceBindings.principal, createdBy: serviceBindings.createdBy, scope: serviceBindings.scope })
|
|
234
243
|
.from(serviceBindings)
|
|
235
244
|
.innerJoin(vaultMembers, and(eq(vaultMembers.principal, serviceBindings.principal), eq(vaultMembers.generation, serviceBindings.generation)))
|
|
236
|
-
.where(and(
|
|
245
|
+
.where(and(unsealed(serviceBindings.scope), isNull(serviceBindings.revokedAt), eq(vaultMembers.status, 'active'))),
|
|
237
246
|
]);
|
|
238
247
|
return [
|
|
239
248
|
...tokens.map((row) => ({ kind: 'token' as const, ...row })),
|
package/src/hyperdrive.ts
CHANGED
|
@@ -48,16 +48,26 @@ export class HyperdrivePool implements Exclude<PoolLike, pg.Pool> {
|
|
|
48
48
|
#busy = 0;
|
|
49
49
|
/** What waits for the client to be idle: `end`. */
|
|
50
50
|
readonly #idle: (() => void)[] = [];
|
|
51
|
+
/** How long the client may sit idle before it closes, or null: closed by `end` alone. */
|
|
52
|
+
readonly #closeIdleMs: number | null;
|
|
53
|
+
#idleTimer: ReturnType<typeof setTimeout> | undefined;
|
|
51
54
|
|
|
52
|
-
|
|
55
|
+
/**
|
|
56
|
+
* `closeIdleMs`: for what outlives a call, a Durable Object, which queries
|
|
57
|
+
* now and then: the client closes once it has been idle that long, and
|
|
58
|
+
* the next query connects again.
|
|
59
|
+
*/
|
|
60
|
+
constructor(connectionString: string, options: { closeIdleMs?: number } = {}) {
|
|
53
61
|
if (connectionString.trim().length === 0) {
|
|
54
62
|
throw new Error('Hyperdrive returned an empty connection string');
|
|
55
63
|
}
|
|
56
64
|
this.#connectionString = connectionString;
|
|
65
|
+
this.#closeIdleMs = options.closeIdleMs ?? null;
|
|
57
66
|
}
|
|
58
67
|
|
|
59
68
|
readonly query: pg.Pool['query'] = (async (...args: unknown[]) => {
|
|
60
69
|
this.#busy += 1;
|
|
70
|
+
clearTimeout(this.#idleTimer);
|
|
61
71
|
try {
|
|
62
72
|
const client = await this.#connected();
|
|
63
73
|
return await new Promise((resolve, reject) => {
|
|
@@ -72,6 +82,7 @@ export class HyperdrivePool implements Exclude<PoolLike, pg.Pool> {
|
|
|
72
82
|
/** The client, for a transaction: held from now until `release`. */
|
|
73
83
|
async connect(): Promise<Pick<pg.PoolClient, 'query'> & { release: () => void }> {
|
|
74
84
|
this.#busy += 1;
|
|
85
|
+
clearTimeout(this.#idleTimer);
|
|
75
86
|
let client: pg.Client;
|
|
76
87
|
try {
|
|
77
88
|
client = await this.#connected();
|
|
@@ -100,6 +111,7 @@ export class HyperdrivePool implements Exclude<PoolLike, pg.Pool> {
|
|
|
100
111
|
|
|
101
112
|
/** Close the client once nothing waits on it: what a Worker hands `waitUntil` when the call is done. */
|
|
102
113
|
async end(): Promise<void> {
|
|
114
|
+
clearTimeout(this.#idleTimer);
|
|
103
115
|
while (this.#busy > 0) {
|
|
104
116
|
await new Promise<void>((resolve) => this.#idle.push(resolve));
|
|
105
117
|
}
|
|
@@ -123,7 +135,9 @@ export class HyperdrivePool implements Exclude<PoolLike, pg.Pool> {
|
|
|
123
135
|
/** One query or transaction done: once none is left, what waits for the client to be idle goes on. */
|
|
124
136
|
#done(): void {
|
|
125
137
|
this.#busy -= 1;
|
|
126
|
-
if (this.#busy
|
|
138
|
+
if (this.#busy > 0) return;
|
|
139
|
+
for (const resolve of this.#idle.splice(0)) resolve();
|
|
140
|
+
if (this.#closeIdleMs !== null && this.#client !== null) this.#idleTimer = setTimeout(() => void this.end(), this.#closeIdleMs);
|
|
127
141
|
}
|
|
128
142
|
|
|
129
143
|
/** The call's client, connecting it the first time. One that fails is dropped: the next query connects again. */
|
package/src/log.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { GENESIS_HASH, sealEntry, type LogFields, type LogKey, type StoredEntry } from '@coffre/core/audit';
|
|
2
|
-
import { and, asc, count, desc, eq, gt, gte, lt, lte, sql, type SQL } from 'drizzle-orm';
|
|
2
|
+
import { and, asc, count, desc, eq, gt, gte, lt, lte, sql, type Placeholder, type SQL } from 'drizzle-orm';
|
|
3
3
|
|
|
4
4
|
import { afterCommit } from './commits.ts';
|
|
5
5
|
import { tablesOf, type Queryable, type Transaction } from './database.ts';
|
|
6
6
|
import { prepared } from './prepared.ts';
|
|
7
|
-
import { clockMillis, forUpdate } from './dialect.ts';
|
|
7
|
+
import { clockMillis, engineOf, forUpdate } from './dialect.ts';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Appending to the audit log, the one table both the app and the vault
|
|
@@ -124,15 +124,21 @@ export async function appendEntries(
|
|
|
124
124
|
key: LogKey,
|
|
125
125
|
entries: readonly NewEntry[],
|
|
126
126
|
check?: (tx: Transaction) => Promise<void>,
|
|
127
|
+
/**
|
|
128
|
+
* The head as a statement of the caller's locked it, with the log's last
|
|
129
|
+
* entry and the clock as that statement read them once it held the lock:
|
|
130
|
+
* nothing to read again.
|
|
131
|
+
*/
|
|
132
|
+
locked?: HeldHead,
|
|
127
133
|
): Promise<Appended> {
|
|
128
134
|
if (entries.length === 0) throw new Error('appendEntries called with no entries');
|
|
129
135
|
const { auditChainHead, auditLog } = tablesOf(tx);
|
|
130
136
|
|
|
131
137
|
// Every append queues here, if its transaction has not already.
|
|
132
|
-
const head = await lockLogHead(tx);
|
|
138
|
+
const head = locked?.head ?? (await lockLogHead(tx));
|
|
133
139
|
await check?.(tx);
|
|
134
|
-
const
|
|
135
|
-
const
|
|
140
|
+
const now = locked?.at ?? (await clockNow(tx))[0]!.now;
|
|
141
|
+
const last = locked === undefined ? (await lastEntry(tx))[0] : locked.last ?? undefined;
|
|
136
142
|
|
|
137
143
|
const expected = last === undefined ? { nextSeq: 0n, headHash: GENESIS_HASH } : { nextSeq: last.seq + 1n, headHash: last.hash };
|
|
138
144
|
if (head.nextSeq !== expected.nextSeq || !head.headHash.equals(expected.headHash)) {
|
|
@@ -179,13 +185,25 @@ export async function appendEntries(
|
|
|
179
185
|
seq += 1n;
|
|
180
186
|
}
|
|
181
187
|
|
|
182
|
-
|
|
183
|
-
|
|
188
|
+
if (engineOf(tx) === 'postgres' && rows.length <= ROWS_AT_ONCE) {
|
|
189
|
+
// The entries and the head that names the last of them, in one statement.
|
|
190
|
+
await tx.execute(sql`WITH appended AS (${tx.insert(auditLog).values(rows).getSQL()})
|
|
191
|
+
UPDATE audit_chain_head SET next_seq = ${seq}, head_hash = ${prevHash} WHERE only_row`);
|
|
192
|
+
} else {
|
|
193
|
+
await tx.insert(auditLog).values(rows);
|
|
194
|
+
await tx.update(auditChainHead).set({ nextSeq: seq, headHash: prevHash }).where(eq(auditChainHead.onlyRow, true));
|
|
195
|
+
}
|
|
184
196
|
const written = { nextSeq: seq, headHash: prevHash };
|
|
185
197
|
afterCommit(tx, () => remember(key, written));
|
|
186
198
|
return { seqStart: head.nextSeq, ...written, occurredAt: now };
|
|
187
199
|
}
|
|
188
200
|
|
|
201
|
+
/** A head locked by a statement of the caller's, and what it read under the lock (`appendEntries`). */
|
|
202
|
+
export type HeldHead = { head: { nextSeq: bigint; headHash: Buffer }; last: { seq: bigint; hash: Buffer } | null; at: number };
|
|
203
|
+
|
|
204
|
+
/** Entries one statement inserts at most, at 21 parameters each: Postgres takes 65,535. */
|
|
205
|
+
const ROWS_AT_ONCE = 3000;
|
|
206
|
+
|
|
189
207
|
const clockNow = prepared((db) => db.select({ now: clockMillis(db) }).from(tablesOf(db).auditChainHead));
|
|
190
208
|
|
|
191
209
|
const lastEntry = prepared((db) => {
|
|
@@ -325,15 +343,22 @@ export async function newestVaultSeq(db: Queryable, action: string): Promise<big
|
|
|
325
343
|
return (row?.seq as bigint | undefined) ?? null;
|
|
326
344
|
}
|
|
327
345
|
|
|
328
|
-
const newestSeq = prepared((db) =>
|
|
346
|
+
const newestSeq = prepared((db) => newestSeqQuery(db, sql.placeholder('action')));
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* `newestVaultSeq`'s query, to run or to read inside another, as a
|
|
350
|
+
* credential's read takes the newest `policy.change` with it: one rule for
|
|
351
|
+
* what the newest is, wherever it is read.
|
|
352
|
+
*/
|
|
353
|
+
export function newestSeqQuery(db: Queryable, action: string | Placeholder) {
|
|
329
354
|
const { auditLog } = tablesOf(db);
|
|
330
355
|
return db
|
|
331
356
|
.select({ seq: auditLog.seq })
|
|
332
357
|
.from(auditLog)
|
|
333
|
-
.where(and(eq(auditLog.author, 'vault'), eq(auditLog.action,
|
|
358
|
+
.where(and(eq(auditLog.author, 'vault'), eq(auditLog.action, action), eq(auditLog.decision, 'allow')))
|
|
334
359
|
.orderBy(desc(auditLog.seq))
|
|
335
360
|
.limit(1);
|
|
336
|
-
}
|
|
361
|
+
}
|
|
337
362
|
|
|
338
363
|
/** How many entries in its name the vault reads back, a page at a time, for its own newest of a kind (`newestAuthentic`). */
|
|
339
364
|
export const LOOK_BACK = { page: 32, pages: 32 };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
-- Workload access (docs/design/workload-access.md, section 11): key-bound sessions, their enrollment codes, and bindings' policies. It only adds: the release before neither reads nor writes any of it, and every check is only looser for its rows, so it serves on this schema unchanged.
|
|
2
|
+
CREATE TABLE "enrollments" (
|
|
3
|
+
"id" uuid PRIMARY KEY NOT NULL,
|
|
4
|
+
"auth_mac" "bytea" NOT NULL,
|
|
5
|
+
"binding_id" uuid NOT NULL,
|
|
6
|
+
"code_hash" "bytea" NOT NULL,
|
|
7
|
+
"code_hint" text NOT NULL,
|
|
8
|
+
"scope" text NOT NULL,
|
|
9
|
+
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
|
10
|
+
"created_by" text NOT NULL,
|
|
11
|
+
"created_with" uuid,
|
|
12
|
+
"expires_at" timestamp with time zone NOT NULL,
|
|
13
|
+
CONSTRAINT "enrollments_code_hash_key" UNIQUE("code_hash"),
|
|
14
|
+
CONSTRAINT "enrollments_auth_mac_check" CHECK (octet_length("enrollments"."auth_mac") = 32),
|
|
15
|
+
CONSTRAINT "enrollments_code_hash_check" CHECK (octet_length("enrollments"."code_hash") = 32),
|
|
16
|
+
CONSTRAINT "enrollments_scope_check" CHECK ("enrollments"."scope"::jsonb IS NOT NULL)
|
|
17
|
+
);
|
|
18
|
+
--> statement-breakpoint
|
|
19
|
+
-- The checks widen to a workload's session, a service's credential like a service token; a session carries the key it is bound to.
|
|
20
|
+
ALTER TABLE "credentials" DROP CONSTRAINT "credentials_kind_check";--> statement-breakpoint
|
|
21
|
+
ALTER TABLE "credentials" DROP CONSTRAINT "credentials_kind_matches_principal";--> statement-breakpoint
|
|
22
|
+
ALTER TABLE "credentials" ADD COLUMN "jkt" text;--> statement-breakpoint
|
|
23
|
+
ALTER TABLE "credentials" ADD COLUMN "not_after" timestamp with time zone;--> statement-breakpoint
|
|
24
|
+
ALTER TABLE "credentials" ADD COLUMN "ancestors" text;--> statement-breakpoint
|
|
25
|
+
ALTER TABLE "credentials" ADD COLUMN "constraints" text;--> statement-breakpoint
|
|
26
|
+
ALTER TABLE "credentials" ADD COLUMN "enrollment_id" uuid;--> statement-breakpoint
|
|
27
|
+
ALTER TABLE "credentials" ADD COLUMN "approved_at" timestamp with time zone;--> statement-breakpoint
|
|
28
|
+
ALTER TABLE "credentials" ADD COLUMN "approved_by" text;--> statement-breakpoint
|
|
29
|
+
-- A binding's policy, inserted with it under the table-wide INSERT, and named by no UPDATE grant: as immutable as the rest of it.
|
|
30
|
+
ALTER TABLE "service_bindings" ADD COLUMN "policy" text;--> statement-breakpoint
|
|
31
|
+
ALTER TABLE "enrollments" ADD CONSTRAINT "enrollments_binding_id_fkey" FOREIGN KEY ("binding_id") REFERENCES "public"."service_bindings"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
|
32
|
+
CREATE INDEX "enrollments_binding_idx" ON "enrollments" USING btree ("binding_id","created_at" DESC NULLS LAST);--> statement-breakpoint
|
|
33
|
+
ALTER TABLE "credentials" ADD CONSTRAINT "credentials_enrollment_id_fkey" FOREIGN KEY ("enrollment_id") REFERENCES "public"."enrollments"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
|
34
|
+
-- Freezes are the log's: a target's newest allowed freeze or lift, and a code's supersession, its tombstone.
|
|
35
|
+
CREATE INDEX "audit_log_freeze_idx" ON "audit_log" USING btree ((("metadata")::jsonb ->> 'target'),"seq" DESC NULLS LAST) WHERE "audit_log"."author" = 'app' AND "audit_log"."action" IN ('workload.freeze', 'workload.unfreeze') AND "audit_log"."decision" = 'allow';--> statement-breakpoint
|
|
36
|
+
CREATE INDEX "audit_log_supersede_idx" ON "audit_log" USING btree ((("metadata")::jsonb ->> 'enrollmentId')) WHERE "audit_log"."author" = 'app' AND "audit_log"."action" = 'enrollment.supersede' AND "audit_log"."decision" = 'allow';--> statement-breakpoint
|
|
37
|
+
CREATE INDEX "credentials_enrollment_roots_idx" ON "credentials" USING btree ("enrollment_id","created_at") WHERE "credentials"."kind" = 'workload' AND "credentials"."ancestors" IS NULL;--> statement-breakpoint
|
|
38
|
+
ALTER TABLE "credentials" ADD CONSTRAINT "credentials_workload_jkt_check" CHECK ("credentials"."kind" <> 'workload' OR "credentials"."jkt" IS NOT NULL);--> statement-breakpoint
|
|
39
|
+
ALTER TABLE "credentials" ADD CONSTRAINT "credentials_kind_check" CHECK ("credentials"."kind" IN ('browser', 'cli', 'service', 'personal', 'handle', 'workload'));--> statement-breakpoint
|
|
40
|
+
ALTER TABLE "credentials" ADD CONSTRAINT "credentials_kind_matches_principal" CHECK (("credentials"."kind" IN ('service', 'workload')) = ("credentials"."principal" LIKE 'token:%'));--> statement-breakpoint
|
|
41
|
+
-- The app makes codes and never changes one; a session's key, hard end, ancestors, limits and code are set when it is made, and never after: renewal moves its expiry, and an approval is the one other change.
|
|
42
|
+
GRANT SELECT, INSERT ON enrollments TO coffre_app;--> statement-breakpoint
|
|
43
|
+
GRANT UPDATE (expires_at, approved_at, approved_by) ON credentials TO coffre_app;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
-- Spent tokens (W157): a token's record goes once no exchange could take the token again. An exchange refuses one issued over an hour ago (MAX_TOKEN_AGE_SECONDS, 30 s of clock tolerance), so two hours after it was spent its record guards nothing. The runtime login still deletes no row itself: it asks this function, which deletes only such records, at most at_most a call. The release before never calls it.
|
|
2
|
+
CREATE FUNCTION prune_consumed_tokens(at_most integer) RETURNS integer
|
|
3
|
+
LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$
|
|
4
|
+
WITH pruned AS (
|
|
5
|
+
DELETE FROM public.consumed_tokens
|
|
6
|
+
WHERE hash IN (SELECT hash FROM public.consumed_tokens WHERE consumed_at < now() - interval '2 hours' LIMIT at_most)
|
|
7
|
+
RETURNING 1
|
|
8
|
+
)
|
|
9
|
+
SELECT count(*)::integer FROM pruned;
|
|
10
|
+
$$;--> statement-breakpoint
|
|
11
|
+
REVOKE ALL ON FUNCTION prune_consumed_tokens(integer) FROM PUBLIC;--> statement-breakpoint
|
|
12
|
+
GRANT EXECUTE ON FUNCTION prune_consumed_tokens(integer) TO coffre_app;
|