Skip to content

fix: host-aware domain routes, bare-word in:, bounded shutdown, JWT revocation, and boot-time service bindings - #12

Merged
vheins merged 11 commits into
rustasea:masterfrom
gitfromwildan:fix/foundation-and-correctness
Nov 21, 2026
Merged

vheins merged 11 commits into
rustasea:masterfrom
gitfromwildan:fix/foundation-and-correctness

Conversation

@gitfromwildan

Copy link
Copy Markdown
Contributor

Summary

Fixes four places where an existing feature behaved wrongly, and adds the database, cache, and queue bindings that M0 listed as missing. Ordered bottom-up so later milestones can build on them: the M4 scheduler needs the queue binding to dispatch, and the scaffold work in M3 needs the database one.

Seven commits, one per scope. Each commit message has the detail; this description covers what the commits cannot say on their own.

Changes

Commit Effect
fix(router): match domain routes against the request host A route under Router::domain answered every host and made the catch-all on the same method+path unreachable. Requests are now routed by Host.
fix(validation): accept bare words in in: and in_array: lists in:admin,editor rejected every value.
fix(foundation): bound the shutdown drain by its timeout graceful(timeout) ignored its timeout, so a stuck request could hold shutdown open forever.
fix(auth): revoke JWT pairs on logout and make refresh tokens single-use JwtGuard::logout did nothing, and a refresh token could be replayed.
feat(rustasea): bind database, cache, and queue services at boot New rustasea::services providers bind a ConnectionResolver, a CacheManager, and the queue connections.
feat(app): register the framework service providers at boot The runnable app uses them.
docs: record the foundation and correctness fixes docs/milestones.md, docs/laravel-parity.md, the module task rows, and the changelog.

Behaviour changes

  • Domain routes: a request whose host matches no domain route now reaches the route without a domain, or gets 404 if there is none. Matching ignores case and the port; a {name} label matches one DNS label, but its value is not exposed as a route parameter. The existing test in tests/dispatch.rs asserted the old behaviour and was updated.
  • Shutdown: after SIGTERM/SIGINT, if draining takes longer than the timeout (30 s through Application::shutdown), the process exits with status 1. Callers keep the same API, so generated apps get this too.
  • JWT: tokens carry a new optional sid claim shared by an access/refresh pair. logout revokes the pair; refresh revokes the old pair atomically before issuing the new one, so a client that retries a refresh with the same token now gets InvalidToken. Revocations are kept in a cache Store, per-process memory by default; JwtGuard::with_revocation_store takes a shared store for multi-process deployments. An unreadable store fails closed with StoreUnavailable. Tokens issued before sid existed still verify and are revoked individually.
  • in: / in_array:: each item is read as JSON when it parses and as text otherwise. Bare numbers stay numbers, so matching is still strict on type.
  • Boot: QueueServiceProvider records the configured default queue connection; with an empty [queue] table it registers nothing, as before.

Testing

Run on rustc 1.100.0, the toolchain CI uses:

  • cargo xtask ci passes.
  • cargo test --workspace --no-fail-fast passes (190 suites, 1977 tests), as does cargo test -p rustasea-storage --features aws,sftp.
  • Cargo.lock is unchanged and cargo metadata --locked passes.
  • New tests: host dispatch (crates/rustasea-router/tests/host_dispatch.rs and unit tests in host.rs), bare-word in:, the shutdown deadline, five JWT revocation cases, and three service-provider cases (crates/rustasea/tests/services.rs).
  • Shutdown checked against the running app: with an unfinished request held open, the process exits 31 s after SIGTERM and logs why; with nothing in flight it exits at once.
  • The app boots with the new providers, logs that the database queue connections were registered, and serves GET / with 200.

Not covered

  • The scaffold templates do not register the new service providers yet, so generated apps get the shutdown and routing fixes but not the bindings.
  • JWT revocation through Redis was not run against a live server; only the in-memory store and a shared in-memory store are tested.
  • The queue dashboard and the database user provider still open their own pool instead of using the bound resolver.

@vheins, could you review this?

A route declared under Router::domain answered every host: dispatch kept only
the first route per method+path, so a domain route shadowed the catch-all for
all requests and the catch-all was unreachable.

Routes sharing a method+path are now grouped. A group with domain routes is
served by a host dispatcher that picks the first route whose domain matches
the Host header (or the URI authority), case-insensitively and without the
port, where a {name} label matches one DNS label, and falls back to the route
without a domain. With no match and no catch-all the answer is 404.

The existing domain test asserted the old behaviour (a request with no Host
reaching the domain route); it now checks both hosts.
Each list item was parsed as JSON and items that did not parse were dropped,
so in:admin,editor produced an empty allow-list and rejected every value; only
numbers or quoted strings worked.

Items are now read the way contains: reads its needle: JSON when it parses
(1 is a number, "1" a string), otherwise the raw text. Matching stays strict
on type and value.
graceful(timeout) ignored its timeout: it resolved on SIGTERM/SIGINT and the
server then drained with no limit, so one stuck request or connection could
hold shutdown open indefinitely.

After the signal, graceful now starts a deadline that exits the process with
status 1 if it is still running once the timeout elapses. Callers keep the
same API: Application::shutdown (30 s) is still the graceful-shutdown signal,
so the runnable app and generated apps get the bound without changes.

Checked against the runnable app: with an unfinished request held open, the
process exits 31 s after SIGTERM; with no requests in flight it exits at once.
JwtGuard::logout returned Ok(()) without doing anything, so a logged-out
token stayed valid until it expired, and a refresh token could be replayed
any number of times.

Each login now issues its access/refresh pair with a shared session id (sid
claim, omitted when empty so older tokens still decode). logout revokes the
pair by recording the sid in a cache Store until the refresh token would
expire; parse and refresh reject a revoked pair. refresh revokes the old pair
with an atomic put_if_absent before issuing the new one, so a refresh token
works once even under concurrent use. Tokens issued before sid existed are
revoked individually by a hash of the token. An unreadable store fails closed
with StoreUnavailable.

The default store is per-process memory; with_revocation_store takes a
shared store (Redis) so every process honours a logout. The claims contract
lists the new field.
No provider put the database, the cache, or the queue in the container, so
each feature that needed one built its own from config.

rustasea::services adds three providers that read the boot-time config:
DatabaseServiceProvider binds an orm::ConnectionResolver (connects lazily, on
first resolve), CacheServiceProvider binds a cache::CacheManager, and
QueueServiceProvider registers the queue connections that need no database
(sync, and redis with its feature) and binds the parsed QueueConfig. A
missing table falls back to the defaults; a table that does not parse is
left unbound and reported, without stopping boot.

A database queue connection needs a live pool, which a synchronous provider
cannot open, so connect_database_queues registers those after boot through
the bound resolver.
The runnable app registers the database, cache, and queue providers ahead of
its own, and connects the database queue connections right after boot.
Started against the shipped config, it logs that the database connections
were registered and serves as before.
docs/milestones.md: M0 gains the database, cache, and queue bindings and the
bounded shutdown drain; M1 the host-aware domain routing; M3 JWT revocation
and bare-word in: lists. The matching open items are removed, and the next M0
action becomes registering the service providers in the scaffold templates.

Citations into the router dispatcher, the umbrella crate, and the app's main
are repointed: this branch moved them, and the into_axum_router and resolve
citations were already off on master.

.agents module docs: F-M0-CFG-03, F-M0-BOOT-04, F-M1-RTE-02, F-M3-VAL-02, and
F-M3-AUTH-01 are Done (60 done, 48 partial, 2 not started). The JWT claims
contract lists the new sid claim (in the auth commit). CHANGELOG entries for
each change.
@github-actions
github-actions Bot requested a review from vheins November 20, 2026 11:50
@vheins

vheins commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator

Review: fix/foundation-and-correctness (PR #12)

Reviewed head ae8fdb93 against master@73a8b886. CI (build, fmt/lint, workspace tests, cargo-audit, cargo-deny, MSRV 1.88) is green, so this is a design/correctness/security pass, not a compile check.

Must fix before merge

  1. Logout with an expired access token does not revoke the pair (crates/rustasea-auth/src/jwt.rs:307). logout returns Ok(()) on ExpiredToken, and decoding failed before sid was read, so the pair's still-valid refresh token survives a "successful" logout. tests.rs:281 currently encodes this no-op. With 1h access / 24h refresh, this is a normal path. Fix: for logout only, validate signature/iss/aud with validate_exp = false, read sid, revoke the pair (hash fallback when no sid).

  2. Concurrent-refresh and store-outage paths are untested (jwt/tests.rs). The two security properties that matter, atomic single-use and fail-closed on an unreadable store, are only asserted sequentially and never with an Err store. Add a join! double-refresh (one Ok / one InvalidToken) and a store stub returning Err -> StoreUnavailable on parse.

Should fix

  1. Per-connection database queue wiring is ignored (crates/rustasea/src/services.rs:146-147). connect_database_queues resolves the default connection and passes one pool to every database driver, so connection = "secondary" silently uses the default DB. Resolve each connection by name.
  2. Host precedence is registration order (crates/rustasea-router/src/host.rs:80). A wildcard {tenant}.example.com registered before admin.example.com shadows the exact host. Prefer exact patterns over wildcards before falling back to registration order.
  3. Shutdown deadline is uncancellable (crates/rustasea-foundation/src/shutdown.rs:20-25). The spawned timer can exit(1) after a successful drain if the runtime outlives it. The current app is safe (main returns after serve), but the public API is not. Make the timer cancellable/droppable.
  4. Revocation TTL can undercut the refresh half by 1s (revoke.rs:38-47). TTL is iat + refresh_ttl from the presented token, and issue_pair uses two Utc::now() calls. Use now + refresh_ttl or add a margin.

Verified good

  • Revocation fails closed at the library layer: every store error maps to StoreUnavailable (no fail-open path).
  • sid is signature-protected, not exposed as a route param, and {name} matches exactly one DNS label; case-folding and port/IPv6-bracket stripping are correct and non-panicking.
  • The dispatch.rs domain/catch-all test was strengthened, not weakened. HEAD still answers GET routes under axum 0.7 on_service(GET).
  • in: bare-word parsing adds string items where it previously dropped everything; in:1 does not accept "1" or 1.0. No panic path.
  • Provider registration is idempotent; boot failures degrade to "not bound" with a log instead of a crash; no eager connection attempt.
  • Docs/CHANGELOG state 30 s (not 31 s) and correctly describe the per-process revocation default.

Nits

  • tests/services.rs:78 driver("sync").is_ok() is tautological (registry seeds sync).
  • Trailing-dot Host api.example.com. falls to catch-all/404; normalize one dot.
  • Domain dedup is exact-string, so API.example.com and api.example.com both register.
  • register_from_config runs twice per boot and re-leaks the default connection name.
  • No negative tests for malformed/duplicate/non-ASCII Host.

Decision

NEEDS_FIX on the expired-token logout path and the two missing auth tests; the rest are follow-ups. The host-routing, validation, boot-wiring, and shutdown changes are otherwise solid.

gitfromwildan added a commit to gitfromwildan/rustasea that referenced this pull request Nov 21, 2026
Review of rustasea#12: logout returned Ok on an expired access token without
reading its sid, so the pair's refresh token, valid for up to a day more,
survived a "successful" logout. logout now verifies the signature, issuer,
and audience without the exp check, then revokes the pair; a malformed or
forged token is still rejected.

A pair's revocation is now kept for one full refresh TTL from the moment of
revoking. It was derived from the presented token's iat, which could end a
second before the refresh half expires because the two halves are stamped
by separate clock reads.

Tests added for the two properties that were only asserted sequentially: two
concurrent refreshes with one token succeed exactly once, and an unreadable
revocation store fails closed with StoreUnavailable on parse, refresh, and
logout. The revocation tests move to jwt/revoke/tests.rs.
@gitfromwildan

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Every item is addressed in new commits on top of ae8fdb9; nothing was rewritten.

Item Commit What changed
1. Logout with an expired access token fix(auth): revoke the pair on logout with an expired access token logout decodes with signature/iss/aud checked and exp not, then revokes the pair. The old test that encoded the no-op now asserts the refresh half is rejected, and that a forged token is still refused.
2. Concurrent refresh and store outage untested same commit tokio::join! double refresh: exactly one Ok, the other InvalidToken. A store whose every call returns Err: parse, refresh, and logout all return StoreUnavailable. Revocation tests moved to jwt/revoke/tests.rs.
3. Per-connection database queues fix(rustasea): open each database queue connection on its own database Each database queue connection resolves the database connection it names (none or default selects the default, as DatabaseSessionStore does). The test uses two database connections and checks both were opened.
4. Host precedence fix(router): try exact domains before placeholders in host dispatch Exact domains are tried before {name} domains; registration order decides within each group.
5. Uncancellable shutdown deadline fix(foundation): let a drained server cancel the shutdown deadline, fix(app): cancel the shutdown deadline once the server has drained graceful records the deadline and drain_complete() cancels it; a second signal replaces it rather than stacking. The app calls it after serve returns. Re-checked against the running app: 30 s exit with a stuck request, immediate exit when idle.
6. Revocation TTL first auth commit A pair's revocation is kept for one full refresh TTL from the moment of revoking, which always covers the refresh half.
Nit: tautological driver("sync") per-connection commit Replaced by a check of the recorded default connection.
Nit: trailing-dot Host, case-only duplicate domains, negative Host tests router commit api.example.com. is normalised; API.example.com and api.example.com dedupe to the first; tests for empty, empty-label, prefix-sharing, punycode, and non-visible-ASCII hosts (all fall back to the catch-all).
Nit: register_from_config twice per boot per-connection commit connect_database_queues registers the database drivers directly, so the config is registered once and the default name is leaked once.

docs: follow the review fixes in status docs and changelog updates the descriptions and citations these changes moved, including two in README.md.

Checked on rustc 1.100.0: cargo xtask ci, cargo test --workspace --no-fail-fast (190 suites, 1985 tests), and cargo test -p rustasea-storage --features aws,sftp pass; cargo metadata --locked passes.

gitfromwildan added a commit to gitfromwildan/rustasea that referenced this pull request Nov 21, 2026
Review of rustasea#12: connect_database_queues resolved the default database
connection and handed that one pool to every database queue connection, so
a queue connection naming another database (connection = "jobs") silently
used the default one.

Each database queue connection now resolves the database connection it
names; no name, or "default", selects the default connection, as
DatabaseSessionStore does. The drivers are registered directly, so the
queue config is no longer registered a second time after boot (which also
re-leaked the default connection name).

The services test now uses two database connections and checks that both
were opened. Its sync-driver assertion was tautological (the registry seeds
sync) and is replaced by a check of the recorded default connection.
gitfromwildan added a commit to gitfromwildan/rustasea that referenced this pull request Nov 21, 2026
Review of rustasea#12: the matching domain route was picked in registration order, so
a {tenant}.example.com route registered before admin.example.com shadowed the
exact host. Exact domains are now tried before {placeholder} domains;
registration order decides within each group.

Also from the review:
- A trailing dot (api.example.com.) names the same host and is stripped.
- A domain registered twice in a different case (API.example.com and
  api.example.com) keeps the first route, as an exact duplicate already did.
- Tests for hosts that are empty, have empty labels, merely share a prefix,
  are punycode, or are not visible ASCII: all fall back to the catch-all.
gitfromwildan added a commit to gitfromwildan/rustasea that referenced this pull request Nov 21, 2026
Review of rustasea#12: the deadline graceful() spawns after the signal could not be
cancelled, so a process that kept running after a successful drain would
still be exited with status 1 when the timeout elapsed. The runnable app was
safe only because main returns right after serving.

graceful() now records the deadline, and drain_complete() cancels it; a
second signal replaces the first deadline instead of stacking another.
@gitfromwildan

Copy link
Copy Markdown
Contributor Author

@vheins every item from your review is addressed in the new commits (mapping in the comment above), and CI is green on 4c10684. Could you take another look?

- Logout decodes with exp disabled so an expired access token still revokes its live refresh half.
- Revocation retention gains a 60s margin so it outlives both halves.
- Add concurrent-refresh (atomic single-use) and store-outage (fail closed) tests.
- Specificity ranking in host selection: exact domains outrank placeholder patterns
- Trailing-dot normalization so `api.example.com.` matches `api.example.com`
- Case-folded domain registration so patterns differing only in case dedup
- Tests for wildcard/exact ordering, trailing dot, and malformed Host values
- Resolve each database-backed queue connection by its declared name
- Fall back to the default connection when the name is unset
- Replace the tautological boot assertion with a provider-only registration
@vheins
vheins force-pushed the fix/foundation-and-correctness branch from 4c10684 to c58901f Compare November 21, 2026 09:26
@vheins
vheins merged commit 93361c0 into rustasea:master Nov 21, 2026
6 checks passed
vheins pushed a commit that referenced this pull request Nov 21, 2026
#12 merged with different review follow-ups than the ones its docs commit
described, and that docs commit was not part of the merge, so citations into
the dispatcher, host dispatch, the JWT guard, the shutdown module, and
services.rs pointed at the wrong lines (two in README.md as well). They are
repointed, and the descriptions now match the merged code: exact domains
before {name} domains, logout revoking from an expired access token, and the
GracefulShutdown guard.

M0 records DATABASE_URL support in the bound resolver, the app's pools going
through it, and generated apps registering the providers, and drops those
items from Partial, Missing, and Next actions. M3 notes why the scaffold's
database user provider item is still open: generated apps have no login flow
to wire it into yet. Changelog entries for both.
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