Repository navigation
fix(server): honour SPARQL Protocol dataset parameters - #1928
Conversation
0704940 to
bf1252d
Compare
bf1252d to
6ce0985
Compare
aaj3f
left a comment
There was a problem hiding this comment.
This is really nice, @bplatz. Given the problem, I was at first a little surprised to see the work being done against the actual query text, rather than lower at dataset construction etc, but then as I thought about things like policy-scoping, consensus abstraction, etc. it made more sense and I think seems to be the right design. No real notes there. Claude helped me find a more mechanical build issue with the sql feature on fluree-db-server, but other than that, no standout notes. Full review below:
The design and work here is sound. I mutated protocol.rs:95 from replace to append and protocol_dataset_replaces_the_query_dataset goes red with the old FROM clauses still there, so §2.1.4's precedence rule is genuinely pinned. I also probed the failure mode that would have made this blocking — a multi-byte character before the insertion point panicking a byte-indexed splice — and it's fine.
The blocker is mechanical rather than a design problem. In routes/mod.rs the new mod sparql_protocol; went in between the existing #[cfg(feature = "sql")] and the mod sql; it was attached to, so sparql_protocol is now gated behind sql and sql is ungated. cargo check -p fluree-db-server --no-default-features --features native gives 17 errors at this head; move the attribute back down one line and it gives 1, and that one is pre-existing. Every build without sql is broken, and CI can't see it because clippy and test are both --all-features and the only --no-default-features jobs are wasm32 ones that don't build the server crate.
The other thing I'd like recorded somewhere, even if it's just a line in the body: the old serde_urlencoded(...).ok().unwrap_or_default() on the update routes meant a single repeated key silently dropped ledger and dryRun together — so a dry run became a real write. That's a live data-affecting bug this PR fixes, and it's currently a sub-bullet.
Everything else is optional: the dataset replacement also discards FROM … TO … and @t: pins silently, reject_outside_sparql is wired on two of seven write routes, and one defensive branch fails open where an error would do.
Adherence to repo commitments:
- Patterns/abstractions: ✔
SparqlParamsbecomes an extractor following the existingevents.rshand-parse pattern, the strict decoder is shared rather than duplicated, and the rewrite lives in the SPARQL crate as pure functions over spans the parser already records.⚠️ only for the#[cfg]placement above. - Performance (speed first, memory second): ✔ both entry points return
Cow::Borrowedbefore parsing when no dataset parameters are present, so the uninvolved request is unchanged; the extra parse falls only on requests that opted in; no engine or operator-loop code touched. No performance-degradation risk. - Testing: ✔ 18 HTTP tests wired through
grp_query.rs:20-21(andharness_coveragemakes that wiring enforced, not remembered) plus 10 unit tests inprotocol.rs, all 10 of which I ran by name. W3C skip/ignore registers unchanged.⚠️ nothing in the suite would have caught the feature-gate break, which is the coverage gap the blocker exposes. - Conventions: ✔ thorough multi-line commit body that names the mechanism and the deviation, self-describing subject,
docs/api/endpoints.mdupdated for both parameter families in the same PR, stale "USING is rejected" comments corrected rather than left to rot.
Verified locally at bf1252dd0: cargo check -p fluree-db-server --no-default-features --features native → 17 errors → 1 after moving the #[cfg]; cargo nextest run -p fluree-db-sparql -E 'test(protocol)' → 10/10 pass; mutation of protocol.rs:95 → the precedence test goes red; multi-byte splice probe passes. Mutations reverted and the worktree left clean. CI is green at that SHA on test, clippy, fmt and testsuite-sparql — which, per the blocker, is exactly the problem.
Requesting changes just for the one-line mod.rs move — everything else can ride along or not, as you prefer. Happy to talk through any of it.
| pub(crate) mod serving; | ||
| mod show; | ||
| #[cfg(feature = "sql")] | ||
| mod sparql_protocol; |
There was a problem hiding this comment.
Blocking — this mod sparql_protocol; landed between the existing #[cfg(feature = "sql")] and the mod sql; it belonged to, so the attribute now gates the wrong item.
sparql_protocol is behind the sql feature and sql is unconditional. query.rs, transact.rs and events.rs all reference super::sparql_protocol::… with no cfg, and sql.rs references fluree_db_api::SqlCreateConfig, validate_sql_endpoint, create_sql_graph_source and friends that only exist under fluree-db-api/sql. So the crate builds only when sql is on.
cargo check -p fluree-db-server --no-default-features --features native at this head gives 17 errors. Moving the attribute back down one line gives 1, and that one (iceberg_ssrf.rs:22, guard_iceberg_connection_urls) is pre-existing — mod iceberg_ssrf; has always been ungated. So 16 errors are introduced here, and every build that has iceberg but not sql is broken; the feature comments present exactly that kind of trimmed build as supported ("builds that do not read Delta tables can drop it with default-features = false").
Nothing in CI can see it: ci.yml:82 and :119 are both --all-features, and the only --no-default-features jobs are the two wasm32 ones, which never build fluree-db-server.
The three lines want to read:
mod sparql_protocol;
#[cfg(feature = "sql")]
mod sql;There was a problem hiding this comment.
Fixed in 68e6dd7. The attribute is back on mod sql;. cargo check -p fluree-db-server --no-default-features --features native,iceberg is now clean, and your native-only command gives just the pre-existing iceberg_ssrf error.
There was a problem hiding this comment.
Also closed the gap that hid it, in 0c3a3a2. The clippy job now has a cargo check -p fluree-db-server --no-default-features --features native step, which fails with the same 17 errors when the attribute is put back where it was. For that build to compile I also gated iceberg_ssrf on iceberg, which clears the pre-existing error.
|
|
||
| let clause = dataset_clause("FROM", default_graphs, named_graphs); | ||
| let (start, end, replacement) = match dataset { | ||
| Some(existing) => (existing.span.start, existing.span.end, clause), |
There was a problem hiding this comment.
Optional. I may be wrong about how much this matters in practice, but replacing existing.span.start..existing.span.end also swallows the two Fluree extensions that live inside a FROM clause: the FROM <from> TO <to> history range (DatasetClause.to_graph) and an @t: snapshot pin carried in the IRI itself — collect_sparql_min_t_requirements (fluree-db-server/src/routes/query.rs:1873-1884) reads both out of exactly that clause.
So GET /query?default-graph-uri=books:main over SELECT … FROM <books:main@t:100> WHERE … silently stops being a pinned-snapshot read and becomes a current-head read. Spec-wise the replacement is correct — §2.1.4 says the protocol dataset wins — but the user probably only meant to name a graph, and for a time-travel database "your @t: quietly disappeared" is a rough way to find out.
Cheapest fix is probably to carry the qualifiers forward when the protocol values name the same ledger; failing that, a 400 when dataset.to_graph.is_some() or any default_graphs IRI contains @t:/@commit: at least makes it loud. Minor and non-blocking — but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
There was a problem hiding this comment.
Agreed. I went with refusing rather than carrying the qualifiers forward, since that gets ambiguous once there are several graphs and §2.1.4 says the protocol dataset wins outright. When the FROM being replaced has a TO range or an @t: / @time: / @iso: / @recorded: / @commit: / @snapshot: suffix, it is now a 400 telling the caller to put the pin on the parameter value, which works (default-graph-uri=books:main@t:100). There is a unit test over all four shapes, which fails with the check disabled, and an HTTP test. docs/api/endpoints.md says the same.
| maybe_rewrite_form_encoded_update(&mut credential); | ||
| maybe_rewrite_form_encoded_update(&mut credential, &mut query_params.using)?; | ||
| if !credential.is_sparql_update() { | ||
| query_params.using.reject_outside_sparql()?; |
There was a problem hiding this comment.
Optional. using.reject_outside_sparql() is wired on update_local and update_ledger_local, but insert_local (:970), upsert_local (:1123), sync_local (:1291) and the two *_ledger_local siblings (:1464, :1618) call extract_query_params and then never consult query_params.using. Those routes don't take SPARQL UPDATE at all, so using-graph-uri there is meaningless either way — but the PR's own rule is "refuse rather than silently ignore", and right now it holds on two of seven write routes. A reject_outside_sparql() right after extract_query_params on each of the others would make it uniform. Same fold-it-in-now caveat.
There was a problem hiding this comment.
Done. reject_outside_sparql() now follows extract_query_params on all five of those routes. There is an HTTP test that an insert with using-graph-uri is a 400 and writes nothing; with the call removed, the insert returns 200.
| return Err(ProtocolDatasetError::UsingConflict); | ||
| } | ||
| // The parser always records it; a hand-built AST cannot reach here. | ||
| let Some(where_keyword) = modify.where_keyword else { |
There was a problem hiding this comment.
Optional (nit). let Some(where_keyword) = modify.where_keyword else { return Ok(Cow::Borrowed(update)) } fails open on a write path: if a Modify ever reached here without the span, the USING clauses would be silently dropped and the update would run unscoped against the default graph — the same outcome the DELETE WHERE arm three lines down refuses precisely because it's dangerous.
The comment is right that it's unreachable today (only parse/query/update.rs:431 and :468 build a Modify, and both set it), so this is genuinely a nit. But since it costs nothing, I'd rather the defensive branch be an error variant than a silent pass-through. It's minor — if you disagree on the substance, happy to leave it.
There was a problem hiding this comment.
Agreed. It now returns a new UnlocatedWhere error instead of passing the update through unscoped.
| format!("{clause} "), | ||
| )); | ||
| } | ||
| UpdateOperation::DeleteWhere(_) => { |
There was a problem hiding this comment.
Optional (framing, not code). The body calls the DELETE WHERE refusal "our choice; the spec doesn't address it". I'd put it slightly differently, because I think the next person to read §2.2.3 will land somewhere else: the spec's MUST-reject rule is about operations that contain USING/USING NAMED/WITH, and a DELETE WHERE contains none — so a literal reading says the protocol dataset ought to scope it, and it's only the grammar (plus the fact that we apply the dataset by rewriting text) that stops us. Refusing is clearly the right call versus running it unscoped, and docs/api/endpoints.md documents it. I'd just record it as a deliberate deviation rather than a silence in the spec, so nobody "fixes" it later.
There was a problem hiding this comment.
Fair. The description now records it as a deliberate deviation: a literal reading of §2.2.3 says the parameters should scope it, and only the grammar plus our text rewrite prevents that.
| /// `FROM` / `FROM NAMED` (Protocol §2.1.4: the protocol dataset takes | ||
| /// precedence), so every consumer of the text — auth scoping, `min-t`, ledger | ||
| /// refresh, execution — sees the same dataset. | ||
| pub(crate) fn resolve_sparql_text( |
There was a problem hiding this comment.
Praise. Applying the dataset by rewriting the text before anything else touches it is the call I'd have argued against going in, and I think it's right here for a reason specific to this codebase: the query text is what bearer ledger scoping (:771), min-t collection (:785), ledger refresh, the warning headers and — for an update — consensus and the transaction log all consume. Rewriting once means none of them needs teaching about the parameters, and the transaction log records an update whose text actually describes what ran. I traced every body_string() in query.rs and stream_query.rs to check the claim; the only SPARQL-bearing ones are the two resolve_sparql_text sites.
| /// repeated key made the struct parse fail — which, swallowed, dropped every | ||
| /// parameter, `ledger` included. A malformed parameter is now a 400 instead of | ||
| /// silently becoming "no parameters". | ||
| fn extract_query_params(request: &Request) -> Result<TransactQueryParams> { |
There was a problem hiding this comment.
Praise, and worth promoting out of a sub-bullet. The old serde_urlencoded::from_str(q).ok().unwrap_or_default() meant one repeated key anywhere in the query string dropped every parameter — including ledger and dryRun. So a request that asked for a dry run and happened to repeat a key became a real write. That's a live, silent, data-affecting bug on main, and it's buried under "Update-route params" in the description. It deserves its own line in the PR title or body so it doesn't get read as a conformance-only change.
| urlencoding::decode(&raw.replace('+', " ")) | ||
| .map(std::borrow::Cow::into_owned) | ||
| .map_err(|e| reject(&e.to_string())) | ||
| super::sparql_protocol::percent_decode_strict(raw).map_err(|why| reject(&why)) |
There was a problem hiding this comment.
Praise. Lifting the strict percent-decoder into the shared module instead of leaving a second copy behind is the right instinct, and the doc comment on percent_decode_strict explaining why verbatim passthrough of a malformed escape is dangerous ("a graph IRI that silently kept its raw escapes would name a graph that does not exist") is the kind of comment that survives.
f939a4e to
2dc4fd9
Compare
69c1691 to
7d0884c
Compare
7d0884c to
520f420
Compare
|
@aaj3f thanks. Everything is in 68e6dd7, and I've replied on each thread:
In the description, the dry-run bug now has its own paragraph in Problem, and |
default-graph-uri was parsed and discarded, named-graph-uri, using-graph-uri, and using-named-graph-uri were not recognised, and a repeated parameter — the protocol's way of naming a second graph — was a 400 "duplicate field" from serde_urlencoded. On the update routes a repeated key made the whole query string unparseable, which silently dropped every parameter, ledger included. Query routes now collect default-graph-uri / named-graph-uri from a hand-parsed query string and apply them by replacing the query's FROM / FROM NAMED (Protocol §2.1.4: the protocol dataset takes precedence), so auth scoping, min-t waits, ledger refresh, and execution all read one dataset. Update routes collect using-graph-uri / using-named-graph-uri from the URL or a form-encoded body and write them into every DELETE/INSERT … WHERE as USING / USING NAMED before the text reaches consensus. An operation that already has USING, USING NAMED, or WITH is a 400 (§2.2.3), as is DELETE WHERE, which has no USING form. On JSON-LD requests the parameters are a 400 instead of being ignored. Query routes also accept the protocol's form-encoded POST (§2.1.2): query=… with the dataset parameters in the body. The rewrite is span-based (fluree_db_sparql::protocol). The parser now records where a DESCRIBE's dataset clause and an update operation's USING clauses belong, and the CONSTRUCT WHERE shorthand's span starts at WHERE like every other form.
…rrides `mod sparql_protocol;` had landed between `#[cfg(feature = "sql")]` and `mod sql;`, so the attribute gated the new module and left `sql` ungated. Every server build without the `sql` feature failed to compile. Protocol dataset follow-ups from review: - default-graph-uri / named-graph-uri no longer replace a FROM that pins a time (`FROM … TO …`, or an @t:-style suffix). Replacing it silently turned a snapshot read into a current-head read; it is now a 400 that says to put the pin on the parameter value. - using-graph-uri / using-named-graph-uri are refused on the insert, upsert and sync routes too, not only on the two update routes. - A Modify without a recorded WHERE position is an error rather than an unscoped update.
68e6dd7 to
d4da593
Compare
Clippy and nextest both run --all-features, so a server module behind the wrong #[cfg] compiles in CI and breaks every trimmed build. The misplaced `sql` gate earlier in this PR was exactly that. A new step checks `fluree-db-server` with only `native`. That build also needed `iceberg_ssrf` gated on `iceberg`. It was always ungated, while its only callers (the iceberg, delta and sql routes) all require the feature.
Problem
The W3C SPARQL 1.1 Protocol defines how a request names its dataset outside the query string:
default-graph-uriand zero or morenamed-graph-uri(§2.1.4).using-graph-uriand zero or moreusing-named-graph-uri(§2.2.3).None of them worked:
default-graph-uriwas parsed and discarded; the field was#[expect(dead_code)]inroutes/query.rs.named-graph-uri,using-graph-uriandusing-named-graph-uriweren't recognised.serde_urlencoded.ledgerincluded.A dry run could become a real write. That dropped-parameters bug is live on
mainand not just a conformance gap:dryRunwas dropped along with everything else, so a request that asked for a dry run and happened to repeat any query key committed its changes.Fix
Queries.
SparqlParamsis now an extractor that hand-parses the query string, following the same pattern asevents.rs, so repeated keys are collected.resolve_sparql_textapplies the dataset by replacing the query'sFROM/FROM NAMED, or inserting one. §2.1.4 says the protocol dataset takes precedence. The one exception is aFROMthat pins a time (FROM … TO …, or an@t:-style suffix): replacing it would silently turn a snapshot or history read into a current-head read, so that is a 400 that says to put the pin on the parameter value.min-twaits, ledger refresh, execution and the warning headers./query/{ledger}the values name graphs within that ledger; on/querythey name ledgers. This is the existing meaning ofFROMon each route, so/query?default-graph-uri=books:mainnow works where aFROMwas previously required.Updates.
using-graph-uri/using-named-graph-uriare collected from the URL, or from the body for the form-encoded transport. They're written into everyDELETE/INSERT … WHEREasUSING/USING NAMEDbefore the text reaches consensus, so the transaction log records the scoped update.USING,USING NAMEDorWITH→ 400 (§2.2.3).DELETE WHERE→ 400. This is a deliberate deviation. §2.2.3 only requires rejecting operations that containUSING,USING NAMEDorWITH, andDELETE WHEREcontains none, so a literal reading says the parameters should scope it. But its grammar has noUSINGform, and we apply the parameters by rewriting the text, so there is nowhere to put them. Running it unscoped would delete from the wrong graph.Form-encoded query POST (§2.1.2). Query routes now accept
application/x-www-form-urlencodedwithquery=…, plus the dataset parameters, in the body. Before, the body was taken as raw SPARQL and failed to parse.querymay appear only once across both.update=sent to a query route is refused as an update.Non-SPARQL requests. The dataset parameters on a JSON-LD query or update are now a 400 instead of being silently ignored. JSON-LD names its dataset with
from/fromNamed. Theusing-*parameters are also a 400 on the insert, upsert and sync routes, which take no SPARQL UPDATE.Update-route params.
extract_query_paramsnow builds from the decoded pair list. As a consequence, a malformed or repeatedledger/graph/dryRun/allowEmptyis now a 400 rather than silently becoming "no parameters". FordryRunthat matters: previously a bad value turned a dry run into a real write.Implementation
fluree_db_sparql::protocolholdsapply_query_datasetandapply_update_using. They're span-based: parse the text, then replace or insert clauses at positions the parser recorded. Text that doesn't parse is returned unchanged, so the normal path reports the syntax error. Parser changes:DescribeQuery.dataset_offsetrecords where the dataset clause goes when a DESCRIBE has no WHERE clause.Modify.where_keywordrecords whereUSINGclauses end.CONSTRUCT WHERE { … }shorthand'sWhereClausespan now starts atWHERE, like every other form. It started at{, which would have put an insertedFROMbetweenWHEREand{.routes/sparql_protocol.rsholds the strict percent-decoder, now shared withevents.rs, and the pair parsing.Stale comments claiming
USING/USING NAMEDwere rejected or unsupported are corrected. Staging already honours both, andit_named_graphs.rscovers them.CI
A new step in the clippy job,
cargo check -p fluree-db-server --no-default-features --features native, builds the server with no optional features. Every other server build in CI is--all-features, so a module gated by the wrong#[cfg]was invisible. An earlier revision of this PR shipped one, and this step fails on it with 17 errors. Getting that build to compile also meant gatingiceberg_ssrfoniceberg: it had always been ungated, though its only callers all require the feature.Tests
fluree-db-server/tests/sparql_protocol_dataset_params.rshas 20 HTTP tests:FROM;ledger;FROMandusing-graph-urion an insert route.The first 14 (all but the form-encoded query ones) fail against the pre-change source, including the rejection cases: those previously succeeded silently, and the
USINGconflict wrote data. Disabling form-query handling fails the four form-query tests. The refusal test asserts that the error points at the update endpoint, so it doesn't pass just because the body is unparseable.fluree_db_sparql::protocolhas 11 unit tests covering every query form, replacement, a time-pinned dataset, IRI validation,USINGon every modify operation, the conflicts andDELETE WHERE. TheCONSTRUCT WHEREcase fails if the span fix is reverted.Run locally, all green:
fluree-db-sparqlandfluree-db-transact;grp_query,grp_http,grp_policy,grp_proxy,harness_coverage;testsuite-sparql.Not run locally: the full
fluree-db-apisuite and the other server groups (raft, bolt, search). CI covers them.Not in this PR
Other protocol-surface gaps found while doing this: