canopy-web worker sessions: a canopy-owned store and a durable refresh claim (#2224)

Status: Done (2026-10-01) — !1549
Epic: &52
Issues: #2515 (w2), #2516 (w3), #2517 (w5), #2518 (w8), #2224 (U5, w5), #2519 (w2), #2520 (U7, w2), #2509 (U8, w3)
Branch: fix/web-session-store, one MR with eight commits, titled "canopy-web sessions: a canopy-owned store and a durable refresh claim (#2515, #2516, #2517, #2518, #2224, #2519, #2520, #2509)". It closes all eight issues. The U1 commit adds this page (Status In progress) and its nav entry; the U8 commit closes the plan.

  • Erratum (2026-10-01): U1 as built. RotatingIdp's /revoke revokes the whole family for any token of it, spent or live, so family_revoked() cannot show which token a logout revoked. It also keeps a per-token record (revoked_tokens()). U5’s "logout during a held refresh revokes the successor" test is corrected to assert that the successor itself reached /revoke.

  • Erratum (2026-10-01): U3 as built, which U4 builds on.

    • The logout CSRF check is the csrf::CsrfCheckedSignOut extractor, which route-authz requires on POST /logout. U4 re-implements it over SessionState: Live compares the snapshot’s csrf_token, Absent only clears cookies, and Unavailable answers 503.

    • SignInPrompt and the canopy_reauth cookie live in services/canopy-web/src/auth/mod.rs, and prompt_login is a session flow key. U4 moves them to web_session/cookie.rs and web_login_flow.prompt_login.

    • The CSRF token is minted at sign-in (rotate_csrf_token mints at the callback), and every page struct that extends base.html carries csrf_token. U4’s create mints it with the session row.

    • U3’s file list also covers csrf.rs, telemetry.rs (canopy_web.auth.revocation_failed), the page handlers, services/canopy-web/static/css/canopy-web.css, the goldens and three test harnesses, and it adds the axum-extra cookie feature that U4’s "Tokens and cookies" names.

  • Erratum (2026-10-01): U3 review. canopy-web’s CSP sends form-action 'self', and Chromium enforces it on the redirects after a form POST, so POST /logout cannot 303 to the issuer. Logout answers a same-origin 200 handoff page (Askama: a meta refresh and a Continue link to the end-session URL or /login), the template U8’s sign-in handoff reuses. A logout with no live session still sets canopy_reauth when no end-session endpoint is advertised, or hands off to the end-session endpoint without id_token_hint. canopy_reauth is SameSite=Lax, so it also arrives on cross-site entries to /login. Tokens and cookies and Logout below are corrected to match.

  • Erratum (2026-10-01): rebased onto the redirect MR (#2534, #2535, #2536). Both OIDC grants and U3’s revocation run on canopy-web’s one shared grant client, auth::refresh::grant_client(), which follows no redirect: a 3xx refresh answer is RefreshError::Rejected, so Ambiguous, and a 3xx revocation answer is a failed revocation. The U2 review found the client’s 5 s connect bound above REFRESH_SLOW_PATH_BUDGET (3 s), so a stalled connect surfaced as the grant’s request timeout (Ambiguous) and ended a session Refresh outcomes says it keeps. U2 lowers it to GRANT_CONNECT_TIMEOUT = 2 s, compile-pinned below the budget less MIN_CALL_FLOOR; Refresh outcomes below is corrected to name the remaining edge.

  • Erratum (2026-10-01): U4 as built.

    • The suites that touch the store moved into the infra lane: auth/refresh_budget_tests.rs and api/refresh_lead_route_tests.rs are now auth/refresh_budget_infra_tests.rs and api/refresh_lead_route_infra_tests.rs (and likewise the expiry-stamp, login-error, logout, observed-hook, validation-error and Studio step-2 suites). U1’s cites are corrected below.

    • The acceptance grep cannot be empty: the immutable migration services/canopy-web/migrations/20260401000000_create_sessions_table.sql names the old crate in a comment. The grep excludes that one file.

    • A Host- cookie must have the path /, so "scoped to the callback" means SameSite=Lax, Host- and Secure under session_secure, no Domain, and Max-Age 900.

    • A refresh commit the store cannot confirm is StoreUnavailable (503). A lost compare-and-set fails closed without re-reading (U5’s classify_commit re-reads). A refresh-failure end lands only while the row still holds the version the failed grant presented. Logout revokes the refresh token of every session step 1 ends, a superseding session included. U4 also touches telemetry.rs (canopy_web.session.slide_failed), api/{errors,mod}.rs, studio/{extractor,mod,probe}.rs and idp-integration.adoc.

  • Erratum (2026-10-01): U5 as built.

    • release lands only while the lease runs, so even the holder’s late release never clears a lapsed claim; end_lapsed binds the lapsed claim’s id.

    • Waiter: any read or claim error is StoreUnavailable, except one the waiter’s own budget cut short, which is RefreshFailed (#1340).

    • Leader: it serves only a token that has not expired, on every path, not only after the version moved: a retried commit can land before an abandoned one.

    • classify_commit has a fifth class, Foreign (the claimed version without our claim), which no writer produces; it fails closed.

    • A validation that hits the 12 s bound ends the session as refresh_rejected and answers the named identity_unavailable login error.

    • The claim statement runs inside the spawned leader, so a dropped client cannot strand it mid-statement. U4’s slow-leader test now asserts that the claim rules the overlap out (the slow leader is served; a late commit under its spent claim writes nothing). U5 also touches auth/{refresh,mod}.rs, web_session/{mod,test_support,layer}.rs, the store, route, SSE and refresh-budget suites, deployment-guide.adoc and api/canopy-web.adoc.

  • Erratum (2026-10-01): U7 as built. The four checks as written accept /.//evil, which the url crate normalises to the protocol-relative //evil, and /%2f%2fevil, which the table refuses. The leading-/, not-// and character checks therefore apply to the raw input, to its one percent-decoding, and again to the normalised output, which is a fixed point. canopy-web takes the workspace percent-encoding dependency for the decoding. The sign-in success log keeps the return target’s path only, never its query.

  • Erratum (2026-10-01): U8 as built. canopy-web-xsite is reached on the compose network as the alias web.canopy-xsite.test on its container port, not through an extra_hosts host-gateway alias. An e2e-only service has no running container for port discovery to record, so an allocated host port would drop out of .ports.env and drift from the realm. Its realm redirect URI is a fixed entry. U8 also stops plan-lint --done from reading a URL path in a plan as a repo cite.

The MR bundles eight issues under the maintainer’s one-MR-per-related-group ruling. U4 and U5 must ship in the same release. This is a Design + Scope plan. GitLab owns tracking. The plan freezes when U1 starts.

Context

canopy-web keeps worker sessions in tower-sessions 0.14 over tower-sessions-sqlx-store 0.15 (services/canopy-web/src/main.rs). Two properties of that stack cause #2224:

  • every write is an unconditional INSERT … ON CONFLICT DO UPDATE of the whole record;

  • after any non-5xx response, the layer writes back any handle that was ever modified.

The refresh single-flight (SessionRefreshGuard, services/canopy-web/src/auth/refresh.rs) is a per-process mutex, released before the handler runs. Four races follow:

  • a logout during a refresh can bring the session back;

  • a slow leader’s write-back can overwrite a newer refresh;

  • when the store is half down, a waiter can re-spend a rotated token;

  • replicas do not share the guard.

Beyond refresh, every writer is a stale whole-record writer: CSRF, the Studio draft, and /login on a signed-in cookie.

ADR-049 D6 requires a refresh that is single-flight across replicas at I3. ADR-050 §4 says a replayed rotated refresh token revokes the whole Kanidm session. Production runs several replicas without sticky sessions (ADR-009). The only authority allowed is canopy-web’s PostgreSQL: Redis (allkeys-lru, no persistence) is not one.

The survey also found two defects in the redirect handling:

  • #2509: the callback reads its OAuth state from the SameSite=Strict session, which a cross-site IdP’s redirect never carries, so sign-in through a cross-site IdP loops. e2e signs in same-site, through host.docker.internal, so it never caught this.

  • #2520: is_safe_redirect (services/canopy-web/src/auth/mod.rs) and its copy is_safe_return_to (services/canopy-web/src/api/auth_sign_in.rs) are string checks. Both accept /%09/evil.example. Browsers strip the tab, so today’s /auth/landing 302 is an open redirect.

Scope

In scope: U1–U8 below.

Out of scope:

  • checking a refreshed token’s sub (ADR-049 D6, at I3);

  • encrypting session grants at rest (#2521);

  • an absolute session lifetime;

  • the portal’s store;

  • the I3 critical section (upstream refresh plus re-federation; see I3 carry-over).

Design

Principles

  • No whole-record writes. Every write is one named statement over its own columns. The draft update and the callback’s create are the only multi-statement transactions.

  • No upserts. Only the callback INSERTs a session row, under a fresh 256-bit token. A deletion is final.

  • Nothing is written after the response.

  • No second presentation. A refresh token is presented only by the holder of a claim already committed in the row. It is never presented again after any outcome in which the IdP may have processed it.

  • Logout is final. That covers the session, any sign-in it started, and any session that superseded it.

These guarantees assume acknowledged commits survive a failover (synchronous replication; see Failure handling).

Data model

services/canopy-web/migrations/<ts>_web_session_store.sql (U4; <ts> sorts after the newest migration at implementation time):

  • DROP TABLE IF EXISTS sessions: the unused table from 20260401000000_create_sessions_table.sql. ADR-016 allows forward-only drops.

  • web_session:

    • id UUID PRIMARY KEY: v7, application-bound, not a bearer.

    • token_hash BYTEA NOT NULL UNIQUE CHECK (octet_length = 32)

    • worker_id TEXT NOT NULL CHECK (<> '')

    • created_at TIMESTAMPTZ NOT NULL DEFAULT now(), idle_expires_at TIMESTAMPTZ NOT NULL

    • csrf_token TEXT NOT NULL

    • grant_version BIGINT NOT NULL DEFAULT 1 CHECK (>= 1)

    • worker_grant JSONB NOT NULL: today’s SessionData, through sqlx::types::Json.

    • studio_draft JSONB NULL

    • Indexes on idle_expires_at and worker_id.

  • web_login_flow:

    • id UUID PRIMARY KEY (v7), flow_hash BYTEA NOT NULL UNIQUE, state_hash BYTEA NOT NULL

    • pkce_verifier TEXT NOT NULL, idp_slug TEXT NOT NULL, return_to TEXT NULL, already validated (U7)

    • replaces_session_id UUID NULL, prompt_login BOOLEAN NOT NULL

    • expires_at TIMESTAMPTZ NOT NULL, with an index.

  • web_session_end, a diagnostic record with no live credential:

    • session_id UUID PRIMARY KEY, token_hash BYTEA NOT NULL, worker_id TEXT NOT NULL

    • created_at TIMESTAMPTZ NOT NULL, ended_at TIMESTAMPTZ NOT NULL DEFAULT now()

    • reason TEXT NOT NULL CHECK (reason IN ('logout','superseded','idle','operator','refresh_refused','refresh_rejected','refresh_lost'))

    • superseded_by UUID NULL

    • Indexes on token_hash, ended_at and worker_id.

U5’s migration, <ts>_web_session_refresh_claim.sql, adds refresh_claim_id UUID and refresh_claim_expires_at TIMESTAMPTZ, both NULL or both set.

Every end is one statement: WITH gone AS (DELETE FROM web_session WHERE <predicate> RETURNING …), logged AS (INSERT INTO web_session_end … SELECT … FROM gone) SELECT … FROM gone. That includes the operator’s end of every session; the runbook uses it, never TRUNCATE.

PostgresStore::migrate() leaves the tower_sessions schema behind, holding plaintext refresh tokens. migrations-lint forbids schema DDL, so the upgrade note tells operators to DROP SCHEMA IF EXISTS tower_sessions CASCADE.

Tokens and cookies (services/canopy-web/src/web_session/, new module)

  • Newtypes (the portal’s hashed opaque-token pattern, services/canopy-portal/src/session.rs):

    • SessionToken: 32 random bytes, unpadded base64url via base64ct, redacted Debug;

    • TokenHash([u8; 32]): SHA-256;

    • SessionId and ClaimId (v7), GrantVersion(i64), CsrfToken, FlowToken;

    • EndReason, pinned to the CHECK list by a test.

  • All three cookies use the __Host- prefix when session_secure (so Secure, the path /, no Domain) and the bare name otherwise (the devstack is plain HTTP). All are HttpOnly.

    • canopy_session: SameSite=Strict. Keep the LOAD-BEARING comment: Strict is the CSRF control for /v1/composition. No Max-Age: a browser-session cookie, with the server’s idle deadline as its real lifetime.

    • canopy_login_flow: SameSite=Lax, because the IdP returns cross-site. Max-Age=900. __Host- stops a sibling subdomain from planting a flow (login fixation).

    • canopy_reauth: SameSite=Lax, Max-Age 30 days. It is set at logout when the IdP has no end-session endpoint; see Logout. Lax, because it only makes sign-in stricter and must arrive on cross-site entries to /login too.

  • Parsing. Cookies go through axum-extra 0.10’s CookieJar: add its cookie feature, and read the 0.10.3 docs first. A malformed value counts as absent.

Request path (services/canopy-web/src/web_session/layer.rs)

  • The middleware. session_context is a route_layer, outermost on the protected router (api::routes() plus the wizard, including /sse) and on the composition router. It loads by token_hash with idle_expires_at > now() and inserts one immutable SessionState:

    • Live(Arc<LoadedSession>);

    • Absent, which also covers an undecodable grant, counted by record_session_decode_failure;

    • Unavailable: a store error or timeout.

  • The idle deadline. The TTL is today’s session_ttl_seconds.max(300) (0 means 28800), read at boot. Sliding is due when fewer than TTL − 60 s remain. The slide repeats that condition and only moves the deadline forward:

    UPDATE … SET idle_expires_at = GREATEST(idle_expires_at, clock_timestamp() + ttl) WHERE id = $1 AND idle_expires_at > clock_timestamp() AND idle_expires_at < clock_timestamp() + ttl - interval '60 seconds'

    Concurrent requests therefore write once per minute at most, and a delayed statement never moves the deadline back. A failure is warned and counted; the request is served.

  • Consumers. require_auth, csrf_middleware and the extractors read SessionState.

    • Unavailable answers 503 with Retry-After: 5. AuthFailure gains StoreUnavailable, and CompositionApiError gains a 503 SessionStoreUnavailable (utoipa annotations; cargo xtask api-docs --update).

    • A refresh re-inserts SessionState::Live.

  • SSE. The stream’s per-event check (services/canopy-web/src/api/sse_stream.rs scope_changed) keeps today’s rule. It reads SessionStore::stream_scope(SessionId), which returns the live row’s program scope. The stream ends when the row is gone, the read fails, or the scope differs from the one it was opened with.

Every writer

The stores (SessionStore, DraftStore, RefreshStore, LoginFlowStore) wrap the PgPool and a StoreConfig. Their SQL is named consts in services/canopy-web/src/web_session/sql.rs.

Every statement runs under a timeout: min(2 s, the remaining budget) on request paths, and 2 s in the leader and sweeper. Each is written so that a late landing is harmless. Single-statement conditional writes are compare-and-set under READ COMMITTED: PostgreSQL re-checks the WHERE clause against the newest row version after waiting on its lock.

Writer Statement and guard

/login, /auth/select

INSERT a web_login_flow row (15 min) with return_to validated by U7, replaces_session_id = the live session the cookie names, and prompt_login set when the canopy_reauth cookie is present. Set the flow cookie, then redirect to the IdP (with prompt=login when set). Never touches web_session. An INSERT error answers 503.

/auth/callback

Take: DELETE FROM web_login_flow WHERE flow_hash = $1 AND state_hash = $2 AND expires_at > now() RETURNING …. Single use; a wrong state consumes nothing. Create, one transaction: (1) end replaces_session_id, reason superseded, with superseded_by = the new id; (2) when (1) ended nothing and web_session_end records that session ended by logout or operator, refuse, so the browser lands on /login; (3) INSERT INTO web_session with a fresh token and CSRF value, no ON CONFLICT. Clear the flow cookie, and the canopy_reauth cookie when the flow carried prompt_login.

Idle slide

The statement above.

Wizard save (services/canopy-web/src/studio/wizard.rs)

Transaction: SELECT studio_draft … FOR NO KEY UPDATE, a synchronous FnOnce(&mut WizardDraft), then UPDATE … SET studio_draft. Cancel sets it to NULL.

CSRF

Read-only from the snapshot. get_or_create_csrf_token and rotate_csrf_token are deleted.

Refresh

U4: compare-and-set on grant_version. U5: the claim below.

Logout (U3, U4)

See Logout.

Operator

The end CTE on worker_id, or on every row in batches (reason operator).

Sweeper (U6)

End CTEs on idle rows (reason idle), in batches of 500 under FOR UPDATE SKIP LOCKED. Expired flows. End-log rows older than 30 days.

Refresh outcomes (U2)

RefreshError (services/canopy-web/src/auth/refresh.rs) keeps whether the request reached the IdP and what came back. GrantOutcome::from(&Result<TokenResponse, RefreshError>) is a total partition:

  • Granted: a parsed 2xx.

  • AcceptedUnreadable: a 2xx whose body is unreadable, too large or unparseable. The IdP rotated.

  • Refused: a 4xx other than 408, 425 or 429.

  • NotProcessed, which the IdP provably did not act on:

    • a connect-phase failure (reqwest::Error::is_connect(), including the grant client’s connect timeout, which sits below the refresh budget) — the request was never sent. A connect still pending when the grant’s remaining budget runs out is a request timeout, so Ambiguous;

    • 408, 425 or 429.

  • Ambiguous: anything else. That is a timeout or connection loss after sending, any 5xx, or any other status. The IdP may have rotated.

The actions:

  • Refused, AcceptedUnreadable and Ambiguous end the session and never present the token again.

  • Only NotProcessed keeps the session, for a later sequential retry.

  • Each outcome is counted.

This narrows ADR-049 D6’s grace for an unavailable upstream ("network error, timeout or 5xx"). Grace now applies only to failures the IdP provably did not process, because a re-presented token that the IdP did rotate revokes the family. ADR-049 Amendment 2 records this.

The refresh claim (U5, services/canopy-web/src/auth/single_flight.rs)

Constants:

  • REFRESH_SLOW_PATH_BUDGET 3 s and MIN_CALL_FLOOR 50 ms, unchanged;

  • REFRESH_VALIDATION_BOUND 12 s, around validation, admission and the expiry stamp (it covers the 10 s JWKS fetch);

  • COMMIT_RECOVERY_CAP 6 s, STORE_OP_TIMEOUT 2 s, REFRESH_CLAIM_LEASE 30 s;

  • const _: () = assert!(LEASE > BUDGET + VALIDATION_BOUND + COMMIT_RECOVERY_CAP).

Polls back off from 20 to 160 ms with ±25% jitter, within the budget.

Statements:

  • view: version, grant, claim and lapsed, on a live row.

  • claim: SET refresh_claim_id = $3, refresh_claim_expires_at = now() + lease WHERE id = $1 AND grant_version = $2 AND refresh_claim_id IS NULL AND idle_expires_at > now() RETURNING worker_grant.

  • commit: SET worker_grant = $3, grant_version + 1, claim NULL WHERE id = $1 AND refresh_claim_id = $2 RETURNING grant_version. It has no lease predicate.

  • release; end_claimed(reason); end_lapsed (reason refresh_lost).

The lease only lets a non-holder end the session. A lapsed claim is never NULL, so that version is never claimed again.

Waiter. resolve_worker_or_fail keeps its fast path. On the slow path it takes the per-process guard (keyed on the SessionId; an optimisation only), then loops on view and the pure next_step(view, loaded_version, now, budget_expired), in this precedence:

  1. no row → NoSession;

  2. the token outlives the lead, or the version is newer and the token unexpired → serve;

  3. budget expired → RefreshFailed, no grant;

  4. a lapsed claim → end_lapsed: one row → NoSession; zero → re-read;

  5. a live claim → wait, then re-read;

  6. no claim → claim:

    • the grant returned with the budget above the floor → lead;

    • below the floor → release, RefreshFailed;

    • zero rows → re-read;

    • an error → best-effort release, StoreUnavailable.

Any read error is StoreUnavailable, with no grant.

Leader. A tokio::spawn task owns the guard and the ClaimId, and the request awaits it. A dropped client neither strands a claim nor loses a successor; a JoinError is Internal, and the claim lapses. The leader presents the claimed token within the remaining budget, then acts on the outcome:

  • NotProcessed → release, RefreshFailed.

  • Refused → end_claimed(refresh_refused). AcceptedUnreadable and Ambiguous → end_claimed(refresh_lost). All three return NoSession.

  • Granted, but validation, admission or the expiry stamp fails or times out → end_claimed(refresh_rejected).

  • Granted and valid → commit, recovered within COMMIT_RECOVERY_CAP (at most 2 commits and 3 reads) and classified by the pure classify_commit:

    • the version moved past the claimed one: the commit landed, either by a lost acknowledgement or a later supersede. The leader then re-reads with view. It serves only a live row whose token has not expired; otherwise it returns RefreshFailed, and the stored successor serves the next request.

    • the claim is still ours: commit once more.

    • no row (Gone): NoSession. When web_session_end records logout or operator, the leader revokes the successor (U3’s revocation), since the logout revoked only the predecessor. After superseded or idle it drops the successor unrevoked: RFC 7009 related-token revocation could end the replacement session.

    • reads failing: StoreUnavailable, leaving the claim.

After a commit lands it fires the #597 observation. A leader never releases after receiving a successor.

Logout (U3, U4)

POST /logout replaces GET /logout. The two sign-out links in services/canopy-web/templates/base.html become forms carrying the CSRF token. Logout checks that token against the live session; with no live session it skips the session steps (see step 4). It takes no lock and never waits on a claim. In order:

  1. End the session by token_hash, reason logout, returning the grant. When nothing ends, follow web_session_end.superseded_by from that token_hash, up to 4 links, and end each live session it reaches with reason logout. So a sign-in completing concurrently cannot outlive the logout.

  2. Delete the pending flow the flow cookie names, and clear the cookie.

  3. Revoke the refresh token when discovery advertises revocation_endpoint (RFC 7009, in services/canopy-web/src/auth/revoke.rs). It sends token, token_type_hint=refresh_token and client_id, with a 2 s timeout. A failure is logged and counted.

  4. Hand off through a same-origin 200 page (a meta refresh and a Continue link; the CSP’s form-action 'self' forbids a cross-origin redirect after the form POST) to the end-session endpoint with id_token_hint when one is advertised. Otherwise set canopy_reauth, so the next sign-in sends prompt=login (ADR-049 D6; ADR-050 for Kanidm, which has no end-session endpoint), and hand off to /login. With no live session, logout clears cookies and still hands off: to the end-session endpoint without id_token_hint, or to /login with canopy_reauth set.

  5. If the DELETE fails or times out, answer 503: "Sign-out could not be confirmed. Try again."

OidcDiscovery (crates/canopy-auth/src/discovery.rs) gains revocation_endpoint: Option<String>. Its client authentication at I3 is the upstream profile’s (see I3 carry-over).

Redirect targets (U7) and the sign-in handoff (U8)

U7: one validator replaces is_safe_redirect and is_safe_return_to: safe_return_path(raw) → Option<String>.

  • It refuses any ASCII control character, whitespace or backslash, in the raw input and again after percent-decoding.

  • It requires a leading / and refuses a leading //.

  • It joins the input onto a fixed base with the url crate (https://canopy.invalid/) and requires the result to keep that origin.

  • It returns the normalised path and query, which is the only form any redirect or page ever emits.

U8: the handoff. /auth/landing is deleted. The callback’s success response is a 200 text/html handoff page, rendered by an Askama template. It carries the new session’s Set-Cookie, a <meta http-equiv="refresh"> and a Continue link, both to the flow row’s stored return_to (or /). The next navigation therefore starts from a same-site document and carries the Strict cookie. Nothing in the request chooses the destination.

Failure handling

  • A store read fails: 503 with Retry-After, and no grant.

  • A claim write fails: best-effort release, 503, and no grant. A claim that lands late lapses and ends the session; the token was never presented.

  • Writes fail after a grant, or the leader crashes: the claim stays, and waiters fail closed. After the lease, the first writer ends the session (refresh_lost): one re-login, no replay.

  • A callback create fails: 503; the flow is consumed.

  • A slide or sweep fails: warned and counted.

  • Replication. Durable logout and no-replay need acknowledged commits to survive failover: synchronous replication (synchronous_commit with a synchronous standby).

    • Under asynchronous replication, a failover can lose an acknowledged logout, so the session, and a copied cookie, works again until its idle deadline.

    • It can also lose a claim or a commit, which allows one re-presentation. A rotating IdP then revokes the family, and the worker signs in again.

    • deployment-guide.adoc (HA) and idp-integration.adoc state both.

I3 carry-over

  • What stays: the tables, cookies, layer, flow table, draft, logout, the outcome partition and the claim.

  • What I3 designs:

    • the critical section of upstream refresh plus re-federation, including a durable partial-completion phase, so a canopy-identity outage after an upstream rotation neither strands nor replays the successor;

    • the upstream profile’s client authentication for both the refresh and RFC 7009 revocation;

    • D7 native grants: a kind column, with token_hash made nullable.

No guarantee in this plan depends on those.

Units — U1 → (U2 ‖ U3) → U4 → U5 → (U6 ‖ U7) → U8

Every unit ships its CHANGELOG.adoc bullet and the doc lines named here. Paths are under services/canopy-web/src/ unless they start with a top-level directory. Each issue lists its tests by name.

Testing applies to every unit:

  • Store tests run on real PostgreSQL over an EphemeralSchema, in modules ending infra_tests (xtask/src/lanes.rs INFRA_MODULE_SUFFIX). Two-replica cases use a second pool.

  • Protocol decisions (next_step, classify_commit, GrantOutcome) are pure and proptested.

  • There is no in-memory store.

    1. U1 (w2) — test(web): a rotating mock IdP that detects refresh-token replay (#2515).

      • services/canopy-web/src/auth/rotating_idp.rs (#[cfg(test)]): token families. A spent token revokes its family (400 invalid_grant, stricter than Kanidm). It serves /revoke (RFC 7009) and /jwks.

      • Knobs: hold_after_rotation, lose_response (rotate, then drop the connection), fail_status_once(code), refuse_connections, expires_in, on_grant.

      • Counters: grants(), replays(), family_revoked(), revoked().

      • The refresh suites (services/canopy-web/src/auth/refresh_budget_infra_tests.rs, services/canopy-web/src/api/refresh_lead_route_infra_tests.rs, services/canopy-web/src/api/mock_exchange.rs) move onto it and assert replays() == 0.

    2. U2 (w3) — fix(web): end the session on any possibly processed refresh (#2516).

      • The partition and its actions on the current store.

      • Proptest: the partition is total over every status code and error kind.

      • Routed tests:

        • lose_response → the session ends, replays() == 0;

        • fail_status_once(503) → ends;

        • fail_status_once(429) and refuse_connections → kept, and a later retry succeeds with replays() == 0.

      • Docs: idp-integration.adoc, and ADR-049 Amendment 2 (docs/modules/ROOT/pages/adrs/adr-049-identity-plane-split.adoc).

    3. U3 (w5) — feat(web): CSRF-checked POST logout with RFC 7009 revocation (#2517).

      • Steps 3–4 of Logout on the current store, with POST /logout, the CSRF check, canopy_reauth and prompt=login at /login and /auth/select.

      • Files: crates/canopy-auth/src/discovery.rs and every OidcDiscovery literal (git grep -l 'introspection_endpoint:'); auth/{mod,revoke}.rs; api/auth_sign_in.rs; services/canopy-web/templates/base.html.

      • xtask/src/cmd/route_authz.rs: the auth-lifecycle routes and their comment, plus a regression test that POST /logout is a CSRF-checked state change and that no GET /logout remains.

      • Tests:

        • revocation when advertised;

        • local-only logout when not, plus prompt=login on the next sign-in;

        • a cross-site POST without the token is refused;

        • the end-session redirect still follows revocation.

      • Docs: idp-integration.adoc.

    4. U4 (w8) — fix(web): replace tower-sessions with a canopy-owned store (#2518).

      • Scope: the store, the flow table, the cookies, the layer, the slide, SSE stream_scope, Logout steps 1, 2 and 5, the callback create, and the compare-and-set refresh.

      • Files:

        • the migration; web_session/{mod,sql,cookie,layer,store,draft,refresh,flow,test_support}.rs;

        • session.rs, auth/{mod,refresh}.rs, csrf.rs, middleware.rs;

        • api/{auth_sign_in,composition_session,composition_errors,composition,sse,sse_stream,applications,audit_log}.rs, api/case_detail/tab.rs, studio/wizard.rs, main.rs, lib.rs;

        • xtask/src/cmd/e2e.rs (a comment).

        • Cargo.toml (root and canopy-web) drops tower-sessions, tower-sessions-sqlx-store and the async-trait dev-dependency.

      • Tests that build a tower-sessions layer move to the new store, into infra_tests modules where they touch it. Hermetic authorization harnesses inject SessionState::Live through web_session::test_support.

      • Docs:

        • ADR-009 Amendment 2 (docs/modules/ROOT/pages/adrs/adr-009-postgresql-session-storage.adoc);

        • data-models/canopy-web.adoc, api/canopy-web.adoc, security.adoc, coding-conventions.adoc, services.adoc, architecture.adoc;

        • configuration-reference.adoc: the idle deadline and the cookie names;

        • deployment-guide.adoc: state, HA and replication, and the upgrade note (stop every replica, deploy, drop tower_sessions; every worker signs in again);

        • docs/modules/ROOT/pages/runbooks/{scaling-deployment,worker-program-scope-cutover}.adoc, with the operator end CTE replacing TRUNCATE;

        • a Playwright "logout is durable" spec in tests/e2e/specs/auth.spec.ts.

      • Acceptance tests:

        • logout during a held refresh stays logged out, and the end reason is logout;

        • a slow leader cannot overwrite a newer refresh;

        • no write recreates a deleted session; the only session INSERT is create, with no ON CONFLICT;

        • concurrent slides write once, and never move the deadline back;

        • a refresh that narrows the program scope ends an open SSE stream;

        • a sign-in started before a logout of its session is refused at create;

        • a logout racing a completing callback ends the superseding session;

        • logout deletes the browser’s pending flow.

    5. U5 (w5) — fix(web): cross-replica refresh single-flight by durable claim (#2224).

      • Files: the migration; auth/single_flight.rs, web_session/refresh.rs, session.rs.

      • Docs: the guarantee paragraph in idp-integration.adoc, with its replication scope.

      • Acceptance tests:

        • two routers, with their own guards and pools on one schema, spend the token once, and on_grant sees the claim committed;

        • a half-down store fails the waiters closed, then ends the session with refresh_lost;

        • a lost commit acknowledgement with expires_in = 3 never serves an expired token, and the next request uses the stored successor;

        • logout during a held refresh revokes the successor (the successor is in revoked_tokens()); a supersede does not;

        • lose_response ends the session with no replay;

        • a lapsed claim is never re-claimed;

        • a model-based two-pool proptest holds: at most one live claim, one version step per commit, no resurrected row.

    6. U6 (w2) — feat(web): sweep expired sessions, login flows and end logs (#2519). web_session/sweep.rs, main.rs. Every replica sweeps every 5 minutes, with a jittered first tick, and two sweepers never log one end twice. Docs: deployment-guide.adoc and data-models/canopy-web.adoc retention.

    7. U7 (w2) — fix(web): one parsing redirect-target validator (#2520).

      • safe_return_path replaces both copies, in services/canopy-web/src/auth/mod.rs and api/auth_sign_in.rs.

      • Tests:

        • a table including /%09/evil.example, /%0a/x, /\evil, //evil, /%2f%2fevil and https://evil;

        • a proptest: every accepted path rejoins onto the base without changing its origin.

      • Sibling search: every Redirect::to, Location and meta-refresh target in canopy-web and canopy-portal goes through a validated value. Report the list.

    8. U8 (w3) — fix(web): sign-in through a cross-site IdP completes (#2509).

      • The handoff page (services/canopy-web/src/auth/mod.rs, a template under services/canopy-web/templates/). /auth/landing and its route are deleted.

      • Cross-site e2e. A second instance, canopy-web-xsite (same image, started only for the e2e run), uses an alias host on another registrable domain from Keycloak’s host.docker.internal (web.canopy-xsite.test, an extra_hosts alias of the host gateway in canopy-e2e). It gets its own CANOPY_WEB__REDIRECT_URL, and the realm client gains that redirect URI.

      • A Playwright spec signs in through it and lands on the dashboard. It asserts the flow cookie reached the callback and the session cookie reached the page after the handoff, and it is shown to fail against the pre-U4 sign-in.

      • Docs: idp-integration.adoc (cross-site IdPs supported), local-dev.adoc.

      • This commit closes the plan, per contributor-workflow.adoc:

        • Status Done (YYYY-MM-DD) — !N;

        • the page moved to docs/modules/ROOT/pages/plans/archive/ and the nav repointed;

        • cargo xtask plan-lint --done <plan> --allow-open for the MR’s eight issues and #2521.

Verification

  1. Per unit:

    • fmt;

    • cargo clippy -p canopy-web --all-targets --profile test — -D warnings, and the same without --profile test;

    • the unit lane and the named infra_tests;

    • cargo doc with broken intra-doc links denied;

    • migrations-lint, quality-budgets, test-lanes-lint --static, secret-loads, route-authz and api-docs.

  2. Rebuild the devstack: cargo xtask dev clean --confirm, then CANOPY_CARGO_FEATURES=canopy-api/test-clock cargo xtask dev start. Sign in, log out in one tab, and confirm a second tab lands on sign-in. cargo xtask e2e runs the cross-site spec.

  3. git grep -nE 'tower[-_]sessions' — services crates xtask tests Cargo.toml Cargo.lock ':!services/canopy-web/migrations/20260401000000_create_sessions_table.sql' is empty.

  4. git push runs the pre-push battery.

Review log

round vendor resolved model verdict

1 (2026-09-30)

Anthropic

claude-opus-5-5

no-ship. Two blockers fixed: the scoped tower_sessions check; repo-relative cites and --allow-open, so plan-lint --done can pass. Also applied:

  • closing the plan in the MR;

  • U4’s file list;

  • the U3 weight;

  • landing escaping;

  • the D6 note;

  • the clippy commands;

  • the MR title;

  • #2521.

2 (2026-09-30)

OpenAI

gpt-6-astra

no-ship. Sixteen findings, all fixed:

  • an ambiguous refresh ends the session (D6 grace narrowed; ADR-049 Amendment 2);

  • SSE keeps its scope check;

  • logout is a CSRF-checked POST, and the landing route is gone;

  • one parsing redirect validator (#2520);

  • __Host- flow cookie;

  • prompt=login after a local-only logout;

  • the successor is revoked after a logout;

  • recovery never serves an expired token;

  • a monotonic, condition-repeating slide;

  • replication-scoped guarantees;

  • the route-audit change;

  • a cross-site e2e;

  • logout ends pending and superseding sign-ins;

  • I3’s critical section is deferred, with no guarantee resting on it;

  • I3 revocation authentication;

  • no TRUNCATE, and an honest logout-failure message.

No round 3.

Edit this page · default