Skip to content

Add trusted policy delegation across SDK and server interfaces - #1804

Merged
bplatz merged 8 commits into
mainfrom
fix/trusted-policy-authorization
Sep 11, 2026
Merged

bplatz merged 8 commits into
mainfrom
fix/trusted-policy-authorization

Conversation

@bplatz

@bplatz bplatz commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Introduces an explicit authorization contract for applications and gateways. Embedded applications can supply a typed policy context, while network clients can use signed policy selections from configured delegation authorities.

Applies the selected context consistently across query formats, datasets, transactions, and supported transports. Adds structured authorization logging, expanded integration coverage, and a request-normalization benchmark.

Applications supplying policy selections should adopt the documented authorization contract. See the updated authorization and migration documentation for issuer/audience settings and transport support.

Compatibility notes:

  • Application-selected policies use the typed SDK context or signed delegation.
  • Storage-proxy access uses separate replication credentials.
  • Raft deployments submit writes through transaction endpoints; GraphQL reads remain supported.
  • Gateway-side migration and deployment checks remain separate from this database change.

Validation:

  • API policy and GraphQL integration suites, plus API/server/credential unit suites, passed.
  • Server HTTP, query, policy, storage-proxy, Bolt, configuration, logging, and live Raft-cluster checks passed, including transport checks with and without OIDC.
  • Request-normalization latency/allocation benchmark completed using the optimized dev-fast profile. It measures claim parsing and request binding, excluding cryptography, networking, and database policy evaluation.
  • Changed-source formatting and whitespace checks passed.

Introduce typed SDK authorization and scoped signed policy delegation. Bind request, dataset, and transport options to verified authority, preserve configured model controls, and enforce authorization through GraphQL mutations and read-back.

Add adversarial regressions and end-user authorization and configuration documentation. Validation: 1,804 tests passed, one ignored; default server build with Raft passes. Solo3 integration checks remain deferred.
Reject delegated policy tokens on storage-proxy endpoints and block GraphQL
mutations when Raft is active, preventing unsupported authorization handoffs
and local writes outside consensus. Preserve GraphQL reads.

Add opt-in structured authorization scope events without token or policy
payloads. Cover OIDC delegation, Bolt reauthentication, push rejection/retry,
CLI/TOML authority configuration, and follower-forwarded Raft queued writes.
Add a request normalization benchmark and update end-user documentation.

Validation: 533 test executions passed with OIDC/Raft, plus two transport
regressions without OIDC; formatting and whitespace checks passed. The
normalization benchmark completed using the optimized dev-fast profile.
Solo3 migration and integration checks remain deferred.
@bplatz
bplatz requested review from aaj3f and zonotope September 7, 2026 21:34
Publish the authorization guide through the documentation navigation and
register the policy benchmark budget and category. Apply Clippy formatting
and closure cleanups to the benchmark and authorization regressions.

Validation: full workspace Clippy with all features and targets passed;
benchmark registry check, 22 documentation tests in a tracked-file checkout,
and 11 authorization regression tests passed. Formatting and whitespace
checks 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.

@bplatz I'm pretty sure I'm in agreement with (and following) all of the work within this PR. The only thing I want to say as a human before we get to Claude's review sweep is that I spent a decent amount of time discussing this review with Claude because, in short, we've established in fluree/db a much more thorough and (rightfully) complex system and set of patterns for "data-centric security" than we ever had in v2/v3 of fluree/db. Which is to say, I think it's getting a little more difficult for Claude (or users, really... myself included) to reason over how policy SHOULD work (when does one scenario trump another; when should certain policy configs; etc). It may be worth, at some point, establishing more explicit policy design over how policy is intended to work, if only to give clarity to when certain patterns are "features not bugs" etc. That's not the scope of this PR and shouldn't prevent it from proceeding, but just want to comment on it now.

Claude-assisted review following:


This is carefully built, @bplatz, and it fixes something that needed fixing badly: at 603974fad any in-scope bearer could pick its own policy context through headers on the SPARQL/Cypher/GraphQL/UPDATE paths, through unstripped opts.policy / policy-values / alias keys on the JSON-LD path, or by sending SPARQL to the connection-scoped /query which ran with no policy at all — and a malformed opts block on a write yielded empty (root) governance. The single-resolution-point design (DataPrincipal.policy_authorization → bind_authorization → apply_to_jsonld) is the design I'd have wanted, it extends the existing GovernanceOptions / merge_policy_opts chain rather than bolting on a parallel one, the signed delegation fails closed with zero authorities and requires an audience, and the storage-proxy refusal is the right call. I'd ask for two things before merge, both verified at HEAD with throwaway tests: (1) /show/*ledger and the MCP sparql_query tool still build governance from principal.identity alone, so a narrowing delegation is silently widened to the identity's local f:policyClass on those two surfaces — the exact downgrade the docs and the storage-proxy change say cannot happen; and (2) representing scope-only service tokens as default_allow: Some(true) counts as a caller policy input, which (a) stops merge_policy_opts from applying a ledger's non-mandatory f:policyDefaults on writes — an anonymous update is denied by the configured class while the same update with a scope-only token commits — and (b) writes opts.identity: null that flips has_policy_opts, so scope-only clients now get 406 on CSV/TSV and leave the plain query path. Both (a) and (b) are regressions relative to the merge-base for existing service-account deployments, inside a security fix. Keeping scope-only tokens on empty governance (still stripping the caller's inputs) restores the base semantics for both. Separately, and not blocking: this should be titled and release-noted as a security fix, and the migration paragraph should name the silent symptom (identity tokens that relied on default-allow: true now see empty results) with its remedies.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ extends GovernanceOptions / merge_policy_opts / build_transact_policy_context; PolicyAuthorization is a thin, non-Deserialize wrapper; no parallel policy dispatch; shared IR untouched.
  • Performance (speed first, memory second): ✔ no hot-path or per-row change; bounded per-request clones and one JSON parse in apply_to_jsonld; bench registered in regression-budget.json + benches.md; ⚠️ scope-only requests silently move from the plain GraphDb path to the dataset/policy path (root wrapper, so no per-row cost) — resolved by the blocking fix above.
  • Testing: ✔ every new test is wired (grp_policy → policy_integration.rs:2188 → policy_authorization_regression.rs → policy_transport_regression.rs; grp_bolt, grp_query, grp_raft, telemetry_test, api grp_policy + lib), all run locally, and two enforcement points go red under mutation; ✖ no test covers /show or MCP with a delegated token, or scope-only tokens against config defaults / delimited output — which is how the three blockers got through.
  • Conventions: ✔ fmt and clippy -D warnings clean on the touched crates (with oidc,raft,credential,native,graphql); errors go through ServerError / ApiError, no unwrap on fallible paths; thorough multi-line commit bodies; docs and configuration reference updated. ⚠️ PR title/body do not say this is a security fix.

Verified locally at branch HEAD (1874fa4d4): cargo fmt --check clean; clippy -D warnings clean on fluree-db-server/-api/-credential with --all-targets; server --lib 174, grp_policy 52, grp_bolt 27, grp_query 101, grp_proxy 51, telemetry_test 6, grp_raft delegated_policy_survives 1 — all passing; api lib 44 + grp_policy 99 + grp_misc it_graphql* 58 passing; mutation of the authority allowlist → 2 tests red; mutation of constrain_options to honor caller inputs → 3 tests red; probes for the scope-only CSV 406 and the scope-only write past config defaults reproduce at HEAD.

Just be sure to get the /show + MCP downgrade and the scope-only governance shape in before this merges — both are small, and the second one restores exactly what the base did for service tokens. Happy to talk through the PolicyAuthorization::unrestricted() shape if you'd rather represent it differently.

/// before each statement.
pub expires_unix: u64,
/// Policy selection constructed from verified claims and server configuration.
pub policy_authorization: fluree_db_api::PolicyAuthorization,

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-server/src/extract/data_bearer.rs:47 — blocking. A delegated token is silently downgraded to identity-only policy on /show/*ledger and the MCP sparql_query tool. This PR adds policy_authorization to DataPrincipal and routes every query/transact/graphql/stream/push/Bolt path through it, but two data-reading surfaces still build governance from the bare identity: routes/show.rs:128-129 takes bearer.identity + data_auth.default_policy_class into graph_commit_builder.rs:279, and mcp/auth.rs:103-108 builds McpPrincipal { identity } from the same EventsTokenPayload (which now parses fluree.policy) so mcp/tools.rs:198-201 wraps with GovernanceOptions { identity } only.

Consequence: a gateway issues fluree.policy: {"policy-class": ["ex:Employee"]} for sub = ex:alice, but alice's local record carries f:policyClass ex:Manager. Every query route evaluates her as Employee (correct); GET /v1/fluree/show/<ledger>?commit=t:N and the MCP SPARQL tool evaluate her as Manager and return the flakes the delegation withheld. That is the "silently downgraded to an ordinary token" outcome docs/security/policy-authorization.md:67 says is rejected, and the outcome this PR correctly refuses on the storage proxy (extract/storage_proxy.rs:113).

Fix: in show.rs replace the two locals with principal.policy_authorization.options() (the builder already takes identity/class; it needs the full GovernanceOptions, or wrap the decoded commit the way the executor wraps read-back), and in mcp/auth.rs either thread the selection through or reject payload.fluree_policy.is_some() exactly as the storage-proxy extractor does. A regression test with a narrowing delegation against a wider local assignment would pin both. Commenting here because show.rs and mcp/auth.rs are 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.

Address in 61cadaf

fluree_db_api::GovernanceOptions {
identity: payload.resolve_identity(),
policy_class: config.default_policy_class.map(|c| vec![c]),
default_allow: scope_only.then_some(true),

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-server/src/extract/data_bearer.rs:222 — blocking. Materializing a scope-only service token as default_allow: Some(true) widens it past ledger-configured policy defaults on writes — verified. has_any_policy_inputs() counts Some(true) as a caller policy input (fluree-db-api/src/dataset.rs:903-909), so merge_policy_opts skips filling the ledger's f:policyClass (config_resolver.rs:398-402) and build_transact_policy_context then builds a root wrapper (no explicit inputs, no restrictions). At the merge-base a scope-only token carried empty governance (apply_auth_identity_to_opts returned early with no bearer identity), so config defaults governed it exactly like an anonymous request.

Repro at HEAD (temporary test, removed): ledger #config with f:policyDefaults { f:defaultAllow true ; f:policyClass ex:EmployeeClass }, a deny-f:modify-on-ex:content policy in that class, f:overrideControl left at its AllowAll default (fluree-db-core/src/ledger_config.rs:272-279). POST /v1/fluree/update/<ledger> rewriting ex:content: anonymous → 400 Employees may not modify document content.; the same body with a scope-only bearer (read+write scopes, no sub/fluree.identity) → 200, committed at t=5. policy-authorization.md:7 describes this ("subject to mandatory ledger configuration"), but it is a fail-open change for every deployment that governs service accounts through non-mandatory f:policyDefaults, and it lands inside the security fix.

Fix: keep scope-only tokens on empty governance rather than default_allow: Some(true) — e.g. a PolicyAuthorization::unrestricted() / scope_only flag whose constrain_options / apply_to_jsonld install no policy inputs (still stripping the caller's), so merge_policy_opts fills config defaults as it did at the base and the read path stays root as before. Then pin it: scope-only token vs. a ledger with permissive config defaults, on both the update and the query route.

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.

Address in 61cadaf

] {
opts.remove(alias);
}
opts.insert("identity".into(), serde_json::to_value(&options.identity)?);

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-api/src/authorization.rs:98 — blocking. The canonical identity: null flips the server's has_policy_opts gate, so scope-only tokens lose delimited output and the plain query path — verified. apply_to_jsonld always inserts opts.identity (as null when there is no identity); routes/query.rs:308-315 tests opts.get("identity").is_some(), which is true for Null; routes/query.rs:2024-2030 then returns 406 CSV format not supported for identity-scoped queries and routes everything else onto the dataset/policy path.

Repro at HEAD (temporary test, removed): POST /v1/fluree/query/<ledger> with Accept: text/csv — anonymous → 200 with three CSV rows; the same request with a scope-only read token → 406. At the merge-base the token's opts were untouched and the request served CSV from the plain GraphDb path. The same gate governs stream_query.rs:405.

Fix: either make has_policy_opts ignore null values (.is_some_and(|v| !v.is_null())) or, together with the previous item, stop writing policy keys for a scope-only authorization. The nulls are deliberate for the multi-query envelope shadowing (query/multi/mod.rs:770-793), so the has_policy_opts change is the smaller of the two. Commenting on the insert because query.rs:308 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.

Address in 61cadaf

Comment thread docs/security/policy-authorization.md Outdated

To measure request binding locally, run `cargo bench -p fluree-db-api --features credential --bench policy_authorization`. The benchmark compares ordinary and delegated claims selecting the same policy class, with simple and multiple-source requests. It reports latency and allocation bytes, including tracking-allocator overhead. It excludes signature verification, issuer lookup, networking, and database policy evaluation, so its results describe normalization cost rather than end-to-end query latency. Set `CRITERION_HOME` to choose the results directory.

Applications that relied on policy-free identities to override policy headers must migrate to explicit contexts. Embedded applications construct typed contexts after resolving user grants. HTTP gateways issue scoped tokens and configure the receiving server's issuer, policy-authority, and audience settings. Preserve the selected governance through queued writes and credential forwarding. Cluster transport authentication is configured independently of policy delegation.

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.

docs/security/policy-authorization.md:85 — optional. I don't think an operator upgrading a stack with data auth + policies will get from this paragraph to what they'll actually see, which is silent: an identity-bearing token that used to pass default-allow: true in the body or the fluree-default-allow header now returns empty results and 400s on writes, with no error saying why. It seems worth naming that symptom and the three remedies in one breath — ledger f:defaultAllow true still fills an unset default (config_resolver.rs:390-392), a scope-only token, or a delegation — and the PR title / release note should say "security fix" so the release-notes reader knows to look. Minor and non-blocking, but if you agree I'd rather see it folded in here than rediscovered on a support call.

Comment thread docs/security/policy-authorization.md Outdated

The signature covers the selection and its ledger/action scopes, audience, and expiry. The existing token verifier checks those claims; the policy-authority allowlist adds a separate receiver-side capability check. Invalid delegation is rejected rather than silently downgraded to an ordinary token. The receiver trusts an authorized issuer to issue grants within the server's existing issuer/scoping model; it does not independently re-evaluate the gateway's application grants. Do not designate a general login issuer as a policy authority unless it controls these claims appropriately.

This same selection is used by JSON-LD, SPARQL, Cypher, GraphQL, streaming queries, multi-query aliases, transaction routes, push ingestion, and Bolt sessions. Query source and envelope options cannot replace it. The token authorizes a uniform selection over its signed scopes, not a map of different policy sets per ledger.

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.

docs/security/policy-authorization.md:69 — optional. Once the /show / MCP item is settled, this transport list should say what those routes and /log do with a delegated token (/log is read-scope-only metadata today, so "not applicable" is a fine answer). Fold-in-now if you agree.

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.

Address in 61cadaf

let tracking = tracking_options_from_body(&body);
let governance = GovernanceOptions::from_json(&body).unwrap_or_default();
let governance =
GovernanceOptions::from_json(&body).map_err(|e| ServerError::bad_request(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.

fluree-db-server/src/routes/transact.rs:247 — prepare_transaction_body no longer does unwrap_or_default() on governance; a malformed opts.policy-class was a silent root write before and is a 400 now. This is the kind of fail-open that hides for years.

}
if let Some(ref classes) = policy.policy_class {
merged.policy_class = Some(classes.clone());
// Denying an override must clear *all* caller-selected grants, even

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-api/src/config_resolver.rs:372-382 — a denied override finally clears inline policy / policy_values instead of keeping the caller's grants under a "denied" banner. Pinned by denied_override_clears_inline_classes_values_and_permissive_defaults.

pub policy: Option<serde_json::Value>,
pub policy_values: Option<std::collections::HashMap<String, serde_json::Value>>,
pub default_allow: Option<bool>,
}

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-credential/src/jwt_claims.rs:118-128 — deny_unknown_fields plus the explicit null rejection on fluree.policy is the right shape: a present-but-malformed delegation must not quietly become a scope-only credential.

.fluree
.query_from()
.sparql(&sparql)
.connection_opts(qc_opts.clone())

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-server/src/routes/query.rs:714 — connection-scoped SPARQL is policed for the first time; the base stream_query.rs comment admitting it "runs unpoliced" was a standing bypass.

impl DataAuthConfig {
/// Validate configuration at startup
pub fn validate(&self) -> Result<(), String> {
if !self.policy_authorities.is_empty() && self.audience.as_deref().is_none_or(str::is_empty)

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-server/src/config.rs:102-105 — requiring an audience whenever an authority is configured (validated at startup and again per token) closes the obvious cross-server replay of a gateway token.

…inding

Rename the CLI flag to --policy-select so the flag, the "fluree.policy":
"request" claim, and the docs share one term.

Move header governance resolution out of query.rs into
policy_auth::bound_governance, and pass the verified signed identity to
bind_authorization instead of the whole credential. Push and commit show
now bind through the same helper as every other route rather than
calling resolve_options themselves.

Split GovernanceOptions::selects_policy_set from has_any_policy_inputs so
merge_policy_opts names the narrower override-control predicate instead
of restating it inline: a deny default alone engages enforcement but does
not replace the configured class selection.

Document the remaining user-visible behavior changes: default-allow:false
as an enforcement input, policy-class: [] as an explicit empty selection,
400 on malformed identity/default-allow, and policy headers acting as
JSON-LD transaction defaults without tracking.
Config graph reads no longer fall back to system defaults on error; an
unreadable config graph could otherwise run a request unrestricted on a
ledger with a configured deny default. A successful read that finds no
config is cached on the view as absent, and as_of/with_graph_id clear
that cache so a different snapshot resolves anew.

The virtual-source crawl intercept executed before policy was bound, so
a wildcard subgraph crawl over an Iceberg or SQL source bypassed the
builder's authorization. Load the source view and apply the prebuilt or
source/global policy before expanding.

Explain on the ledger and connection routes used header-bound
governance, which is empty for request-selected credentials; use the
finalized body selection instead. Policy-scoped explains now withhold
ledger and annotation statistics and mark the plan as heuristic.

An explicit deny-all selection (empty classes, deny default, no inline
rules) short-circuits config merging so locked ledger defaults cannot
widen it; from_trusted_options emits that shape for empty host input so
it survives JSON and consensus serialization.

Add the policy_http server bench with its regression budget, document
the fail-closed and scoped-explain behavior, and fix clippy lints in
the new tests.
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.

2 participants