Repository navigation
feat(server): Graph Store HTTP Protocol endpoint and default-graph sync - #1934
Conversation
91c953d to
df23ede
Compare
df23ede to
897d79a
Compare
aaj3f
left a comment
There was a problem hiding this comment.
This is exciting @bplatz, both generally for support of the 1.1 Graph Store HTTP protocol and also, for Fluree AI (@jakep36 for visibility) as /sync can now be used where previously we were having to abstract a kind of "upsert + evaluate absences for deletions". My first question was whether the new protocol path would perform at the same speed as the pre-existing API paths, but that question immediately became moot once I realized this just maps verbs from the protocol to the mechanisms already in place (maybe an obvious design choice, but still a good one). Full review below (I think the RDF/XML finding in particular deserves some attention):
This is a really nice piece of work, and the design decision at the centre of it is the one I'd have wanted: rather than building a second write path, every verb maps onto a mechanism that already exists and has already been hardened, and GET re-enters query_ledger so read policy applies for free instead of being reimplemented (the contrast with /export/*ledger, which is admin-gated precisely because it bypasses per-flake policy, is exactly the right instinct). The system-graph guard is layered three deep and I verified all three layers; the Option<String> widening on a persisted consensus body is tested against the encoding that's actually on disk rather than a convenient one; and the docs page is genuinely good.
Two things are holding me up. First, the RDF/XML half of GET returns 406 for any caller whose token or credential carries an identity — query.rs:2943 refuses RDF/XML on the identity-scoped branch, and that's the branch every authenticated whole-graph CONSTRUCT takes — so half the advertised content negotiation is dead in exactly the production posture; #1940 fixes it, so landing these together (or pulling that three-line removal into this PR) resolves it.
Second, and this is the one I'd ask for regardless of merge order: I deleted enforce_write_access from both PUT/POST and DELETE and the whole HTTP suite stayed green, because the harness runs on DataAuthMode::None. For a new public endpoint whose DELETE drops a graph, I'd like that gate pinned by a test before it ships — and the same fixture gives you coverage for the RDF/XML case.
Adherence to repo commitments:
- Patterns/abstractions: ✔ Extends
TurtleOp,execute_transaction,TransactionBodyand the query route rather than adding a parallel write engine; the one-MethodRoutercomposition atroutes/mod.rs:282-286is the right way around axum's merge restriction. - Performance (speed first, memory second): ✔ The query engine and transaction hot paths are untouched. New endpoint-local costs only: two extra
graph_existsscans per write for the 201/200 decision, and a whole-graph CONSTRUCT perGET(and perHEAD). No performance-degradation risk to any existing path. - Testing:
⚠️ it_graph_scoped_writes.rsandgraph_store_http.rsare correctly wired (grp_ledger.rs:14,grp_http.rs:7) and the lifecycle / status-matrix / error-code coverage is good; the system-graph guard goes red under mutation. But the authorization gate has zero coverage — mutation-proven — and the RDF/XMLGETpath is untested for the only configuration where it's broken. - Conventions: ✔ Multi-line commit body carrying the rationale, self-describing title, clippy/fmt green in CI, and the docs (
docs/api/graph-store.md, sync, endpoints, CLI, compatibility, named-graphs) are all updated with the behaviour change called out.
Verified locally at branch HEAD df23ede5f: cargo nextest run -p fluree-db-server --all-features --test grp_http -E 'test(/graph_store_http/)' → 5/5 passing with all five new test names present; two mutation checks (authz removal → still green; system-graph guard → red as expected), worktree restored clean after each. CI at this exact SHA is fully green (test, clippy, fmt, testsuite-sparql, wasm32, wasm-smoke, sql-bridge), so the stacked-PR no-CI trap doesn't apply.
So — nothing here needs rethinking, and I'd flip to approve on an authz test plus either #1940 landing first or that query.rs hunk coming along for the ride. Happy to talk through any of the optional notes.
| .get(header::ACCEPT) | ||
| .and_then(|v| v.to_str().ok()) | ||
| .map(str::to_string); | ||
| let format = negotiate(accept.as_deref())?; |
There was a problem hiding this comment.
fluree-db-server/src/routes/query.rs:2935-2945
Blocking — the RDF/XML half of GET returns 406 for exactly the callers who will use it in production.
negotiate resolves Accept: application/rdf+xml to GraphFormat::RdfXml and sets it on the forwarded request (graph_store.rs:318-324), but execute_sparql_ledger takes the identity-scoped branch whenever qc_opts.has_any_policy_inputs() && !has_dataset_clause (query.rs:2935), and that branch hard-406s RDF/XML at query.rs:2943-2945. has_any_policy_inputs() is true as soon as identity.is_some() (dataset.rs:1104-1116), and bind_authorization sets headers.identity from a bearer token's identity or a signed DID (policy_auth.rs:36-65). Neither CONSTRUCT this endpoint builds carries a FROM, so has_dataset_clause is false.
Concretely: GET /v1/fluree/data/mydb:main?graph=urn:example:tools with Accept: application/rdf+xml and a valid bearer token returns 406 "RDF/XML is not supported for identity-scoped SPARQL queries". Unauthenticated it works, which is why graph_store_http.rs (built on ServerConfig::default(), i.e. DataAuthMode::None) can't see it.
#1940 deletes that branch's RDF/XML refusal and adds construct_graph_formats_on_policy_and_dataset_paths to cover it — its body names this as a fix — so the cleanest resolution is merge order: land #1940 first, or land the two together, rather than reworking anything here. If #1934 is going to sit on main on its own for any length of time, I'd pull the three-line removal of query.rs:2942-2946 into this PR instead.
Commenting here because fluree-db-server/src/routes/query.rs is not in this diff.
There was a problem hiding this comment.
Fixed in this PR (9edb522) rather than relying on merge order. One correction: removing the refusal alone isn't enough, because #1940 also adds the block that formats the graph on that branch. The identity-scoped branch now formats CONSTRUCT/DESCRIBE as RDF/XML the same way the dataset branch does, with the same "CONSTRUCT/DESCRIBE only" guard. The new auth test does an identity-scoped RDF/XML GET and fails if the refusal is put back. #1940 will take its own version of this hunk when it's rebased.
| bearer.as_ref(), | ||
| credential.did(), | ||
| )?; | ||
| enforce_write_access(&state, &ledger, bearer.as_ref(), &credential)?; |
There was a problem hiding this comment.
Blocking — nothing tests that the new write verbs are authorized, and I proved it by deleting the gate.
graph_store_http.rs:25-31 builds its ServerConfig from ..Default::default(), and DataAuthMode::None is the default (config.rs:53-56). So every one of the five HTTP tests runs with authorization switched off, and enforce_write_access returns Ok(()) on its first branch without ever consulting a principal.
I replaced enforce_write_access(&state, &ledger, bearer.as_ref(), &credential)?; with Ok::<(), ServerError>(())?; at both call sites — graph_store.rs:144 (PUT/POST) and graph_store.rs:218 (DELETE) — and re-ran cargo nextest run -p fluree-db-server --all-features --test grp_http -E 'test(/graph_store_http/)': 5 passed, 0 failed. A future refactor can drop the gate off a destructive verb and the suite stays green.
This is a new public HTTP surface whose DELETE drops a whole graph, so I think the gate needs pinning before it ships. The cheap version is one test: a second seeded_app_with_auth() that sets data_auth_mode = DataAuthMode::Required, then assert PUT / POST / DELETE with no credential are 401 and with a read-only bearer are 404 "Ledger not found" (the existing existence-leak-avoiding shape at transact.rs:632-636). That also gives you the fixture the RDF/XML finding above needs.
There was a problem hiding this comment.
Added graph_store_requires_authorization, with data auth required. The write verbs without a credential get 401, and with a read-only bearer 404. Your mutation found one more gap: the first draft sent the reader's DELETE before the graph existed, so the absent-graph 404 hid the missing gate. It now runs against a graph that exists and checks the graph survives. Removing either gate fails the test; without the DELETE gate the reader actually drops the graph.
| .and_then(|v| v.to_str().ok()) | ||
| .map(str::to_string); | ||
| let format = negotiate(accept.as_deref())?; | ||
| if !state.fluree.graph_exists(&ledger, &graph).await? { |
There was a problem hiding this comment.
Optional — this is more of a question than a suggestion, but graph_exists answers before anything has authorized the caller, so GET is a graph-existence oracle.
read_graph calls state.fluree.graph_exists(&ledger, &graph) at line 298 and only then hands off to query_ledger, which is where the DataAuthMode::Required 401 (query.rs:1109-1117) and the bearer can_read check (query.rs:1138-1144) live. graph_exists (admin.rs:1237-1263) is a raw Spot scan with no policy applied at all.
So on a stack with data_auth.mode = Required, an unauthenticated GET /v1/fluree/data/L?graph=<candidate> returns 404 "graph <candidate> does not exist" when the graph is absent and 401 "Authentication required" when it holds a triple — which lets an anonymous caller confirm any graph IRI they can guess. The same split distinguishes a graph a policy-restricted reader is not allowed to see (404 vs. an empty 200) from one that isn't there.
I recognize this is a narrow leak — it's an oracle, not an enumeration, and /v1/fluree/exists/*ledger already makes ledger existence public. But enforce_write_access goes out of its way to avoid exactly this on the write side (transact.rs:634 — "Avoid existence leak", returning 404 Ledger not found rather than 403), so the read side reading the other way is a little inconsistent. Minimally this could be fixed by running the CONSTRUCT first and only calling graph_exists to disambiguate an empty result into 200-vs-404 — the auth error then lands before any existence signal, and for ?default it costs nothing since graph_exists short-circuits to Ok(true). Non-blocking, but if you agree it's right I'd rather see it in this PR than lost in the backlog.
There was a problem hiding this comment.
Agreed, and I went a step further than running the CONSTRUCT first, because that still leaves the policy half of the oracle (an empty 200 versus a 404). GET and HEAD on a named graph now send ASK { GRAPH <g> { ?s ?p ?o } } through the query route first. Authentication and read policy answer before existence, and a graph with no triple the caller may see is a 404. graph_exists is gone from the read path. The auth test checks that unauthenticated reads of a present and an absent graph both get 401, and it fails if the raw check comes back.
|
|
||
| /// `GET /data/<ledger...>?graph=<iri>` (or `?default`); `HEAD` is answered | ||
| /// from the same handler with the body dropped. | ||
| pub async fn get( |
There was a problem hiding this comment.
Optional — HEAD costs a full GET.
The module doc says HEAD is "answered from the same handler with the body dropped", which is accurate — axum routes HEAD to the get handler and discards the body. But that means a HEAD on a 10M-triple graph runs the whole-graph CONSTRUCT, instantiates the Graph, canonicalizes it and serializes the document, then throws all of it away. Clients use HEAD on this protocol precisely because they expect it to be cheap.
graph_exists plus the negotiated Content-Type is everything a HEAD can honestly answer here (there's no Content-Length to promise without serializing anyway), so short-circuiting on parts.method == Method::HEAD before the CONSTRUCT would be a few lines. Minor and non-blocking — but if you agree, I'd rather fold it in now.
There was a problem hiding this comment.
Done, and with the change above it stays authorized. HEAD stops at the ASK (one row, through the query route) and answers with the negotiated Content-Type, without building the graph. A plain short-circuit on graph_exists would have skipped authorization and made HEAD the same oracle.
| )); | ||
| } | ||
|
|
||
| let existed = state.fluree.graph_exists(&ledger, &graph).await?; |
There was a problem hiding this comment.
Optional — three ledger-state materializations per write, to pick a status code.
let existed = graph_exists(…) at line 159 and let created = !existed && graph_exists(…) at line 196 each do ledger_cached → snapshot().to_ledger_state() → a flake_limit: 1 Spot scan (admin.rs:1246-1262), on top of the one the write itself does. It's also a TOCTOU: two concurrent PUTs that both observe existed == false both answer 201.
Neither is harmful, and 201-vs-200 does need some before/after signal — I mostly want to note it so the cost is deliberate rather than incidental. If the commit report already carries enough to tell "this graph had no triples before" (the sync delta knows), deriving created from the report would drop both scans.
There was a problem hiding this comment.
Leaving this one as is. Both scans read at most one row, and the race (two concurrent first PUTs both answering 201) is harmless. Closing it would mean deciding the status inside the write lock. The sync delta doesn't say whether the graph was empty before, so deriving created from the report would need a new field just for a status code.
| )) | ||
| } | ||
|
|
||
| async fn read_graph(state: Arc<AppState>, ledger: String, request: Request) -> Result<Response> { |
There was a problem hiding this comment.
Optional, and genuinely a question — a whole-graph GET has no bound.
read_graph issues CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o } for ?default, and the formatter builds the entire graph plus the entire serialized document in memory before the first byte ships (format/graph_text.rs:32-33 in #1940's tree; the JSON-LD path in this tree does the same through a serde_json::Value DOM). #1942 tracks the JSON-LD DOM specifically, but not the whole-graph materialization that all four formats share.
I don't think this is a regression — the same CONSTRUCT was always reachable through POST /query/{ledger} — but this PR turns "dump the entire default graph" into a one-line unauthenticated-by-default GET, which changes how likely someone is to do it by accident. Is it worth a note in docs/api/graph-store.md that GET is unpaged and whole-graph, or a Fluree-Max-Bytes-style ceiling on this route?
There was a problem hiding this comment.
I added a note to docs/api/graph-store.md: GET builds and serializes the whole graph, so for a large graph, query it through /query with LIMIT/OFFSET or export the ledger. I didn't add a byte ceiling for this one route; #1942 tracks the memory side, and a per-route limit would be a new mechanism.
| let graph = graph_target(graph, default_graph, true)?; | ||
| if let GraphSel::Graph(iri) = &graph { | ||
| use fluree_db_core::graph_registry::{ | ||
| config_graph_iri, txn_meta_graph_iri, validate_absolute_graph_iri, |
There was a problem hiding this comment.
Praise — the system-graph defense is layered three deep and I checked all three.
The route guard here, graph_exists's g_id < FIRST_USER_GRAPH_ID floor (admin.rs:1251), and stage.rs:1412-1425's ReservedGraphTarget on CLEAR/DROP.
I mutated the route guard (pointing normalize_ledger_id at the wrong ledger id so it computes non-matching system IRIs) and the request still came back 404 rather than touching #txn-meta — the depth is real, not decorative.
| @@ -194,26 +194,60 @@ pub enum TransactionBody { | |||
| /// object map, matching `fluree_db_cypher::ParamMap`. | |||
There was a problem hiding this comment.
Praise — the String → Option<String> widening on a persisted body is the kind of change that usually goes wrong quietly, and this one is right for the right reason.
The envelope is JSON (lib.rs:488-499 explains why — serde_json::Value won't round-trip postcard), so serde_json::from_str::<TransactionBody>(r#"{"JsonLdGraphSync":{"graph_iri":"urn:g",…}}"#) is testing the encoding that actually exists on disk, and the separate BodyKind ordinal is postcard, which is why GraphInsert is appended at 14 and pinned by body_kind_wire_tests.
Both halves are covered by the right test.
| GraphSel::Graph(iri) => format!("DROP GRAPH <{iri}>"), | ||
| GraphSel::Default => "CLEAR DEFAULT".to_string(), | ||
| }; | ||
| submit_sparql_update( |
There was a problem hiding this comment.
Praise — the comment "The IRI was validated above, so it cannot close the <…>" is load-bearing and it checks out.
validate_absolute_graph_iri (graph_registry.rs:69-80) rejects >, \, " and whitespace, so neither DROP GRAPH <{iri}> here nor GRAPH <{iri}> at line 305 can be broken out of. Nice to see the interpolation justified rather than assumed.
6c14d9d to
62a0ab6
Compare
19c1287 to
25afb38
Compare
4e12772 to
fe02c0e
Compare
fe02c0e to
8784074
Compare
8784074 to
1bea1dd
Compare
aaafadf to
ce4176d
Compare
eea365c to
cb1ea03
Compare
Adds the W3C SPARQL 1.1 Graph Store HTTP Protocol at /v1/fluree/data/<ledger>?graph=<iri> (or ?default): - PUT replaces the graph through graph sync, so one commit carries only the difference; an empty body clears it, as the protocol specifies. - POST adds the body's triples through a new graph insert. - DELETE is DROP GRAPH, or CLEAR DEFAULT for the default graph. - GET/HEAD run a CONSTRUCT through the query route, so read policy applies; JSON-LD or RDF/XML by Accept, 406 otherwise. - 201 when PUT/POST bring a graph into existence, 404 for an absent graph, 415 for an unsupported body type. Writes forward to the Raft leader or the transaction server; reads run locally. Sync can now target the default graph: /sync and `fluree sync` without a graph sync the default graph, and ?default says so explicitly. Txn.sync_graph is a GraphSel, and parse_graph_insert is shared by sync and graph insert. The API's SyncPayload becomes GraphPayload, with sync_graph_with, stage_graph_insert_tracked and graph_exists. SyncGraphReport.graph_iri is None for the default graph. The consensus sync bodies carry an optional graph (an entry holding a plain string still decodes), and GraphInsert is appended as BodyKind 14.
cb1ea03 to
0cb6562
Compare
GET checked graph_exists (a raw scan, no policy) before the query route authorized the caller. An anonymous request got 404 for an absent graph and 401 for a present one, and a policy-restricted reader could tell a hidden graph from a missing one. GET and HEAD on a named graph now ask existence with an ASK through the query route, so authentication and read policy answer first. A graph with no triple the caller may see is a 404. HEAD stops at the ASK instead of building and serializing the graph. The identity-scoped SPARQL path refused RDF/XML outright, which is the path every authenticated caller takes, so a GET with Accept: application/rdf+xml was a 406 for them. It now formats CONSTRUCT/DESCRIBE as RDF/XML like the other query paths. A new test runs the graph store with data auth required. It covers the write verbs without a credential (401) and with a read-only one (404, with DELETE against a graph that exists), unauthenticated reads of present and absent graphs alike, HEAD, and an identity-scoped RDF/XML GET. Removing either write gate, restoring the RDF/XML refusal, or checking existence before authorization each fails it. The graph store docs say GET is whole-graph and unpaged, and how existence follows what the caller can see.
|
@aaj3f thanks. Both blockers are fixed in this PR (9edb522), and I've replied on each thread:
I also took the existence-oracle and |
Summary
This implements the W3C SPARQL 1.1 Graph Store HTTP Protocol at
/v1/fluree/data/{ledger}?graph=<iri>(or?default). RDF tools that speak the protocol can read, replace, add to and remove a graph without a Fluree-specific client. It also lets sync target the default graph, which becomes what/syncdoes when no graph is named.PUT201if it created the graph, else200POST201/200DELETEDROP GRAPH, orCLEAR DEFAULT200, or404if absentGET/HEADCONSTRUCT(HEAD: anASK) through the query route, so auth and read policy apply200, or404if absentOther statuses:
400for a request that names neither or both ofgraphanddefault, a system graph, or a malformed body.406when no format inAcceptis available.415for an unsupported body type.Behaviour
PUTandPOSTtake Turtle, N-Triples, TriG (the same rules as/sync) or JSON-LD.GETreturns JSON-LD or RDF/XML. CONSTRUCT has no Turtle output yet, so aGETthat accepts only Turtle or N-Triples is a406until the follow-up output PR.PUTbody clears the graph with noallowEmptyopt-in, as the protocol specifies. An emptyPOSTis a400.DELETEor an emptyPUT,GETis a404. The default graph always exists.GETandHEADask existence with anASKthrough the query route, so authentication and read policy answer before existence does. An unauthenticated read is a401whether or not the graph exists, and a graph with no triple the caller may see is a404.HEADstops at theASKrather than building the graph.GETis unpaged: it builds and serializes the whole graph, which the docs now say./data/*ledgeris one method router:getmerged withput/post/deleteunder the leader-forward layer./syncwithoutgraphsyncs the default graph, and?defaultsays so explicitly.fluree syncwithout--graphdoes the same. Previously a missinggraphwas a 400, so no working client changes behaviour.Implementation
fluree-db-transact:Txn.sync_graphis nowOption<GraphSel>; a default-graph sync scans g_id 0 with no graph Sid.parse_graph_insert, shared by sync and graph insert.fluree-db-api:SyncPayload(from feat(server): accept Turtle, N-Triples and TriG on /sync #1932) becomesGraphPayload { JsonLd, Rdf }, with sync'sallow_emptypassed separately.sync_graph_with(ledger, &GraphSel, GraphPayload, …),stage_graph_insert_tracked,graph_exists, and builder methodssync_graph_payload(graph, payload, allow_empty)andinsert_graph_payload.SyncGraphReport.graph_iriis nowOption<String>,Nonefor the default graph. Blank nodes in a default-graph sync use the skolem scope key@default.fluree-db-consensus:JsonLdGraphSyncandRdfGraphSynccarrygraph_iri: Option<String>. A queued entry written with a plain string still decodes, and a test covers that.GraphInsert { graph_iri, payload: GraphBody }, appended asBodyKindordinal 14 and handled by both committers.fluree-db-server:routes/graph_store.rs./synctakes the graph target (graph IRI,default, or none).execute_transactionandexecute_turtle_transactioncarry graph ops, andsubmit_sparql_updateis factored out forDELETE.ServerError::UnsupportedMediaType(415).fluree-db-cli:--graphis optional onfluree sync.docs/api/graph-store.md. Sync, endpoints, server-integration, CLI, compatibility, overview, Turtle and named-graph pages are updated.Known limitation
GETdoes not return edge annotations. The annotation's own triples come back, but not the link to its edge, because CONSTRUCT does not serialize RDF 1.2 annotations yet. AGETfollowed by aPUTof the result therefore drops those links. This is documented on the Graph Store page, and the fix belongs with CONSTRUCT's annotation output.Testing
API (
it_graph_scoped_writes.rs, 5 tests):graph_exists.HTTP (
graph_store_http.rs, 5 tests):PUT201 → identicalPUTwith no commit →GETin JSON-LD and RDF/XML → 406 →HEAD→POST→ a smallerPUTretracts →DELETE→ 404;PUT;GET ?defaultexcludes named graphs);401) and with a read-only one (404, withDELETEagainst a graph that exists), unauthenticated reads of present and absent graphs alike,HEAD, and an identity-scoped RDF/XMLGET.Plus
sync_route_targets_the_default_graph(omittinggraphbehaves the same as?default).Consensus: old-format decode, and the
GraphInsertround trip and hash.Raft:
graph_store_writes_forward_through_the_raft_queuesendsPUT/POST/DELETEthrough a follower.CLI:
sync_without_graph_targets_the_default_graph.Non-vacuity: each of these was broken on purpose and a test failed each time:
graph_exists;GraphInsertas a sync;/syncrequiring an explicit target;PUT/POSTwrite gate, and separately theDELETEone;Local runs:
grp_ledger/grp_transact/grp_misc/grp_import/backstop;raft;grp_http/grp_query/grp_policy/grp_raft;Lints: clippy with and without
raft, and fmt.Not run locally: the full workspace suite (CI),
testsuite-sparql(not touched), andfluree-db-docs, which passes 21 of 22 here; the one failure comes from gitignored design pages on this machine.The API, consensus and Raft suites were not rerun after the last change, which made
graphoptional on/syncand in the CLI and touched only server parameter handling and the CLI.Follow-up: #1931 (the Raft tests avoid resubmitting byte-identical keyless bodies).
Related: #1930.