Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test: guard definer e2e cases 12-14 (replay, BYPASSRLS loss, v276 lock timeout); fix stale reindex call-order comment

garrytanbfb7e1f6235e
diff --git a/test/e2e/guard-definer-postgres.test.ts b/test/e2e/guard-definer-postgres.test.ts
index f4613dfe25..80aef08619 100644
--- a/test/e2e/guard-definer-postgres.test.ts
+++ b/test/e2e/guard-definer-postgres.test.ts
@@ -18,6 +18,8 @@ import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { LATEST_VERSION, runMigrations } from '../../src/core/migrate.ts';
import { guardFunctionProblems } from '../../src/commands/doctor/checks/guard-functions.ts';
import { derivationNeedles } from '../../src/core/page-body/segment-derive.ts';
+import { v276 } from '../../src/core/schema-migrations/v276-guard-triggers-security-definer.ts';
+import { withEnv } from '../helpers/with-env.ts';
const DATABASE_URL = process.env.DATABASE_URL;
const describeE2E = DATABASE_URL ? describe : describe.skip;
@@ -358,6 +360,11 @@ describeE2E('purge and withdrawal guards under a scoped write role (#7632)', ()
for (const fn of GUARDS) expect(stderr).toContain(`${fn}()`);
for (const trigger of ['facts_refuse_purged', 'takes_refuse_purged', 'pages_refuse_purged', 'page_segment_derivations_refuse_purging']) expect(stderr).toContain(trigger);
expect(stderr).toContain('left as they were');
+ // Generated by gstack /ship coverage audit (#7642).
+ // Value: protects=v276 names on stderr every non-guard function whose search_path it could not finish with pg_temp;
+ // fails_when=the unhardened-function listing is dropped from hardenGuards; why_new=the guard names above also come
+ // from the function loop; seam=none; no_claim=none beyond protects
+ expect(stderr).toContain('gbrain_try_jsonb(text)');
expect((await catalog(brain.conn)).guards.every(g => !g.secdef)).toBe(true);
await notOwner.disconnect();
@@ -373,4 +380,87 @@ describeE2E('purge and withdrawal guards under a scoped write role (#7632)', ()
await brain.conn.end();
}
}, 300_000);
+
+ // Generated by gstack /ship coverage audit (#7642).
+ // Value: protects=a brain already at the latest version that boots again (schema blob replay, no migration runs) keeps
+ // the definer guards, trigger placement and pg_temp on every pinned path; fails_when=the hardening fragment stops being
+ // the blob's last statement or a blob CREATE OR REPLACE drops SECURITY DEFINER; why_new=10a/10b run v276, which
+ // re-hardens everything; seam=none; no_claim=PGLite replay (pglite-upgrade-replay golden covers it)
+ test('12. a brain at the latest version that boots again (schema blob replay, no migration) keeps the catalog, and doctor passes', async () => {
+ const engine = new PostgresEngine();
+ try {
+ await engine.connect({ database_url: url });
+ const { value } = await capturingStderr(() => runMigrations(engine));
+ expect(value.applied).toBe(0);
+ await engine.initSchema();
+ expect(await catalog(conn)).toEqual(EXPECTED);
+ expect(await guardFunctionProblems(engine)).toEqual({ problems: [], fix: [] });
+ } finally {
+ await engine.disconnect();
+ }
+ }, 300_000);
+
+ // Generated by gstack /ship coverage audit (#7642).
+ // Value: protects=doctor names a guard whose owner neither bypasses RLS nor owns its ledger, a guard that really lets
+ // purged content through; fails_when=the reads_under_rls probe is dropped or its owner/force condition inverted;
+ // why_new=every other case runs the guards as a superuser owner; seam=none; no_claim=FORCE ROW LEVEL SECURITY on an
+ // owner-owned ledger (same branch, not exercised)
+ test('13. doctor names a guard whose owner reads its ledger under RLS, and that guard does let purged content through', async () => {
+ const weakOwner = `gbrain_test_guard_owner_${suffix}`;
+ await admin!.unsafe(`CREATE ROLE ${weakOwner} NOLOGIN NOSUPERUSER NOBYPASSRLS`);
+ createdRoles.push(weakOwner);
+ const [fn] = await conn.unsafe<Array<{ owner: string }>>(`SELECT pg_get_userbyid(proowner) AS owner FROM pg_proc WHERE oid = 'gbrain_refuse_purged_page()'::regprocedure`);
+ const owner = fn!.owner;
+ const insertPurgedPage = `INSERT INTO pages (slug, type, title, compiled_truth, content_hash) VALUES ('notes/again-example', 'note', 't', 'x', $1) RETURNING 1 AS stored`;
+ const engine = new PostgresEngine();
+ try {
+ await conn.unsafe(`GRANT USAGE ON SCHEMA public TO ${weakOwner}; GRANT SELECT ON page_purges TO ${weakOwner};
+ ALTER FUNCTION gbrain_refuse_purged_page() OWNER TO ${weakOwner}`);
+ await engine.connect({ database_url: url });
+ expect(await guardFunctionProblems(engine)).toEqual({
+ problems: [`gbrain_refuse_purged_page()'s owner ${weakOwner} neither bypasses RLS nor owns page_purges unforced, so the guard reads them filtered`],
+ fix: [`-- give gbrain_refuse_purged_page() an owner that bypasses RLS (ALTER FUNCTION gbrain_refuse_purged_page() OWNER TO <owner of the tables>), or ALTER ROLE ${weakOwner} BYPASSRLS;`],
+ });
+ await as(conn, WRITER, async run => {
+ expect(rowsOf(await run(insertPurgedPage, [PURGED_HASH]))).toEqual([{ stored: 1 }]);
+ });
+ } finally {
+ await conn.unsafe(`ALTER FUNCTION gbrain_refuse_purged_page() OWNER TO ${owner}; REVOKE ALL ON page_purges FROM ${weakOwner}; REVOKE USAGE ON SCHEMA public FROM ${weakOwner}`);
+ await engine.disconnect();
+ }
+ await as(conn, WRITER, async run => {
+ expect(failure(await run(insertPurgedPage, [PURGED_HASH])).code).toBe('P0001');
+ });
+ });
+
+ // Generated by gstack /ship coverage audit (#7642).
+ // Value: protects=v276 stops with the typed schema_lock_blocked refusal naming the table when another session holds a
+ // lock, leaves that trigger as it was, and finishes once the lock is gone; fails_when=SET LOCAL lock_timeout or the
+ // 55P03 mapping is dropped (upgrade hangs or throws untyped); why_new=no test holds a lock against v276; seam=none;
+ // no_claim=the blocking-session sample (v276 passes sessions: null) and transaction-pooler behavior
+ test('14. v276 refuses with schema_lock_blocked when another session holds a lock on a table whose trigger it moves, and finishes after', async () => {
+ const engine = new PostgresEngine();
+ const holder = postgres(url, { max: 1, prepare: false, onnotice: () => {} });
+ const factsTiming = async () => (await catalog(conn)).triggers.find(t => t.trigger === 'facts_refuse_purged')?.timing;
+ try {
+ await conn.unsafe(`DROP TRIGGER facts_refuse_purged ON facts;
+ CREATE TRIGGER facts_refuse_purged BEFORE UPDATE OF fact, source_id, visibility, entity_slug ON facts FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact()`);
+ await engine.connect({ database_url: url });
+ const session = await holder.reserve();
+ try {
+ await session.unsafe('BEGIN; LOCK TABLE facts IN ACCESS SHARE MODE');
+ const error = await withEnv({ GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS: '1' }, () => v276.handler!(engine).then(() => null, (e: unknown) => e));
+ expect(error).toMatchObject({ code: 'schema_lock_blocked', detail: 'v276 on facts' });
+ expect(await factsTiming()).toBe('BEFORE');
+ } finally {
+ await session.unsafe('ROLLBACK');
+ session.release();
+ }
+ await withEnv({ GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS: '1' }, () => v276.handler!(engine));
+ expect(await catalog(conn)).toEqual(EXPECTED);
+ } finally {
+ await holder.end();
+ await engine.disconnect();
+ }
+ }, 300_000);
});
diff --git a/test/reindex-search-vector.serial.test.ts b/test/reindex-search-vector.serial.test.ts
index 7912d21ea6..74f550324c 100644
--- a/test/reindex-search-vector.serial.test.ts
+++ b/test/reindex-search-vector.serial.test.ts
@@ -179,8 +179,8 @@ describe('runReindexSearchVector', () => {
expect(result.language).toBe('english');
expect(state.calls.length).toBe(16);
- // Trigger recreates (calls 1, 2) and chunks backfill (call 4) embed the
- // language literal. Pages backfill (call 3) is UPDATE-to-self that
+ // Trigger recreates (calls 1, 2) and chunks backfill (call 5) embed the
+ // language literal. Pages backfill (call 4) is UPDATE-to-self that
// re-fires the trigger, so the language literal lives in the trigger
// function body — not in the UPDATE statement.
expect(state.calls[1]).toContain("'english'");