Plan: BFF Token Refresh (Issue #411)
Status
| Step | Description | Status |
|---|---|---|
1 |
Extend |
Not started |
2 |
New helper |
Not started |
3 |
|
Not started |
4 |
Flip every BFF call site from |
Not started |
5 |
Concurrency: two parallel BFF requests on the same session can both hit refresh simultaneously. Per-session |
Not started |
6 |
Tests: 4 unit tests in |
Not started |
7 |
Drop the back-compat shims left by 422: remove |
Not started |
8 |
Docs sync. CHANGELOG |
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— capturesaccess_tokenfrom OIDC token response, stores in session. Does not capturerefresh_tokenorexpires_in. -
services/canopy-web/src/session.rs:61—SessionData.access_token: String. Norefresh_tokenfield. -
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_expcaptured from OIDC login response, stored in session. -
with_fresh_tokenhelper 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_tokenin 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:
-
OidcDiscoverystruct +BootstrapResult.discovery: Arc<OidcDiscovery>. -
Provider-neutral config keys (
oidc_*). -
JwksProvider::from_discoveryconstructor.
-
-
services/canopy-web/src/session.rs— extendsSessionData. -
services/canopy-web/src/auth.rs— capturesrefresh_token+expires_in. -
services/canopy-web/src/clients.rs—with_fresh_tokenhelper. -
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 |
|---|---|
|
Add |
|
Capture refresh_token + expires_in at login. |
|
New helper — |
|
|
|
Flip ~9 call sites. |
|
Drop deprecated |
|
Drop |
|
Drop |
|
New (4 tests). |
|
Single-assertion + 6-minute-idle spec. |
|
|
|
Service-to-service auth bullet flips to Resolved. |
|
This plan; moves to |
No schema migrations. No new workspace dependencies.
Verification
Per-step
-
cargo nextest run -p canopy-auth --test refresh_test— 4 unit tests pass. -
cargo xtask e2e — applications.spec.ts— Playwright regression spec passes (6-minute-idle then action) where it previously 401’d. -
cargo xtask validate— full battery green.
End-to-end
-
Log in as a caseworker via
/login. Verifyapplication-processpage renders with full data (not the empty-default fallback). -
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.
-
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_tokenin 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.