Skip to content

fix(policy): key the class cache on the graph, not just the subject - #1580

Merged
bplatz merged 1 commit into
fluree:mainfrom
christophediprima:fix/policy-class-cache-graph-key
Aug 16, 2026
Merged

bplatz merged 1 commit into
fluree:mainfrom
christophediprima:fix/policy-class-cache-graph-key

Conversation

@christophediprima

@christophediprima christophediprima commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

PolicyContext::class_cache is a HashMap<Sid, Vec<Sid>>. The same subject IRI can carry different rdf:type values in different named graphs, so two graphs sharing a subject collapse into one cache entry and whichever populated it first decides the classes for both.

Every f:onClass restriction evaluated for that subject afterwards uses the wrong class set — allowing or denying based on population order rather than on the data. That is order-dependent behaviour in an authorization path, not a stale-cache annoyance.

This is not a hypothetical shape. Named graphs are a general feature — any from-named query spans them — and docs/security/policy-in-queries.md:203-205 explicitly recommends f:onClass as the tool to reach for when "different graphs need different policy regimes". That is precisely the restriction this bug corrupts, so the documented workaround for graph-differentiated policy is the one that misbehaves on multi-graph data.

It has gone unnoticed because it needs the same subject IRI present in two graphs with different types, which is rarer than multi-graph data generally. I came across it while auditing how far the graph identifier travels through the read path; R2RML rr:graphMap routing is the workload that produces the shape per row #1581, which is why I went looking. Nothing about the bug or the fix is specific to R2RML.

What changes

The graph was already available at both ends and simply wasn't carried across:

  • populate_class_cache (fluree-db-policy/src/class_lookup.rs) receives a GraphDbRef, whose g_id is a public field, so the insert side now keys on the graph it actually read.
  • The two lookups live in filter_flakes_for_graph / allow_flake_for_graph (fluree-db-query/src/policy/enforcer.rs) — the one boundary where the graph was being dropped. Both now take a g_id: GraphId.
  • class_cache becomes HashMap<(GraphId, Sid), Vec<Sid>>; cache_subject_classes and get_cached_subject_classes take the graph.

One design note worth a reviewer's eye. Callers pass the graph of the GraphDbRef they populated the cache from, rather than a literal. Populate and lookup therefore agree by construction rather than by convention. Two callers — block_fetch.rs and graph_commit_builder.rs — build that ref with a hardcoded graph 0, so their behaviour is byte-identical after this change. That hardcoding is a separate defect and is deliberately left alone here, but because the lookup now follows the ref, fixing it later corrects both halves in one edit instead of two.

Tests — two units in evaluate.rs: the same subject cached with different classes in graphs 3 and 4 keeps both entries; a graph with no entry misses rather than borrowing another graph's classes (a miss degrades to "no classes", which is the conservative direction).

Be aware of what those tests do not do. They cannot be run against the unfixed code, because the accessors did not take a graph at all — so they pin the new keying without demonstrating the old wrong decision. Showing the authorization outcome end to end needs an enforcer-level integration test over a real two-graph ledger. That belongs with the rr:graphMap work, where the data shape arises naturally, and I would rather say so than let the test count imply more coverage than it has.

Why it is worth having on its own: it is a correctness bug in an authorization path, the fix is contained, and it stands independent of anything else I have open — it needs no other change to be worth landing, and nothing else needs to land first.

`PolicyContext::class_cache` was a `HashMap<Sid, Vec<Sid>>`. The same subject
IRI can carry different `rdf:type` values in different named graphs, so two
graphs sharing a subject collapsed into one entry and whichever populated it
first decided the classes for both.

Every `f:onClass` restriction evaluated for that subject afterwards used the
wrong class set — allowing or denying depending on population order rather
than on the data. That is order-dependent behaviour in an authorization path,
not a stale-cache annoyance.

It has gone unnoticed because it needs the same subject in two graphs to be
observable, which is a shape almost nothing produces today. R2RML `rr:graphMap`
routing produces exactly that shape.

The graph was already available at both ends and simply not carried across:

- `populate_class_cache` receives a `GraphDbRef`, whose `g_id` is public, so
  the insert side keys on the graph it actually read.
- the two lookups sit in `filter_flakes_for_graph` / `allow_flake_for_graph`,
  the one boundary where the graph was being dropped. Both now take `g_id`.

Callers pass the graph of the `GraphDbRef` they populated the cache from, so
populate and lookup agree by construction rather than by convention. Two of
them — `block_fetch.rs` and `graph_commit_builder.rs` — build that ref with a
hardcoded graph 0, so their behaviour is unchanged here; that hardcoding is a
separate defect and is left for its own change, but it now flows through to the
lookup automatically once fixed rather than needing a second edit.

The added tests pin the keying and the miss behaviour (a graph with no entry
must miss rather than borrow another graph's classes). They cannot be run
against the old code, since the accessors did not take a graph — demonstrating
the wrong-decision outcome end to end needs an enforcer-level integration test,
which is worth adding alongside the `rr:graphMap` work where the shape occurs
naturally.

Verified with CI's flags: `cargo clippy --all --all-features --all-targets`
clean; `fluree-db-policy --all-features` 39 passed; `fluree-db-query` and
`fluree-db-api` lib tests 904 and 1342 passed.

@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.

Thanks for this @christophediprima -- order-dependent authorization is the worst kind of latent bug — correct in every test that populates one graph, wrong the day two graphs share a subject — and this fixes it at the right altitude: the cache key names the graph, the two accessors take the graph, and the five call sites pass the graph of the ref they already hold, so populate and lookup agree by construction rather than convention. The sequencing logic is also right: rr:graphMap (#1581) is exactly the feature that makes this shape common, and landing the policy fix first means the graph-routing work arrives onto a correct cache. I verified rather than trusted: cold package builds in an isolated worktree — fluree-db-policy 39/39 with both new tests present by name, fluree-db-query --lib 1304/0, clippy clean on both crates — and confirmed the signature changes strand no caller (zero in-repo callers of allow_flake_for_graph; zero uses of any changed symbol in fluree/solo's Rust, so the next pin bump is unaffected).

Adherence to repo commitments:

  • Correctness: ✔ The keying fix is complete at the boundary it names; the hardcoded graph-0 refs in block_fetch/graph_commit_builder are honestly scoped out with behavior unchanged and automatic flow-through once fixed.
  • Performance (speed first, memory second): ✔ Effectively neutral — the new per-flake Sid clone is an Arc refcount bump dominated by the pre-existing RwLock read and Vec clone on the same path; no allocation, lock, or collect added to any loop. Optional nested-map note above if it ever profiles.
  • Shared abstractions: ✔ Extends the existing filter_flakes_for_graph per-graph parameter shape (snapshot/overlay/t were already per-graph; g_id joins them) rather than inventing a parallel mechanism.
  • Testing: ✔ Both new tests run and pin the fix's contract; the deferred enforcer-level integration test is named with its natural home (#1581) rather than skipped silently.
  • Conventions: ✔ Conventional multi-line commit with real root-cause narration; doc comments record the why on the key type; no AI-attribution trailers; clippy/fmt clean.

Verified locally at branch HEAD 18ad842c4: see the summary's verification block.

Recommend merge, ideally before #1581 so the graph-routing work lands on the corrected cache.

@@ -127,7 +130,7 @@ impl QueryPolicyEnforcer {
// Get subject classes from cache

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-db-query/src/policy/enforcer.rs:130 — optional, performance. get_cached_subject_classes(g_id, &flake.s) now clones the Sid per flake to build the owned tuple key (cache.get(&(g_id, subject.clone()))). Since Sid is u16 + Arc<str> this is a refcount bump, not an allocation, and the pre-existing per-flake costs on this path (the RwLock read, the Vec<Sid> clone per hit) dominate it — so I'm not blocking on it. If policy-filtered scans ever show this in a profile, a nested HashMap<GraphId, HashMap<Sid, Vec<Sid>>> restores borrowed lookups and gives per-graph invalidation for free; we may want that shape anyway if graph-scoped cache clearing becomes a thing.

@@ -163,6 +166,7 @@ impl QueryPolicyEnforcer {
pub async fn allow_flake_for_graph(

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-db-query/src/policy/enforcer.rs:166 — observation, no action. allow_flake_for_graph has no callers anywhere in this repo, and none in fluree/solo either (checked against solo's src/rust for the pin-bump question). The signature change is therefore free — noting it so nobody burns time hunting for a missed call site.

);
}

#[test]

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-db-policy/src/evaluate.rs:1198-1236 — praise. The tests pin the two properties that define the fix (per-graph entries, miss-not-borrow) and the comments explain the production shape each guards against. Declining to fake an end-to-end test the current shapes can't exercise — and saying where it should land instead — is the right call.

@bplatz
bplatz merged commit 3ce1352 into fluree:main Aug 16, 2026
15 checks passed
q-qp-p pushed a commit to q-qp-p/fluree-db that referenced this pull request Aug 25, 2026
…ens main

fluree#1580's (correct) graph-keyed cache widened the field type past clippy's
type_complexity threshold under -D warnings, so main's clippy job is red
and every PR inherits it through the merge-ref checkout. A ClassCache
type alias is clippy's own suggested shape; no behavior change.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants