//! The back-channel logout worker (contracts.md 2.5). It delivers the outbox rows that `im-core` queued //! when an `im` session ended: it signs a logout token for each row and POSTs it to the client's //! `backchannel_logout_uri` as the form field `logout_token`. //! //! A delivery is done on `200` or `204`. Anything else, or no answer within ten seconds, is a failure and //! the row is retried after the backoff of contracts.md 2.5 (10 s, 30 s, 1 min, 5 min, then every 15 min) //! until 24 hours after the row was queued; then it is abandoned and logged. Redirects are never //! followed. A failure never affects the logout that queued the row: that already committed. //! //! Due rows are delivered a few at a time (see [`DELIVERY_CONCURRENCY`]), so one slow client does not hold up //! the others. Their outcomes are recorded in the order the rows were due. //! //! The token carries `iss`, `aud` (the client), `iat`, `exp` (two minutes), the row's `jti`, the logout //! `events`, `sub` and `sid` (when the row names a session). It carries no `nonce`. Every attempt of a //! row re-signs the token with fresh `iat` and `exp` but the same `jti`, so a repeat is recognisable as one //! logout (contracts.md 2.5). use std::sync::Arc; use std::time::Duration; use futures_util::{StreamExt, stream}; use im_core::model::Client; use im_core::store::Store; use im_core::store::backchannel::{Attempt, Delivery}; use im_core::time::{now_stamp, stamp_after, stamp_plus, unix_now}; use serde_json::{Value, json}; use tokio::sync::watch; use crate::oidc::signing; /// The event name of a logout token (OpenID Back-Channel Logout 1.0). pub const LOGOUT_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout"; /// How long a client has to answer one delivery. pub const DELIVERY_TIMEOUT: Duration = Duration::from_secs(10); /// Lifetime of a logout token, in seconds (contracts.md 2.5: two minutes). const LOGOUT_TOKEN_TTL: i64 = 2 * 60; /// How long a row is retried before it is abandoned (contracts.md 2.5: 24 hours). pub const RETRY_WINDOW: Duration = Duration::from_secs(24 * 60 * 60); /// How often the worker looks for due rows. const TICK: Duration = Duration::from_secs(5); /// The most rows one pass delivers. const BATCH: i64 = 20; /// How many deliveries run at once. Each waits up to [`DELIVERY_TIMEOUT`] on its client, so they run together /// and the pass takes about as long as its slowest client, not the sum of all of them. pub const DELIVERY_CONCURRENCY: usize = 8; /// How long to wait before the next try after `failures` failed tries (contracts.md 2.5). pub fn backoff(failures: i64) -> Duration { match failures { 1 => Duration::from_secs(10), 2 => Duration::from_secs(30), 3 => Duration::from_secs(60), 4 => Duration::from_secs(5 * 60), _ => Duration::from_secs(15 * 60), } } /// The HTTP client of the worker: ten-second timeouts and no redirects, so a logout is never sent /// to another host. pub fn http_client() -> reqwest::Client { reqwest::Client::builder() .redirect(reqwest::redirect::Policy::none()) .timeout(DELIVERY_TIMEOUT) .connect_timeout(DELIVERY_TIMEOUT) .build() .expect("the back-channel HTTP client can be built with fixed settings") } /// Runs [`process_due`] every few seconds until `stop` is set. Failures are logged and the next pass /// tries again. pub fn spawn( store: Store, key: Arc<[u8; 32]>, issuer: String, mut stop: watch::Receiver, ) -> tokio::task::JoinHandle<()> { tokio::spawn(async move { let http = http_client(); loop { tokio::select! { () = tokio::time::sleep(TICK) => {} _ = stop.wait_for(|stopped| *stopped) => break, } if let Err(error) = process_due(&store, &key, &issuer, &http, &now_stamp()).await { tracing::error!(error = %error, "back-channel pass failed"); } } }) } /// Delivers every row due at `now`, oldest first, and records each outcome. Returns how many rows were /// attempted. pub async fn process_due( store: &Store, key: &[u8; 32], issuer: &str, http: &reqwest::Client, now: &str, ) -> im_core::Result { let due = store.due_deliveries(now, BATCH).await?; // The deliveries are built in a loop and polled `DELIVERY_CONCURRENCY` at a time. `buffered` keeps the // order of `due`, so the outcomes are recorded oldest first. let mut pending = Vec::with_capacity(due.len()); for job in &due { pending.push(deliver(store, key, issuer, http, job)); } let attempts: Vec = stream::iter(pending) .buffered(DELIVERY_CONCURRENCY) .collect() .await; for (job, attempt) in due.iter().zip(&attempts) { match attempt { Attempt::Delivered => tracing::info!(row = %job.id, "back-channel logout delivered"), Attempt::Retry { attempts, next, error, } => tracing::warn!( row = %job.id, attempts, next = %next, error = %error, "back-channel logout failed; retry scheduled" ), Attempt::Abandon { attempts, error } => tracing::error!( row = %job.id, attempts, error = %error, "back-channel logout abandoned" ), } // A failed write must not hold up the rows after it: they were already sent, and an unrecorded row // is sent again on the next pass. The failure is logged and the loop goes on. if let Err(error) = store.record_attempt(&job.id, attempt, &now_stamp()).await { tracing::error!(row = %job.id, error = %error, "back-channel attempt could not be recorded"); } } Ok(due.len()) } /// One attempt for one row. Every failure path returns an [`Attempt`]; nothing here is fatal. async fn deliver( store: &Store, key: &[u8; 32], issuer: &str, http: &reqwest::Client, job: &Delivery, ) -> Attempt { let attempts = job.attempts + 1; let client = match store.client_by_id(&job.client_id).await { Ok(Some(client)) => client, Ok(None) => return abandon(attempts, "the client no longer exists"), Err(error) => return failure(job, attempts, &error.to_string()), }; let Some(uri) = client.backchannel_logout_uri.clone() else { return abandon(attempts, "the client has no back-channel logout URI"); }; let token = match logout_token(store, key, issuer, &client, job).await { Ok(token) => token, Err(error) => return failure(job, attempts, &error.to_string()), }; match http .post(&uri) .form(&[("logout_token", token.as_str())]) .send() .await { Ok(response) if matches!(response.status().as_u16(), 200 | 204) => Attempt::Delivered, Ok(response) => failure( job, attempts, &format!("the client answered {}", response.status()), ), Err(error) => failure(job, attempts, &describe(&error)), } } /// A failed attempt: retried after the backoff, or abandoned when the retry window has passed. fn failure(job: &Delivery, attempts: i64, error: &str) -> Attempt { let window_over = stamp_plus(&job.created_at, RETRY_WINDOW).is_none_or(|deadline| now_stamp() >= deadline); if window_over { return abandon(attempts, &format!("{error}; given up after 24 hours")); } Attempt::Retry { attempts, next: stamp_after(backoff(attempts)), error: error.to_owned(), } } fn abandon(attempts: i64, error: &str) -> Attempt { Attempt::Abandon { attempts, error: error.to_owned(), } } /// A short description of a transport error, for the log and the row. Never the token. fn describe(error: &reqwest::Error) -> String { if error.is_timeout() { "the client did not answer within 10 seconds".to_owned() } else if error.is_connect() { "the client could not be reached".to_owned() } else { "the delivery failed".to_owned() } } /// Signs the logout token of one row for `client` (contracts.md 2.5). async fn logout_token( store: &Store, key: &[u8; 32], issuer: &str, client: &Client, job: &Delivery, ) -> im_core::Result { let now = unix_now(); let mut claims = json!({ "iss": issuer, "aud": client.id, "iat": now, "exp": now + LOGOUT_TOKEN_TTL, "jti": job.jti, "events": { LOGOUT_EVENT: {} }, "sub": job.sub, }); if let (Some(sid), Some(object)) = (&job.sid, claims.as_object_mut()) { object.insert("sid".into(), Value::String(sid.clone())); } signing::sign(store, key, &claims).await } #[cfg(test)] mod tests { use super::*; use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; use im_core::model::amr; use im_core::store::backchannel::EndReason; use im_core::store::clients::NewClient; use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState}; use im_core::time::stamp_after; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; /// Reads one HTTP request from `stream` and returns its body. async fn read_body(stream: &mut TcpStream) -> String { let mut buf = Vec::new(); let mut chunk = [0u8; 1024]; loop { let n = stream.read(&mut chunk).await.expect("read"); if n == 0 { break; } buf.extend_from_slice(&chunk[..n]); if let Some(head_end) = buf.windows(4).position(|w| w == b"\r\n\r\n") { let head = String::from_utf8_lossy(&buf[..head_end]).to_ascii_lowercase(); let length = head .lines() .find_map(|line| line.strip_prefix("content-length:")) .and_then(|value| value.trim().parse::().ok()) .unwrap_or(0); if buf.len() >= head_end + 4 + length { return String::from_utf8_lossy(&buf[head_end + 4..head_end + 4 + length]) .into_owned(); } } } String::from_utf8_lossy(&buf).into_owned() } /// A local server that answers successive connections with the given statuses. Returns its URL and /// a handle that yields the request bodies it received. async fn server(statuses: Vec) -> (String, tokio::task::JoinHandle>) { let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); let addr = listener.local_addr().expect("address"); let handle = tokio::spawn(async move { let mut bodies = Vec::new(); for status in statuses { let (mut stream, _) = listener.accept().await.expect("accept"); bodies.push(read_body(&mut stream).await); let answer = format!( "HTTP/1.1 {status} test\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" ); stream.write_all(answer.as_bytes()).await.expect("write"); } bodies }); (format!("http://{addr}/auth/backchannel-logout"), handle) } #[tokio::test] async fn a_failed_delivery_is_retried_until_the_client_answers() { let (_dir, state) = crate::boot::test_state().await; signing::maintain(&state.store, &state.key) .await .expect("signing key"); let (uri, received) = server(vec![500, 200]).await; let client = state .store .create_client(&NewClient { name: "Board", secret_hash: "secret", redirect_uris: &[], post_logout_redirect_uris: &[], backchannel_logout_uri: Some(&uri), allowed_scopes: "openid", service_key: Some("iz"), }) .await .expect("client"); let user = state .store .create_user("ada@example.com", "Ada", "hash", false) .await .expect("user"); let session = state .store .create_session( &NewSession { user_id: &user.id, decided_on: SignInState::of(&user), token_hash: "token", csrf_token: "csrf", amr: amr::PASSWORD, ip: None, user_agent: None, idle: SESSION_IDLE, max_age: std::time::Duration::from_secs(3600), }, 10, ) .await .expect("session") .expect("not refused") .session; state .store .touch_client_session(&session.id, &client.id) .await .expect("client session"); assert!( state .store .end_session(&user.id, &session.id, EndReason::Logout) .await .expect("end") ); let http = http_client(); let issuer = state.config.base_url.clone(); // The first pass meets the 500: the row waits for its first backoff. let first = process_due(&state.store, &state.key, &issuer, &http, &now_stamp()) .await .expect("first pass"); assert_eq!(first, 1); let row = state.store.backchannel_rows().await.expect("rows")[0].clone(); assert_eq!(row.state, "pending"); assert_eq!(row.attempts, 1); assert!( row.last_error.as_deref().is_some_and(|e| e.contains("500")), "{:?}", row.last_error ); // Once the backoff has passed, the second pass gets the 200. let later = stamp_after(std::time::Duration::from_secs(60)); assert_eq!( process_due(&state.store, &state.key, &issuer, &http, &later) .await .expect("second pass"), 1 ); let row = state .store .backchannel_row(&row.id) .await .expect("row") .expect("present"); assert_eq!(row.state, "sent"); // Both deliveries carried a logout token for this client and session, without a nonce. let bodies = received.await.expect("server"); assert_eq!(bodies.len(), 2); let token = bodies[1].strip_prefix("logout_token=").expect("form field"); let payload = token.split('.').nth(1).expect("payload"); let claims: serde_json::Value = serde_json::from_slice(&BASE64_URL_SAFE_NO_PAD.decode(payload).expect("base64")) .expect("json"); assert_eq!(claims["aud"], client.id.as_str()); assert_eq!(claims["sid"], session.id.as_str()); assert_eq!(claims["sub"], user.id.as_str()); assert!(claims["events"][LOGOUT_EVENT].is_object()); assert!(claims.get("nonce").is_none()); } }