Plan: BFF Token Refresh (Issue #411)

Status

Step Description Status

1

Extend services/canopy-web/src/auth.rs (the post-#422 refactored version) to capture refresh_token and expires_in from the OIDC token-exchange response. Persist both in SessionData (services/canopy-web/src/session.rs:61) alongside access_token: add refresh_token: String, access_token_exp: DateTime<Utc>. expires_in (seconds) → absolute DateTime<Utc> at session creation so we don’t repeat clock-skew handling on every BFF call. Threat-model note: refresh_tokens are stored in the existing PostgreSQL session table (tower-sessions-sqlx-store) at the same protection level as today’s access_token. PG-at-rest encryption (ADR-017 SOPS+age) covers the DB volume; session_id is a random UUID. Defense-in-depth field-level encryption of refresh_token deferred — would file a separate issue if the threat model changes (e.g., post-UAT Pub 1075 ATO review).

Not started

2

New helper services/canopy-web/src/auth/refresh.rs — pub async fn refresh_token(discovery: &OidcDiscovery, client_id: &str, refresh_token: &str) → Result<TokenResponse, AuthError>. POSTs to discovery.token_endpoint (no hardcoded path; provider-neutral by construction post-#422) with grant_type=refresh_token. RFC 6749 standard grant. Returns new access_token + refresh_token (Keycloak rotates by default; Okta optionally; Auth0 by default) + new expires_in.

Not started

3

ServiceClients::with_fresh_token in services/canopy-web/src/clients.rs. Signature: pub async fn with_fresh_token(self: &Arc<Self>, session: &tower_sessions::Session, worker: &mut SessionData, discovery: &OidcDiscovery, oidc_client_id: &str) → Result<ServiceClients, AuthError>. Fast path: if worker.access_token_exp - chrono::Duration::seconds(30) > Utc::now(), returns (*self).clone().with_token(worker.access_token.clone()). Slow path: take the per-session refresh mutex (Step 5), re-read session in case another request just refreshed, if still expired call auth::refresh::refresh_token(discovery, oidc_client_id, &worker.refresh_token).await?, mutate worker in place with the new tokens, persist via store_session(session, worker).await?, return (*self).clone().with_token(…​). The 30 s buffer protects in-flight requests crossing the expiry boundary. The keep-this-simple choice: returns ServiceClients not Cow<ServiceClients> — clone cost is one Arc bump per inner client (~12 services), invisible at request rate.

Not started

4

Flip every BFF call site from clients.with_token(&worker.access_token) to clients.with_fresh_token(&session, &mut worker, &discovery, &oidc_client_id).await?. Touched files: services/canopy-web/src/api/{applications,actions,appeals,cases,dashboard,notices,renewals}.rs (~9 call sites). The discovery doc + client id come from request-scoped extensions wired in canopy-web’s app builder.

Not started

5

Concurrency: two parallel BFF requests on the same session can both hit refresh simultaneously. Per-session tokio::sync::Mutex<()> guards the refresh critical section, keyed off session id. SessionRefreshGuard extension maps session-id → Arc<Mutex<()>> via a tokio RwLock<HashMap<…​>>. First caller refreshes; second sees the freshly-stored token on session re-read. Single-flight pattern; same shape as canopy-mq’s reconnect single-flight (crates/canopy-mq/src/connection.rs).

Not started

6

Tests: 4 unit tests in crates/canopy-auth/tests/refresh_test.rs covering (a) successful refresh updates session data, (b) refresh failure → AuthError::RefreshFailed, (c) concurrent refreshes single-flight, (d) buffer threshold (29 s before expiry → no refresh, 31 s before → refresh). 1 Playwright update: tests/e2e/specs/applications.spec.ts flips the dual-assertion to single-assertion (no more graceful-empty fallback) and adds a 6-minute-idle spec that exercises the refresh path.

Not started

7

Drop the back-compat shims left by 422: remove JwksProvider::new (the deprecated Keycloak-path fallback), drop [serde(alias = "keycloak_*")] annotations on settings + config. The codebase is now provider-neutral end-to-end.

Not started

8

Docs sync. CHANGELOG == Unreleased / === Fixed. playwright-e2e.adoc "service-to-service auth" PI bullet flips to "Resolved 2026-MM-DD". Plan moves to plans/archive/bff-token-refresh.adoc post-merge.

Not started

Issue: #411
Branch: fix/bff-token-refresh — must branch off main AFTER #422 has merged. Do not branch off #422’s open MR; that creates merge-order dependencies the GitLab UI can’t model cleanly. If B1 work needs to start before #422 lands, branch off main and rebase forward when #422 merges.
Labels: type::fix, priority::high, service::web, service::security, program::infrastructure, workflow::blocked (flips to workflow::ready when #422 merges).

Context

services/canopy-web/src/clients.rs:51 already forwards the worker’s session JWT via bearer_auth to upstream services. Upstream services validate via the shared JWKS (crates/canopy-auth/src/jwks.rs) with audience = "canopy". Both the canopy-ui and canopy-api Keycloak clients have audience mappers (verified at devstack/keycloak/canopy-realm.json). So the auth shape is right.

The 401 is token expiry without refresh. Keycloak’s default access-token TTL is 5 minutes. Worker session lasts 30 minutes (per CLAUDE.md). After 5 minutes of caseworker inactivity on a long page, the next BFF call forwards a stale access_token and the upstream rejects it. The application-process page renders with empty data because clients.applications.get(…​) returns Err(401) and the handler falls back to defaults.

Code references

  • services/canopy-web/src/auth.rs:187-209 — captures access_token from OIDC token response, stores in session. Does not capture refresh_token or expires_in.

  • services/canopy-web/src/session.rs:61 — SessionData.access_token: String. No refresh_token field.

  • services/canopy-web/src/api/applications.rs:62-80 — call-site graceful-degradation path that masks the 401.

  • tests/e2e/specs/applications.spec.ts:17-39 — Playwright spec with the dual-assertion (banner OR error div) pattern that documents the bug.

Why this depends on #422

User has explicitly asked that the fix not bake in Keycloak-specific behaviour. OAuth 2.0 RFC 6749 refresh_token grant is standard across OIDC providers (Keycloak, Okta, Auth0, Azure AD all support it). But the token-endpoint URL has to come from somewhere. Pre-#422 it would have been format!("{base}/protocol/openid-connect/token", …​) — Keycloak-specific path. Post-#422 it’s discovery.token_endpoint — provider-neutral by construction.

So this MR depends on #422 (oidc-pluggability-refactor) merging first, or at minimum being available on the same branch.

Scope

In scope:

  • refresh_token + access_token_exp captured from OIDC login response, stored in session.

  • with_fresh_token helper that refreshes when expiry is < 30 s away.

  • Single-flight refresh per session.

  • All ~9 BFF call sites updated.

  • Cleanup of #422’s back-compat shims (JwksProvider::new + serde aliases).

  • Playwright regression coverage (6-minute-idle scenario).

Out of scope:

  • IdP-pluggability refactor — handled by #422.

  • Service-account / client-credentials flow — separate concern. File if/when a background-job consumer of canopy-web’s BFF emerges.

  • Field-level encryption of refresh_token in session storage — defer until threat model changes (post-UAT Pub 1075 ATO review).

  • Automatic logout on refresh-token expiry — current behaviour redirects to /login, which is correct UX.

Dependencies

  • #422 must merge first. Provides:

    • OidcDiscovery struct + BootstrapResult.discovery: Arc<OidcDiscovery>.

    • Provider-neutral config keys (oidc_*).

    • JwksProvider::from_discovery constructor.

  • services/canopy-web/src/session.rs — extends SessionData.

  • services/canopy-web/src/auth.rs — captures refresh_token + expires_in.

  • services/canopy-web/src/clients.rs — with_fresh_token helper.

  • services/canopy-web/src/api/{applications,actions,appeals,cases,dashboard,notices,renewals}.rs — call-site flips.

No schema migrations. No new workspace dependencies.

Design

Refresh-token capture

Today (post-#422):

let access_token = body["access_token"].as_str()?;
// access_token stored, refresh_token + expires_in dropped.

Post-this-MR:

let access_token = body["access_token"].as_str()?;
let refresh_token = body["refresh_token"].as_str()?;
let expires_in: u64 = body["expires_in"].as_u64().unwrap_or(300);
let access_token_exp = Utc::now() + Duration::seconds(expires_in as i64);
// All three persisted in SessionData.

with_fresh_token flow

impl ServiceClients {
    pub async fn with_fresh_token(
        self: &Arc<Self>,
        session: &tower_sessions::Session,
        worker: &mut SessionData,
        discovery: &OidcDiscovery,
        oidc_client_id: &str,
    ) -> Result<ServiceClients, AuthError> {
        // Fast path: token has > 30s left.
        if worker.access_token_exp - Duration::seconds(30) > Utc::now() {
            return Ok((*self).clone().with_token(worker.access_token.clone()));
        }

        // Slow path: take per-session mutex, re-check, refresh if still needed.
        let guard = session_refresh_lock(session).await;
        let _held = guard.lock().await;

        // Re-read session — another request may have refreshed already.
        if let Ok(fresh) = load_session(session).await {
            *worker = fresh;
            if worker.access_token_exp - Duration::seconds(30) > Utc::now() {
                return Ok((*self).clone().with_token(worker.access_token.clone()));
            }
        }

        // Refresh.
        let resp = auth::refresh::refresh_token(
            discovery,
            oidc_client_id,
            &worker.refresh_token,
        ).await?;

        worker.access_token = resp.access_token.clone();
        worker.refresh_token = resp.refresh_token;
        worker.access_token_exp = Utc::now() + Duration::seconds(resp.expires_in as i64);

        store_session(session, worker).await?;

        Ok((*self).clone().with_token(resp.access_token))
    }
}

Single-flight refresh

SessionRefreshGuard — a tokio RwLock<HashMap<SessionId, Arc<Mutex<()>>>> extension on the request — gives each session a private mutex. The first request to expire takes the mutex, refreshes, stores. The second waits on the mutex, then re-reads the session and sees the fresh token. No double-refresh, no rate-limit violation against the IdP.

This mirrors canopy-mq’s reconnect single-flight (crates/canopy-mq/src/connection.rs:reconnect()).

Files Touched

File Change

services/canopy-web/src/session.rs

Add refresh_token: String, access_token_exp: DateTime<Utc>.

services/canopy-web/src/auth.rs

Capture refresh_token + expires_in at login.

services/canopy-web/src/auth/refresh.rs

New helper — refresh_token against discovery.token_endpoint.

services/canopy-web/src/clients.rs

with_fresh_token helper.

services/canopy-web/src/api/{applications,actions,appeals,cases,dashboard,notices,renewals}.rs

Flip ~9 call sites.

crates/canopy-auth/src/jwks.rs

Drop deprecated JwksProvider::new.

crates/canopy-common/src/settings.rs

Drop #[serde(alias = "keycloak_*")].

services/canopy-web/src/config.rs

Drop #[serde(alias = "keycloak_*")].

crates/canopy-auth/tests/refresh_test.rs

New (4 tests).

tests/e2e/specs/applications.spec.ts

Single-assertion + 6-minute-idle spec.

CHANGELOG.adoc

== Unreleased / === Fixed entry.

docs/modules/ROOT/pages/plans/archive/playwright-e2e.adoc

Service-to-service auth bullet flips to Resolved.

docs/modules/ROOT/pages/plans/bff-token-refresh.adoc

This plan; moves to plans/archive/ post-merge.

No schema migrations. No new workspace dependencies.

Verification

Per-step

  1. cargo nextest run -p canopy-auth --test refresh_test — 4 unit tests pass.

  2. cargo xtask e2e — applications.spec.ts — Playwright regression spec passes (6-minute-idle then action) where it previously 401’d.

  3. cargo xtask validate — full battery green.

End-to-end

  1. Log in as a caseworker via /login. Verify application-process page renders with full data (not the empty-default fallback).

  2. Wait 6 minutes (Keycloak access-token TTL = 5 min). Trigger an action (e.g., file an appeal). Confirm 200 response and the upstream service logs no 401.

  3. Open two browser tabs to the same case detail. Hit a refresh action simultaneously. Confirm only ONE refresh request lands at Keycloak (single-flight check via docker compose logs keycloak \| grep token).

Risk + Rollback

Risk: refresh failures (IdP unreachable, refresh_token expired) surface as 500 s on user-visible pages.
Mitigation: when refresh_token fails, redirect to /login (the user re-authenticates). Same UX as if the session itself expired. Logged at WARN.

Rollback: revert the MR. The #422 abstractions stay; this MR only adds the refresh path on top of them.

Potential Improvements

(Out of scope; file separately if/when relevant.)

  • Field-level encryption of refresh_token in session storage (defense-in-depth beyond ADR-017 PG-at-rest). Defer until threat model changes (e.g., post-UAT Pub 1075 ATO review).

  • Service-account / client-credentials flow for any future background job that calls upstream services. File when the first such consumer emerges.

  • Refresh-on-401 retry — if a BFF call still 401s after a fresh-token refresh (IdP rotated keys mid-flight), retry once with a new refresh. Today’s behaviour surfaces the 401 to the caller.

Errata

(none)

Edit this page · default