@capybara-hq/kernel 0.1.0-rc.134 → 0.1.0-rc.135

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/bootstrap.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schemaVersion": 1,
4
4
  "marketplace": {
5
5
  "url": "https://github.com/capybara-hq/plugins.git",
6
- "commit": "51e2cc85e7d660867500f23259d883459bd2609f"
6
+ "commit": "d5b799da18c7ca44e3b97f9bc13dae6b61495dfd"
7
7
  },
8
8
  "plugins": [
9
9
  {
@@ -69,11 +69,18 @@ export declare const KernelConfigSchema: z.ZodObject<{
69
69
  url: z.ZodString;
70
70
  migrationUrl: z.ZodOptional<z.ZodString>;
71
71
  extensionsUrl: z.ZodOptional<z.ZodString>;
72
+ extensionCredentialsDir: z.ZodOptional<z.ZodString>;
73
+ extensionProvisioningUrl: z.ZodOptional<z.ZodString>;
74
+ extensionConnectionLimit: z.ZodDefault<z.ZodNumber>;
75
+ extensionStatementTimeoutMs: z.ZodDefault<z.ZodNumber>;
76
+ extensionIdleTransactionTimeoutMs: z.ZodDefault<z.ZodNumber>;
77
+ extensionTempFileLimitKb: z.ZodDefault<z.ZodNumber>;
72
78
  extensionEffectRelayLogin: z.ZodOptional<z.ZodString>;
73
79
  extensionPoolMax: z.ZodDefault<z.ZodNumber>;
74
80
  poolMax: z.ZodDefault<z.ZodNumber>;
75
81
  connectTimeoutMs: z.ZodDefault<z.ZodNumber>;
76
82
  idleTimeoutMs: z.ZodDefault<z.ZodNumber>;
83
+ rlsOwnerRole: z.ZodDefault<z.ZodString>;
77
84
  rls: z.ZodDefault<z.ZodEnum<{
78
85
  enforce: "enforce";
79
86
  off: "off";
@@ -342,7 +342,58 @@ export const KernelConfigSchema = z.strictObject({
342
342
  .optional()
343
343
  .meta(meta({
344
344
  secret: true,
345
- description: "PostgreSQL connection URL for the shared extension login",
345
+ description: "PostgreSQL endpoint and former shared login name for dedicated extension database identities",
346
+ })),
347
+ extensionCredentialsDir: z
348
+ .string()
349
+ .min(1)
350
+ .optional()
351
+ .meta(meta({
352
+ description: "Directory of operator-managed per-extension PostgreSQL password files",
353
+ })),
354
+ extensionProvisioningUrl: z
355
+ .string()
356
+ .min(1)
357
+ .optional()
358
+ .meta(meta({
359
+ secret: true,
360
+ description: "PostgreSQL administration URL for one-shot extension database provisioning only",
361
+ })),
362
+ extensionConnectionLimit: z
363
+ .number()
364
+ .int()
365
+ .min(2)
366
+ .max(1000)
367
+ .default(32)
368
+ .meta(meta({
369
+ description: "Maximum PostgreSQL sessions per extension across replicas, workers, lanes, and migrations",
370
+ })),
371
+ extensionStatementTimeoutMs: z
372
+ .number()
373
+ .int()
374
+ .positive()
375
+ .max(2_147_483_647)
376
+ .default(60_000)
377
+ .meta(meta({
378
+ description: "Default statement timeout for each dedicated extension login in milliseconds",
379
+ })),
380
+ extensionIdleTransactionTimeoutMs: z
381
+ .number()
382
+ .int()
383
+ .positive()
384
+ .max(2_147_483_647)
385
+ .default(30_000)
386
+ .meta(meta({
387
+ description: "Default idle-in-transaction timeout for each dedicated extension login in milliseconds",
388
+ })),
389
+ extensionTempFileLimitKb: z
390
+ .number()
391
+ .int()
392
+ .positive()
393
+ .max(2_147_483_647)
394
+ .default(65_536)
395
+ .meta(meta({
396
+ description: "Temporary file budget for each dedicated extension database session in KiB",
346
397
  })),
347
398
  extensionEffectRelayLogin: z
348
399
  .string()
@@ -379,11 +430,18 @@ export const KernelConfigSchema = z.strictObject({
379
430
  .meta(meta({
380
431
  description: "How long an idle PostgreSQL connection stays in the pool, in milliseconds",
381
432
  })),
433
+ rlsOwnerRole: z
434
+ .string()
435
+ .min(1)
436
+ .default("capybara_owner")
437
+ .meta(meta({
438
+ description: "PostgreSQL role expected to own the kernel schema and org tables in enforce mode",
439
+ })),
382
440
  rls: z
383
441
  .enum(["off", "scoped", "enforce"])
384
442
  .default("off")
385
443
  .meta(meta({
386
- description: "PostgreSQL row-level security mode where off leaves scope unset, scoped sets transaction-local scope while policies admit all rows, and enforce filters by transaction-local scope on tables with RLS enabled when the runtime login is subject to the policies. Both scoped modes require session-capable connections, with ordinary standalone queries sharing a round trip with their scope setup.",
444
+ description: "PostgreSQL row-level security mode where off leaves scope unset, scoped sets transaction-local scope while policies admit all rows, and enforce filters by transaction-local scope. Enforce requires the split database roles, the owner migration, and enabled and forced org policies at startup. Both scoped modes require session-capable connections, with ordinary standalone queries sharing a round trip with their scope setup.",
387
445
  })),
388
446
  })
389
447
  .prefault({}),
@@ -5,11 +5,15 @@ export type ExtensionDbConnection = {
5
5
  login: string;
6
6
  url: string;
7
7
  separate: boolean;
8
+ /** Only dedicated identities can be handed to an isolated extension. */
9
+ dedicated?: true;
8
10
  };
9
11
  /** Kernel-owned credentials, resolved from the canonical extension name. */
10
12
  export interface ExtensionDbIdentity {
11
13
  resolve(name: string): ExtensionDbConnection;
12
14
  readonly sharedLogin?: string | undefined;
15
+ /** Used only by the one-shot operator to provision staged extensions. */
16
+ provisionedNames?(): string[];
13
17
  }
14
18
  export declare class ConfiguredExtensionDbIdentity implements ExtensionDbIdentity {
15
19
  private readonly identity;
@@ -17,11 +21,12 @@ export declare class ConfiguredExtensionDbIdentity implements ExtensionDbIdentit
17
21
  get sharedLogin(): string | undefined;
18
22
  resolve(name: string): ExtensionDbConnection;
19
23
  }
20
- export declare function extensionDbIdentity(db: Pick<KernelConfig["db"], "url" | "extensionsUrl">): ExtensionDbIdentity;
24
+ export declare function validateExtensionCredentials(db: Pick<KernelConfig["db"], "extensionsUrl" | "extensionCredentialsDir">): void;
25
+ export declare function extensionDbIdentity(db: Pick<KernelConfig["db"], "url" | "extensionsUrl" | "extensionCredentialsDir">): ExtensionDbIdentity;
21
26
  export declare function pluginSchemaName(name: string): string;
22
- export declare function assertExtensionSession(client: pg.ClientBase, login: string): Promise<void>;
27
+ export declare function assertExtensionSession(client: pg.ClientBase, login: string, dedicatedSchema?: string): Promise<void>;
23
28
  /** A missing schema is normal before a plugin's first migration. */
24
- export declare function assertExtensionSchemaOwner(client: pg.ClientBase, schema: string, login: string): Promise<void>;
29
+ export declare function assertExtensionSchemaOwner(client: pg.ClientBase, schema: string, login: string, required?: boolean): Promise<void>;
25
30
  /** One small, scope-aware pool per active extension instance. The host owns its lifetime. */
26
31
  export declare function extensionDbPool(identity: ExtensionDbConnection, name: string, config: {
27
32
  connectTimeoutMs?: number | undefined;
@@ -7,6 +7,10 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
+ import { createHash } from "node:crypto";
11
+ import { closeSync, constants, fstatSync, openSync, readdirSync, readFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { EXTENSION_NAME_RE } from "@capybara-hq/plugin-sdk";
10
14
  import { Inject, Injectable } from "@nestjs/common";
11
15
  import pg from "pg";
12
16
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
@@ -28,19 +32,99 @@ ConfiguredExtensionDbIdentity = __decorate([
28
32
  __param(0, Inject(KernelConfigService))
29
33
  ], ConfiguredExtensionDbIdentity);
30
34
  export { ConfiguredExtensionDbIdentity };
35
+ function readExtensionPassword(directory, name) {
36
+ if (!EXTENSION_NAME_RE.test(name))
37
+ throw new Error(`Invalid extension name: ${name}`);
38
+ let fd;
39
+ try {
40
+ fd = openSync(join(directory, `${name}.password`), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
41
+ }
42
+ catch {
43
+ throw new Error(`Cannot open database credential for extension ${name} in db.extensionCredentialsDir`);
44
+ }
45
+ try {
46
+ const info = fstatSync(fd);
47
+ if (!info.isFile() || (info.mode & 0o7777) !== 0o600)
48
+ throw new Error(`Database credential for extension ${name} must be a regular file with mode 0600`);
49
+ const password = readFileSync(fd, "utf8").replace(/\r?\n$/, "");
50
+ if (!password ||
51
+ [...password].some((character) => {
52
+ const code = character.charCodeAt(0);
53
+ return code < 32 || code > 126;
54
+ })) {
55
+ throw new Error(`Database credential for extension ${name} must contain a printable ASCII password`);
56
+ }
57
+ return password;
58
+ }
59
+ finally {
60
+ closeSync(fd);
61
+ }
62
+ }
63
+ function credentialNames(directory) {
64
+ try {
65
+ return readdirSync(directory)
66
+ .filter((file) => file.endsWith(".password"))
67
+ .map((file) => file.slice(0, -".password".length))
68
+ .sort();
69
+ }
70
+ catch {
71
+ throw new Error("Cannot read db.extensionCredentialsDir");
72
+ }
73
+ }
74
+ export function validateExtensionCredentials(db) {
75
+ if (db.extensionsUrl === undefined)
76
+ return;
77
+ const directory = db.extensionCredentialsDir;
78
+ if (!directory)
79
+ throw new Error("db.extensionsUrl requires db.extensionCredentialsDir");
80
+ const seen = new Map();
81
+ for (const name of credentialNames(directory)) {
82
+ const fingerprint = createHash("sha256")
83
+ .update(readExtensionPassword(directory, name))
84
+ .digest("hex");
85
+ const other = seen.get(fingerprint);
86
+ if (other)
87
+ throw new Error(`Database credentials for extensions ${other} and ${name} must use distinct passwords`);
88
+ seen.set(fingerprint, name);
89
+ }
90
+ }
31
91
  export function extensionDbIdentity(db) {
32
92
  const url = db.extensionsUrl ?? db.url;
33
93
  const separate = db.extensionsUrl !== undefined;
34
- let login;
94
+ let endpoint;
35
95
  try {
36
- login = new pg.Client({ connectionString: url }).user;
96
+ endpoint = new pg.Client({ connectionString: url });
37
97
  }
38
98
  catch {
39
99
  throw new Error("Invalid PostgreSQL connection URL for extensions");
40
100
  }
101
+ const { user: login, database } = endpoint;
41
102
  if (!login)
42
103
  throw new Error("PostgreSQL connection needs a login");
43
- return { sharedLogin: separate ? login : undefined, resolve: () => ({ login, url, separate }) };
104
+ const directory = db.extensionCredentialsDir;
105
+ if (!separate)
106
+ return { resolve: () => ({ login, url, separate: false }) };
107
+ if (!directory)
108
+ throw new Error("db.extensionsUrl requires db.extensionCredentialsDir");
109
+ if (!database)
110
+ throw new Error("Dedicated extension connections need a PostgreSQL database");
111
+ if (!URL.canParse(url))
112
+ throw new Error("db.extensionsUrl must be a PostgreSQL URL");
113
+ return {
114
+ sharedLogin: login,
115
+ provisionedNames: () => credentialNames(directory),
116
+ resolve(name) {
117
+ const password = readExtensionPassword(directory, name);
118
+ const hash = createHash("sha256").update(database).update("\0").update(name).digest("hex");
119
+ const username = `cap_ext_${hash.slice(0, 40)}`;
120
+ const target = new URL(url);
121
+ target.searchParams.delete("user");
122
+ target.searchParams.delete("password");
123
+ target.username = username;
124
+ target.password = encodeURIComponent(password);
125
+ return { login: username, url: target.toString(), separate: true, dedicated: true };
126
+ },
127
+ };
44
128
  }
45
129
  export function pluginSchemaName(name) {
46
130
  return `plugin_${name.replaceAll("-", "_")}`;
@@ -58,17 +142,33 @@ const extensionLoginCheck = `
58
142
  ), false) as isolated
59
143
  from pg_catalog.pg_roles r where r.rolname = $1
60
144
  `;
61
- export async function assertExtensionSession(client, login) {
145
+ export async function assertExtensionSession(client, login, dedicatedSchema) {
62
146
  const { rows: [actual], } = await client.query("select current_user as login");
63
147
  const { rows: [role], } = await client.query(extensionLoginCheck, [login]);
64
148
  if (actual?.login !== login || !role?.isolated) {
65
149
  throw new Error("db.extensionsUrl must authenticate as a restricted extension login with no access to capybara");
66
150
  }
151
+ if (dedicatedSchema !== undefined) {
152
+ const { rows: [privileges], } = await client.query(`select pg_catalog.has_database_privilege(current_database(), 'CREATE') as can_create,
153
+ exists (
154
+ select from pg_catalog.pg_shdepend d
155
+ cross join lateral pg_catalog.pg_identify_object(d.classid, d.objid, d.objsubid) obj
156
+ where d.dbid = (select oid from pg_catalog.pg_database where datname = current_database())
157
+ and d.refclassid = 'pg_catalog.pg_authid'::regclass
158
+ and d.refobjid = current_user::regrole and d.deptype = 'o'
159
+ and coalesce(obj.schema, case when obj.type = 'schema' then obj.name end) <> $1
160
+ ) as foreign_owner`, [dedicatedSchema]);
161
+ if (!privileges || privileges.can_create || privileges.foreign_owner)
162
+ throw new Error(`Extension login ${login} has database CREATE or owns objects outside its schema`);
163
+ }
67
164
  }
68
165
  /** A missing schema is normal before a plugin's first migration. */
69
- export async function assertExtensionSchemaOwner(client, schema, login) {
166
+ export async function assertExtensionSchemaOwner(client, schema, login, required = false) {
70
167
  const { rows: [namespace], } = await client.query(`select pg_catalog.pg_get_userbyid(nspowner) as owner
71
168
  from pg_catalog.pg_namespace where nspname = $1`, [schema]);
169
+ if (required && !namespace) {
170
+ throw new Error(`Missing extension schema ${schema}. Run the one-shot extension database provisioner.`);
171
+ }
72
172
  if (namespace && namespace.owner !== login) {
73
173
  throw new Error(`Extension schema ${schema} is owned by ${namespace.owner}, expected ${login}. Run capybara migrate with the owner URL to transfer plugin schemas.`);
74
174
  }
@@ -85,8 +185,8 @@ export function extensionDbPool(identity, name, config, onError) {
85
185
  onConnect: async (client) => {
86
186
  if (!identity.separate)
87
187
  return;
88
- await assertExtensionSession(client, identity.login);
89
- await assertExtensionSchemaOwner(client, schema, identity.login);
188
+ await assertExtensionSession(client, identity.login, identity.dedicated ? schema : undefined);
189
+ await assertExtensionSchemaOwner(client, schema, identity.login, identity.dedicated);
90
190
  await client.query("select pg_catalog.set_config('search_path', $1, false)", [searchPath]);
91
191
  },
92
192
  });
@@ -0,0 +1,9 @@
1
+ import pg from "pg";
2
+ import type { KernelConfig } from "../config/schema.js";
3
+ import type { ExtensionDbConnection } from "./extension-db.js";
4
+ export declare const EMPTY_EXTENSION_SCHEMA_COMMENT = "Capybara provisioned empty extension schema";
5
+ export declare function createProvisionedExtensionSchema(admin: pg.ClientBase, schema: string, login: string): Promise<void>;
6
+ type ExtensionLimits = Pick<KernelConfig["db"], "extensionConnectionLimit" | "extensionStatementTimeoutMs" | "extensionIdleTransactionTimeoutMs" | "extensionTempFileLimitKb">;
7
+ /** Runs in the operator transaction under the extension provisioning lock. */
8
+ export declare function provisionExtensionRole(admin: pg.ClientBase, name: string, identity: ExtensionDbConnection, limits: ExtensionLimits): Promise<boolean>;
9
+ export {};
@@ -0,0 +1,89 @@
1
+ import { createHash, createHmac, pbkdf2Sync, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import pg from "pg";
3
+ export const EMPTY_EXTENSION_SCHEMA_COMMENT = "Capybara provisioned empty extension schema";
4
+ export async function createProvisionedExtensionSchema(admin, schema, login) {
5
+ const identifier = pg.escapeIdentifier(schema);
6
+ await admin.query(`create schema ${identifier} authorization ${pg.escapeIdentifier(login)}`);
7
+ await admin.query(`comment on schema ${identifier} is ${pg.escapeLiteral(EMPTY_EXTENSION_SCHEMA_COMMENT)}`);
8
+ }
9
+ const scramIterations = 4096;
10
+ function scramVerifier(password, salt, iterations) {
11
+ const salted = pbkdf2Sync(password, salt, iterations, 32, "sha256");
12
+ const client = createHmac("sha256", salted).update("Client Key").digest();
13
+ const stored = createHash("sha256").update(client).digest("base64");
14
+ const server = createHmac("sha256", salted).update("Server Key").digest("base64");
15
+ return `SCRAM-SHA-256$${iterations}:${salt.toString("base64")}$${stored}:${server}`;
16
+ }
17
+ function matchesCredential(password, stored) {
18
+ const match = stored?.match(/^SCRAM-SHA-256\$(\d+):([A-Za-z0-9+/]+=*)\$/);
19
+ if (!match || !stored)
20
+ return false;
21
+ const iterations = Number(match[1]);
22
+ if (iterations < 1 || iterations > 100_000)
23
+ return false;
24
+ const expected = Buffer.from(scramVerifier(password, Buffer.from(match[2], "base64"), iterations));
25
+ const actual = Buffer.from(stored);
26
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
27
+ }
28
+ /** Runs in the operator transaction under the extension provisioning lock. */
29
+ export async function provisionExtensionRole(admin, name, identity, limits) {
30
+ if (!identity.dedicated)
31
+ throw new Error("Extension provisioning requires a dedicated login");
32
+ const client = new pg.Client({ connectionString: identity.url });
33
+ if (!client.database || !client.password) {
34
+ throw new Error(`Missing PostgreSQL database or credential for extension ${name}`);
35
+ }
36
+ const database = await admin.query("select current_database() as db");
37
+ if (database.rows[0]?.db !== client.database)
38
+ throw new Error(`The provisioner and extension ${name} must use the same PostgreSQL database`);
39
+ const login = pg.escapeIdentifier(identity.login);
40
+ const defaults = {
41
+ statement_timeout: `${limits.extensionStatementTimeoutMs}ms`,
42
+ idle_in_transaction_session_timeout: `${limits.extensionIdleTransactionTimeoutMs}ms`,
43
+ temp_file_limit: `${limits.extensionTempFileLimitKb}kB`,
44
+ search_path: "public",
45
+ };
46
+ const marker = `Capybara extension login for ${client.database}/${name}`;
47
+ const { rows: [existing], } = await admin.query(`select pg_catalog.shobj_description(r.oid, 'pg_authid') as marker,
48
+ exists (select from pg_catalog.pg_stat_activity where usename = r.rolname) as active,
49
+ r.rolcanlogin and not (r.rolsuper or r.rolcreatedb or r.rolcreaterole
50
+ or r.rolreplication or r.rolbypassrls or r.rolinherit)
51
+ and r.rolconnlimit = $2 and coalesce(r.rolvaliduntil, 'infinity') = 'infinity' as restricted,
52
+ r.rolpassword as verifier, settings.setconfig as defaults
53
+ from pg_catalog.pg_authid r
54
+ left join pg_catalog.pg_db_role_setting settings on settings.setrole = r.oid and settings.setdatabase = 0
55
+ where r.rolname = $1`, [identity.login, limits.extensionConnectionLimit]);
56
+ if (existing && existing.marker !== marker) {
57
+ throw new Error(`Refusing to take over unexpected extension login ${identity.login}`);
58
+ }
59
+ const sameCredential = existing && matchesCredential(client.password, existing.verifier);
60
+ if (existing?.restricted &&
61
+ sameCredential &&
62
+ Object.entries(defaults).every(([key, value]) => existing.defaults?.includes(`${key}=${value}`))) {
63
+ return false;
64
+ }
65
+ if (existing?.active) {
66
+ throw new Error(`Drain sessions for extension ${name} before provisioning its database login`);
67
+ }
68
+ if (!existing) {
69
+ await admin.query(`create role ${login} nologin`);
70
+ await admin.query(`comment on role ${login} is ${pg.escapeLiteral(marker)}`);
71
+ }
72
+ if (!sameCredential) {
73
+ try {
74
+ const verifier = scramVerifier(client.password, randomBytes(16), scramIterations);
75
+ await admin.query(`alter role ${login} password ${pg.escapeLiteral(verifier)}`);
76
+ }
77
+ catch {
78
+ throw new Error(`Could not set the PostgreSQL password for extension ${name}`);
79
+ }
80
+ }
81
+ await admin.query(`alter role ${login} login nosuperuser nocreatedb nocreaterole noreplication nobypassrls noinherit
82
+ connection limit ${limits.extensionConnectionLimit} valid until 'infinity'`);
83
+ for (const [key, value] of Object.entries(defaults)) {
84
+ await admin.query(`alter role ${login} set ${key} = ${pg.escapeLiteral(value)}`);
85
+ }
86
+ await admin.query(`grant connect on database ${pg.escapeIdentifier(client.database)} to ${login}`);
87
+ await admin.query(`grant usage on schema public to ${login}`);
88
+ return true;
89
+ }
@@ -1,6 +1,7 @@
1
+ import type { KernelConfig } from "../config/schema.js";
1
2
  import { type ExtensionDbIdentity } from "./extension-db.js";
2
3
  /**
3
4
  * One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
4
5
  * to transfer ownership. Run before starting replicas with the new extension identity.
5
6
  */
6
- export declare function transferKnownExtensionSchemas(bootstrapUrl: string, identity: ExtensionDbIdentity, declaredNames: Iterable<string>, connectTimeoutMs?: number, runtimeLogin?: string): Promise<void>;
7
+ export declare function transferKnownExtensionSchemas(bootstrapUrl: string, identity: ExtensionDbIdentity, declaredNames: Iterable<string>, connectTimeoutMs?: number, provisioning?: KernelConfig["db"]): Promise<void>;
@@ -3,14 +3,18 @@ import pg from "pg";
3
3
  import { EXTENSION_EFFECT_HANDOFF } from "../infra/database/extension-handoff.js";
4
4
  import { assertExtensionSession, pluginSchemaName, } from "./extension-db.js";
5
5
  import { provisionExtensionHandoff } from "./extension-handoff-schema.js";
6
+ import { createProvisionedExtensionSchema, provisionExtensionRole, } from "./extension-role-provision.js";
6
7
  import { assertSameMigrationDatabase, lockMigrationSchema } from "./migrator.js";
7
8
  import { pgConnectOptions } from "./pool.js";
8
- async function transferExtensionSchema(client, schema, target, sources) {
9
+ async function transferExtensionSchema(client, schema, target, sources, dedicated = false) {
9
10
  await lockMigrationSchema(client, schema, "transaction");
10
11
  const { rows: [namespace], } = await client.query(`select oid, pg_catalog.pg_get_userbyid(nspowner) as owner
11
12
  from pg_catalog.pg_namespace where nspname = $1`, [schema]);
12
- if (!namespace)
13
+ if (!namespace) {
14
+ if (dedicated)
15
+ await createProvisionedExtensionSchema(client, schema, target);
13
16
  return;
17
+ }
14
18
  if (namespace.owner !== target && !sources.has(namespace.owner)) {
15
19
  throw new Error(`Unexpected owner ${namespace.owner} for extension schema ${schema}`);
16
20
  }
@@ -73,7 +77,22 @@ async function transferExtensionSchema(client, schema, target, sources) {
73
77
  }
74
78
  }
75
79
  }
76
- async function confirmTargetDatabase(owner, target, connectTimeoutMs) {
80
+ async function revokeForeignSchemaGrants(client, schema, relayLogin) {
81
+ const { rows } = await client.query(`select distinct case when acl.grantee = 0 then null else pg_get_userbyid(acl.grantee) end as grantee,
82
+ acl.privilege_type as privilege
83
+ from pg_namespace n cross join lateral aclexplode(n.nspacl) acl
84
+ where n.nspname = $1 and acl.grantee <> n.nspowner
85
+ and not (acl.grantee = to_regrole($2) and acl.privilege_type = 'USAGE')
86
+ order by grantee, privilege`, [schema, relayLogin]);
87
+ const revoked = [];
88
+ for (const { grantee, privilege } of rows) {
89
+ const recipient = grantee === null ? "PUBLIC" : pg.escapeIdentifier(grantee);
90
+ await client.query(`revoke ${privilege} on schema ${pg.escapeIdentifier(schema)} from ${recipient} cascade`);
91
+ revoked.push(`Revoked foreign ${privilege} on schema ${pg.escapeIdentifier(schema)} from ${recipient}`);
92
+ }
93
+ return revoked;
94
+ }
95
+ async function confirmTargetDatabase(owner, target, schema, connectTimeoutMs) {
77
96
  const client = new pg.Client({
78
97
  connectionString: target.url,
79
98
  ...pgConnectOptions({ connectTimeoutMs }),
@@ -81,7 +100,7 @@ async function confirmTargetDatabase(owner, target, connectTimeoutMs) {
81
100
  client.on("error", () => { });
82
101
  try {
83
102
  await client.connect();
84
- await assertExtensionSession(client, target.login);
103
+ await assertExtensionSession(client, target.login, target.dedicated ? schema : undefined);
85
104
  await assertSameMigrationDatabase(owner, client);
86
105
  }
87
106
  catch (cause) {
@@ -95,7 +114,7 @@ async function confirmTargetDatabase(owner, target, connectTimeoutMs) {
95
114
  * One-shot cutover. The URL authenticates the bootstrap/legacy login, which must be able
96
115
  * to transfer ownership. Run before starting replicas with the new extension identity.
97
116
  */
98
- export async function transferKnownExtensionSchemas(bootstrapUrl, identity, declaredNames, connectTimeoutMs, runtimeLogin) {
117
+ export async function transferKnownExtensionSchemas(bootstrapUrl, identity, declaredNames, connectTimeoutMs, provisioning) {
99
118
  const owner = new pg.Client({
100
119
  connectionString: bootstrapUrl,
101
120
  ...pgConnectOptions({ connectTimeoutMs }),
@@ -103,44 +122,109 @@ export async function transferKnownExtensionSchemas(bootstrapUrl, identity, decl
103
122
  owner.on("error", () => { });
104
123
  try {
105
124
  await owner.connect();
125
+ if (provisioning) {
126
+ const { rows: [role], } = await owner.query("select rolsuper from pg_catalog.pg_roles where rolname = current_user");
127
+ if (!role?.rolsuper)
128
+ throw new Error("db.extensionProvisioningUrl must authenticate as a PostgreSQL superuser");
129
+ await lockMigrationSchema(owner, "extension-provisioning", "session");
130
+ }
106
131
  await owner.query("begin");
107
132
  try {
108
133
  await owner.query("set local search_path = pg_catalog");
109
134
  await owner.query("set local lock_timeout = '30s'");
110
135
  const { rows: [legacy], } = await owner.query(`
111
- select current_user as login,
112
- pg_catalog.has_database_privilege(pg_catalog.current_database(), 'CREATE') as can_create
136
+ select current_user as login, pg_get_userbyid(nspowner) as kernel_owner
137
+ from pg_catalog.pg_namespace where nspname = 'capybara'
113
138
  `);
114
139
  if (!legacy)
115
140
  throw new Error("Could not verify the schema transfer login");
116
141
  const { rows: registered } = await owner.query(`select name from capybara.extension_name_owners
117
142
  union select name from capybara.extension_installs`);
118
- const names = new Set([...declaredNames, ...registered.map((row) => row.name)]);
143
+ const names = new Set([
144
+ ...declaredNames,
145
+ ...registered.map((row) => row.name),
146
+ ...(provisioning ? (identity.provisionedNames?.() ?? []) : []),
147
+ ]);
119
148
  const resolved = [...names].sort().map((name) => {
120
149
  if (!EXTENSION_NAME_RE.test(name))
121
150
  throw new Error(`Invalid extension name: ${name}`);
122
- return { schema: pluginSchemaName(name), target: identity.resolve(name) };
151
+ return { name, schema: pluginSchemaName(name), target: identity.resolve(name) };
123
152
  });
124
- const sources = new Set([legacy.login, ...resolved.map(({ target }) => target.login)]);
153
+ const legacySources = new Set([legacy.login, legacy.kernel_owner]);
125
154
  if (identity.sharedLogin !== undefined)
126
- sources.add(identity.sharedLogin);
155
+ legacySources.add(identity.sharedLogin);
156
+ const sources = new Set([...legacySources, ...resolved.map(({ target }) => target.login)]);
127
157
  const targets = resolved.filter(({ target }) => target.separate);
158
+ const unchanged = new Set();
159
+ const revoked = [];
160
+ if (provisioning) {
161
+ const { rows: owned } = await owner.query(`select nspname as schema, pg_get_userbyid(nspowner) as login
162
+ from pg_namespace where nspname = any($1::text[])`, [targets.map(({ schema }) => schema)]);
163
+ const owners = new Map(owned.map(({ schema, login }) => [schema, login]));
164
+ if (identity.sharedLogin && owned.some(({ login }) => login === identity.sharedLogin)) {
165
+ const stale = await owner.query(`select 1 from pg_catalog.pg_stat_activity where usename = $1 and datname = current_database()`, [identity.sharedLogin]);
166
+ if (stale.rows.length) {
167
+ throw new Error("Drain shared extension database sessions before transferring ownership");
168
+ }
169
+ }
170
+ const runtime = new pg.Client({ connectionString: provisioning.url });
171
+ runtime.on("error", () => { });
172
+ try {
173
+ await runtime.connect();
174
+ await assertSameMigrationDatabase(owner, runtime);
175
+ }
176
+ finally {
177
+ await runtime.end();
178
+ }
179
+ const { rows: [database], } = await owner.query("select current_database() as name");
180
+ if (!database)
181
+ throw new Error("Could not verify the extension provisioning database");
182
+ await owner.query(`revoke create, temporary on database ${pg.escapeIdentifier(database.name)} from public`);
183
+ for (const { name, schema, target } of targets) {
184
+ const changed = await provisionExtensionRole(owner, name, target, provisioning);
185
+ if (!changed && owners.get(schema) === target.login)
186
+ unchanged.add(schema);
187
+ }
188
+ await owner.query("commit");
189
+ await owner.query("begin");
190
+ await owner.query("set local search_path = pg_catalog");
191
+ await owner.query("set local lock_timeout = '30s'");
192
+ }
128
193
  const validated = new Set();
129
- for (const { target } of targets) {
130
- if (validated.has(target.url))
194
+ for (const { target, schema } of targets) {
195
+ if (unchanged.has(schema) || validated.has(target.url))
131
196
  continue;
132
- await confirmTargetDatabase(owner, target, connectTimeoutMs);
197
+ await confirmTargetDatabase(owner, target, schema, connectTimeoutMs);
133
198
  validated.add(target.url);
134
199
  }
135
200
  for (const { schema, target } of targets) {
136
- await transferExtensionSchema(owner, schema, target.login, sources);
137
- // Repeated migrations may use the restricted runtime login. Only the one-shot
138
- // provisioner can create the contract table and grant access to it.
139
- if (runtimeLogin !== undefined && legacy.can_create) {
140
- await provisionExtensionHandoff(owner, schema, target.login, runtimeLogin);
201
+ await transferExtensionSchema(owner, schema, target.login, target.dedicated ? legacySources : sources, target.dedicated);
202
+ if (provisioning && target.dedicated) {
203
+ const relayLogin = provisioning.extensionEffectRelayLogin ?? "capybara_runtime";
204
+ await provisionExtensionHandoff(owner, schema, target.login, relayLogin);
205
+ revoked.push(...(await revokeForeignSchemaGrants(owner, schema, relayLogin)));
206
+ }
207
+ if (target.dedicated && identity.sharedLogin) {
208
+ const namespace = pg.escapeIdentifier(schema);
209
+ const old = pg.escapeIdentifier(identity.sharedLogin);
210
+ const { rows } = await owner.query("select 1 from pg_catalog.pg_roles where rolname = $1", [identity.sharedLogin]);
211
+ if (rows.length) {
212
+ await owner.query(`revoke all on schema ${namespace} from ${old}`);
213
+ await owner.query(`revoke all on all tables in schema ${namespace} from ${old}`);
214
+ await owner.query(`revoke all on all sequences in schema ${namespace} from ${old}`);
215
+ await owner.query(`revoke all on all routines in schema ${namespace} from ${old}`);
216
+ }
217
+ }
218
+ }
219
+ if (provisioning && identity.sharedLogin) {
220
+ const { rows: [old], } = await owner.query(`select current_database() as db from pg_catalog.pg_roles where rolname = $1`, [identity.sharedLogin]);
221
+ if (old) {
222
+ await owner.query(`revoke create on database ${pg.escapeIdentifier(old.db)} from ${pg.escapeIdentifier(identity.sharedLogin)}`);
141
223
  }
142
224
  }
143
225
  await owner.query("commit");
226
+ for (const message of revoked)
227
+ process.stderr.write(`${JSON.stringify(message)}\n`);
144
228
  }
145
229
  catch (error) {
146
230
  await owner.query("rollback").catch(() => { });
@@ -31,6 +31,8 @@ export declare function migrate(connectionString: string, owner: MigrationOwner,
31
31
  signal?: AbortSignal | undefined;
32
32
  /** Verify the effective PostgreSQL role before running an isolated extension migration. */
33
33
  extensionLogin?: string | undefined;
34
+ /** Dedicated logins own a pre-provisioned schema and cannot create schemas. */
35
+ extensionDedicated?: boolean | undefined;
34
36
  /** 迁移会话的 `statement_timeout`(毫秒);不给不设。 */
35
37
  statementTimeoutMs?: number | undefined;
36
38
  /** 迁移会话的 `lock_timeout`(毫秒,含按 schema 的咨询锁);不给不设。 */
@@ -140,7 +140,7 @@ export async function migrate(connectionString, owner, opts = {}) {
140
140
  try {
141
141
  await client.connect();
142
142
  if (opts.extensionLogin !== undefined)
143
- await assertExtensionSession(client, opts.extensionLogin);
143
+ await assertExtensionSession(client, opts.extensionLogin, opts.extensionDedicated ? schema : undefined);
144
144
  if (opts.statementTimeoutMs !== undefined) {
145
145
  await client.query(`set statement_timeout = ${Math.max(1, Math.floor(opts.statementTimeoutMs))}`);
146
146
  }
@@ -149,7 +149,7 @@ export async function migrate(connectionString, owner, opts = {}) {
149
149
  }
150
150
  await lockMigrationSchema(client, schema, "session");
151
151
  if (opts.extensionLogin !== undefined) {
152
- await assertExtensionSchemaOwner(client, schema, opts.extensionLogin);
152
+ await assertExtensionSchemaOwner(client, schema, opts.extensionLogin, opts.extensionDedicated);
153
153
  }
154
154
  if (schema === "capybara") {
155
155
  const { rows: [privileges], } = await client.query(kernelMigrationPrivileges);
@@ -157,7 +157,8 @@ export async function migrate(connectionString, owner, opts = {}) {
157
157
  throw new Error(`The migration login must own the capybara schema. ${migrateHint}`);
158
158
  }
159
159
  }
160
- await client.query(`create schema if not exists ${ident(schema)}`);
160
+ if (!opts.extensionDedicated)
161
+ await client.query(`create schema if not exists ${ident(schema)}`);
161
162
  await client.query(`create table if not exists ${table} (
162
163
  name text primary key,
163
164
  checksum text not null,
@@ -15,6 +15,7 @@ import { itemRemovedError } from "../catalog/ownership.js";
15
15
  import { oweDeployedExtensionSync } from "../catalog/scope-jobs.js";
16
16
  import { pluginSchemaName } from "../ctx/create-ctx.js";
17
17
  import { ConfiguredExtensionDbIdentity } from "../db/extension-db.js";
18
+ import { EMPTY_EXTENSION_SCHEMA_COMMENT } from "../db/extension-role-provision.js";
18
19
  import { oweHostServicesStop } from "../device-access/host-service-stop.js";
19
20
  import { revokeSiteGrantsOfExtensionEverywhere } from "../device-access/site-grants.js";
20
21
  import { ApiError } from "../errors.js";
@@ -22,6 +23,7 @@ import { audit } from "../identity/audit.js";
22
23
  import { SuperAdminLock } from "../identity/super-admin.js";
23
24
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
24
25
  import { afterCommit } from "../infra/database/after-commit.js";
26
+ import { EXTENSION_EFFECT_HANDOFF } from "../infra/database/extension-handoff.js";
25
27
  import { KernelDb } from "../infra/database/kernel-db.js";
26
28
  import { asPlatform } from "../infra/database/org-scope.js";
27
29
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -579,7 +581,21 @@ function fallbackView(name, known, err) {
579
581
  /** 插件名已留下的数据:权限快照、部署配置、任一组织的配置,或插件 schema(`plugin_<name>`)。 */
580
582
  async function hasRetainedData(db, name) {
581
583
  return asPlatform("whether any org kept config for a plugin", async () => {
582
- const schema = await sql `SELECT 1 AS x FROM pg_namespace WHERE nspname = ${pluginSchemaName(name)}`.execute(db);
584
+ const schema = await sql `SELECT 1 AS x FROM pg_catalog.pg_namespace n
585
+ WHERE n.nspname = ${pluginSchemaName(name)} AND (
586
+ pg_catalog.obj_description(n.oid, 'pg_namespace') IS DISTINCT FROM ${EMPTY_EXTENSION_SCHEMA_COMMENT}
587
+ OR EXISTS (
588
+ SELECT FROM pg_catalog.pg_depend d
589
+ WHERE d.refclassid = 'pg_catalog.pg_namespace'::regclass AND d.refobjid = n.oid
590
+ AND d.deptype = 'n'
591
+ AND NOT EXISTS (
592
+ SELECT FROM pg_catalog.pg_class c
593
+ WHERE d.classid = 'pg_catalog.pg_class'::regclass AND c.oid = d.objid
594
+ AND c.relname = ${EXTENSION_EFFECT_HANDOFF} AND c.relkind = 'r'
595
+ AND c.relowner <> n.nspowner
596
+ )
597
+ )
598
+ )`.execute(db);
583
599
  if (schema.rows.length > 0)
584
600
  return true;
585
601
  // org-filter: whether any org kept config for the plugin name (a deployment-wide existence check)
@@ -3,6 +3,7 @@ import type { Redis } from "ioredis";
3
3
  import type { core } from "zod";
4
4
  import type { KernelAppOptions } from "../app.js";
5
5
  import { TRIGGER_EVENTS_BACKEND } from "../automations/events/token.js";
6
+ import type { KernelConfig } from "../config/schema.js";
6
7
  import type { BusSubscriber } from "../ctx/bus.js";
7
8
  import { type DeviceAccessBackend, type InboxBackend, type PluginReadsBackend, type Route, type TriggersBackend } from "../ctx/create-ctx.js";
8
9
  import { ExtensionEffects } from "../ctx/durable-effects.service.js";
@@ -149,8 +150,8 @@ export declare class ExtensionHost {
149
150
  */
150
151
  static migrateOnly(specifiers: string[], opts: {
151
152
  dbUrl: string;
152
- handoffRuntimeLogin?: string;
153
153
  extensionIdentity?: ExtensionDbIdentity;
154
+ extensionProvisioning?: KernelConfig["db"];
154
155
  resolveFrom?: string;
155
156
  connectTimeoutMs?: number;
156
157
  autoApprove?: boolean;
@@ -194,6 +194,7 @@ async function migratePlugin(connection, manifest, migrationsDir, connectTimeout
194
194
  connectTimeoutMs,
195
195
  signal,
196
196
  extensionLogin: connection.separate ? connection.login : undefined,
197
+ extensionDedicated: connection.dedicated,
197
198
  });
198
199
  return { schema, applied };
199
200
  }
@@ -264,8 +265,8 @@ let ExtensionHost = class ExtensionHost {
264
265
  for (const manifest of ordered)
265
266
  assertSecretsReachable(manifest);
266
267
  const identity = opts.extensionIdentity ?? extensionDbIdentity({ url: opts.dbUrl });
267
- if (opts.extensionIdentity) {
268
- await transferKnownExtensionSchemas(opts.dbUrl, identity, dirs.keys(), opts.connectTimeoutMs, opts.handoffRuntimeLogin);
268
+ if (opts.extensionProvisioning?.extensionProvisioningUrl) {
269
+ await transferKnownExtensionSchemas(opts.extensionProvisioning.extensionProvisioningUrl, identity, dirs.keys(), opts.connectTimeoutMs, opts.extensionProvisioning);
269
270
  }
270
271
  let toMigrate = ordered;
271
272
  if (!opts.autoApprove && ordered.length > 0) {
@@ -47,6 +47,7 @@ export async function ensureMigrated(d, name, sha256, dir) {
47
47
  connectTimeoutMs: d.connectTimeoutMs,
48
48
  signal: signals.length > 0 ? AbortSignal.any(signals) : undefined,
49
49
  extensionLogin: d.extensionDb?.separate ? d.extensionDb.login : undefined,
50
+ extensionDedicated: d.extensionDb?.dedicated,
50
51
  ...(d.timeoutMs !== undefined && {
51
52
  statementTimeoutMs: d.timeoutMs,
52
53
  lockTimeoutMs: Math.min(d.timeoutMs, MIGRATION_LOCK_TIMEOUT_MS),
package/dist/index.d.ts CHANGED
@@ -20,6 +20,8 @@ export { createKv } from "./ctx/kv.js";
20
20
  export { createLock } from "./ctx/lock.js";
21
21
  export { createQueue } from "./ctx/queue.js";
22
22
  export { createKeyring, createSecrets, type DerivedKeys, type Keyring, REWRAP_BATCH_SIZE, type RewrapResult, rewrapToCurrentMasterKey, } from "./ctx/secrets.js";
23
+ export { extensionDbIdentity } from "./db/extension-db.js";
24
+ export { createProvisionedExtensionSchema, provisionExtensionRole, } from "./db/extension-role-provision.js";
23
25
  export { type KernelDatabase, type KernelSchemaDb, kernelDb } from "./db/kernel-schema.js";
24
26
  export { type MigrationOwner, migrate } from "./db/migrator.js";
25
27
  export { createDb } from "./db/pool.js";
@@ -64,7 +66,7 @@ export type { RlsMode } from "./infra/database/scoped-dialect.js";
64
66
  export { onProcessFault } from "./infra/health/process-fault.js";
65
67
  export { GUARD_CIRCUIT_LIMIT, GUARD_CIRCUIT_WINDOW_MS, installProcessGuards, type ProcessGuardDeps, } from "./infra/lifecycle/process-guards.js";
66
68
  export { handleShutdownSignals, type ShutdownSignalHandle, type ShutdownSignalOptions, } from "./infra/lifecycle/shutdown-signals.js";
67
- export { KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll, prepareKernelDatabase, } from "./kernel.js";
69
+ export { declaredExtensionNames, KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll, prepareKernelDatabase, } from "./kernel.js";
68
70
  export { createLogger, type KernelLogger, LOG_FORMATS, LOG_LEVELS, type LogFormat, type LoggerOptions, type LogLevel, type LogOutput, } from "./log.js";
69
71
  export { createConfiguredLogger, loggerOptionsFromConfig } from "./log-config.js";
70
72
  export { type ContextJob, type JobWrapper, type LogContext, logContext, setJobWrapper, setTraceContextSource, withJobContext, withLogContext, } from "./log-context.js";
package/dist/index.js CHANGED
@@ -19,6 +19,8 @@ export { createKv } from "./ctx/kv.js";
19
19
  export { createLock } from "./ctx/lock.js";
20
20
  export { createQueue } from "./ctx/queue.js";
21
21
  export { createKeyring, createSecrets, REWRAP_BATCH_SIZE, rewrapToCurrentMasterKey, } from "./ctx/secrets.js";
22
+ export { extensionDbIdentity } from "./db/extension-db.js";
23
+ export { createProvisionedExtensionSchema, provisionExtensionRole, } from "./db/extension-role-provision.js";
22
24
  export { kernelDb } from "./db/kernel-schema.js";
23
25
  export { migrate } from "./db/migrator.js";
24
26
  export { createDb } from "./db/pool.js";
@@ -61,7 +63,7 @@ export { asPlatform, currentScope, setUnscopedQueryCheck, withOrgScope, } from "
61
63
  export { onProcessFault } from "./infra/health/process-fault.js";
62
64
  export { GUARD_CIRCUIT_LIMIT, GUARD_CIRCUIT_WINDOW_MS, installProcessGuards, } from "./infra/lifecycle/process-guards.js";
63
65
  export { handleShutdownSignals, } from "./infra/lifecycle/shutdown-signals.js";
64
- export { KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll, prepareKernelDatabase, } from "./kernel.js";
66
+ export { declaredExtensionNames, KERNEL_MIGRATIONS_DIR, KERNEL_SCHEMA, migrateAll, prepareKernelDatabase, } from "./kernel.js";
65
67
  export { createLogger, LOG_FORMATS, LOG_LEVELS, } from "./log.js";
66
68
  export { createConfiguredLogger, loggerOptionsFromConfig } from "./log-config.js";
67
69
  export { logContext, setJobWrapper, setTraceContextSource, withJobContext, withLogContext, } from "./log-context.js";
@@ -1,11 +1,4 @@
1
- import { type Kysely } from "kysely";
2
- /**
3
- * Why `db.rls: enforce` would filter nothing on this pool, or undefined when it can work (RLS spec
4
- * §10):
5
- * - PostgreSQL never applies a row level security policy to a superuser or a role with BYPASSRLS,
6
- * even on a table that forces RLS. The official compose file's `POSTGRES_USER` is a superuser, so
7
- * such a deployment needs a role of its own before enforcing;
8
- * - the policies ship dark: migration 0182 creates them without `ENABLE` / `FORCE ROW LEVEL
9
- * SECURITY`, which a later migration (phase 5) runs. Until then no org-scoped table applies them.
10
- */
11
- export declare function rlsEnforceProblem(pool: Kysely<any>): Promise<string | undefined>;
1
+ import { type QueryExecutorProvider } from "kysely";
2
+ export declare function matchesOrgScopePredicate(clause: string | null): boolean;
3
+ /** Checks the serving login and migrated schema before the kernel starts in enforce mode. */
4
+ export declare function rlsEnforceProblem(pool: QueryExecutorProvider, expectedOwner: string): Promise<string | undefined>;
@@ -1,33 +1,77 @@
1
1
  import { sql } from "kysely";
2
- /**
3
- * Why `db.rls: enforce` would filter nothing on this pool, or undefined when it can work (RLS spec
4
- * §10):
5
- * - PostgreSQL never applies a row level security policy to a superuser or a role with BYPASSRLS,
6
- * even on a table that forces RLS. The official compose file's `POSTGRES_USER` is a superuser, so
7
- * such a deployment needs a role of its own before enforcing;
8
- * - the policies ship dark: migration 0182 creates them without `ENABLE` / `FORCE ROW LEVEL
9
- * SECURITY`, which a later migration (phase 5) runs. Until then no org-scoped table applies them.
10
- */
11
- // biome-ignore lint/suspicious/noExplicitAny: the pool carries no schema types
12
- export async function rlsEnforceProblem(pool) {
13
- const role = await sql `
14
- select rolsuper as superuser, rolbypassrls as bypass from pg_roles
15
- where rolname = current_user`.execute(pool);
16
- const row = role.rows[0];
17
- if (row?.superuser)
2
+ // PostgreSQL deparses the uncorrelated subqueries with result aliases. Check the
3
+ // policy expression in full so an extra condition or a substituted setting is drift.
4
+ export function matchesOrgScopePredicate(clause) {
5
+ const normalized = clause
6
+ ?.replace(/\s+/g, " ")
7
+ .replace(/\b(?:capybara|pg_catalog)\.(?=\w+\()/g, "");
8
+ return (normalized === "rls_admits(org_id)" ||
9
+ normalized ===
10
+ "rls_admits(org_id, ( SELECT rls_scope_unrestricted() AS rls_scope_unrestricted), " +
11
+ "( SELECT current_setting('capybara.org_id'::text, true) AS current_setting))");
12
+ }
13
+ /** Checks the serving login and migrated schema before the kernel starts in enforce mode. */
14
+ export async function rlsEnforceProblem(pool, expectedOwner) {
15
+ const { rows: [role], } = await sql `
16
+ select bool_or(rolsuper) as superuser, bool_or(rolbypassrls) as bypass
17
+ from pg_catalog.pg_roles where rolname in (current_user, session_user)`.execute(pool);
18
+ if (role?.superuser)
18
19
  return "the database role is a superuser";
19
- if (row?.bypass)
20
+ if (role?.bypass)
20
21
  return "the database role has BYPASSRLS";
21
- const off = await sql `
22
- select c.relname as table from pg_class c
23
- join pg_namespace n on n.oid = c.relnamespace and n.nspname = 'capybara'
24
- where c.relkind = 'r' and not (c.relrowsecurity and c.relforcerowsecurity)
25
- and exists (select 1 from pg_attribute a
26
- where a.attrelid = c.oid and a.attname = 'org_id' and not a.attisdropped)
27
- order by 1`.execute(pool);
28
- if (off.rows.length > 0) {
29
- const first = off.rows[0]?.table;
30
- return `row level security is not enabled and forced on ${off.rows.length} org-scoped table(s) (${first}, …; RLS spec phase 5 enables them)`;
22
+ const { rows: [schema], } = await sql `
23
+ select pg_catalog.pg_get_userbyid(nspowner) as owner,
24
+ (pg_catalog.pg_has_role(current_user, nspowner, 'MEMBER')
25
+ or pg_catalog.pg_has_role(session_user, nspowner, 'MEMBER')) as "canOwn"
26
+ from pg_catalog.pg_namespace where nspname = 'capybara'`.execute(pool);
27
+ if (!schema)
28
+ return "the capybara schema is missing";
29
+ if (schema.canOwn)
30
+ return "the database role owns or is a member of the owner of the capybara schema";
31
+ if (schema.owner !== expectedOwner)
32
+ return `the capybara schema has unexpected owner ${schema.owner}; expected ${expectedOwner}`;
33
+ // The deparser may omit a visible function's schema. Check its catalog dependencies too.
34
+ const { rows: tables } = await sql `
35
+ select c.relname as "table", pg_catalog.pg_get_userbyid(c.relowner) as owner,
36
+ (c.relrowsecurity and c.relforcerowsecurity) as active,
37
+ p.polcmd as command,
38
+ pg_catalog.pg_get_expr(p.polqual, c.oid) as "using",
39
+ pg_catalog.pg_get_expr(p.polwithcheck, c.oid) as "withCheck",
40
+ exists (
41
+ select from pg_catalog.pg_depend d
42
+ where d.classid = 'pg_catalog.pg_policy'::pg_catalog.regclass and d.objid = p.oid
43
+ and d.refclassid = 'pg_catalog.pg_proc'::pg_catalog.regclass
44
+ and not exists (
45
+ select from (values
46
+ (pg_catalog.to_regprocedure('capybara.rls_admits(text)')),
47
+ (pg_catalog.to_regprocedure('capybara.rls_admits(text,boolean,text)')),
48
+ (pg_catalog.to_regprocedure('capybara.rls_scope_unrestricted()'))
49
+ ) as allowed(oid) where allowed.oid = d.refobjid
50
+ )
51
+ ) as "hasOtherFunctions",
52
+ (c.relname = 'conversation_events' and not a.attnotnull) as "nullableEventOrg"
53
+ from pg_catalog.pg_class c
54
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace and n.nspname = 'capybara'
55
+ join pg_catalog.pg_attribute a on a.attrelid = c.oid and a.attname = 'org_id' and not a.attisdropped
56
+ left join pg_catalog.pg_policy p on p.polrelid = c.oid and p.polname = 'org_scope'
57
+ where c.relkind in ('r', 'p')
58
+ order by c.relname`.execute(pool);
59
+ for (const table of tables) {
60
+ const name = `capybara.${table.table}`;
61
+ if (table.owner !== expectedOwner)
62
+ return `${name} has unexpected owner ${table.owner}; expected ${expectedOwner}`;
63
+ if (table.command === null)
64
+ return `${name} is missing its org_scope policy`;
65
+ if (!table.active)
66
+ return `row level security is not enabled and forced on ${name}`;
67
+ if (table.command !== "*")
68
+ return `${name} org_scope policy must apply to ALL commands`;
69
+ if (table.hasOtherFunctions ||
70
+ !matchesOrgScopePredicate(table.using) ||
71
+ !matchesOrgScopePredicate(table.withCheck))
72
+ return `${name} org_scope policy must use the kernel rls_admits(org_id) predicate for USING and WITH CHECK`;
73
+ if (table.nullableEventOrg)
74
+ return "capybara.conversation_events.org_id must be NOT NULL";
31
75
  }
32
76
  return undefined;
33
77
  }
package/dist/kernel.d.ts CHANGED
@@ -10,6 +10,8 @@ import type { PendingExtension } from "./extensions/approvals.js";
10
10
  export declare const KERNEL_MIGRATIONS_DIR: string;
11
11
  /** The kernel's PG schema. */
12
12
  export declare const KERNEL_SCHEMA = "capybara";
13
+ /** Static names of config-declared extensions, for deployment and fixture provisioning. */
14
+ export declare function declaredExtensionNames(specifiers: string[], resolveFrom?: string): Promise<Set<string>>;
13
15
  /** Only a login with migration privileges can initialize the kernel schema at startup. */
14
16
  export declare function prepareKernelDatabase(db: KernelConfig["db"], opts?: {
15
17
  pool?: QueryExecutorProvider;
package/dist/kernel.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { fileURLToPath } from "node:url";
2
- import { extensionDbIdentity } from "./db/extension-db.js";
2
+ import { extensionDbIdentity, validateExtensionCredentials } from "./db/extension-db.js";
3
3
  import { canMigrateKernel, migrate, verifyMigrations } from "./db/migrator.js";
4
4
  import { createDb } from "./db/pool.js";
5
5
  import { ExtensionHost } from "./extensions/host.js";
@@ -12,11 +12,18 @@ import { ExtensionHost } from "./extensions/host.js";
12
12
  export const KERNEL_MIGRATIONS_DIR = fileURLToPath(new URL("../src/migrations/", import.meta.url));
13
13
  /** The kernel's PG schema. */
14
14
  export const KERNEL_SCHEMA = "capybara";
15
+ /** Static names of config-declared extensions, for deployment and fixture provisioning. */
16
+ export function declaredExtensionNames(specifiers, resolveFrom) {
17
+ return ExtensionHost.declaredNames(specifiers, resolveFrom === undefined ? {} : { resolveFrom });
18
+ }
15
19
  const coreMigrations = { schema: KERNEL_SCHEMA, dir: KERNEL_MIGRATIONS_DIR };
16
20
  /** Only a login with migration privileges can initialize the kernel schema at startup. */
17
21
  export async function prepareKernelDatabase(db, opts = {}) {
18
22
  if (db.migrationUrl !== undefined)
19
23
  throw new Error("db.migrationUrl may only be set for capybara migrate");
24
+ if (db.extensionProvisioningUrl !== undefined)
25
+ throw new Error("db.extensionProvisioningUrl may only be set for capybara migrate");
26
+ validateExtensionCredentials(db);
20
27
  const prepare = async (pool) => {
21
28
  if (await canMigrateKernel(pool)) {
22
29
  await migrate(db.url, coreMigrations, {
@@ -45,6 +52,9 @@ export async function prepareKernelDatabase(db, opts = {}) {
45
52
  */
46
53
  export async function migrateAll(config, opts = {}) {
47
54
  const connectTimeoutMs = config.db.connectTimeoutMs;
55
+ if (config.db.extensionProvisioningUrl !== undefined && config.db.extensionsUrl === undefined)
56
+ throw new Error("db.extensionProvisioningUrl requires db.extensionsUrl");
57
+ validateExtensionCredentials(config.db);
48
58
  const kernel = await migrate(config.db.migrationUrl ?? config.db.url, coreMigrations, {
49
59
  connectTimeoutMs,
50
60
  });
@@ -52,7 +62,7 @@ export async function migrateAll(config, opts = {}) {
52
62
  dbUrl: config.db.url,
53
63
  ...(config.db.extensionsUrl !== undefined && {
54
64
  extensionIdentity: extensionDbIdentity(config.db),
55
- handoffRuntimeLogin: config.db.extensionEffectRelayLogin ?? "capybara_runtime",
65
+ extensionProvisioning: config.db,
56
66
  }),
57
67
  connectTimeoutMs,
58
68
  autoApprove: config.extensionPermissions.autoApprove,
@@ -226,10 +226,9 @@ let KernelLifecycle = class KernelLifecycle {
226
226
  await sql `select 1`.execute(this.pool);
227
227
  this.checkpoint();
228
228
  if (cfg().db.rls === "enforce") {
229
- // never fails the start: enforcement is a backstop, and the operator decides
230
- const problem = await rlsEnforceProblem(this.pool);
229
+ const problem = await rlsEnforceProblem(this.pool, cfg().db.rlsOwnerRole);
231
230
  if (problem !== undefined) {
232
- this.log.error(`db.rls is enforce, but ${problem}: PostgreSQL filters nothing by the org scope there`);
231
+ throw new Error(`Cannot start with db.rls=enforce: ${problem}. Prepare separate database logins and run capybara migrate before enabling enforcement.`);
233
232
  }
234
233
  }
235
234
  // In flight for the stop: aborted when the shutdown begins, which then waits for its session to end
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.134",
3
+ "version": "0.1.0-rc.135",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -82,7 +82,7 @@
82
82
  "@types/yauzl": "3.4.0",
83
83
  "pg-cursor": "^2.22.1",
84
84
  "ws": "^8.22.0",
85
- "@capybara-hq/testing": "0.1.0-rc.54"
85
+ "@capybara-hq/testing": "0.1.0-rc.55"
86
86
  },
87
87
  "scripts": {
88
88
  "build": "tsc -b"
@@ -0,0 +1,30 @@
1
+ -- Phase 5 activates the existing kernel policies. Bound the wait for table locks while serving.
2
+ SET LOCAL lock_timeout = '2s';
3
+
4
+ -- capybara:allow-destructive catalog-driven verification and activation of existing kernel policies
5
+ DO $$
6
+ DECLARE
7
+ target record;
8
+ BEGIN
9
+ FOR target IN
10
+ SELECT c.relname, EXISTS (
11
+ SELECT FROM pg_catalog.pg_policy p
12
+ WHERE p.polrelid = c.oid AND p.polname = 'org_scope'
13
+ ) AS has_policy
14
+ FROM pg_catalog.pg_class c
15
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
16
+ JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid
17
+ WHERE n.nspname = 'capybara' AND c.relkind IN ('r', 'p')
18
+ AND a.attname = 'org_id' AND NOT a.attisdropped
19
+ ORDER BY has_policy, c.relname
20
+ LOOP
21
+ IF NOT target.has_policy THEN
22
+ RAISE EXCEPTION 'Missing org_scope policy on capybara.%', target.relname;
23
+ END IF;
24
+ EXECUTE format(
25
+ 'ALTER TABLE ONLY capybara.%I ENABLE ROW LEVEL SECURITY, FORCE ROW LEVEL SECURITY',
26
+ target.relname
27
+ );
28
+ END LOOP;
29
+ END
30
+ $$;