@coffre/db 0.10.2 → 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.
Files changed (38) hide show
  1. package/dist/connect.d.ts +1 -1
  2. package/dist/{database-DBtn3jqp.d.ts → database-Dh4W2pAj.d.ts} +1 -1
  3. package/dist/dialect.d.ts +1 -1
  4. package/dist/grants.d.ts +12 -5
  5. package/dist/grants.js +13 -8
  6. package/dist/hyperdrive.d.ts +9 -2
  7. package/dist/hyperdrive.js +16 -2
  8. package/dist/index.d.ts +2 -2
  9. package/dist/log.d.ts +1 -1
  10. package/dist/migrations/postgres/0015_workload_access.sql +43 -0
  11. package/dist/migrations/postgres/0016_spent_tokens.sql +12 -0
  12. package/dist/migrations/postgres/meta/0015_snapshot.json +3256 -0
  13. package/dist/migrations/postgres/meta/0016_snapshot.json +3256 -0
  14. package/dist/migrations/postgres/meta/_journal.json +14 -0
  15. package/dist/migrations/sqlite/0015_workload_access.sql +70 -0
  16. package/dist/migrations/sqlite/meta/0015_snapshot.json +2959 -0
  17. package/dist/migrations/sqlite/meta/_journal.json +7 -0
  18. package/dist/portable.d.ts +2 -2
  19. package/dist/{schema-NBVA9q-s.d.ts → schema-DG2t57Kf.d.ts} +327 -2
  20. package/dist/schema-sqlite.d.ts +346 -1
  21. package/dist/schema-sqlite.js +53 -5
  22. package/dist/schema-version.d.ts +1 -1
  23. package/dist/schema-version.js +21 -0
  24. package/dist/schema.d.ts +2 -2
  25. package/dist/schema.js +54 -5
  26. package/package.json +2 -2
  27. package/src/grants.ts +18 -9
  28. package/src/hyperdrive.ts +16 -2
  29. package/src/migrations/postgres/0015_workload_access.sql +43 -0
  30. package/src/migrations/postgres/0016_spent_tokens.sql +12 -0
  31. package/src/migrations/postgres/meta/0015_snapshot.json +3256 -0
  32. package/src/migrations/postgres/meta/0016_snapshot.json +3256 -0
  33. package/src/migrations/postgres/meta/_journal.json +14 -0
  34. package/src/migrations/sqlite/0015_workload_access.sql +70 -0
  35. package/src/migrations/sqlite/meta/0015_snapshot.json +2959 -0
  36. package/src/migrations/sqlite/meta/_journal.json +7 -0
  37. package/src/schema.sqlite.ts +73 -2
  38. 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
- /** A service token or trust binding of 0.4, which carries no scope of its own yet. */
209
- export type Unsealed = { kind: 'token' | 'binding'; id: string; principal: string };
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
- * that carry no scope yet, as 0.4 made them: what the app seals with each
214
- * account's grants once a process (`sealScopes`), and what `coffre migrate`
215
- * says it will. A credential a binding issued carries its binding's.
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
- isNull(credentials.scope),
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(isNull(serviceBindings.scope), isNull(serviceBindings.revokedAt), eq(vaultMembers.status, 'active'))),
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
- constructor(connectionString: string) {
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 === 0) for (const resolve of this.#idle.splice(0)) resolve();
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. */
@@ -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;