Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(train M): folder rules fail closed for a database role that cannot read the access tables

garrytan32713c91e20a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 41ad86184d..bee36b688e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -37,6 +37,7 @@ identifiers and attribution are available in the pre-removal Git revision
- Works the same on a repo-less brain: members, groups, bindings and folder rules live in the database. A source records which store holds its folder rules when its first rule is created, and only `gbrain access rule migrate --source <id>` moves them; doctor `access_policy_store_mismatch` names it when the filesystem changes.
- The member-access and folder-rule SQL functions end their pinned `search_path` with `pg_temp`, like every other gbrain function (#7632), and frontmatter recovery never guesses a duplicated `readable_by` key: the file is held until a person fixes it.
- Remote callers can no longer write pages under `.gbrain/`.
+- On Postgres, a database role that neither owns the folder access tables nor bypasses row-level security now needs read policies on them (docs/ENGINES.md, "Folder access tables"). Without them its page writes are refused with `writer_coordinator_required` (`unreadable_state`) and its reads show nothing, instead of reading the tables as empty and treating every page as unruled. The owner, BYPASSRLS roles and PGLite are unaffected.
- A harness that sends an audience its credential's `may_act_for` does not list gets `on_behalf_of_not_permitted` with the operator's command; an audience inside tool arguments is always refused (`on_behalf_of_in_arguments`). `may_act_for: *` is accepted and doctor warns (`access_may_act_for_wildcard`).
## [0.60.534.0] - 2026-11-01
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index b4a42f53d0..bed043697e 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -458,6 +458,28 @@ CREATE POLICY trust_policy_state_writer ON trust_policy_state FOR ALL TO <writer
```
<!-- gbrain:maintainer-rls-recipe:end -->
+<a id="folder-access-tables"></a>**Folder access tables.** A page write stamps the folder rules covering its slug
+from `access_policy_state` and `access_rules`, and remote reads hide the prefixes listed in
+`access_pending_coverage`, all as the database role doing the write or read. A role that row-level security keeps
+from reading those tables never reads them as "no rule": the stamp refuses the write with
+`writer_coordinator_required` (relationship `unreadable_state`, naming the table), and reads treat every page as
+under a pending prefix, so nothing is shown. The owner (without `FORCE ROW LEVEL SECURITY`) and a role that
+bypasses RLS are not affected, and `gbrain access` rule commands refuse such a role with `permission_denied`. A scoped
+role that writes or serves pages needs these policies; they let it read the rules and lock a source's policy row while
+stamping, but not change either. Row-level security does not cover TRUNCATE or triggers, so the recipe also revokes
+those. A policy that filters these rows hides rules from the role and so reveals the pages under them: keep `USING (true)`:
+
+<!-- gbrain:access-rls-recipe:begin (applied verbatim by test/access-folder-scoped-role.test.ts) -->
+```sql
+CREATE POLICY access_policy_state_reader ON access_policy_state FOR SELECT TO <writer-role> USING (true);
+CREATE POLICY access_policy_state_stamp_lock ON access_policy_state FOR UPDATE TO <writer-role>
+ USING (true) WITH CHECK (false);
+CREATE POLICY access_rules_reader ON access_rules FOR SELECT TO <writer-role> USING (true);
+CREATE POLICY access_pending_coverage_reader ON access_pending_coverage FOR SELECT TO <writer-role> USING (true);
+REVOKE TRUNCATE, TRIGGER, REFERENCES ON access_policy_state, access_rules, access_pending_coverage FROM <writer-role>;
+```
+<!-- gbrain:access-rls-recipe:end -->
+
**In engine-sql.** A read in a migrated domain takes a `ScopedRead` when it
runs through this helper and a `LegacyUnscopedRead` when it runs on the pool
(`src/core/engine-sql/brands.ts`); the engine obtains the branded executor, so
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 75561496e3..f711a2d688 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/core/search/evidence-delivery.ts 1755 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned)
src/commands/config.ts 1524 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)
src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)
-src/core/behavior-change-notice.ts 1592 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +4 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218), re-summed at the train S merge: 1588 + 4 = 1592
+src/core/behavior-change-notice.ts 1593 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +4 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218), re-summed at the train S merge: 1588 + 4 = 1592; +1 GBRA-218 train M folder_access_scoped_role_gbra218 row (1593 measured)
diff --git a/src/commands/doctor/checks/folder-access.ts b/src/commands/doctor/checks/folder-access.ts
index 050a159adf..1161e7e983 100644
--- a/src/commands/doctor/checks/folder-access.ts
+++ b/src/commands/doctor/checks/folder-access.ts
@@ -108,6 +108,19 @@ async function guarded(name: string, run: (engine: BrainEngine, sources: string[
async function runFolderAccess(ctx: DoctorContext): Promise<Check[]> {
const engine = connectedEngine(ctx);
+ const [state] = await engine.executeRaw<{ unreadable: boolean }>('SELECT gbrain_access_state_unreadable() AS unreadable').catch(() => []);
+ if (state?.unreadable) {
+ const skipped = 'Skipped: this database role cannot read the folder access tables (see access_policy_pending).';
+ return [
+ { name: 'access_policy_pending', status: 'warn', details: { unreadable: true, docs: 'docs/ENGINES.md#folder-access-tables' },
+ message: 'This database role cannot read the folder access tables (row-level security hides them), so remote reads show no page, '
+ + 'page writes are refused with writer_coordinator_required and folder-rule commands are refused. Run gbrain as their owner, or give the role '
+ + 'the policies in docs/ENGINES.md ("Folder access tables").' },
+ infoCheck('access_policy_widening_held', skipped, 'unknown'),
+ infoCheck('access_policy_invalid', skipped, 'unknown'),
+ infoCheck('access_policy_store_mismatch', skipped, 'unknown'),
+ ];
+ }
const sources = await policySources(engine).catch(() => null);
const checks: Check[] = [];
checks.push({ name: 'access_policy_pending', ...await guarded('access_policy_pending', pending, engine, sources) });
diff --git a/src/core/access/caller.ts b/src/core/access/caller.ts
index 66a783493d..7003815e64 100644
--- a/src/core/access/caller.ts
+++ b/src/core/access/caller.ts
@@ -74,7 +74,8 @@ export async function stdioMemberIdentity(engine: BrainEngine): Promise<string[]
/**
* GBRA-218 (A2): the folder-rule part of a caller's record, read live from the applied rulebook: the
* source-qualified ids of the rules `identity` satisfies, and every prefix that reads as nobody (a narrowing being
- * stamped, an invalid policy file). An unreadable rulebook satisfies nothing and covers everything (fail closed).
+ * stamped, an invalid policy file). An unreadable rulebook satisfies nothing and covers everything (fail closed), and so
+ * does one row-level security hides from this database role.
*/
export async function folderAccessFor(engine: Pick<BrainEngine, 'executeRaw'>, identity: readonly string[]): Promise<{ satisfiedRuleIds: string[]; folderCoverage: FolderCoverage[] }> {
return folderAccessForAll(engine, [identity]);
@@ -91,7 +92,8 @@ export async function folderAccessForAll(engine: Pick<BrainEngine, 'executeRaw'>
? await engine.executeRaw<{ source_id: string; rule_id: string; readable_by: string[] }>('SELECT source_id, rule_id, readable_by FROM access_rules WHERE readable_by && $1::text[]', [union])
: [];
const satisfied = rules.filter(r => identities.every(id => (r.readable_by ?? []).some(reader => id.includes(reader))));
- const coverage = await engine.executeRaw<{ source_id: string; prefix: string }>('SELECT DISTINCT source_id, prefix FROM access_pending_coverage ORDER BY source_id, prefix');
+ const coverage = await engine.executeRaw<{ source_id: string; prefix: string }>(`SELECT * FROM (SELECT DISTINCT source_id, prefix FROM access_pending_coverage
+ UNION ALL SELECT '!unreadable', '' WHERE gbrain_access_state_unreadable()) c ORDER BY source_id, prefix`);
return { satisfiedRuleIds: satisfied.map(r => `${r.source_id}:${r.rule_id}`).sort(), folderCoverage: coverage.map(c => ({ source_id: c.source_id, prefix: c.prefix })) };
} catch {
return { satisfiedRuleIds: [], folderCoverage: [{ source_id: '!unreadable', prefix: '' }] };
diff --git a/src/core/access/policy.ts b/src/core/access/policy.ts
index e2af32e884..7a59effdaf 100644
--- a/src/core/access/policy.ts
+++ b/src/core/access/policy.ts
@@ -145,7 +145,17 @@ const key = (r: FolderRule) => `${r.id}\u0000${r.prefix}`;
* Makes `target` the applied rulebook inside the caller's locked transaction. Rules whose (id, prefix) pair is new get
* pending coverage until the restamp finishes. Returns whether pages need restamping.
*/
+/** Refuses when row-level security keeps this database role from reading the folder access tables (they would read as empty). */
+async function requireReadableAccessState(engine: Exec): Promise<void> {
+ const [row] = await engine.executeRaw<{ unreadable: boolean }>('SELECT gbrain_access_state_unreadable() AS unreadable');
+ if (row?.unreadable) {
+ throw opError('permission_denied', 'This database role cannot read the folder access tables (row-level security hides them), so no folder rule was changed, applied or cleared.',
+ 'Run it as the owner of the access tables, or give this role the policies in docs/ENGINES.md ("Folder access tables").', { docs: 'docs/ENGINES.md#folder-access-tables' });
+ }
+}
+
async function installRulebook(tx: Exec, sourceId: string, target: readonly FolderRule[], revision: number, actor: string): Promise<boolean> {
+ await requireReadableAccessState(tx);
const current = await appliedRules(tx, sourceId);
const before = new Map(current.map(r => [r.id, r]));
const after = new Map(target.map(r => [r.id, r]));
@@ -179,6 +189,7 @@ export interface RestampProgress { pages_scanned: number; pages_restamped: numbe
* written meanwhile, the pending coverage goes, and pending revisions count as applied, atomically.
*/
export async function restampSource(engine: BrainEngine, sourceId: string, opts: { batch?: number; onProgress?: (p: RestampProgress) => void } = {}): Promise<RestampProgress> {
+ await requireReadableAccessState(engine);
const batch = opts.batch ?? RESTAMP_BATCH;
const progress: RestampProgress = { pages_scanned: 0, pages_restamped: 0 };
let after = 0;
@@ -279,6 +290,7 @@ export async function proposeRevision(engine: BrainEngine, sourceId: string, des
/** Finishes an interrupted narrowing (pending coverage or stamps that drifted from the applied rulebook). Idempotent. */
export async function resumePolicy(engine: BrainEngine, sourceId: string, onProgress?: (p: RestampProgress) => void): Promise<RestampProgress & { pending_before: string[] }> {
await readAccessStore(engine, sourceId);
+ await requireReadableAccessState(engine);
const pending = (await coverageRows(engine, sourceId)).filter(c => c.reason === 'pending').map(c => c.prefix);
const [state] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM access_policy_state WHERE source_id = $1', [sourceId]);
if (!state?.n) return { pages_scanned: 0, pages_restamped: 0, pending_before: [] };
@@ -431,5 +443,6 @@ export async function markPolicyInvalid(engine: BrainEngine, sourceId: string, p
}
export async function clearPolicyInvalid(engine: Exec, sourceId: string): Promise<void> {
+ await requireReadableAccessState(engine);
await engine.executeRaw(`DELETE FROM access_pending_coverage WHERE source_id = $1 AND reason = 'invalid'`, [sourceId]);
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index a3a7621f43..4f4516fa1a 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1381,6 +1381,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', id: 'member_access_hatch_scope_gbra218', text: 'On a brain where any page names readers or any member exists, the escape hatches no longer turn the remote read filter off: remote reads still hide pages the caller\'s member is not listed on, and secondary surfaces that use the identity-free filter (proactive brief, retrieval reflex, entity resolution, known-as-of) hide every restricted page and keep hiding `visibility: private` pages under a hatch. A brain with no restriction keeps the old hatch behaviour exactly. A credential bound to a disabled or removed member is refused at verification (`access_member_disabled`).' },
{ since: 'TBD', id: 'shared_agent_audience_gbra231', text: 'A shared agent can now read as the people a turn serves: its harness names the audience in the `X-Gbrain-On-Behalf-Of` header or request-level `_meta.on_behalf_of` (member ids, `group:<id>`, `guest`), and the call returns only pages every entry may read, within the agent\'s own source grant; a channel audience (more than one member, a group or a guest) never sees a `visibility: private` page. Each entry must be in the credential\'s `may_act_for` (`gbrain auth rescope --token <name> --may-act-for <list>`; for stdio, config `mcp.stdio_may_act_for`), which earlier releases stored without enforcing. An audience inside tool arguments is refused (`on_behalf_of_in_arguments`). Every remote MCP response now carries `_meta.access` (member, groups, audience, policy revisions, privacy relaxation), and `whoami` returns it as `access.applied`.' },
{ since: 'TBD', id: 'folder_access_rules_gbra218', text: 'A source can now keep whole folders to named members with folder rules (`gbrain access rule add --prefix partners/alice-example/ --readers alice-example,group:team-a --source <id>`, preview then `--yes`). On a repo-less source the rules live in the database; on a git-backed source they live in `.gbrain/access.yml`, committed through `gbrain git commit-push` and applied on sync. A remote read of a page under a rule needs the caller\'s member to be listed on every rule covering it, on top of the page\'s own `readable_by`; no hatch, grant or `--as` relaxes it. Narrowing applies at once; a change that widens (removing a rule or a reader) is held until `gbrain access apply --source <id>` previews it and `--yes --expect <plan_hash>` approves it. While an apply is unfinished its prefixes read as nobody remotely (`access_policy_pending`, fixed by `gbrain access resume --source <id>`). `gbrain export` carries each source\'s applied rules under `.gbrain/`, and `gbrain import` installs them before any page (`--access-policy <source>` picks one source\'s rules from a multi-source export). Remote callers cannot write `.gbrain/` pages. Nothing changes on a source with no folder rule.' },
+ { since: 'TBD', id: 'folder_access_scoped_role_gbra218', text: 'On Postgres, a database role that neither owns the folder access tables (`access_policy_state`, `access_rules`, `access_pending_coverage`) nor bypasses row-level security, and holds no policy that lets it read them, no longer reads them as "no rule": a page write it makes is refused with `writer_coordinator_required` (`unreadable_state`, naming the table), and its reads treat every page as under a pending folder prefix, so remote reads show nothing. The owner, a role that bypasses RLS and PGLite are unaffected; docs/ENGINES.md ("Folder access tables") lists the four policies a scoped role needs.' },
{ since: '0.60.516.0', id: 'quoted_fence_marker_8059', text: 'A page that quotes a facts or takes fence marker in prose (text after the marker on its line, or a blockquote line) is now held or refused with the fence reason `quoted_marker` instead of `repeated_marker` or `unclosed_ambiguous_tail`, and `gbrain repair fences`, `gbrain repair content`, `gbrain sync unblock --apply` and the maintenance run repair it by wrapping each mention in backticks, with a receipt per file; readers count fence lines exactly as before. The edit is kept only when every fence row stays where it was and nothing the privacy boundary hid becomes visible. Existing `invalid_fence` holds are screened once more on the next sync. `forget` now locates the facts fence it rewrites with the parser\'s code-aware search, so a marker quoted in code above the fence no longer moves the rewrite.' },
// #7199 (re-port of #7228). since is stamped at the merge slot.
{ since: '0.60.516.0', id: 'classic_drift_rescreen_7199', text: 'A `file_drift` hold with side `unknown` that an older gbrain wrote before sync compared a record-less page with its file at the last synced commit is now compared once more, also with the file\'s last three earlier committed versions, and imports when the page equals one of them; otherwise it stays held and is not re-screened again. Such a hold now names what the page was compared with, and `gbrain sync status` lists it under its own verdict (`file_drift_unknown`, needs a person). A managed sync that holds files a person must decide now reports `reason: held_needs_human` with `held_needs_human: <count>` (JSON) and prints `Synced; N file(s) held for a person (gbrain sync status --source <id>).`; the source still syncs and its status stays `synced`.' },
diff --git a/src/core/function-search-path.ts b/src/core/function-search-path.ts
index ec2c536bf6..babbaa4b1e 100644
--- a/src/core/function-search-path.ts
+++ b/src/core/function-search-path.ts
@@ -25,6 +25,7 @@ export const PINNED_FUNCTION_NAMES = [
'auto_enable_rls', 'bump_page_generation_clock_fn', 'bump_page_generation_fn', 'enforce_minion_queue_protocol',
'gbrain_access_derive_page_readers', 'gbrain_access_folder_rules', 'gbrain_access_mark_restricted', 'gbrain_access_norm_readers',
'gbrain_access_origin_restricted', 'gbrain_access_pending_covers', 'gbrain_access_readers', 'gbrain_access_stamp_folder_rules',
+ 'gbrain_access_state_unreadable',
'gbrain_advance_page_revision', 'gbrain_advance_tag_revision', 'gbrain_bump_trust_generation',
'gbrain_clear_atom_page_state', 'gbrain_count_git_canonical_sources', 'gbrain_count_modifications', 'gbrain_forget_page_retrievals',
'gbrain_fts_input', 'gbrain_graduation_fence', 'gbrain_guard_effect_protocol', 'gbrain_guard_inserted_facts',
diff --git a/src/core/schema-migrations/v283-folder-access-rules.ts b/src/core/schema-migrations/v283-folder-access-rules.ts
index 9fa80178e4..6dd216a5dd 100644
--- a/src/core/schema-migrations/v283-folder-access-rules.ts
+++ b/src/core/schema-migrations/v283-folder-access-rules.ts
@@ -1,4 +1,5 @@
import type { Migration } from './types.ts';
+import { requireMaintainerPoliciesSql } from '../derived-state-maintainers.ts';
// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
@@ -25,6 +26,12 @@ import type { Migration } from './types.ts';
// read-time lineage test treats an origin under a folder rule or a covered
// prefix as restricted. Nothing is rewritten on upgrade: with no rule, every
// page keeps folder_rule_ids NULL.
+// A role that neither owns these tables nor bypasses RLS reads them empty, so
+// nothing here may read empty as "no rule": the stamp refuses the write
+// (writer_coordinator_required, unreadable_state, as v281 does), and where
+// gbrain_access_state_unreadable() holds, reads and the derivation-privacy
+// test treat every page as covered and the policy commands refuse.
+// No SECURITY DEFINER (#7659).
// No schema.sql mirror: like v282, these exist only through migrations.
// Provisional number: renumbered at the merge slot.
export const v283: Migration = {
@@ -87,6 +94,15 @@ CREATE OR REPLACE FUNCTION gbrain_access_folder_rules(p_source TEXT, p_slug TEXT
SELECT array_agg(p_source || ':' || r.rule_id ORDER BY r.rule_id COLLATE "C")
FROM access_rules r WHERE r.source_id = p_source AND starts_with(p_slug, r.prefix)
$fn$;
+CREATE OR REPLACE FUNCTION gbrain_access_state_unreadable() RETURNS boolean
+ LANGUAGE sql STABLE PARALLEL SAFE SET search_path = pg_catalog, public, pg_temp AS $fn$
+ SELECT EXISTS (SELECT 1 FROM pg_catalog.unnest(ARRAY['access_policy_state', 'access_rules', 'access_pending_coverage']::pg_catalog.regclass[]) AS t(rel)
+ WHERE pg_catalog.row_security_active(t.rel) AND NOT EXISTS (
+ SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid OPERATOR(pg_catalog.=) t.rel::pg_catalog.oid AND p.polpermissive
+ AND p.polcmd::pg_catalog.text OPERATOR(pg_catalog.=) ANY (ARRAY['*', 'r']::pg_catalog.text[])
+ AND EXISTS (SELECT 1 FROM pg_catalog.unnest(p.polroles) AS r(id)
+ WHERE CASE WHEN r.id OPERATOR(pg_catalog.=) 0::pg_catalog.oid THEN true ELSE pg_catalog.pg_has_role(r.id, 'USAGE') END)))
+$fn$;
CREATE OR REPLACE FUNCTION gbrain_access_pending_covers(p_source TEXT, p_slug TEXT) RETURNS boolean
LANGUAGE sql STABLE PARALLEL SAFE SET search_path = pg_catalog, public, pg_temp AS $fn$
SELECT EXISTS (SELECT 1 FROM access_pending_coverage c WHERE c.source_id = p_source AND starts_with(p_slug, c.prefix))
@@ -94,6 +110,8 @@ $fn$;
CREATE OR REPLACE FUNCTION gbrain_access_stamp_folder_rules() RETURNS trigger
LANGUAGE plpgsql SET search_path = pg_catalog, public, pg_temp AS $fn$
BEGIN
+ ${requireMaintainerPoliciesSql('access_policy_state', ['SELECT', 'UPDATE'])}
+ ${requireMaintainerPoliciesSql('access_rules', ['SELECT'])}
IF EXISTS (SELECT 1 FROM access_policy_state s WHERE s.source_id = NEW.source_id) THEN
PERFORM 1 FROM access_policy_state s WHERE s.source_id = NEW.source_id FOR SHARE;
NEW.folder_rule_ids := gbrain_access_folder_rules(NEW.source_id, NEW.slug);
diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.ts
index 5b879c80cf..659e55e55b 100644
--- a/src/core/search/private-visibility.ts
+++ b/src/core/search/private-visibility.ts
@@ -102,10 +102,11 @@ export function folderRulesAllowedSql(alias: string, satisfied: readonly string[
/**
* The pending or invalid prefixes of the current record as a conjunct (empty when none); an ill-formed entry hides
- * everything. Outside any caller record the prefixes are read live, so a page under a pending prefix stays hidden.
+ * everything. Outside any caller record the prefixes are read live, so a page under a pending prefix stays hidden;
+ * a database role that row-level security keeps from reading them reads every page as covered.
*/
function coverageSql(alias: string): string {
- if (!callerAccessStore.getStore()) return ` AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = ${alias}.source_id AND starts_with(${alias}.slug, pc.prefix))`;
+ if (!callerAccessStore.getStore()) return ` AND NOT EXISTS (SELECT 1 FROM access_pending_coverage pc WHERE pc.source_id = ${alias}.source_id AND starts_with(${alias}.slug, pc.prefix)) AND NOT (SELECT gbrain_access_state_unreadable())`;
const coverage = currentCallerAccess().folderCoverage;
if (!coverage.length) return '';
return coverage.map(c => !isValidSourceId(c.source_id) || (c.prefix !== '' && !validPrefix(c.prefix)) ? ' AND FALSE'
@@ -518,9 +519,12 @@ export function derivationPrivateSql(alias: string): string {
return `(NOT ${privateSnapshotFilterFragment(alias)} OR ${privacyAliasSql(alias)} OR ${namesReadersSql(alias)} OR ${folderRestrictedSql(alias)})`;
}
-/** GBRA-218 (A2): the page row sits under an applied folder rule (its stamp) or a pending or invalid folder prefix. */
+/**
+ * GBRA-218 (A2): the page row sits under an applied folder rule (its stamp) or a pending or invalid folder prefix, or
+ * this database role cannot read the folder access tables.
+ */
export function folderRestrictedSql(alias: string): string {
- return `(${alias}.folder_rule_ids IS NOT NULL OR gbrain_access_pending_covers(${alias}.source_id, ${alias}.slug))`;
+ return `(${alias}.folder_rule_ids IS NOT NULL OR gbrain_access_pending_covers(${alias}.source_id, ${alias}.slug) OR (SELECT gbrain_access_state_unreadable()))`;
}
/**
@@ -530,7 +534,7 @@ export function folderRestrictedSql(alias: string): string {
export async function folderRestricted(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string): Promise<boolean> {
try {
const [row] = await engine.executeRaw<{ restricted: boolean }>(
- 'SELECT (gbrain_access_folder_rules($1, $2) IS NOT NULL OR gbrain_access_pending_covers($1, $2)) AS restricted', [sourceId, slug]);
+ 'SELECT (gbrain_access_folder_rules($1, $2) IS NOT NULL OR gbrain_access_pending_covers($1, $2) OR gbrain_access_state_unreadable()) AS restricted', [sourceId, slug]);
return row?.restricted === true;
} catch {
return true;
diff --git a/test/access-folder-scoped-role.test.ts b/test/access-folder-scoped-role.test.ts
new file mode 100644
index 0000000000..9bf8c57872
--- /dev/null
+++ b/test/access-folder-scoped-role.test.ts
@@ -0,0 +1,194 @@
+/**
+ * GBRA-218 (A2) folder rules under a scoped database role. The folder-rule stamp and the pending-coverage reads run as
+ * the role doing the write or read. A role that neither owns the access tables nor bypasses RLS read them empty: a page
+ * written under a ruled prefix was stamped with no rule and read remotely as unruled, and a prefix still being narrowed
+ * stayed visible. Contract: an access table that row-level security hides from the role is never read as "no rule".
+ * The stamp refuses the write (writer_coordinator_required, unreadable_state) and every pending-coverage read covers
+ * everything. A role holding the docs/ENGINES.md access recipe (applied verbatim) gets the correct stamp and the
+ * normal read. Postgres only (PGLite has no roles): test/e2e/access-folder-scoped-role-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { folderAccessFor } from '../src/core/access/caller.ts';
+import { restampSource } from '../src/core/access/policy.ts';
+import { folderRestricted, folderRulesAllowedSql, withCallerAccess } from '../src/core/search/private-visibility.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const SCOPED = `gbrain_access_scoped_${randomUUID().replaceAll('-', '').slice(0, 12)}`;
+const ACCESS_TABLES = ['access_policy_state', 'access_rules', 'access_pending_coverage'];
+const UNREADABLE = /writer_coordinator_required: writer state is unreadable to this database role/;
+const ALICE = ['member:alice-example'];
+
+/** The SQL between the access recipe markers in docs/ENGINES.md, for `role`. */
+function docsRecipe(role: string): string {
+ // test-reads-source-ok[structural]: the operator recipe is applied verbatim, so the documented policies are the tested ones.
+ const doc = readFileSync(new URL('../docs/ENGINES.md', import.meta.url), 'utf8');
+ const block = /<!-- gbrain:access-rls-recipe:begin[^>]*-->\s*```sql\n([\s\S]*?)```\s*<!-- gbrain:access-rls-recipe:end -->/.exec(doc);
+ if (!block) throw new Error('docs/ENGINES.md has no access-rls-recipe block');
+ return block[1]!.replaceAll('<writer-role>', role);
+}
+
+(testBackends().includes('postgres') ? describe : describe.skip)('folder rules under a scoped database role (Postgres)', () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ let tables: string[] = [];
+
+ /** Open policies for the scoped role on every table except `hidden`. */
+ async function policies(hidden: string[]) {
+ for (const table of tables) {
+ await engine.executeRaw(`DROP POLICY IF EXISTS ${SCOPED}_open ON ${table}`);
+ if (!hidden.includes(table)) await engine.executeRaw(`CREATE POLICY ${SCOPED}_open ON ${table} FOR ALL TO ${SCOPED} USING (true) WITH CHECK (true)`);
+ }
+ }
+ /** Runs `fn` inside a transaction as the scoped role; the transaction rolls back. */
+ async function asScoped<T>(fn: (tx: BrainEngine) => Promise<T>): Promise<{ value?: T; error?: string; state?: string }> {
+ const marker = new Error('scoped-probe-rollback');
+ let value: T | undefined;
+ try {
+ await engine.transaction(async tx => {
+ await tx.executeRaw(`SET LOCAL ROLE ${SCOPED}`);
+ await tx.executeRaw(`SELECT set_config('gbrain.write_principal_kind','application',true), set_config('gbrain.write_principal_id','scoped-probe',true)`);
+ value = await fn(tx);
+ throw marker;
+ });
+ } catch (e) {
+ if (e !== marker) {
+ const detail = (e as { detail?: string }).detail;
+ return { error: (e as Error).message, ...(detail?.startsWith('{') ? { state: JSON.parse(detail).state } : {}) };
+ }
+ }
+ return { value };
+ }
+ const insertPage = (tx: BrainEngine, slug: string) => tx.executeRaw<{ folder_rule_ids: string[] | null }>(
+ `INSERT INTO pages(source_id,slug,type,title,compiled_truth,content_hash) VALUES('default',$1,'note','T','b',repeat('a',64)) RETURNING folder_rule_ids`, [slug]);
+ /** Whether `slug` passes the folder-rule read predicate for `identity`, with the caller record read as the role. */
+ async function remoteReads(tx: BrainEngine, slug: string, identity: string[]): Promise<boolean> {
+ const folder = await folderAccessFor(tx, identity);
+ return withCallerAccess({ identity, ...folder }, async () =>
+ (await tx.executeRaw(`SELECT 1 FROM pages p WHERE p.source_id = 'default' AND p.slug = $1 AND ${folderRulesAllowedSql('p', folder.satisfiedRuleIds)}`, [slug])).length === 1);
+ }
+ /** The same predicate outside any caller record (the live pending-coverage read). */
+ const liveReads = async (tx: BrainEngine, slug: string) =>
+ (await tx.executeRaw(`SELECT 1 FROM pages p WHERE p.source_id = 'default' AND p.slug = $1 AND ${folderRulesAllowedSql('p', [])}`, [slug])).length === 1;
+
+ beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engine = pg.engine; close = pg.close;
+ await engine.executeRaw(`CREATE ROLE ${SCOPED} NOLOGIN NOSUPERUSER NOBYPASSRLS`);
+ await engine.executeRaw(`GRANT USAGE ON SCHEMA public TO ${SCOPED}`);
+ await engine.executeRaw(`GRANT ALL ON ALL TABLES IN SCHEMA public TO ${SCOPED}`);
+ await engine.executeRaw(`GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO ${SCOPED}`);
+ for (const table of ACCESS_TABLES) await engine.executeRaw(`ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY`);
+ tables = (await engine.executeRaw<{ t: string }>(`SELECT tablename AS t FROM pg_tables WHERE schemaname = 'public' ORDER BY 1`)).map(r => r.t);
+ await engine.executeRaw(`INSERT INTO access_policy_state(source_id) VALUES('default')`);
+ await engine.executeRaw(`INSERT INTO access_rules(source_id,rule_id,prefix,readable_by,revision) VALUES('default','r1','partners/',ARRAY['member:alice-example'],1)`);
+ await engine.executeRaw(`INSERT INTO pages(source_id,slug,type,title,compiled_truth,content_hash) VALUES('default','drafts/x','note','T','b',repeat('a',64)), ('default','notes/y','note','T','b',repeat('a',64))`);
+ await engine.executeRaw(`INSERT INTO access_pending_coverage(source_id,prefix,reason,revision) VALUES('default','drafts/','pending',2)`);
+ }, 180_000);
+ afterAll(async () => {
+ if (engine) {
+ await engine.executeRaw(`DROP OWNED BY ${SCOPED}`).catch(() => undefined);
+ await engine.executeRaw(`DROP ROLE IF EXISTS ${SCOPED}`);
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+ }
+ await close?.();
+ resetGateway();
+ });
+
+ test('the owner stamps the rule and reads the pending prefix as covered', async () => {
+ const [row] = await engine.transaction(async tx => {
+ await tx.executeRaw(`SELECT set_config('gbrain.write_principal_kind','application',true), set_config('gbrain.write_principal_id','owner-probe',true)`);
+ return insertPage(tx, 'partners/a');
+ });
+ expect(row!.folder_rule_ids).toEqual(['default:r1']);
+ expect(await liveReads(engine, 'drafts/x')).toBe(false);
+ expect(await liveReads(engine, 'notes/y')).toBe(true);
+ });
+
+ test('a scoped role that cannot read the rulebook is refused, not stamped with no rule', async () => {
+ await policies(ACCESS_TABLES);
+ const outcome = await asScoped(tx => insertPage(tx, 'partners/b'));
+ expect(outcome.error).toMatch(UNREADABLE);
+ expect(outcome.value).toBeUndefined();
+ });
+
+ test('a scoped role that reads the policy row but not the rules is refused', async () => {
+ await policies(['access_rules']);
+ const outcome = await asScoped(tx => insertPage(tx, 'partners/b'));
+ expect(outcome).toEqual({ error: expect.stringMatching(UNREADABLE), state: 'access_rules' });
+ });
+
+ test('a scoped role that can read the policy row but not lock it is refused', async () => {
+ await policies(ACCESS_TABLES);
+ await engine.executeRaw(`CREATE POLICY ${SCOPED}_ro ON access_policy_state FOR SELECT TO ${SCOPED} USING (true)`);
+ await engine.executeRaw(`CREATE POLICY ${SCOPED}_ro ON access_rules FOR SELECT TO ${SCOPED} USING (true)`);
+ try {
+ const outcome = await asScoped(tx => insertPage(tx, 'partners/b'));
+ expect(outcome).toEqual({ error: expect.stringMatching(UNREADABLE), state: 'access_policy_state' });
+ } finally {
+ for (const t of ['access_policy_state', 'access_rules']) await engine.executeRaw(`DROP POLICY IF EXISTS ${SCOPED}_ro ON ${t}`);
+ }
+ });
+
+ test('a scoped role that cannot read the rules reads every page as covered and cannot restamp', async () => {
+ await policies(['access_rules']);
+ const outcome = await asScoped(async tx => ({
+ record: await remoteReads(tx, 'notes/y', ALICE),
+ live: await liveReads(tx, 'notes/y'),
+ restricted: await folderRestricted(tx, 'default', 'notes/y'),
+ }));
+ expect(outcome).toEqual({ value: { record: false, live: false, restricted: true } });
+ const restamp = await asScoped(tx => restampSource(tx, 'default'));
+ expect(restamp.error).toMatch(/cannot read the folder access tables/);
+ });
+
+ test('a scoped role that cannot read the pending prefixes reads every page as covered', async () => {
+ await policies(['access_pending_coverage']);
+ const outcome = await asScoped(async tx => ({
+ record: await remoteReads(tx, 'drafts/x', ALICE),
+ unruled: await remoteReads(tx, 'notes/y', ALICE),
+ live: await liveReads(tx, 'drafts/x'),
+ restricted: await folderRestricted(tx, 'default', 'notes/y'),
+ }));
+ expect(outcome).toEqual({ value: { record: false, unruled: false, live: false, restricted: true } });
+ });
+
+ test('the docs/ENGINES.md access recipe, applied verbatim, stamps the rule and keeps the normal read', async () => {
+ await policies(ACCESS_TABLES);
+ const recipe = docsRecipe(SCOPED);
+ const created = [...recipe.matchAll(/CREATE POLICY (\w+) ON (\w+)/g)].map(m => ({ name: m[1]!, table: m[2]! }));
+ expect([...new Set(created.map(p => p.table))].sort()).toEqual([...ACCESS_TABLES].sort());
+ await engine.executeRaw(recipe);
+ try {
+ const outcome = await asScoped(async tx => {
+ const [row] = await insertPage(tx, 'partners/b');
+ return {
+ stamped: row!.folder_rule_ids,
+ stranger: await remoteReads(tx, 'partners/b', ['member:bob-example']),
+ alice: await remoteReads(tx, 'partners/b', ALICE),
+ pending: await remoteReads(tx, 'drafts/x', ALICE),
+ unruled: await remoteReads(tx, 'notes/y', ['member:bob-example']),
+ rulesUnchanged: (await tx.executeRaw(`UPDATE access_rules SET readable_by = ARRAY['member:bob-example'] WHERE rule_id = 'r1' RETURNING 1`)).length,
+ rulesKept: (await tx.executeRaw(`DELETE FROM access_rules WHERE rule_id = 'r1' RETURNING 1`)).length,
+ coverageKept: (await tx.executeRaw(`DELETE FROM access_pending_coverage WHERE source_id = 'default' RETURNING 1`)).length,
+ };
+ });
+ expect(outcome).toEqual({ value: { stamped: ['default:r1'], stranger: false, alice: true, pending: false, unruled: true, rulesUnchanged: 0, rulesKept: 0, coverageKept: 0 } });
+ const policyRowLocked = await asScoped(tx => tx.executeRaw(`UPDATE access_policy_state SET created_at = now() WHERE source_id = 'default'`));
+ expect(policyRowLocked.error).toMatch(/row-level security/);
+ for (const table of ACCESS_TABLES) {
+ expect((await asScoped(tx => tx.executeRaw(`TRUNCATE ${table} CASCADE`))).error).toMatch(/permission denied/);
+ }
+ } finally {
+ for (const p of created) await engine.executeRaw(`DROP POLICY IF EXISTS ${p.name} ON ${p.table}`);
+ await engine.executeRaw(`GRANT ALL ON ${ACCESS_TABLES.join(', ')} TO ${SCOPED}`);
+ }
+ });
+});
diff --git a/test/e2e/access-folder-scoped-role-postgres.test.ts b/test/e2e/access-folder-scoped-role-postgres.test.ts
new file mode 100644
index 0000000000..05eed40e42
--- /dev/null
+++ b/test/e2e/access-folder-scoped-role-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../access-folder-scoped-role.test.ts'));
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index cd9b1209eb..558e335de1 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -573,7 +573,8 @@
"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=691cabb9e3951b1ac732fceaf826aaaa2e69cab650caaac6df2cbbaf47764ad4",
"gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3a5530179ad6f056532e398fb4de58610125625e09140340ff138a2e268772a8",
"gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",
- "gbrain_access_stamp_folder_rules()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5185d4f512c372e3c42ef274294d2ab2daf1b93f3ce46516f514831cbee10f7d",
+ "gbrain_access_stamp_folder_rules()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7fb49ce62f4f6153ef0c844a1816f5f5bb7d765b8610ff66fec137283469fc09",
+ "gbrain_access_state_unreadable()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=06cb94c05b12fa615072f97c1d0979de2f92914c8f1f54dc521262865fa27a0b",
"gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2a431195dc4c4150e3428251d0dec0a685cdc2992525c1b4b54dff103d5d99c9",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=810fecb358043c1c5490f7074955f3543a0af4c8e5b3cacb489232bfea6c980a",
"gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=eb43f514d9784dabdae32a80d97116a9a49f1eeb1dc7a67e832e714ed7fa0a14",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index 175bb9461d..1d2608a90e 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -573,7 +573,8 @@
"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=691cabb9e3951b1ac732fceaf826aaaa2e69cab650caaac6df2cbbaf47764ad4",
"gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3a5530179ad6f056532e398fb4de58610125625e09140340ff138a2e268772a8",
"gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",
- "gbrain_access_stamp_folder_rules()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5185d4f512c372e3c42ef274294d2ab2daf1b93f3ce46516f514831cbee10f7d",
+ "gbrain_access_stamp_folder_rules()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7fb49ce62f4f6153ef0c844a1816f5f5bb7d765b8610ff66fec137283469fc09",
+ "gbrain_access_state_unreadable()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=06cb94c05b12fa615072f97c1d0979de2f92914c8f1f54dc521262865fa27a0b",
"gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2a431195dc4c4150e3428251d0dec0a685cdc2992525c1b4b54dff103d5d99c9",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=810fecb358043c1c5490f7074955f3543a0af4c8e5b3cacb489232bfea6c980a",
"gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=eb43f514d9784dabdae32a80d97116a9a49f1eeb1dc7a67e832e714ed7fa0a14",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index c753fc8644..eb19d67123 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -573,7 +573,8 @@
"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=691cabb9e3951b1ac732fceaf826aaaa2e69cab650caaac6df2cbbaf47764ad4",
"gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3a5530179ad6f056532e398fb4de58610125625e09140340ff138a2e268772a8",
"gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",
- "gbrain_access_stamp_folder_rules()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5185d4f512c372e3c42ef274294d2ab2daf1b93f3ce46516f514831cbee10f7d",
+ "gbrain_access_stamp_folder_rules()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7fb49ce62f4f6153ef0c844a1816f5f5bb7d765b8610ff66fec137283469fc09",
+ "gbrain_access_state_unreadable()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=06cb94c05b12fa615072f97c1d0979de2f92914c8f1f54dc521262865fa27a0b",
"gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2a431195dc4c4150e3428251d0dec0a685cdc2992525c1b4b54dff103d5d99c9",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=810fecb358043c1c5490f7074955f3543a0af4c8e5b3cacb489232bfea6c980a",
"gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=eb43f514d9784dabdae32a80d97116a9a49f1eeb1dc7a67e832e714ed7fa0a14",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 59914743e4..57b0eac86c 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -45,7 +45,7 @@
"PERSISTENCE_REQUEST_SLUG_INTENT_INDEX": "5f2e4a3dde452e610fe7eaae949642c00d7c61a363b1cd344d7f0917db233aa5",
"PERSISTENCE_SYNC_RUN_INDEXES": "e1b12613c5fd2facb850e6857b0bddcf49b2478ec258fa226fe15e71e55df9c1",
"PERSISTENCE_SYNC_WATERMARK_INDEX": "93523954a30e8483717f07ec97a3e0cd062b15d8a60cc759281054b06c23bb40",
- "PINNED_FUNCTION_NAMES": "701225b24141cec2c3faa1dbfc80ac86a0c5fe41440204eeca2f0c8b2873ee0e",
+ "PINNED_FUNCTION_NAMES": "aa10ffdebfc6025cbd0235255d01682f16026426ce2383fcd0db57f024e356f1",
"PLANNER_REPAIR_TABLES": "008725595e099adba279d4292661eb4a59930b777c35db43c340220f7f12e093",
"TABLES": "3fc77a0fccb525f9b791098f9eae27b19adaa3f5dadbabcff2a719137cbc3ef8",
"TOKEN_TTL_MAX_SECONDS": "f4a45bec6ec0bacc859dc57732ceb76cec7eb72f242b5a6c89d47190d0525ab4",
@@ -4583,8 +4583,8 @@
"idempotent": true,
"name": "folder_access_rules",
"sql": {
- "length": 7048,
- "sha256": "54c5690108691d5a49e1d7981236646e5e4be04ee386229eb30cb294eb0ad9a2"
+ "length": 9609,
+ "sha256": "7d754ee2a64386296663b3482d6eb55c9feacb5529fbba389bf25802a05b942d"
},
"sqlFor": "absent",
"transaction": "absent",
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index d10503cadf..3594d277e1 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -573,7 +573,8 @@
"gbrain_access_origin_restricted(p_id integer, p_source_id text, p_type text, fm jsonb)": "RETURNS boolean kind=f lang=plpgsql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=691cabb9e3951b1ac732fceaf826aaaa2e69cab650caaac6df2cbbaf47764ad4",
"gbrain_access_pending_covers(p_source text, p_slug text)": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=3a5530179ad6f056532e398fb4de58610125625e09140340ff138a2e268772a8",
"gbrain_access_readers(fm jsonb)": "RETURNS text[] kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=18348cb56089106aaec6470076ee652d7ed3bfbcb20e950a24abd52a21e7a380",
- "gbrain_access_stamp_folder_rules()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=5185d4f512c372e3c42ef274294d2ab2daf1b93f3ce46516f514831cbee10f7d",
+ "gbrain_access_stamp_folder_rules()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=7fb49ce62f4f6153ef0c844a1816f5f5bb7d765b8610ff66fec137283469fc09",
+ "gbrain_access_state_unreadable()": "RETURNS boolean kind=f lang=sql volatility=s secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=06cb94c05b12fa615072f97c1d0979de2f92914c8f1f54dc521262865fa27a0b",
"gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=2a431195dc4c4150e3428251d0dec0a685cdc2992525c1b4b54dff103d5d99c9",
"gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=810fecb358043c1c5490f7074955f3543a0af4c8e5b3cacb489232bfea6c980a",
"gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public, pg_temp] body_sha256=eb43f514d9784dabdae32a80d97116a9a49f1eeb1dc7a67e832e714ed7fa0a14",