Skip to content

Apply a request's policy on the graph-scoped read path, and to hydration - #1935

Merged
zonotope merged 11 commits into
mainfrom
fix/graph-query-builder-policy
Sep 28, 2026
Merged

zonotope merged 11 commits into
mainfrom
fix/graph-query-builder-policy

Conversation

@zonotope

@zonotope zonotope commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1766

What was wrong

fluree.graph(<ledger>).query() never applied a request's policy. The builder loads its own view, and the two execution methods it hands that view to both take an already-wrapped &GraphDb and neither wraps. Nothing else on the path did either, so a native ledger was read unfiltered whatever the request carried.

The issue describes this as opts.policy being ignored. It is wider than that. Every input has_any_policy_inputs() recognises was dropped: inline policy, policy-class, policy-values, identity, and default-allow in both directions. That held on all three terminals (execute, execute_formatted, execute_tracked), at any point in time via graph_at. A ledger's own configured f:policyDefaults were dropped too, so a governed ledger read unfiltered even with no opts block at all.

Two further defects turned up while writing the coverage, both pre-existing and independent of #1766. Subgraph ("crawl") hydration filters flakes only when the formatter is handed the governing PolicyContext, and two read surfaces executed rows under a policy and then formatted without one. Row counts were right, so the leak appeared inside the hydrated node rather than in the row count.

Changes

GraphQueryBuilder::load_view wraps policy. One wrap_request_policy helper serves both the native and graph-source branches: a request selecting any policy is wrapped with it, gated on has_any_policy_inputs exactly as apply_source_or_global_policy gates the from-driven path, and a request selecting nothing leaves the ledger's or source's configured defaults in force. load_view is the single choke point all three terminals share, and wrapping there also makes crawl hydration correct for free, because execute_formatted already branched on view.policy().

Three details in that helper are load-bearing and each is pinned by its own test. has_any_policy_inputs rather than selects_policy_set, or a bare default-allow: false slips through. The server_identity copy from the builder's execution options, because the verified identity never arrives in the request body and without it an f:IdentityRestricted override control refuses a request the config permits. And wrap_policy_defaults in the else arm, or configured defaults stay lost.

A governed graph source's model now governs a request that selects no policy. The graph-source branch previously returned its view unwrapped in that case, so a bare read bypassed the model. The from-driven path has always applied it. This is the one behaviour change that is not simply "the request's policy now works": it changes what every reader of a governed source sees on a bare read, and a source registered without f:defaultAllow is fail-closed.

FromQueryBuilder formats against the view it executed on. The single-ledger JSON-LD branch of execute_formatted and execute_formatted_string built a policy-wrapped view, ran on it, discarded it, and re-resolved the alias through db_or_graph_source for a fresh unwrapped one. query_connection_jsonld_returning_target_with_options now returns a FormatTarget carrying either that view or the multi-ledger dataset, and both terminals format against it. The multi-ledger branch was always correct, so the same crawl was right with two ledgers in from and wrong with one.

The GraphQL read path formats under its view's policy. graphql.rs wraps its view and then formatted through to_jsonld_async, which passes policy: None. Every GraphQL root field lowers to a subgraph projection, so this was the whole surface rather than an edge of it. Both sites now share one hydrate_rows helper.

Policy-aware SDL derivation hides a class or property denied outright, which is why this was not caught earlier. A per-subject f:query rule legitimately keeps its property in the schema, because some subjects do allow it, and such a rule disclosed other identities' values.

Breaking

A read of a governed ledger or graph source now returns less than it did. Specifically: a request carrying policy options through fluree.graph(...).query() is now enforced rather than ignored; a bare read of a ledger with configured f:policyDefaults, or of a --model graph source, is now governed by those defaults; a materialized read through fluree.graph(...).load() is governed by those same configured defaults; and a crawl through query_from or GraphQL now omits what the request cannot see.

The MCP sparql_query agent tool is the most exposed of these. execute_sparql_agent_json takes its identity from the authenticated principal (fluree-db-server/src/mcp/tools.rs:106), and its None arm reads through state.fluree.graph(&ledger).query().sparql(...) (:221-236). That arm is reached when a request carries no MCP principal, or a principal whose identity is None. Before this PR that branch applied no policy at all: not merely ignoring a request's opts, which SPARQL cannot carry anyway, but dropping the ledger's own configured f:policyDefaults. An agent reaching it read the unfiltered ledger. After this PR it is governed by those defaults, so an agent reading a governed ledger anonymously will start getting less back. configured_policy_defaults_apply_to_sparql is the exact shape that tool issues, and reverting the load_view wrap turns it red.

A caller sending malformed policy options now sees a 400 where it saw a 500, or a 404 on the tracked terminal.

Every one of those cases was previously a policy bypass, so nothing that was correct changes. An unconfigured ledger with no policy options is byte-identical and stays on the plain-query path, because wrap_policy_defaults returns such a view untouched.

Not changed

The SPARQL branches of FromQueryBuilder's formatted terminals pass no policy either, and are left alone deliberately. policy is consumed only inside if result.output.has_hydration() (format/mod.rs), Column::Hydration is built only by the JSON-LD parser, and CONSTRUCT/DESCRIBE return through the construct formatter before the hydration branch on rows policy already filtered. SPARQL cannot hydrate, so passing no policy is harmless there.

Tests

18 new tests. it_policy_graph_builder.rs covers #1766's full surface: each of the six policy inputs, all three terminals, graph_at time travel, configured defaults on both the JSON-LD and SPARQL surfaces, crawl hydration, and the verified identity arriving via execution options. it_policy_query_connection.rs covers the two FromQueryBuilder terminals. it_graphql_policy.rs covers the GraphQL surface with a per-subject rule, asserting the property survives introspection first so the test exercises execution-level filtering rather than the SDL hiding the field.

Every expected count is derived from the fixture rather than read off another builder. Each test runs an unrestricted control first, so an enforced count cannot pass merely because the fixture is unreadable. The crawl-hydration test on the graph-scoped builder makes no cross-check against the from-driven one, because that builder had the same defect and is fixed here too, so the comparison would only restate crawl_hydration_honors_policy_on_a_single_ledger.

Each fix was mutation-checked: reverting it individually fails exactly the intended test or pair, and nothing else.

graph_scoped_builder_enforces_governed_source in it_iceberg_policy.rs asserted 5 rows for a bare read of a governed source, which was the unfiltered value. It now asserts 0 through both builders, with a newly registered model-less source returning 5 to keep the non-vacuity guard the old assertion provided.

Verification

cargo clippy --all --all-features --all-targets -- -D warnings and cargo fmt --all --check both clean. testsuite-sparql is untouched, so its separate pair does not apply.

Green: grp_policy 133, grp_query 471, grp_query_sparql 388, grp_misc 299 (358 with --features graphql), grp_transact 204, grp_ledger 203, grp_graphsource 161, grp_reasoning 144, grp_import 118, grp_query_reason 100, grp_index 93, grp_query_history 65. Server: grp_query 107, grp_http 101, grp_policy 67, grp_proxy 51.

Feature-gated targets that do not run by default were run explicitly, since this touches code they cover: it_graph_source_r2rml 67, it_iceberg_policy 15, it_delta_local_fs 11, it_iceberg_local_fs 6, it_delta_differential 3, it_iceberg_warehouse_root 1.

Two pre-existing tests flake under concurrent test binaries and are unrelated to this branch. Both query the view-level path, one involves no policy at all, and the rate tracks concurrency rather than the diff. Written up separately.

Notes for review

The issue's own repro does not reproduce as written: it uses compact IRIs inside opts.policy, which are not expanded against the request @context (docs/security/policy-model.md), so it returns every row on both builders. Every request-side IRI in the new tests is absolute for that reason.

The issue's Exposure section is stale in one direction and understates the exposure in another. execute_query_proxy no longer uses this builder at all: it reads through fluree.db() with a ViewQueryBuilder. But there are two server call sites of .graph(id).query(), not one: the SPARQL graph-source fallback in routes/query.rs, and the MCP sparql_query tool's no-identity branch described under Breaking. The second is on the agent surface and was an unconditional bypass of configured defaults, so taken together I read this as supporting P0 rather than the P1 the issue carries. Flagging it rather than relabelling, since the call is the issue owner's.

The issue's Scope section says the graph-source half was already fixed on feature/iceberg-static-policy. Only the request-policy half was; configured defaults were still dropped there, which is the second commit here.

@zonotope
zonotope requested review from aaj3f and bplatz September 25, 2026 12:54
@zonotope zonotope added bug Something isn't working as expected area:query Query execution, planning, fast paths, overlay, result formatting labels Sep 25, 2026

@bplatz bplatz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving: the fix and its tests look right. Please read the three inline comments before merging. They cover the load() path, error status codes, and docs/labels for the behaviour change.

///
/// Execution receives the view already wrapped and does not wrap it again.
/// See [`Self::wrap_request_policy`] for which requests engage enforcement.
async fn load_view(&self) -> Result<crate::view::GraphDb> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fluree.graph(L).load().await?.query() still bypasses policy. Graph::load() (graph.rs:70) calls load_graph_db_at directly, and GraphSnapshot::query() never wraps, so request opts and configured f:policyDefaults are both ignored. With this PR's fixtures:

// setup(L), q = with_opts(by_name(), deny_property(NAME))
fluree.graph(L).query().jsonld(&q).execute_formatted()                // 0 rows
fluree.graph(L).load().await?.query().jsonld(&q).execute_formatted()  // 5 rows
// setup_configured(L), q = by_name() with no opts: also 0 vs 5

docs/getting-started/rust-api.md presents load() as the reusable form of graph().query(), so the two now give different answers. The fix probably belongs in Graph::load / GraphSnapshot::query rather than in GraphSnapshotQueryBuilder, because the CLI (query.rs:952) and wasm build that builder over views they have already wrapped. A follow-up issue linked with Follow-up: #N is fine if you'd rather not widen this PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in 96fceaf

let mut opts = match self.core.input.as_ref() {
Some(crate::view::QueryInput::JsonLd(json)) => {
crate::GovernanceOptions::from_json(json)
.map_err(|e| ApiError::query(e.to_string()))?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A malformed policy option is a caller error, but this returns it as a 500 (ApiError::query builds Internal). execute_tracked also maps every load_view error to 404 (line 331), and that now includes policy-building failures. With "opts": {"policy-values": "x"}:

  • execute / execute_formatted: 500
  • execute_tracked: 404
  • the same query through query_from(): 400

Suggest ApiError::invalid_query here, and e.status_code() in place of the hardcoded 404 at line 331.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in 96fceaf

.expect("ungoverned query");
assert_eq!(rows(&via_graph_open), 5, "{via_graph_open}");
.expect("bare graph-scoped query");
assert_eq!(rows(&via_graph_open), 0, "{via_graph_open}");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The docs don't reflect this change yet. docs/graph-sources/iceberg.md:1041 still says "A request with no policy inputs is unrestricted, as for a native ledger". docs/security/cross-ledger-policy.md:173 (a configured f:policySource "is not enough on its own to force enforcement" for queries) also looks out of date.

For the Breaking section:

  • The PR has no breaking-change label, so release notes will list it under Bug Fixes.
  • fluree query <governed-source> in the CLI is now filtered by the model, and returns nothing if the source was registered without --default-allow. That CLI path also doesn't forward the CLI's policy flags (pre-existing), so a SPARQL user there can't select a policy.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in 6fb855a

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@zonotope this is a great fix to a not-so-great problem. I spent a good amount of additional human-time (if I ever start referring to "critical thinking" as something like "organic tokens" please end my life for me), if only because there have been sooo many PRs recently around policy and--besides simply trying to keep everything coherent in my own mind--I just want to make sure we're still building on consistent patterns... extending rather than reverting the work of previous PRs... etc.

I think this holds up entirely. I mean, the issue is real, but, for example, I wanted to make sure that @bplatz's changes to now have else => wrap_policy_defaults(view) were still true, and was glad to see that your PR is just fixing the fact that paths were NOT obeying that and now they do.

I also double-checked that this wouldn't cause operator-level (i.e. Fluree AI) issues by forcing adoption pattern changes. That also holds-up, as Fluree AI has already been updated to recognize that queries with no policy posture against a dataset with f:policyDefaults governance will still be governed by those defaults. That is to say, Fluree AI is being explicit about "root-like" queries when a privileged operator (e.g. app internal scenarios) intends for that.

This is a really long approval, just wanted to give additional context. Full review below:


This is really nicely done — the choice to wrap at load_view rather than at each of the three terminals is the right altitude, and FormatTarget is better than the obvious alternative because it makes the wrong thing unrepresentable at the call site instead of merely unwritten. The test work is what sold me: every assertion runs its unrestricted control first, so an enforced 0 can't pass because the fixture was unreadable, and the GraphQL test asserting the property survives introspection before querying it is exactly the guard that makes it a test of execution rather than of the SDL.

I verified the three fixes independently rather than reading them. Reverting the load_view wrap alone turns 14 it_policy_graph_builder tests red and nothing else; reverting the two FormatTarget::Single policy arguments and the GraphQL one turns exactly the three hydration tests red and nothing else. I also checked the "Not changed" SPARQL argument on my own rather than taking it: Column::Hydration reaches the IR only from the JSON-LD parser (parse/mod.rs → parse/lower.rs:198), add_hydration has no production caller, the execute/dependency.rs constructions are inside #[cfg(test)], and fluree-db-cypher has no reference to it at all — so SPARQL genuinely cannot hydrate and passing no policy there really is harmless. It holds.

One correction worth your eye before merge, because it bears on the P1-versus-P0 call #1766 explicitly asks for: the body says the only server call site of .graph(id).query() is the SPARQL graph-source fallback, but fluree-db-server/src/mcp/tools.rs:221-236 is a second one — the MCP sparql_query tool's no-identity branch. Before this PR that read a governed ledger ignoring even its configured f:policyDefaults, and configured_policy_defaults_apply_to_sparql (which your fix makes pass) is the exact shape that tool issues. So this closes a second live hole on the agent surface, and I think Breaking should say so — an agent reading a governed ledger anonymously today will start getting less back. Everything else from me is small: a comment in the new test file that says the from-driven crawl still leaks when commit f09ef3c3a fixes it, the wrap_request_policy doc comment being true of the builder but not of the server's header transport, and a note about the eight sites that now hand-write the same match view.policy() branch.

The one hunk I'd want a second opinion treated as a product decision rather than a bug fix is 217d686d4 — a governed graph source now governs a bare read that selects no policy. It's clearly the correct semantics and it matches what apply_source_or_global_policy has always done on the from path, but it changes what every reader of a governed source sees, and a source registered without f:defaultAllow is fail-closed. You've flagged it as such in the body, so this is agreement rather than an objection.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ with a note — wraps at the shared load_view choke point and reuses wrap_policy / wrap_policy_defaults / has_any_policy_inputs rather than inventing a parallel gate; the note is that policy-on-hydration still travels as a per-call-site parameter alongside the view.policy_enforcer() channel cypher_typed uses (finding 4).
  • Performance (speed first, memory second): ✔ No performance-degradation risk. load_view runs once per request, never per row or per subject; GovernanceOptions::from_json short-circuits on a missing opts key; wrap_policy_defaults's config resolve is hoisted rather than added, since complete_config_defaults already ran it for every view and it short-circuits on config_is_resolved(). Net small win from deleting the db_or_graph_source re-resolution on the single-ledger format path. An unconfigured ledger is unchanged; a configured one pays for the policy it asked for.
  • Testing: ✔ 18 new tests, all wired into targets that actually run — it_policy_graph_builder into grp_policy, the it_policy_query_connection and it_graphql_policy additions into grp_policy / grp_misc (the latter behind #[cfg(feature = "graphql")], so --all-features), it_iceberg_policy as its own required-features target. All 18 appeared by name in my run. testsuite-sparql green on this head and untouched.
  • Conventions: ✔ with one nit — clippy and fmt clean on the exact head, no stale-doc claims I could find, behavior change documented in the PR body; the nit is subject-only commit messages carrying none of the PR body's reasoning (finding 6).

Verified locally at branch HEAD f09ef3c3a: cargo nextest run -p fluree-db-api --features native,graphql,iceberg --test grp_policy --test grp_misc --test it_iceberg_policy → 506 run, 506 passed, 5 skipped, with all 18 new test names present; two mutation checks each red on exactly their intended tests and nothing else; worktree restored clean afterwards. (--all-features doesn't build on my machine — the delta feature's cxx dependency can't find the C++ stdlib headers under this macOS SDK — but CI's --all-features nextest, clippy, fmt and testsuite-sparql are all green on that exact SHA.)

Approving so you can merge when ready — but I'd like the MCP call site reflected in Breaking first, since it changes the answer to the severity question the issue asks, and the stale test comment is cheap to fix while you're in there.

Not anchorable inline: the commit messages. All four subjects are self-describing, which is the part that feeds release notes, so this is genuinely minor. But they're subject-only, and the reasoning in this PR is unusually good — the has_any_policy_inputs-versus-selects_policy_set choice, why wrap_policy_defaults rather than Ok(view) in the else arm, why the server_identity copy is load-bearing, and the #1408 rationale for boxing FormatTarget::Single. Right now all of that lives in the PR body, which doesn't survive into git log for whoever git-blames wrap_request_policy in a year. Most of it is already written; it's a copy into the commit bodies.

}

result
self.wrap_request_policy(result?).await

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional — fluree-db-server/src/mcp/tools.rs:221-236: the "only server call site" claim in the body isn't right, and the second one bears on the P1-versus-P0 question #1766 asks.

The "Notes for review" section says the only server call site of .graph(id).query() is the SPARQL graph-source fallback in routes/query.rs. I think there's a second one, and it's the more exposed of the two: the MCP sparql_query agent tool.

Its identity-carrying branch goes through db_with_policy, but the None arm — identity = principal.as_ref().and_then(|p| p.identity.as_deref()), so a principal whose token resolves no identity, or a request extract_principal finds no principal for — falls straight to state.fluree.graph(&ledger).query().sparql(…). What that means for an operator: before this PR the MCP agent tool read governed ledgers with no policy applied at all — not merely ignoring the request's opts, but dropping the ledger's own configured f:policyDefaults as well. Any agent that reached that branch saw the unfiltered ledger.

That isn't inference. Reverting just this line and running grp_policy turns configured_policy_defaults_apply_to_sparql red, and that test is the exact shape the MCP tool issues — SPARQL, no opts, configured defaults on the ledger.

So this PR closes a second live hole, and it's the one on the agent tool surface. I think Breaking should say so (an agent reading a governed ledger anonymously today will start getting less back), and it should feed into the P1-versus-P0 call the issue explicitly asks for — the proxy-route narrowing you found doesn't settle that question on its own.

Commenting here because fluree-db-server/src/mcp/tools.rs is not in this diff.

/// `view.policy()` is set. An unwrapped view hydrates forbidden nodes without
/// changing the row count, so this asserts on node contents.
///
/// No cross-check here. The `from`-driven builder re-loads an unwrapped view

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional — this comment says the from-driven builder still leaks, but f09ef3c3a in this same PR fixes it.

No cross-check here. The from-driven builder re-loads an unwrapped view before formatting and leaks the denied property, so matching it would encode that leak. Tracked separately.

That was true when this commit landed, but the last commit on the branch fixes it — and it_policy_query_connection::crawl_hydration_honors_policy_on_a_single_ledger asserts precisely that the from-driven builder now filters the same crawl. The PR body carries the same claim ("The two builders disagree on crawl hydration").

It's a small thing, but it's a comment in a security test file telling a future reader that a live leak exists in a sibling path, so I'd rather it not outlive the PR. Something like "No cross-check here: the from-driven builder's single-ledger crawl is fixed in this same branch and covered by it_policy_query_connection::crawl_hydration_honors_policy_on_a_single_ledger, so a comparison would just restate that test" keeps the "why no comparison" point without the stale premise.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

corrected in b51de22

/// leaves the ledger's or source's configured defaults in force, and those
/// leave an unconfigured ledger untouched.
///
/// SPARQL has nowhere to carry an `opts` block, so only configured defaults

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional — more of a question than a suggestion: this is exactly right about the builder, but I wonder if a reader will take it as true of the product.

On the server, SPARQL does have a policy transport — headers — and routes/query.rs:2706-2708 says so in its own words: "SPARQL has no body opts block, so headers are the only transport for policy-class, policy, policy-values, and default-allow." Those header-derived qc_opts have no way to reach this builder.

Tracing where that lands (by reading, not by standing up a server): a SPARQL request carrying policy headers with no dataset clause is caught at routes/query.rs:2792 and goes to db_with_policy(ledger_id, …), which resolves through Fluree::db() with no graph-source fallback — so for a graph-source alias it returns NotFound and the ? at :2811 turns it into a 404 before it can reach the fallback at :3105. Fail-closed, so a usability gap rather than a leak, and pre-existing either way — your change doesn't introduce it. The dataset-clause branch at :2856-2868 handles that same graph-source-not-found case explicitly, which is what made the asymmetry visible to me.

I don't think any of that belongs in this PR. But two clauses on this doc comment — that the builder can't see request policy for SPARQL, and that the server's header transport therefore can't reach it either — would stop the next reader concluding the product has no SPARQL policy story at all.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clarified in 4254dba

/// Carries the view or dataset the query actually executed on, policy included.
/// Re-resolving the alias instead would produce an unwrapped view, and hydration
/// would then expand subjects the request was denied.
pub(crate) enum FormatTarget {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional (altitude) — genuinely a question, and I may be wrong about the cost/benefit here.

FormatTarget is the right move: it makes "format against the view you ran on" unrepresentable-otherwise at that call site, which is stronger than remembering to pass a parameter. But it fixes two call sites, and the underlying shape is still that policy rides as an Option<&PolicyContext> argument every formatter call has to remember, because GraphDbRef (fluree-db-core/src/graph_db_ref.rs:41-58) deliberately doesn't carry it.

Counting the duplication: eight sites hand-write the same match <view>.policy() { Some(p) => …_with_policy(…, p), None => …(…) } branch — graph_query_builder.rs:308 and :553, query/builder.rs:335 and :615, view/query.rs:972 and :1122, view/dataset_query.rs:457 and :584 — and the three sites this PR repairs are the ones where somebody wrote only the None half. That looks to me like the mechanism by which this keeps recurring, rather than anyone being careless.

The repo already has the other shape: cypher_typed::NodeHydrator::new takes the full &GraphDb and reads view.policy_enforcer() off it (format/cypher_typed.rs:470-473), so Cypher/Bolt node hydration structurally cannot forget. Moving JSON-LD hydration to that channel is a much bigger change than this PR should carry, and I'm not asking for it.

What might be cheap: a QueryResult::format_async_for_view(&GraphDb, &FormatterConfig) that folds the eight-way branch into one place, so the obvious call is also the correct one. If that reads as scope creep to you I'm happy to leave it — but if you think it's right, I'd rather see it in this PR than lost in the backlog, since you have the whole map of these call sites loaded right now and nobody else does.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

implemented in 4312a6c

/// it rides the builder's execution options from the auth layer, and without
/// it an `f:IdentityRestricted` override control refuses a request the config
/// would permit.
async fn wrap_request_policy(&self, view: GraphDb) -> Result<GraphDb> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional — docs/security/programmatic-policy.md:160-162 still steers policy-carrying queries away from this builder.

For FROM-driven queries where policy options are embedded in the query body, use query_from().

The implicit "and not .graph().query()" is what wrap_request_policy retires. Worth a line there noting that the graph-scoped builder now honors body opts too, and that a ledger's configured f:policyDefaults govern a bare read on both. The repo's own gate here is soft — there's no validate-docs job in ci.yml — so this is just keeping the prose honest rather than a CI concern.

Commenting here because docs/security/programmatic-policy.md is not in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

corrected in 6fb855a

/// `expected` comes from the fixture and is the standard. The `from`-driven run
/// only cross-checks it. The unrestricted control runs first, so an enforced
/// count cannot pass merely because the fixture is unreadable.
async fn assert_enforced(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Praise — the non-vacuity discipline in assert_enforced is what made the rest of this PR cheap to trust.

It runs the unrestricted control first and asserts all 5 fixture rows before asserting the enforced count, so an enforced 0 can never pass because the fixture happened to be unreadable. Same discipline shows up twice more: at it_iceberg_policy.rs:1090-1105, where the newly registered model-less source is what stops the flipped 0 assertions passing on a builder that simply denied every bare read; and at it_graphql_policy.rs:230-238, where asserting the property survives introspection first is what makes it a test of execution-level filtering rather than of the SDL.

Flagging it so it survives a later refactor — this is the part a future cleanup would be tempted to trim as redundant.

/// The single view of a one-ledger query. Boxed because it is by far the
/// larger variant and this rides an async fn's state machine, where frame
/// size has overflowed the worker stack before (fluree/db#1408).
Single(Box<GraphDb>),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Praise — boxing this with the fluree/db#1408 frame-size rationale written down, rather than boxing reflexively or not at all.

The next person to look at this will know why the larger variant is boxed and what breaks if they unbox it, which is exactly the comment that usually isn't there.

}
// Single-ledger: the view the query ran on, so hydration is
// filtered by the policy that filtered the rows.
FormatTarget::Single(view) => Ok(crate::format::format_results_async(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Praise — worth noting this hunk isn't only a correctness fix.

Deleting the db_or_graph_source re-resolution means the single-ledger execute_formatted path stops doing a full extra view load per query — a small but real saving on query_from().execute_formatted(), on top of closing the hydration leak.

@zonotope zonotope added the breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section label Sep 28, 2026
@zonotope
zonotope merged commit 0c5d32c into main Sep 28, 2026
16 checks passed
@zonotope
zonotope deleted the fix/graph-query-builder-policy branch September 28, 2026 18:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:query Query execution, planning, fast paths, overlay, result formatting breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

graph-scoped query builder ignores opts.policy for native ledgers

3 participants