Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): harden definer paths for R8-M1
Josué0b8e3594e0a8
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 641cde629..c57d40107 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.691",+ "version": "0.1.692","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.691",+ "version": "0.1.692","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex 392a3831e..8acf89846 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.691",+ "version": "0.1.692","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/db.ts b/control-api/src/db.tsindex f090bcc96..389f549f3 100644--- a/control-api/src/db.ts+++ b/control-api/src/db.ts@@ -16,6 +16,7 @@ import {import { applyCodexSubscriptionOAuthStateSchema } from './services/codexSubscriptionOAuthState.js'import {applyEntityChangeCheckpointSchema,+ applyEntityChangeDefinerSearchPathSchema,applyEntityChangeSchema,} from './services/entityChangeSchema.js'import {@@ -6319,6 +6320,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [legacyVersions: ['0120_entity_change_checkpoint_cursor_convergence'],apply: applyEntityChangeCheckpointSchema,},+ {+ version: '0124_entity_change_definer_search_path',+ apply: applyEntityChangeDefinerSearchPathSchema,+ },]async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {diff --git a/control-api/src/services/entityChangeSchema.ts b/control-api/src/services/entityChangeSchema.tsindex 22816800c..8120c6442 100644--- a/control-api/src/services/entityChangeSchema.ts+++ b/control-api/src/services/entityChangeSchema.ts@@ -39,7 +39,7 @@ export async function applyEntityChangeSchema(db: DbClient): Promise<void> {ON entity_change_feed (created_at, sequence);CREATE OR REPLACE FUNCTION entity_change_capture_resource() RETURNS trigger- LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$DECLAREresource_key UUID;event_kind TEXT;@@ -96,7 +96,7 @@ export async function applyEntityChangeSchema(db: DbClient): Promise<void> {$$;CREATE OR REPLACE FUNCTION entity_change_capture_scope() RETURNS trigger- LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$DECLAREcapture_scope TEXT;capture_type TEXT;@@ -168,7 +168,7 @@ export async function applyEntityChangeSchema(db: DbClient): Promise<void> {requested_batch_size INTEGER,retention_seconds INTEGER) RETURNS TABLE (feed_sequence BIGINT, feed_cursor UUID, feed_scope TEXT)- LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$DECLAREchanged_scopes TEXT[];changed_scope TEXT;@@ -251,7 +251,7 @@ export async function applyEntityChangeCheckpointSchema(db: DbClient): Promise<vcurrent_sequence BIGINT,invalidated_scopes TEXT[])- LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$DECLAREcursor_sequence BIGINT;current_watermark BIGINT;@@ -307,3 +307,21 @@ export async function applyEntityChangeCheckpointSchema(db: DbClient): Promise<vGRANT EXECUTE ON FUNCTION entity_change_read_checkpoint(UUID, INTEGER) TO control_api_runtime;`)}++/**+ * Repair the pinned path on databases that already applied the original+ * entity-change migrations. PostgreSQL implicitly searches pg_temp first for+ * relations and types unless it is explicitly listed at the end.+ */+export async function applyEntityChangeDefinerSearchPathSchema(db: DbClient): Promise<void> {+ await db.query(`+ ALTER FUNCTION entity_change_capture_resource()+ SET search_path = pg_catalog, public, pg_temp;+ ALTER FUNCTION entity_change_capture_scope()+ SET search_path = pg_catalog, public, pg_temp;+ ALTER FUNCTION entity_change_dispatch_batch(INTEGER, INTEGER)+ SET search_path = pg_catalog, public, pg_temp;+ ALTER FUNCTION entity_change_read_checkpoint(UUID, INTEGER)+ SET search_path = pg_catalog, public, pg_temp;+ `)+}diff --git a/control-api/test/db.migrationsOrder.test.ts b/control-api/test/db.migrationsOrder.test.tsindex cae62b0ad..e299316cc 100644--- a/control-api/test/db.migrationsOrder.test.ts+++ b/control-api/test/db.migrationsOrder.test.ts@@ -151,6 +151,33 @@ describe('CONTROL_API_MIGRATIONS ordering invariant', () => {expect(sql).not.toMatch(/current_watermark > pruned_watermark/i)})+ it('registers an additive temp-schema repair for entity-change definer functions', async () => {+ const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')+ const migration = CONTROL_API_MIGRATIONS.find(+ candidate => candidate.version === '0124_entity_change_definer_search_path'+ )+ expect(migration).toBeDefined()+ if (!migration) return++ const query = vi.fn().mockResolvedValue({ rows: [], rowCount: 0 })+ await migration.apply({ query } as never)++ const sql = query.mock.calls.map(([statement]) => String(statement)).join('\n')+ for (const functionName of [+ 'entity_change_capture_resource',+ 'entity_change_capture_scope',+ 'entity_change_dispatch_batch',+ 'entity_change_read_checkpoint',+ ]) {+ expect(sql).toMatch(+ new RegExp(+ `ALTER FUNCTION ${functionName}[\\s\\S]+?SET search_path = pg_catalog, public, pg_temp`,+ 'i'+ )+ )+ }+ })+it('requires 0116_mcp_secret_rollback_permits to persist expiring rollback permits', async () => {const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')// Renumbered twice while syncing onto dev: 0101 -> 0109 -> 0116. The earlierdiff --git a/control-api/test/db.realPostgresMigration.integration.test.ts b/control-api/test/db.realPostgresMigration.integration.test.tsindex e90ab93db..df47b04c4 100644--- a/control-api/test/db.realPostgresMigration.integration.test.ts+++ b/control-api/test/db.realPostgresMigration.integration.test.ts@@ -1858,6 +1858,83 @@ describeRealPostgres('control-api real Postgres migrations', () => {}})+ it('prevents temp-type shadowing in entity-change SECURITY DEFINER triggers', async () => {+ const { CONTROL_API_MIGRATIONS, initDb } = await import('../src/db.js')+ await initDb({ connect: () => dbPool.connect() })++ const attackerRole = `entity_change_shadow_${randomBytes(5).toString('hex')}`+ const attackerPassword = randomBytes(24).toString('hex')+ let attackerPool: Pool | undefined+ try {+ await adminPool.query(+ `CREATE ROLE ${quoteIdent(attackerRole)} LOGIN PASSWORD '${attackerPassword}'`+ )+ await adminPool.query(`GRANT gfs_controller TO ${quoteIdent(attackerRole)}`)+ const attackerUrl = new URL(connectionString)+ attackerUrl.username = attackerRole+ attackerUrl.password = attackerPassword+ attackerPool = new Pool({ connectionString: attackerUrl.toString(), max: 1 })++ const attacker = await attackerPool.connect()+ try {+ await attacker.query('CREATE TEMP TABLE temp_schema_bootstrap (id INTEGER)')+ await attacker.query(`+ CREATE FUNCTION pg_temp.entity_change_shadow_check(value pg_catalog.text)+ RETURNS BOOLEAN LANGUAGE plpgsql AS $$+ BEGIN+ RAISE EXCEPTION 'temporary type shadow executed as %', current_user;+ END;+ $$+ `)+ await attacker.query(`+ CREATE DOMAIN pg_temp.text AS pg_catalog.text+ CHECK (pg_temp.entity_change_shadow_check(VALUE))+ `)++ const resourceId = randomUUID()+ await expect(+ attacker.query(+ `INSERT INTO gfs_resources (resource_id, drive, name, kind, path_cache)+ VALUES ($1, $2, 'shadow-probe', 'file', '/shadow-probe')`,+ [resourceId, `shadow-${randomUUID()}`]+ )+ ).resolves.toBeDefined()+ const stored = await dbPool.query('SELECT 1 FROM gfs_resources WHERE resource_id = $1', [+ resourceId,+ ])+ expect(stored.rowCount).toBe(1)+ } finally {+ attacker.release()+ }++ const migrationVersions = await adminPool.query<{ version: string }>(+ `SELECT version FROM schema_migrations WHERE version = $1`,+ ['0124_entity_change_definer_search_path']+ )+ expect(migrationVersions.rows).toHaveLength(1)++ const functionPaths = await dbPool.query<{ function_name: string; config: string[] | null }>(`+ SELECT procedure.proname AS function_name, procedure.proconfig AS config+ FROM pg_proc procedure+ JOIN pg_namespace namespace ON namespace.oid = procedure.pronamespace+ WHERE namespace.nspname = 'public'+ AND procedure.proname IN (+ 'entity_change_capture_resource',+ 'entity_change_capture_scope',+ 'entity_change_dispatch_batch',+ 'entity_change_read_checkpoint'+ )+ `)+ expect(functionPaths.rows).toHaveLength(4)+ for (const { config } of functionPaths.rows) {+ expect(config).toContain('search_path=pg_catalog, public, pg_temp')+ }+ } finally {+ await attackerPool?.end()+ await adminPool.query(`DROP ROLE IF EXISTS ${quoteIdent(attackerRole)}`)+ }+ })+it('commits GFS grant/share batches atomically and invalidates only after commit', async () => {const operator = await dbPool.query<{ id: string }>(`SELECT id::text FROM control_admin_users