Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(doctor): rls fails only when the public schema may be anon-reachable; plain Postgres warns (#4939)

time-attack39dd634b270a
diff --git a/docs/guides/rls-and-you.md b/docs/guides/rls-and-you.md
index 5052ff338f..519d2f0efc 100644
--- a/docs/guides/rls-and-you.md
+++ b/docs/guides/rls-and-you.md
@@ -1,8 +1,9 @@
# RLS and you
Short version: every table in your gbrain's `public` schema needs Row Level
-Security enabled. If one doesn't, `gbrain doctor` now fails, not warns, and the
-process exits 1.
+Security enabled. If one doesn't and the schema may be reachable with an anon
+key (Supabase, or PostgREST roles on the database), `gbrain doctor` fails and
+the process exits 1. On a plain Postgres with no such exposure it warns.
This guide explains why, what to do when you hit the check, and the escape hatch
for the cases where you really do want a table to stay readable by the anon key.
@@ -256,14 +257,21 @@ running and will flag any table that came over without RLS.
## Self-hosted Postgres
If you're running Postgres without PostgREST in front, the anon-key exposure
-doesn't apply. But gbrain still fails the check on missing RLS, because:
+doesn't apply. Doctor looks for an exposure signal before it fails the check:
+the PostgREST role names (`anon`, `authenticated`, `authenticator`,
+`service_role`) in `pg_roles`, or a Supabase database URL. With neither, a
+table without RLS is a `warn`:
-- The framing is "RLS on all public tables" is a gbrain security invariant,
- not a Supabase-specific workaround.
-- The `ALTER TABLE ... ENABLE RLS` fix is harmless on any Postgres: it only
- constrains non-bypass roles, which gbrain doesn't use.
-- If you ever put PostgREST or a similar tool in front later, the guard is
- already in place.
+```
+rls: warn — 1 table(s) WITHOUT Row Level Security: local_notes. No PostgREST
+exposure detected (...), so this is a warning: enable RLS before putting
+PostgREST or a similar API in front of the public schema. Fix: ALTER TABLE ...
+```
+
+The fix is still worth running: `ALTER TABLE ... ENABLE ROW LEVEL SECURITY` is
+harmless on any Postgres (it only constrains non-bypass roles, which gbrain
+doesn't use), and the guard is in place if you add PostgREST later. Once one
+of those roles exists, the same table fails the check.
-If this framing doesn't fit your deployment, file an issue with the specifics
-so we can decide whether a self-hosted-exempt mode is justified.
+**Say to your agent:** *"Check whether my brain's database tables are protected
+before I expose it."*
diff --git a/src/commands/doctor/checks/schema-health.ts b/src/commands/doctor/checks/schema-health.ts
index 02939ff8d0..2c856a8667 100644
--- a/src/commands/doctor/checks/schema-health.ts
+++ b/src/commands/doctor/checks/schema-health.ts
@@ -10,6 +10,7 @@
import { embedBackfillFix } from '../../../core/embed-consent.ts';
import * as db from '../../../core/db.ts';
import { loadConfig } from '../../../core/config.ts';
+import { isSupabasePoolerUrl } from '../../../core/connection-manager.ts';
import { LATEST_VERSION } from '../../../core/migrate.ts';
import { schemaVersionHealth } from '../../../core/schema-version-health.ts';
import { pgvectorCheck, pagesUpsertArbiterCheck, linkSourceCheckConstraintCheck } from './core-health.ts';
@@ -154,6 +155,7 @@ async function runRls(ctx: DoctorContext): Promise<Check[]> {
message: `RLS enabled on ${tables.length - exempt.length}/${tables.length} public tables${suffix}`,
});
} else {
+ const exposure = await publicSchemaExposure(sql);
const names = gaps.join(', ');
// Double-escape " inside identifiers so a pathological table name
// like `weird"table` renders as `"weird""table"` in the remediation
@@ -166,14 +168,12 @@ async function runRls(ctx: DoctorContext): Promise<Check[]> {
const exemptInfo = exempt.length > 0
? ` (${exempt.length} other table(s) explicitly exempt.)`
: '';
- checks.push({
- name: 'rls',
- status: 'fail',
- message:
- `${gaps.length} table(s) WITHOUT Row Level Security: ${names}.${exemptInfo} ` +
- `Fix: ${fixes} ` +
- `If a table should stay readable by the anon key on purpose, see docs/guides/rls-and-you.md for the GBRAIN:RLS_EXEMPT comment escape hatch.`,
- });
+ const fixTail = `Fix: ${fixes} ` +
+ `If a table should stay readable by the anon key on purpose, see docs/guides/rls-and-you.md for the GBRAIN:RLS_EXEMPT comment escape hatch.`;
+ const gapLine = `${gaps.length} table(s) WITHOUT Row Level Security: ${names}.${exemptInfo} `;
+ checks.push(exposure
+ ? { name: 'rls', status: 'fail', message: `${gapLine}The public schema may be served to the anon key (${exposure}). ${fixTail}` }
+ : { name: 'rls', status: 'warn', message: `${gapLine}No PostgREST exposure detected (no anon, authenticated, authenticator or service_role role; not a Supabase URL), so this is a warning: enable RLS before putting PostgREST or a similar API in front of the public schema. ${fixTail}` });
}
} catch {
checks.push(checkError('rls', 'check RLS status'));
@@ -184,6 +184,17 @@ async function runRls(ctx: DoctorContext): Promise<Check[]> {
export const rlsEntry: DoctorEntry = { name: 'rls', emits: ['rls'], run: runRls };
+/** PostgREST role conventions or a Supabase host mean the public schema may be reachable with the anon key; null when neither is present. */
+async function publicSchemaExposure(sql: ReturnType<typeof db.getConnection>): Promise<string | null> {
+ const roles = await sql`SELECT rolname FROM pg_roles
+ WHERE rolname IN ('anon', 'authenticated', 'authenticator', 'service_role') ORDER BY rolname`;
+ if (roles.length > 0) return `PostgREST role(s) present: ${(roles as unknown as Array<{ rolname: string }>).map(r => r.rolname).join(', ')}`;
+ const url = loadConfig()?.database_url ?? '';
+ let host = '';
+ try { host = new URL(url.replace(/^postgres(ql)?:\/\//, 'http://')).hostname; } catch { /* no parsable URL */ }
+ return /(^|\.)supabase\.(co|com)$/i.test(host) || isSupabasePoolerUrl(url) ? 'Supabase database URL' : null;
+}
+
async function runSchemaVersion(ctx: DoctorContext): Promise<Check[]> {
const { progress } = ctx;
const engine = connectedEngine(ctx);
diff --git a/test/e2e/mechanical.test.ts b/test/e2e/mechanical.test.ts
index 96091985d3..f0d5a0981f 100644
--- a/test/e2e/mechanical.test.ts
+++ b/test/e2e/mechanical.test.ts
@@ -1106,7 +1106,42 @@ describeE2E('E2E: RLS Verification', () => {
}
});
- test('gbrain doctor fails with exit 1 when a public table is missing RLS', async () => {
+ // #4939: doctor fails a missing-RLS table only when the public schema may be
+ // reachable with the anon key (PostgREST roles or a Supabase URL). The
+ // fail-path tests below create the PostgREST `anon` role for their duration.
+ async function withPostgrestRole<T>(fn: () => Promise<T>): Promise<T> {
+ const conn = getConn();
+ const existed = (await conn.unsafe(`SELECT 1 FROM pg_roles WHERE rolname = 'anon'`)).length > 0;
+ if (!existed) await conn.unsafe(`CREATE ROLE anon NOLOGIN`);
+ try { return await fn(); } finally { if (!existed) await conn.unsafe(`DROP ROLE IF EXISTS anon`); }
+ }
+
+ test('gbrain doctor warns, not fails, on a missing-RLS table when nothing exposes the public schema (#4939)', async () => {
+ const conn = getConn();
+ const tbl = `gbrain_rls_plain_pg_${suffix}`;
+ try {
+ Bun.spawnSync({
+ cmd: ['bun', 'run', 'src/cli.ts', 'init', '--non-interactive', '--url', process.env.DATABASE_URL!],
+ cwd: cliCwd, env: cliEnv(), timeout: 15_000,
+ });
+ expect((await conn.unsafe(`SELECT 1 FROM pg_roles WHERE rolname IN ('anon','authenticated','authenticator','service_role')`)).length).toBe(0);
+ await conn.unsafe(`CREATE TABLE public.${tbl} (id int)`);
+ await conn.unsafe(`ALTER TABLE public.${tbl} DISABLE ROW LEVEL SECURITY`);
+ const result = Bun.spawnSync({
+ cmd: ['bun', 'run', 'src/cli.ts', 'doctor', '--json'],
+ cwd: cliCwd, env: cliEnv(), timeout: 20_000,
+ });
+ const rls = JSON.parse(new TextDecoder().decode(result.stdout)).checks.find((c: any) => c.name === 'rls');
+ expect(rls.status).toBe('warn');
+ expect(rls.message).toContain(tbl);
+ expect(rls.message).toContain('No PostgREST exposure detected');
+ expect(rls.message).toContain('ENABLE ROW LEVEL SECURITY');
+ } finally {
+ await conn.unsafe(`DROP TABLE IF EXISTS public.${tbl}`);
+ }
+ }, 60_000);
+
+ test('gbrain doctor fails with exit 1 when a public table is missing RLS', () => withPostgrestRole(async () => {
const conn = getConn();
const tbl = `gbrain_rls_regression_${suffix}`;
try {
@@ -1149,7 +1184,7 @@ describeE2E('E2E: RLS Verification', () => {
const v35sql = (MIGRATIONS.find(m => m.version === 35)?.sqlFor as any)?.postgres;
if (v35sql) await conn.unsafe(v35sql);
}
- }, 60_000);
+ }), 60_000);
test('GBRAIN:RLS_EXEMPT comment with valid reason exempts a non-RLS public table', async () => {
const conn = getConn();
@@ -1178,7 +1213,7 @@ describeE2E('E2E: RLS Verification', () => {
}
}, 60_000);
- test('GBRAIN:RLS_EXEMPT comment WITHOUT reason= still fails doctor', async () => {
+ test('GBRAIN:RLS_EXEMPT comment WITHOUT reason= still fails doctor', () => withPostgrestRole(async () => {
const conn = getConn();
const tbl = `gbrain_rls_exempt_bad_${suffix}`;
try {
@@ -1204,9 +1239,9 @@ describeE2E('E2E: RLS Verification', () => {
} finally {
await conn.unsafe(`DROP TABLE IF EXISTS public.${tbl}`);
}
- }, 60_000);
+ }), 60_000);
- test('Non-exempt unrelated COMMENT on a no-RLS table still fails doctor', async () => {
+ test('Non-exempt unrelated COMMENT on a no-RLS table still fails doctor', () => withPostgrestRole(async () => {
const conn = getConn();
const tbl = `gbrain_rls_comment_${suffix}`;
try {
@@ -1230,7 +1265,7 @@ describeE2E('E2E: RLS Verification', () => {
} finally {
await conn.unsafe(`DROP TABLE IF EXISTS public.${tbl}`);
}
- }, 60_000);
+ }), 60_000);
// Regression test for the v24 self-healing guard. If an operator manually
// drops budget_ledger and/or budget_reservations (they are migration-only