fix(rest): derive the per-user settings key injectively (#270)#310
Merged
Conversation
The per-user settings key was `format!("{iss}|{sub}")`, which is not
injective: `(iss="https://idp", sub="a|b")` and `(iss="https://idp|a",
sub="b")` render identically, so two distinct principals shared one
settings document — mutual read and overwrite. Subjects containing `|`
are routine (Auth0/Cognito emit `google-oauth2|1076…`).
Derive the key as `u2:{iss_len}:{iss}:{sub}` instead. Length-prefixing
the issuer is unambiguous for any byte content and needs no reserved
delimiter. A NUL separator would also work in theory but not here:
PostgreSQL rejects U+0000 in TEXT, and `user_key` is a TEXT PRIMARY KEY.
`UserKey` becomes a private-field newtype with exactly two constructors
(`from_principal`, `local`) and no `From<String>`/`FromStr`/`Deserialize`,
so a colliding key cannot be hand-assembled. The auth-disabled key is now
the untypable `l2:` rather than `local|default`.
Documents written under the old encoding are adopted on first access and
removed from the old key, so upgrading does not orphan a user's theme and
saved queries. A batch migration is impossible by construction — deriving
the new key needs `iss` and `sub` separately, and the legacy key is
exactly the ambiguous string that cannot be split back apart — so this
runs lazily on the request path, where the real Principal is in hand.
Adoption is skipped when either component contains `|`: that document may
already be commingled between principals and must not be promoted.
The hit path stays a single read; the legacy key is consulted only on a
miss. Backend-agnostic, so SQLite, PostgreSQL, MongoDB and S3 are covered
identically with no schema change — `user_key` is opaque on all four.
Also fixes the If-Match handling on these endpoints, which shared the
blast radius:
- A malformed `If-Match` parsed to `None` — "no precondition" — silently
turning a request that asked to be conditional into an unconditional
last-writer-wins overwrite. It now fails the precondition (412). On
PATCH it additionally opted the request into the conflict-absorbing
retry loop, the opposite of what the caller asked for.
- `If-Match: *` was also `None`, so it blind-created a document rather
than asserting one exists (RFC 9110 §13.1.1).
- The endpoint emitted weak ETags, but If-Match requires strong
comparison (§8.8.3.2), under which a `W/` validator can never match —
the advertised optimistic-concurrency contract was unimplementable. It
now emits `"{n}"` and still accepts `W/"{n}"` from older clients. The
FHIR handlers keep weak ETags, which FHIR mandates.
Adds `SettingsStore::delete_settings` (all four backends) — needed to
move rather than duplicate a document, and the lifecycle the other three
methods already implied.
Hoists the two auth startup checks into `AuthConfig::validate()`. They
only existed in the hfs binary, so any other embedder of the library
crates could build an enabled config with no pinned issuer — and the
issuer is what qualifies a subject into a per-user identity.
Bumps EXPECTED_MINIO_SETTINGS_TESTS to 5 for the added MinIO test; that
guard fails the build on a count mismatch by design.
This was referenced Jul 20, 2026
Contributor
Author
|
Filed the out-of-scope findings from this PR as follow-ups:
#311 subsumes the private |
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
mauripunzueta
marked this pull request as ready for review
July 20, 2026 18:50
…ctivity # Conflicts: # crates/rest/src/extractors/user.rs
smunini
previously approved these changes
Jul 22, 2026
…ctivity # Conflicts: # crates/persistence/tests/minio_s3_tests.rs
smunini
approved these changes
Jul 22, 2026
smunini
approved these changes
Jul 22, 2026
smunini
approved these changes
Jul 22, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #270.
What was actually still broken
Two of the issue's four checkboxes had already landed on
mainand are left alone here:subis already rejected —crates/auth/src/provider/jwks_bearer.rsfilters empty and addssubtorequired_spec_claims.HFS_AUTH_ISSUERis already required —crates/hfs/src/main.rs, since5dda82ba9(the original auth PR). No deployment with auth on and no issuer has ever booted, so there is no compat cost to worry about.What remained: the non-injective key, and the
If-Matchnote at the bottom of the issue.The key
format!("{iss}|{sub}")is not injective —(iss="https://idp", sub="a|b")and(iss="https://idp|a", sub="b")render identically, so two principals shared one settings document. Subjects containing|are routine (Auth0/Cognito emitgoogle-oauth2|1076…).Now
u2:{iss_len}:{iss}:{sub}. Length-prefixing the issuer is unambiguous for any byte content and reserves no character. A\0delimiter was considered and rejected: PostgreSQL refusesU+0000inTEXTanduser_keyis aTEXT PRIMARY KEY, so it would fail at insert on one of the four backends.UserKeyis now a private-field newtype with exactly two constructors and noFrom<String>/FromStr/Deserialize, so a colliding key can't be hand-assembled. This deliberately diverges fromTenantId, which is freely constructible because tenant IDs legitimately come from config and headers — there's a note in the code so nobody "fixes" the inconsistency later.The auth-disabled key becomes
l2:, which no principal-derived key can equal.Migration — all four backends, no schema change
user_keyis an opaque primary key on SQLite, PostgreSQL, MongoDB and S3, so changing the derivation needs no DDL anywhere. What it would do is orphan every deployed document — includingrecentQueries, which holds FHIR search strings and therefore potentially names/MRNs/DOBs. Orphaned means unreachable and undeletable through any API, so leaving them was not acceptable.A batch migration is impossible by construction: deriving the new key needs
issandsubseparately, but the stored legacy key is exactly the ambiguous string that cannot be split back apart. (SettingsStorealso has no enumeration primitive.) So adoption runs lazily on the request path, where the realPrincipalis in hand. It's backend-agnostic, so all four are covered by one code path.Two safety properties:
|. That document may already be commingled between principals; promoting it would launder one user's settings into another's. Those callers correctly start empty.The hit path is still a single read — the legacy key is only consulted on a miss, which after first access never happens again for that user.
If-Match
The issue's closing note was right, and the surrounding code had more wrong with it:
If-Matchwas discarded..parse().ok()→None→ no precondition → unconditional last-writer-wins. A request that explicitly asked to be conditional silently became unconditional. Now 412. On PATCH it was worse:Nonealso opted the request into the conflict-absorbing retry loop.If-Match: *was treated as "no precondition" and blind-created the document. Per RFC 9110 §13.1.1 it asserts the resource exists, so it now 412s against an empty store. (update.rsalready got this right for FHIR routes.)If-Matchrequires strong comparison (§8.8.3.2), under which aW/validator can never match — a conformant client echoing our own ETag back would be 412'd forever. Now emits"{n}", still acceptsW/"{n}"from clients built against earlier releases. The FHIR handlers keep weak ETags, which FHIR mandates — that divergence is intentional and documented at both sites.The three assertions that encoded the old behavior were rewritten to assert the correct behavior, not deleted.
Also
SettingsStore::delete_settingsacross all four backends. Needed to move rather than duplicate a document, and it's the lifecycle the other three methods already implied (a document you can create should be erasable).AuthConfig::validate()hoists the two startup checks offmain.rsonto the type. They only existed in the binary, so any other embedder of the library crates could build an enabled config with no pinned issuer — andissis what qualifies a subject into a per-user identity.EXPECTED_MINIO_SETTINGS_TESTSbumped 4 → 5 for the added MinIO test. That guard fails the build on a count mismatch by design, so it needed updating with the test.Testing
|-bearing subjects, empty/multibyte issuers, local-key unforgeability, legacy-key gating; the fullIf-Matchtri-state;AuthConfig::validate.If-Matchon PUT and PATCH (asserting the write did not land),*against empty and populated stores, strong-ETag emission with weak still accepted, legacy adoption end-to-end, and adoption not clobbering an existing current document.delete_settingsidempotency for SQLite, PostgreSQL, MongoDB, MinIO/S3.Not compiled or run locally — this environment has no C linker, so build scripts can't compile. Everything here is
cargo fmt-clean and reviewed by hand; CI is the first real check. Draft for that reason.Deliberately out of scope
Found while working on this, each worth its own issue rather than growing this PR:
If-Matchis a comma-separated#entity-taglist and none of the four call sites split on it. Here a multi-tag header now 412s (safe); onupdate.rs/patch.rsit produces a permanent 412 (a live FHIR conformance bug). The fix belongs inConditionalHeaders.delete.rsignoresIf-Matchentirely — same defect class, on a destructive method.user_settingshas no tenant column on any backend, sopurge_tenant_dataprovably cannot reach PHI-bearingrecentQueries. Deliberate and documented as user-global, but it leaves tenant offboarding/erasure incomplete.validate_aud = falsewhenever no audience is configured — currently a startup warning; worth deciding if it should be more.