Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(access): keep a member-bound write to a federated source to its member (#8982 item 1)

garrytanc7af4d8164d3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 90cfbe86c8..83d445022a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**A page a member-bound credential creates in a federated source is now readable only by that member.** A token or OAuth client bound to a member (`gbrain auth rescope --member <id>`) and granted `--sources <id>` for a federated source wrote its pages there with no readers. Every credential without a source grant reads `default` plus every federated source, so another member's no-grant token and an unbound token read those pages over `get_page`, `search`, `query`, `recall` and `list_pages`. Such a page is now written with `readable_by: [member:<id>]`, as a page the credential writes to `default` already was, and `POST /ingest` refuses the credential. A write source that is not federated keeps the audience its grants give it. Pages written before the upgrade keep their readers: check them with `gbrain access who-can-read <slug>`.
+
+### Itemized changes
+
+- `src/core/source-resolver.ts`: `noGrantFloorReads` says whether a caller with no source grant reads a source unqualified: `default`, or a source in the federated set `noGrantFederatedScope` threads for that floor. It throws when the sources cannot be read.
+- `src/core/persistence/page-visibility.ts`: `defaultSourceMemberWriter` keys on `noGrantFloorReads` instead of the literal `default`, so a member-bound write to a federated source is stamped too. A source table it cannot read refuses the write instead of publishing the page shared.
+- `src/commands/serve-http-webhooks.ts`: the `POST /ingest` refusal names the credential's write source.
+- Docs: `docs/guides/multi-source-brains.md`, `docs/tutorials/company-brain.md` (Model C), `docs/mcp/ADMIN.md`.
+- Tests: `test/access-federated-member-writes.test.ts` (PGLite, and Postgres with `DATABASE_URL`): a member-bound token granted a federated source creates a page that another member and an unbound token, reading the federated set as the HTTP transports do, cannot read; a non-federated source stays unstamped and out of unbound reads; a member-bound write cannot leave its granted source; `POST /ingest` refuses with nothing queued.
+
## [0.60.622.0] - 2026-11-09
**`think` keeps an entity's trajectory when the question names a month.** A question such as "What was the MRR of acme-example in April 2026?" bounds think's evidence to April (PR #5086), and that window used to cost the trajectory block twice over: a metric whose readings fall before and after April (March and June) injected nothing, although the March reading was the value in force all April; and an entity page last edited outside April was dropped from the gathered pages, so when the question's noun phrase ("the acme-example team") did not resolve on its own, no entity was found. Each metric's latest reading before the window now joins the readings inside it, unless its `valid_until` ended by the time the window opens, and pages the window drops still name the entities whose trajectory is read; they stay out of the evidence. BrainBench Cat 25's hermetic gate goes from 4 of 6 probes (FAIL) to 6 of 6 (PASS).
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index 7f0fc2c776..7a06a39b4b 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -244,12 +244,12 @@ who may read it, before any member's bot connects:
```
The first id is the token's write source, so a member's saved memories land
- in their own private source.
+ in their own private source. Keep that source unfederated.
A credential bound to a member (`--member`) whose write source is `default`
(a token with no `--sources` or with `--sources default`, or an OAuth client
- left at its registration default) writes where every credential without a
- source grant reads. A page such a credential creates is therefore written
+ left at its registration default) or a federated source writes where every
+ credential without a source grant reads. A page such a credential creates is therefore written
with `readable_by: [member:<id>]`, readable only by that member (and the
local CLI); rewriting it without `readable_by` keeps those readers, and the
member shares it by naming readers (`readable_by: [alice-example,
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index 58bd68bf8b..0dc739caca 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -240,7 +240,7 @@ Inside one source, bind each member's credential with `gbrain auth rescope
only some members may read, or keep a whole folder to them with `gbrain access
rule add --prefix <folder>/ --readers <members> --source <id>`.
A member-bound credential whose write source is `default` (no `--sources`, or an
-OAuth client at its registration default) keeps a page it creates to that
+OAuth client at its registration default) or a federated source keeps a page it creates to that
member until the member names more readers
([details](../tutorials/company-brain.md#two-scoping-models-pick-the-one-that-matches-your-shape)).
One agent serving several people in a shared channel holds `--may-act-for
diff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.md
index 6b31328e26..8ff1aacaba 100644
--- a/docs/tutorials/company-brain.md
+++ b/docs/tutorials/company-brain.md
@@ -130,7 +130,7 @@ gbrain access check --token alice-laptop # what this credential can rea
gbrain access who-can-read notes/renewal-notes # the members and groups a page admits
```
-A credential bound with `--member` whose write source is `default` (a token with no `--sources` or `--sources default`, or an OAuth client left at its registration default) writes where every credential without a source grant reads, so a page it creates is written with `readable_by: [member:<id>]` and only that member reads it; it keeps those readers when the member rewrites it without the field, and the member shares it by naming readers (`readable_by: [alice-example, group:team-a]`). An edit to an existing page that names no readers leaves it shared, `remember` facts go on the member's own page as before, and `POST /ingest` refuses such a credential. Pages derived from such a page (extracted atoms, chronicle events, `derived_from` pages, and a synthesized concept that uses it) follow the rule for pages with readers and are readable by no remote caller, the writer included. A page that teammates should read, such as a shared `people/` or `companies/` entity page or a page in a folder a rule already scopes to a group, names its readers when it is created; otherwise the first member to create a slug keeps it, and every other remote credential writing that slug (another member, an unbound token, a shared agent) gets `page_not_found`. The operator widens such a page from the brain host by adding `readable_by` to it. A member-bound `put_page` over a page deleted within the last 72 hours is a create, so it is kept to the member too. A credential whose write source is another source (`--sources private-alice-example,default`, first id the write source) keeps writing exactly what it sends. Earlier releases wrote these pages with no readers, so other members and unbound tokens read them; run `gbrain access who-can-read <slug>` on pages your members wrote and add `readable_by` on the host where needed.
+A credential bound with `--member` whose write source is `default` (a token with no `--sources` or `--sources default`, or an OAuth client left at its registration default) or a federated source (`gbrain sources federate <id>`) writes where every credential without a source grant reads, so a page it creates is written with `readable_by: [member:<id>]` and only that member reads it; it keeps those readers when the member rewrites it without the field, and the member shares it by naming readers (`readable_by: [alice-example, group:team-a]`). An edit to an existing page that names no readers leaves it shared, `remember` facts go on the member's own page as before, and `POST /ingest` refuses such a credential. Pages derived from such a page (extracted atoms, chronicle events, `derived_from` pages, and a synthesized concept that uses it) follow the rule for pages with readers and are readable by no remote caller, the writer included. A page that teammates should read, such as a shared `people/` or `companies/` entity page or a page in a folder a rule already scopes to a group, names its readers when it is created; otherwise the first member to create a slug keeps it, and every other remote credential writing that slug (another member, an unbound token, a shared agent) gets `page_not_found`. The operator widens such a page from the brain host by adding `readable_by` to it. A member-bound `put_page` over a page deleted within the last 72 hours is a create, so it is kept to the member too. A credential whose write source is a source that is not federated (`--sources private-alice-example,default`, first id the write source) keeps writing exactly what it sends. Earlier releases wrote these pages with no readers, so other members and unbound tokens read them; run `gbrain access who-can-read <slug>` on pages your members wrote and add `readable_by` on the host where needed.
A remote caller whose credential is bound to a listed member (directly or through a group) reads the page on every read path; every other remote caller, including an unbound token, an unbound stdio server, a bot with `--private-pages granted-sources` and an operator escape hatch (`GBRAIN_REMOTE_PRIVATE_PAGES=1`, `search.remote_private_pages=visible`), gets the same `not_found` as for a page that does not exist. `readable_by` only narrows: a `visibility: private` page stays private to a listed member unless the member's credential also has `--private-pages granted-sources`. A malformed `readable_by` reads as nobody. A page derived from a restricted page (an extracted atom, a synthesized concept, a chronicle event) is readable by no remote caller. The local CLI is unchanged; `--as <member>` previews one member's view. Pages that already carried `readable_by` before you upgraded read as nobody until `gbrain repair access` (preview, then `--apply`) derives their readers. This works the same on a repo-less brain: members, groups and bindings live in the database.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 4a28864e2c..52875aab07 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 1759 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); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)
src/commands/config.ts 1526 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); 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 1690 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; 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); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); 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.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 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, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2
+src/core/behavior-change-notice.ts 1691 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; 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); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); 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.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 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, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 #8982 federated_member_writes_8982 row (since TBD until the merge slot; rows are data and cannot move)
diff --git a/src/commands/serve-http-webhooks.ts b/src/commands/serve-http-webhooks.ts
index a3de28f821..5fb6b5a9ba 100644
--- a/src/commands/serve-http-webhooks.ts
+++ b/src/commands/serve-http-webhooks.ts
@@ -302,16 +302,18 @@ function verifyWebhookSig(secret: unknown, sigHeader: string, payload: Buffer):
}
/**
- * GST-2051: a member-bound credential writing to default would publish where every no-grant credential reads; the capture
- * job cannot keep the page to the member, so POST /ingest refuses it (answering res) and put_page, which does, stays open.
+ * GST-2051: a member-bound credential writing to default or a federated source would publish where every no-grant credential
+ * reads; the capture job cannot keep the page to the member, so POST /ingest refuses it (answering res) and put_page, which
+ * does, stays open.
*/
async function refusedDefaultSourceMember(engine: BrainEngine, authInfo: AuthInfo, res: Response): Promise<boolean> {
- if (!authInfo.principal || !await defaultSourceMemberWriter(engine, { remote: true, principal: authInfo.principal as WriteAuthority['principal'], sourceId: authInfo.sourceId ?? 'default' })) return false;
+ const sourceId = authInfo.sourceId ?? 'default';
+ if (!authInfo.principal || !await defaultSourceMemberWriter(engine, { remote: true, principal: authInfo.principal as WriteAuthority['principal'], sourceId })) return false;
res.status(403).json({
error: 'permission_denied',
- message: 'POST /ingest is unavailable to a credential bound to a member whose write source is default: its pages would land where other members ' +
+ message: `POST /ingest is unavailable to a credential bound to a member whose write source is ${sourceId}, which every credential without a source grant reads: its pages would land where other members ` +
'and unbound credentials read. Write through the MCP put_page op, which keeps a new page to its member, ' +
- 'or ask the brain operator to grant this credential its own write source (gbrain auth rescope --sources <private-source>,default).',
+ 'or ask the brain operator to grant this credential its own write source that is not federated (gbrain auth rescope --sources <private-source>,default).',
});
return true;
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index e22220747f..0d25a2bdb8 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1492,6 +1492,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.621.0', id: 'ungranted_member_writes_gst2051', text: 'A token or OAuth client bound to a member (`gbrain auth rescope --member <id>`) whose write source is `default` (no `--sources`, `--sources default`, or an OAuth client at its registration default) writes where every credential without a source grant reads. A page it creates there is now written with `readable_by: [member:<id>]`, so other members and unbound tokens no longer read it; rewriting it without `readable_by` keeps those readers, naming readers widens it, an edit to an existing page with no readers leaves it shared, and `POST /ingest` refuses such a credential. Pages derived from such a page (atoms, chronicle events, `derived_from` pages, a synthesized concept using it) are readable by no remote caller, the writer included; a page teammates should read names its readers when created, because every other remote credential, unbound tokens included, gets page_not_found writing a slug a member created until the operator adds readable_by on the brain host. Credentials writing to another source and unbound credentials are unchanged, and pages written before the upgrade keep their readers (`gbrain access who-can-read <slug>`).' },
{ since: '0.60.622.0', id: 'think_window_trajectory_gst731', text: '`think` on a question that names one month or day (or given `since`/`until`) still gets the entity\'s trajectory: each metric\'s latest reading before the window now joins the readings inside it, as the value in force when the window opens (unless its `valid_until` ended by then), and an entity page dated outside the window still names whose trajectory to read (it stays out of the evidence). Before, "MRR in April" with readings in March and June, or a company page last edited outside the month, injected no trajectory. `WINDOW_EXCLUDED_<n>_TRAJECTORY_POINTS` no longer counts the carried reading.' },
{ since: '0.60.622.0', id: 'purge_cancels_deferred_write_gst1602', text: 'With `persistence.refresh_barrier` on, `gbrain forget <id> --purge` no longer refuses `purge_blocked_pending_recovery` while a write deferred behind a refresh holds the claim in its staged body: the deferred write was never claimed, so the purge cancels it with `purged_content`, as it does a queued one, and removes the content at once instead of up to 15 minutes later.' },
+ { since: 'TBD', id: 'federated_member_writes_8982', text: 'A token or OAuth client bound to a member whose write source is a federated source (`gbrain sources federate <id>`) now writes the pages it creates with `readable_by: [member:<id>]`, as one writing to `default` does, because every credential without a source grant reads federated sources too; `POST /ingest` refuses such a credential. Before this, other members\' no-grant tokens and unbound tokens read those pages. A write source that is not federated is unchanged, and pages written before the upgrade keep their readers (`gbrain access who-can-read <slug>`).' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/page-visibility.ts b/src/core/persistence/page-visibility.ts
index 3d626f2cd1..2242dd7b4f 100644
--- a/src/core/persistence/page-visibility.ts
+++ b/src/core/persistence/page-visibility.ts
@@ -7,6 +7,8 @@ import { parseStoredActor, storedActorIdentity } from '../access/actor.ts';
import { hasReaders, normalizePrincipal, normalizeReaders, readersAllow, NOBODY } from '../access/principals.ts';
import { catalogueError } from '../error-catalogue.ts';
import type { SqlEngine, WriteAuthority } from './model.ts';
+import type { BrainEngine } from '../engine.ts';
+import { noGrantFloorReads } from '../source-resolver.ts';
/** Publication uses fresh policy, independent of the read-side telemetry cache (read through the resolver). */
export async function excludesPrivateWrites(engine: SqlEngine, remote: boolean): Promise<boolean> {
@@ -142,20 +144,21 @@ export async function remoteReadersChecked<T extends { parsedPage: { frontmatter
}
/**
- * GST-2051: the member a remote write's token or OAuth client is bound to, as `member:<id>`, when the write goes to
- * `default`: the no-grant floor of every token without `--sources` and the registration default of every OAuth
- * client, read by every credential without a source grant, unbound ones included. Null for a local, unbound, attested
- * or audience write, and for any other source (the operator chose that source's audience). Read from the stored
- * binding at preparation, so a binding removed after submission takes effect; a disabled member's page names a reader
- * nobody holds and is refused, and a binding that cannot be read throws instead of publishing the page shared.
+ * GST-2051: the member a remote write's token or OAuth client is bound to, as `member:<id>`, when the write goes to a
+ * source every credential without a source grant reads, unbound ones included (noGrantFloorReads): `default`, the
+ * no-grant floor of every token without `--sources` and the registration default of every OAuth client, and since
+ * #8982 every federated source. Null for a local, unbound, attested or audience write, and for any other source (the
+ * operator chose that source's audience through its grants). Read from the stored binding and source config at
+ * preparation, so a binding removed after submission takes effect; a disabled member's page names a reader nobody
+ * holds and is refused, and a binding or source table that cannot be read throws instead of publishing the page shared.
*/
-export async function defaultSourceMemberWriter(engine: SqlEngine, authority: Pick<WriteAuthority, 'remote' | 'actingFor' | 'principal' | 'sourceId'>): Promise<string | null> {
+export async function defaultSourceMemberWriter(engine: BrainEngine, authority: Pick<WriteAuthority, 'remote' | 'actingFor' | 'principal' | 'sourceId'>): Promise<string | null> {
const { principal } = authority;
- if (!authority.remote || authority.actingFor || authority.sourceId !== 'default' || (principal.kind !== 'legacy_token' && principal.kind !== 'oauth_client')) return null;
+ if (!authority.remote || authority.actingFor || (principal.kind !== 'legacy_token' && principal.kind !== 'oauth_client')) return null;
const [row] = await engine.executeRaw<{ member_id: string | null }>(principal.kind === 'legacy_token'
? 'SELECT member_id FROM access_tokens WHERE id::text = $1'
: 'SELECT member_id FROM oauth_clients WHERE client_id = $1', [principal.id]);
- return row?.member_id ? `member:${row.member_id}` : null;
+ return row?.member_id && await noGrantFloorReads(engine, authority.sourceId) ? `member:${row.member_id}` : null;
}
/**
diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.ts
index 49da64fc06..d28aa496c4 100644
--- a/src/core/source-resolver.ts
+++ b/src/core/source-resolver.ts
@@ -965,6 +965,15 @@ export async function noGrantFederatedScope(
}
}
+/**
+ * #8982: whether a caller with no source grant reads `sourceId` unqualified: `default`, or a source in the federated
+ * set noGrantFederatedScope threads for that floor. Throws when the sources cannot be read, so a write policy keyed on
+ * it fails closed instead of treating an unreadable table as "not shared".
+ */
+export async function noGrantFloorReads(engine: BrainEngine, sourceId: string): Promise<boolean> {
+ return sourceId === 'default' || ((await localFederatedSourceIds(engine, 'default', 'seed_default'))?.includes(sourceId) ?? false);
+}
+
/**
* #2561 — compute the federated read scope for an UNQUALIFIED local CLI call.
*
diff --git a/test/access-federated-member-writes.test.ts b/test/access-federated-member-writes.test.ts
new file mode 100644
index 0000000000..9a63139405
--- /dev/null
+++ b/test/access-federated-member-writes.test.ts
@@ -0,0 +1,150 @@
+/**
+ * #8982 item 1: GST-2051 keeps a page a member-bound credential creates to that member when it writes where every
+ * credential without a source grant reads. That floor is `default` plus every federated source
+ * (`config.federated`, noGrantFederatedScope), so a member-bound token granted `--sources <federated-source>` used to
+ * publish its pages unstamped there, readable by another member's no-grant token and by an unbound token.
+ * 1. Protects: a page such a credential creates in a federated source names its member as its only reader, so another
+ * member and an unbound token (reading the federated set as the HTTP transports do) get page_not_found and no
+ * search, query, recall or list_pages hit, and POST /ingest refuses it. A non-federated source keeps the audience
+ * its grants give it (no stamp), and a member-bound write cannot land in a source outside its grant.
+ * 2. Fails when: a member-bound put_page into a federated source lands without readers, or a write leaves its source.
+ * 3. Existing coverage (access-ungranted-member-writes) only writes to `default`.
+ * 4. Real seams: tokens minted by the token service and bound with SQL, verified by the serve --http verifier, read
+ * scope from noGrantFederatedScope (the transports' helper), dispatched through MCP dispatch on a repo-less brain.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import express from 'express';
+import type { Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { mountWebhooks } from '../src/commands/serve-http-webhooks.ts';
+import type { ServeHttpContext } from '../src/commands/serve-http.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const FEDERATED = 'source-a';
+const ISOLATED = 'source-b';
+const marker = (tag: string) => 'fedmember' + tag + randomUUID().slice(0, 8);
+const note = (title: string, body: string) => ['---', 'type: note', 'title: ' + title, '---', '# ' + title, '', body].join('\n');
+
+for (const kind of testBackends()) {
+ describe('writes to a federated source from a member-bound credential (' + kind + ', repo-less)', () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ const tokens: Record<string, string> = {};
+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+
+ async function call(who: string, op: string, params: Record<string, unknown>) {
+ const auth = await provider().verifyAccessToken(tokens[who]) as unknown as AuthInfo;
+ const sourceId = auth.sourceId ?? 'default';
+ const localFederatedSourceIds = await noGrantFederatedScope(engine, auth.hasSourceGrant, sourceId);
+ const out = await dispatchToolCall(engine, op, { ...params }, { remote: true, transport: 'http', auth, sourceId, takesHoldersAllowList: ['world'],
+ ...(localFederatedSourceIds ? { localFederatedSourceIds } : {}) });
+ const text = out.content.map(c => c.text).join('\n');
+ let json: Record<string, unknown> = {};
+ try { json = JSON.parse(text); } catch { /* prose */ }
+ return { isError: out.isError === true, text, json };
+ }
+ async function stored(slug: string, source: string) {
+ const [row] = await engine.executeRaw<{ frontmatter: Record<string, unknown>; page_readers: string[] | null }>(
+ 'SELECT frontmatter, page_readers FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [source, slug]);
+ return row;
+ }
+ /** What each read op shows `who` of a page whose body carries `canary`: true where the canary leaks. */
+ async function reads(who: string, slug: string, canary: string, source: string) {
+ const seen: Record<string, boolean> = {};
+ for (const [key, op, params] of [['get_page', 'get_page', { slug, source_id: source }], ['get_page_unqualified', 'get_page', { slug }],
+ ['search', 'search', { query: canary }], ['query', 'query', { query: 'note ' + canary }], ['recall', 'recall', { query: canary }], ['list_pages', 'list_pages', {}]] as const) {
+ const out = await call(who, op, params as Record<string, unknown>);
+ seen[key] = op === 'list_pages' ? out.text.includes(slug) : out.text.includes(canary + '.');
+ }
+ return seen;
+ }
+ const none = { get_page: false, get_page_unqualified: false, search: false, query: false, recall: false, list_pages: false };
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }
+ __resetPrivateVisibilityCacheForTests();
+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ($1, $1, '{"federated": true}'::jsonb), ($2, $2, '{"federated": false}'::jsonb)
+ ON CONFLICT (id) DO UPDATE SET config = EXCLUDED.config`, [FEDERATED, ISOLATED]);
+ for (const id of ['alice-example', 'bob-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
+ for (const [name, member, sourceGrant] of [['alice-a', 'alice-example', [FEDERATED]], ['alice-b', 'alice-example', [ISOLATED]], ['bob-b', 'bob-example', [ISOLATED]],
+ ['bob', 'bob-example', undefined], ['public', null, undefined]] as const) {
+ const minted = await mintLegacyToken(engine, { name, scopes: ['read', 'write'], takesHolders: ['world'], ...(sourceGrant ? { sourceGrant: [...sourceGrant] } : {}) });
+ tokens[name] = minted.token;
+ if (member) await engine.executeRaw('UPDATE access_tokens SET member_id = $2 WHERE id = $1::uuid', [minted.id, member]);
+ }
+ }, 240_000);
+ afterAll(async () => { await close?.(); }, 60_000);
+
+ test('the no-grant floor reads the federated source, not the isolated one', async () => {
+ expect(await noGrantFederatedScope(engine, false, 'default')).toEqual(['default', FEDERATED]);
+ }, 60_000);
+
+ test('a page it creates in a federated source names only its member: another member and an unbound token read nothing of it', async () => {
+ const canary = marker('new');
+ const slug = 'notes/alice-fed-' + canary;
+ const put = await call('alice-a', 'put_page', { slug, content: note('Alice fed', 'Alice fed code ' + canary + '.'), request_id: randomUUID() });
+ expect({ isError: put.isError, source: put.json.source_id ?? put.json.source }).toEqual({ isError: false, source: FEDERATED });
+ expect(await stored(slug, FEDERATED)).toMatchObject({ frontmatter: { readable_by: ['member:alice-example'] }, page_readers: ['member:alice-example'] });
+ expect(await reads('bob', slug, canary, FEDERATED)).toEqual(none);
+ expect(await reads('public', slug, canary, FEDERATED)).toEqual(none);
+ expect((await call('public', 'get_page', { slug, source_id: FEDERATED })).json.code).toBe('page_not_found');
+ expect((await call('alice-a', 'get_page', { slug })).text).toContain(canary + '.');
+ }, 240_000);
+
+ test('a non-federated source keeps the audience its grants give it: no stamped readers, unbound tokens cannot reach it', async () => {
+ const canary = marker('iso');
+ const slug = 'notes/alice-iso-' + canary;
+ expect((await call('alice-b', 'put_page', { slug, content: note('Alice iso', 'Alice iso code ' + canary + '.') })).isError).toBe(false);
+ expect(await stored(slug, ISOLATED)).toMatchObject({ page_readers: null });
+ expect((await stored(slug, ISOLATED)).frontmatter.readable_by).toBeUndefined();
+ expect(await reads('public', slug, canary, ISOLATED)).toEqual(none);
+ expect(await reads('bob', slug, canary, ISOLATED)).toEqual(none);
+ expect((await call('bob-b', 'get_page', { slug })).text).toContain(canary + '.');
+ }, 240_000);
+
+ test('a member-bound write cannot leave the source its grant names', async () => {
+ const canary = marker('wrong');
+ const slug = 'notes/alice-wrong-' + canary;
+ for (const target of ['default', ISOLATED]) {
+ const out = await call('alice-a', 'put_page', { slug, source_id: target, content: note('Alice wrong', 'Alice wrong code ' + canary + '.'), request_id: randomUUID() });
+ expect(out.isError).toBe(true);
+ expect(await stored(slug, target)).toBeUndefined();
+ }
+ expect(await stored(slug, FEDERATED)).toBeUndefined();
+ }, 240_000);
+
+ test('POST /ingest refuses it and queues nothing; a non-federated grant still reaches the route', async () => {
+ const app = express();
+ const pass: express.RequestHandler = (_req, _res, next) => next();
+ mountWebhooks(app, { engine, resourceVerifier: provider(), resourceMetadataUrl: 'http://127.0.0.1/.well-known/oauth-protected-resource',
+ ingestRateLimiter: pass, githubWebhookLimiter: pass, broadcastEvent: () => {} } as unknown as ServeHttpContext);
+ const server = await new Promise<Server>(resolve => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });
+ try {
+ const base = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
+ const ingest = (who: string, body: string) => fetch(base + '/ingest', { method: 'POST', body,
+ headers: { authorization: 'Bearer ' + tokens[who], 'content-type': 'text/markdown' } });
+ const [before] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM minion_jobs WHERE name = 'ingest_capture'");
+ const refused = await ingest('alice-a', note('Alice ingest', 'Ingest ' + marker('ingest') + '.'));
+ expect(refused.status).toBe(403);
+ expect(await refused.json()).toMatchObject({ error: 'permission_denied', message: expect.stringContaining('write source is ' + FEDERATED) });
+ const [after] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM minion_jobs WHERE name = 'ingest_capture'");
+ expect(after.n).toBe(before.n);
+ expect((await ingest('alice-b', note('Alice iso ingest', 'Ingest ' + marker('ingestiso') + '.'))).status).toBe(202);
+ } finally {
+ await new Promise<void>(resolve => server.close(() => resolve()));
+ }
+ }, 240_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 48bce91274..de8f7fb6bf 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -13,6 +13,7 @@
# themselves from scripts/postgres-arm-weights.json.
test/access-as.test.ts
test/access-binding.test.ts
+test/access-federated-member-writes.test.ts
test/access-folder-lock-order.test.ts
test/access-folder-multiconn.test.ts
test/access-folder-rules.test.ts