Repository navigation
fix(policy): judge schema writes by modify policy - #2218
Conversation
Schema triples (rdfs:subClassOf, rdfs:subPropertyOf, rdfs:domain, rdfs:range, and rdf:type declaring a class or property) were exempt from f:modify policy. A policy on a class or property also covers its subclasses and subproperties, so the hierarchy decides what policies allow; writing it unchecked could widen what a view policy lets other identities read. Writes of schema triples are now judged like any other flake. View policy still lets every schema triple through, so query planning and formatting read the ontology as before. The exemption moves from the shared evaluators to the view entry points (allow_view_flake*), and the modify loop in stage no longer skips schema flakes. CLEAR and DROP of a graph holding schema triples are judged too. Tests: it_policy_tx::schema_writes_follow_modify_policy; the pinned it_named_graphs test now expects a view-only identity's CLEAR of a schema-only default graph to be refused (test_clear_default_schema_flakes_follow_modify_policy).
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is a good fix, and at a design level no pushback from me: the exemption only ever had a view-side reason (planning and formatting read the ontology), so keeping it at the view entry points and judging writes like any other flake is the right altitude. I went looking for a view path that called the shared evaluator directly and would now lose the exemption, and didn't find one; the ontology still reads under a default-deny view policy on every path I tried (scans, the crawl formatter, rdfs reasoning, time travel and history).
This PR also makes one product call that I'd like to name so it's a deliberate one: every schema triple now needs modify permission, class and property declarations and rdfs:domain/rdfs:range included, not only the two hierarchy edges that policy expansion reads. The ways I see to draw it:
- as written, which closes the widening and also a write channel: before this, an identity that could transact at all could write any of these triples (literals included) onto any subject, and every reader saw them. The cost is that a restricted identity maintaining the ontology needs a grant, which is what the compatibility entry is for, as long as the grant it suggests works (inline);
- judging only
rdfs:subClassOfandrdfs:subPropertyOf, which closes the widening and breaks less, but leaves declarations and domain/range writable by anyone and readable by everyone; - as written, plus a one-release opt-out in ledger config, which eases the upgrade for a deployment with restricted ontology maintainers, at the cost of new config surface and keeping the hole one setting away.
It's your call; fwiw my own lean is the way you've written it.
One more headline note, on something this PR didn't introduce: the premise here is that the hierarchy decides what policies allow, but on an indexed ledger a retracted rdfs:subPropertyOf/rdfs:subClassOf edge keeps deciding until the next index. compute_schema_hierarchy_with_overlay (fluree-db-core/src/schema_hierarchy.rs:524) unions the current-state scan's asserts into the last index root's edges, so a retraction still in novelty can't take away what the index recorded, and the reasoning copy of the same derivation (fluree-db-query/src/execute/reasoning_prep.rs:89) does the same. It's another case of the "second path re-derives what the first does and drops part of it" class: the index-time SchemaExtractor handles retractions and the two read-time derivations don't. Repro and details inline. I'd rather see the core fix folded in here, since this is the PR that makes the hierarchy part of what policy protects; whether the reasoning copy collapses onto it in the same change is your call.
Full review below:
✅ Approve.
This is carefully built, @bplatz, and the test that writes the same edge as root and then shows the reader's view widen is the best argument for the check; both it and the updated CLEAR test go red when I put back either the stage.rs skip or the evaluator-level modify bypass. On its own terms the move looks complete to me: every write path judges through the one modify loop (stage, graph management, and stage_flakes for push/import all go through enforce_modify_policies), and I couldn't find a db write path that stages schema triples implicitly, so the break only reaches an identity that writes ontology on purpose with nothing covering it. The two things I'd accommodate before merge are the maintainer grant in the docs (as written it doesn't let a maintainer declare a class) and, if you agree, the pre-existing retraction staleness from the headline; the rest are small.
What I probed beyond the PR's tests, in case it's useful:
- View paths keep the exemption. For a default-deny reader allowed only
ex:nameandrdf:type:ex:Sub ?p ?oreturns itsrdf:type rdfs:Classandrdfs:subClassOf,?s rdfs:subPropertyOf ?oreturns the edge, a{"ex:Sub": ["*"]}crawl returns the class node,?s a ex:Superfindsex:alice(anex:Sub) withrdfsreasoning and nothing without it, and time travel tot:1and at:1→latest history both return the edge (assert and retract), while the data stays hidden throughout. - Escalation is refused in both directions. An identity whose only modify grant is
f:onProperty ex:qgets a 403 forex:secret rdfs:subPropertyOf ex:q, for the reverseex:q rdfs:subPropertyOf ex:secret, and for retracting an existingex:ssn rdfs:subPropertyOf ex:q. With modify on bothex:qandrdfs:subPropertyOf, writing the edge andex:bob ex:secretin one transaction is refused, because the modify set expands through the pre-transaction hierarchy (fails closed), and the data write goes through from the next transaction, which is what I'd expect. - No implicit schema writes. I couldn't find a db write path that stages schema triples the user didn't write; the CLI's
fluree model class|entity|accesscommands writerdf:type rdfs:Classexplicitly, which is the docs point inline.
Adherence to repo commitments:
- Patterns/abstractions: ✔ moves the exemption to the view entry points rather than adding a parallel check.
QueryPolicyEnforcer(fluree-db-query/src/policy/enforcer.rs:125,:181) still carries its own copy ahead of the entry point, which is harmless, but it means the query paths never exercise the entry-point check (inline). - Performance (speed first, memory second): ✔ No performance-degradation risk. The view path makes the same two
is_schema_flakecalls per non-schema flake it made before (enforcer plus entry point, where it was enforcer plus evaluator), each a namespace-code and short-name compare with no allocation; the modify loop now evaluates schema flakes it used to skip, which is ordinary per-flake write cost (anf:querymodify policy now runs for them too), not a query hot-path change. - Deployment targets: ✔ n/a. The evaluator and the modify loop are shared by every host, but the change adds no runtime requirement (no task, cache or filesystem use), so the memory-backed integration tests are the right evidence.
- Testing:
⚠️ the new and updated tests are wired (grp_policy,grp_graphsource), ran by name in CI'stestjob ata1b93280f, and go red under both mutations; nothing pins the async view entry's bypass, and the refusals assert onlyis_err()(both inline). - Conventions: ✔ thorough commit body,
breaking-changelabel and a compatibility entry; two doc comments still describe the old exemption (inline).
Verified locally at branch HEAD: cargo test -p fluree-db-api --test grp_policy --test grp_graphsource (144 + 255 passed, including schema_writes_follow_modify_policy and test_clear_default_schema_flakes_follow_modify_policy by name) and cargo test -p fluree-db-policy --lib (43 passed); mutation checks on stage.rs, evaluate.rs and schema_hierarchy.rs; scratch probes (since deleted) for view, reasoning, history, escalation, retraction and the documented maintainer grant.
Approving so you can merge when ready, but maybe worth folding in the docs grant and the hierarchy fix first.
|
|
||
| ### Schema writes | ||
|
|
||
| Schema triples — `rdfs:subClassOf`, `rdfs:subPropertyOf`, `rdfs:domain`, `rdfs:range`, and `rdf:type` declaring a class or property — are checked against `f:modify` like any other flake. A policy on a class or property also covers its subclasses or subproperties, so the hierarchy is part of what policy protects: an identity needs modify permission for the schema triple itself, for example an `f:onProperty` policy on `rdfs:subPropertyOf`, or `f:defaultAllow`. Every identity can still read the schema; view policy lets it through. |
There was a problem hiding this comment.
🟠 Should address: the maintainer grant this section suggests doesn't let a maintainer declare a class or property.
I tried it: an identity with default-allow: false, a view-all policy, and f:modify f:onProperty on rdfs:subPropertyOf and rdfs:subClassOf can write ex:Lead rdfs:subClassOf ex:Super, but {"@id": "ex:Lead", "@type": "rdfs:Class", "rdfs:subClassOf": {"@id": "ex:Super"}} is refused (403), and so is {"@id": "ex:email", "@type": "rdf:Property", "rdfs:domain": {"@id": "ex:Super"}}, because the rdf:type rdfs:Class and rdfs:domain triples aren't covered. That's the first thing a maintainer writes, and it's what fluree model class define, model entity define and model access enable emit (fluree-db-cli/src/commands/model/class.rs:133, entity.rs:171, access.rs:449).
The obvious next try doesn't work either: a bare f:modify f:onClass rdfs:Class is refused for a new class, since bare f:modify class targeting reads pre-state classes and a class being declared has none. What did work was adding a verb policy, f:onClass rdfs:Class with f:action [f:create, f:update], where the declared class's post-state type brings it under the grant. f:onProperty rdf:type also works, but the same identity can then retype any data subject (ex:bob a ex:Super went through), so it's not one to suggest.
Maybe this section, and the compatibility entry at docs/reference/compatibility.md:358 that gives the same example, could show a grant covering the whole shape. Illustrative, IRIs compacted:
[
{"@id": "ex:ontologyEdges", "f:action": {"@id": "f:modify"}, "f:allow": true,
"f:onProperty": [{"@id": "rdfs:subClassOf"}, {"@id": "rdfs:subPropertyOf"}, {"@id": "rdfs:domain"}, {"@id": "rdfs:range"}]},
{"@id": "ex:ontologyTerms", "f:action": [{"@id": "f:create"}, {"@id": "f:update"}], "f:allow": true,
"f:onClass": [{"@id": "rdfs:Class"}, {"@id": "owl:Class"}, {"@id": "rdf:Property"}, {"@id": "owl:ObjectProperty"}, {"@id": "owl:DatatypeProperty"}]}
]I only ran the rdfs:Class part of the second policy; the property types should behave the same way, but it's worth a test. It might also be worth one sentence that f:onProperty rdfs:subPropertyOf lets the holder write any subproperty edge, the ex:ssn rdfs:subPropertyOf ex:name one included, so it's a grant for someone already trusted with what policies allow.
There was a problem hiding this comment.
Addressed in 2d84bd9. Used an rdf:type grant with a $value condition in place of the f:onClass verb grant, which also covers a class subject's other properties.
| /// and formatting to work correctly. This includes: | ||
| /// Query planning and formatting read the ontology whatever the reader may | ||
| /// see. Writing a schema flake is judged by modify policy like any other: | ||
| /// policy targets widen through the class and property hierarchy, so an |
There was a problem hiding this comment.
🟠 Should address (pre-existing, not introduced here): on an indexed ledger, retracting a hierarchy edge doesn't narrow policy until the next index.
fluree-db-core/src/schema_hierarchy.rs:524 starts the policy hierarchy from snapshot.schema (the last index root's edges) and adds the asserts its current-state scan finds; nothing removes an edge whose retraction is still in novelty. So the ex:ssn rdfs:subPropertyOf ex:name case this comment describes can't be undone promptly: retracting the edge leaves ex:ssn covered by the ex:name policies until the ledger reindexes.
Repro (scratch test on this branch): seed ex:ssn rdfs:subPropertyOf ex:q and ex:bob ex:ssn "123-45-6789", rebuild_and_publish_index, reload, then retract the edge as root. A reader with only f:view f:onProperty ex:q (default deny) still gets ["123-45-6789"] for ex:bob ex:ssn ?v, while a view-all query for ex:ssn rdfs:subPropertyOf ?o returns [], and an identity with only f:modify on ex:q can still write ex:bob ex:ssn. The same steps without the index give [] and a 403. Replacing line 524 with an empty IndexSchema makes the indexed case come out [] and 403 too, so that merge is the mechanism. rdfs reasoning has the same staleness through its own copy (fluree-db-query/src/execute/reasoning_prep.rs:89): ex:bob ex:q ?v still answers after the retraction.
I'm not sure dropping the merge is the fix by itself, since I didn't run the wider suites that way and the index root may carry edges the default-graph scan doesn't. The index-time SchemaExtractor already does the right thing (fluree-db-indexer/src/stats/schema_extractor.rs:61 from_prior plus on_flake, which drops an edge on a retraction), so replaying novelty's rdfs:subClassOf/rdfs:subPropertyOf flakes over the indexed schema that way, rather than unioning the asserts in, would fix policy, SHACL targeting and GraphQL (every caller of this function) at once. I recognize it's outside this diff, but since this PR is the one stating that the hierarchy is part of what policy protects, I'd rather see it folded in here than tracked separately.
Commenting here because fluree-db-core/src/schema_hierarchy.rs is not in this diff.
There was a problem hiding this comment.
Addressed in 3e44a8f. Dropped the union rather than replaying novelty over the index schema, since the default-graph scan already reads indexed and unindexed state; an edge in a named graph, which only the index schema carried, now counts neither before nor after an index build.
| executor: &dyn PolicyQueryExecutor, | ||
| tracker: &Tracker, | ||
| ) -> Result<bool> { | ||
| if is_schema_flake(property, object) { |
There was a problem hiding this comment.
🟡 Optional: nothing pins this entry point's bypass, and it's the one a caller relies on directly.
I removed these three lines, and the matching ones in the sync allow_view_flake. test_schema_flake_always_allowed went red for the sync one, but all of grp_policy (148 tests, including a scratch probe reading the ontology under a default-deny view policy) and the fluree-db-query policy unit tests (the r2rml::policy ones included) stayed green with this one gone. The query paths don't notice because QueryPolicyEnforcer checks is_schema_flake itself before calling here (fluree-db-query/src/policy/enforcer.rs:125, :181); the R2RML view check (fluree-db-query/src/r2rml/policy.rs:429) calls allow_view_flake_async directly and is the caller that depends on these lines.
Since the point of the PR is that the exemption now lives in the view entry points and not the shared evaluator, a unit test next to test_schema_flake_always_allowed that pins both halves would hold that in place: under a deny-all set, allow_view_flake_async allows an rdfs:subClassOf flake and allow_modify_flake_write_async_detailed denies it. This is minor and non-blocking, but if you agree it's right I'd rather see it folded in now than lost in the backlog.
| /// 5. Return default_allow if no policy allowed | ||
| /// | ||
| /// The view entry points let every schema flake through first | ||
| /// ([`is_schema_flake`]); writing one is judged like any other. |
There was a problem hiding this comment.
🟡 Nit: two doc comments still describe the old exemption.
This comment has it right, but fluree-db-policy/src/evaluate.rs:6 (the module doc, "Schema flake bypass (schema flakes always allowed)") and fluree-db-policy/src/lib.rs:22 (step 1 of the evaluation semantics, "Schema bypass: Schema flakes (rdfs:subClassOf, etc.) always allowed") still read as if every evaluation skips them. docs/ledger-config/setting-groups.md:26 also says schema flakes "bypass policy", which is still true of reading but could say view policy now. So minor, but if you agree I'd fold these into this PR.
| .transact_tracked_with_policy(ledger.clone(), input, CommitOpts::default(), &cfg) | ||
| .await; | ||
| assert!( | ||
| refused.is_err(), |
There was a problem hiding this comment.
🟡 Nit: is_err() would also pass for the wrong error.
Both mutations I tried (putting the stage.rs skip back, and putting the bypass back in allow_modify_flake_write_async_detailed) turn this red, so the test has teeth today. It would be just as green, though, if the transaction failed for an unrelated reason. Asserting the policy refusal itself (status 403, "Policy enforcement prevents modification.", which is what transact_tracked_with_policy returned for these edges when I ran them) pins the reason. The same goes for result.is_err() in test_clear_default_schema_flakes_follow_modify_policy (it_named_graphs.rs:4937). Minor, fold it in if you agree.
compute_schema_hierarchy_with_overlay scanned the default graph's current rdfs:subClassOf and rdfs:subPropertyOf edges, then unioned them into the last index root's schema. A retraction still in novelty couldn't remove what the index recorded, so on an indexed ledger a retracted edge kept widening class and property policy targets, for view and modify, until the ledger reindexed. SHACL targeting and GraphQL interfaces read the same hierarchy. The scan already covers indexed and unindexed state, so it now decides alone. The index root's schema is extracted from every graph, so an edge in a named graph counted after an index build and not before one. It now counts in neither, like the scan. rdfs query reasoning kept its own copy of the function, with the same union; it now calls the core one. Test: it_policy_indexed::retracted_subproperty_edge_narrows_policy_before_reindex checks view, modify and rdfs reasoning on an indexed ledger after the edge's retraction.
schema_writes_follow_modify_policy and test_clear_default_schema_flakes_follow_modify_policy asserted only that the write failed, which a failure for any other reason would satisfy too. They now expect a 403 with the modify-policy refusal message.
The suggested grant, f:onProperty on rdfs:subPropertyOf and rdfs:subClassOf, let a maintainer write hierarchy edges but not declare a class or property: rdf:type rdfs:Class and rdfs:domain/range stayed uncovered. The Schema writes section now gives a pair that covers every schema triple: modify on the four schema properties, and on rdf:type with a condition admitting only class and property types. An unconditioned rdf:type grant would let its holder retype any data subject, and a class-targeted grant on rdfs:Class covers a class subject's other properties too. The section also says a hierarchy grant is for an identity trusted with what policies allow, and the compatibility entry points to the pair. Test: it_policy_tx::ontology_maintainer_grant_covers_schema_triples_only runs the documented pair. Declarations of each type, on new and existing terms, and edge writes and retractions go through; retyping a data subject, writing its other properties alongside a schema type, and a non-schema property on a class are refused.
Under deny-all view and modify sets, schema_flakes_bypass_view_policy_only expects allow_view_flake_async and its detailed twin to let an rdfs:subClassOf flake through, and allow_modify_flake_write_async_detailed to deny it. Query paths check is_schema_flake in QueryPolicyEnforcer before reaching the entry point, so nothing else covered the async view bypass the R2RML view check relies on. The evaluate and lib module docs and the setting-groups page still described the exemption as covering every evaluation.
Brings #2217 (SPARQL reads list members as values; CONSTRUCT writes lists), #2218 (schema writes judged by modify policy), #2208, #2169, #2168, #2153, #2149 and #2148 into next. Resolutions: - Nameservice: branch_records is the one branch listing (strict, retracted branches kept for GC) on every backend, resolved through next's bindings; Fluree::list_branches filters retracted ones. The lifecycle conformance suite reads live branches through a helper. DynamoDB's narrow listing is wired into its trait impl. - JSON-LD adapter: main's graph scoping (Walk, Scope, node_graph, selectors) with next's triple terms, @annotation, @reifies, blank-label and number datatype handling. to_graph_events writes a JSON-LD named graph under its @id and refuses a graph selector. main's f:reifiesGraph anchor is dropped: next writes an annotation as an rdf:reifies link in its graph. emit_quad_list_item takes (graph, index). - Bulk import: an annotation's link is written to the graph its slots name, and a triple-term statement in a named graph is spooled under that graph (both landed in the default graph); emit_quad_reified_triple is implemented. resolve_object_value keeps main's vector refusals and next's term-table path. - Ledger manager: a store that fails to load fails the load or keeps the reloaded ledger's state (main), over next's load_decoding_root and activation swap rule. - Novelty keeps main's KeptEffects without the retired arena's reifies capture. The pool's resolve_events_at and compaction's split_lifecycles follow fluree_db_core::same_t. - Retired annotation arena files stay deleted. - Tests from main adapted to next: one Fluree per storage directory, async genesis_ledger, storage-namespace content stores, u32 graph ids, a store broken by hiding a dictionary branch (next has no disk cache), a refused import leaving no ledger. next's tests that pinned bulk import refusing @graph and SPARQL's RDF list view now check what main changed them to.
Writing a schema triple is now checked against
f:modifypolicy like any other write. Retracting a hierarchy edge now narrows policy at once, not at the next index build.Why
Schema triples (
rdfs:subClassOf,rdfs:subPropertyOf,rdfs:domain,rdfs:range, andrdf:typedeclaring a class or property) were exempt from both view and modify policy. A policy on a class or property also covers its subclasses and subproperties, so the hierarchy is part of what policy protects. An identity able to write it without a modify check could change what view policies let other identities read.For the same reason, the hierarchy policy reads has to be current. On an indexed ledger it wasn't: a retracted
rdfs:subClassOforrdfs:subPropertyOfedge kept counting until the ledger reindexed, because the hierarchy merged the last index's schema into its scan of current state. A retraction still in novelty couldn't remove what the index recorded.What changes
CLEARandDROPof a graph holding them. An identity withf:defaultAllow, or with no policy, is unaffected. A restricted identity that maintains the ontology needs a policy for those triples.docs/security/policy-in-transactions.mdgives a pair that covers them: modify on the four schema properties, and onrdf:typewith a condition admitting only class and property types.rdfsquery reasoning. An edge in a named graph used to count after an index build and not before; it now counts in neither.In code, the schema exemption moves out of the evaluators that view and modify share (
fluree-db-policy/src/evaluate.rs) and into the view entry points only (allow_view_flake*). The modify loop instage.rsno longer skips schema flakes.compute_schema_hierarchy_with_overlay(fluree-db-core/src/schema_hierarchy.rs) no longer merges insnapshot.schema.rdfsreasoning's copy of that function (reasoning_prep.rs) is removed, and reasoning calls the core function.Tests
it_policy_tx::schema_writes_follow_modify_policy:subPropertyOfand asubClassOfedge, with a 403 policy refusal;f:onProperty rdfs:subPropertyOfmodify policy may write the edge.it_policy_tx::ontology_maintainer_grant_covers_schema_triples_onlyruns the grant the docs give. Declarations of each class and property type, on new and existing terms, and edge writes and retractions go through. Retyping a data subject, writing its other properties alongside a schema type, and a non-schema property on a class are refused.it_policy_indexed::retracted_subproperty_edge_narrows_policy_before_reindex: on an indexed ledger, after the edge is retracted, the reader no longer sees the subproperty's value, the parent's modify grant no longer covers it, andrdfsreasoning no longer entails the parent from it.evaluate::tests::schema_flakes_bypass_view_policy_only: under deny-all sets, the async view entry points let a schema flake through and the write entry point denies it.it_named_graphs::test_clear_default_schema_flakes_follow_modify_policypreviously pinned the exemption. It now expects a view-only identity'sCLEAR DEFAULTof a schema-only graph to be refused with a 403 policy refusal.Each new test fails with the old behaviour restored.
Docs
docs/reference/compatibility.md: a behaviour-change entry.docs/security/policy-in-transactions.md: a new "Schema writes" section with the ontology maintainer grant.docs/security/policy-in-queries.mdanddocs/ledger-config/setting-groups.md: the schema exemption is now described as applying to view policy only.