| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | use std::sync::Arc; |
| 19 | use std::time::Duration; |
| 20 | |
| 21 | use futures_util::{StreamExt, stream}; |
| 22 | use im_core::model::Client; |
| 23 | use im_core::store::Store; |
| 24 | use im_core::store::backchannel::{Attempt, Delivery}; |
| 25 | use im_core::time::{now_stamp, stamp_after, stamp_plus, unix_now}; |
| 26 | use serde_json::{Value, json}; |
| 27 | use tokio::sync::watch; |
| 28 | |
| 29 | use crate::oidc::signing; |
| 30 | |
| 31 | |
| 32 | pub const LOGOUT_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout"; |
| 33 | |
| 34 | |
| 35 | pub const DELIVERY_TIMEOUT: Duration = Duration::from_secs(10); |
| 36 | |
| 37 | |
| 38 | const LOGOUT_TOKEN_TTL: i64 = 2 * 60; |
| 39 | |
| 40 | |
| 41 | pub const RETRY_WINDOW: Duration = Duration::from_secs(24 * 60 * 60); |
| 42 | |
| 43 | |
| 44 | const TICK: Duration = Duration::from_secs(5); |
| 45 | |
| 46 | |
| 47 | const BATCH: i64 = 20; |
| 48 | |
| 49 | |
| 50 | |
| 51 | pub const DELIVERY_CONCURRENCY: usize = 8; |
| 52 | |
| 53 | |
| 54 | pub fn backoff(failures: i64) -> Duration { |
| 55 | match failures { |
| 56 | 1 => Duration::from_secs(10), |
| 57 | 2 => Duration::from_secs(30), |
| 58 | 3 => Duration::from_secs(60), |
| 59 | 4 => Duration::from_secs(5 * 60), |
| 60 | _ => Duration::from_secs(15 * 60), |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | |
| 65 | |
| 66 | pub fn http_client() -> reqwest::Client { |
| 67 | reqwest::Client::builder() |
| 68 | .redirect(reqwest::redirect::Policy::none()) |
| 69 | .timeout(DELIVERY_TIMEOUT) |
| 70 | .connect_timeout(DELIVERY_TIMEOUT) |
| 71 | .build() |
| 72 | .expect("the back-channel HTTP client can be built with fixed settings") |
| 73 | } |
| 74 | |
| 75 | |
| 76 | |
| 77 | pub fn spawn( |
| 78 | store: Store, |
| 79 | key: Arc<[u8; 32]>, |
| 80 | issuer: String, |
| 81 | mut stop: watch::Receiver<bool>, |
| 82 | ) -> tokio::task::JoinHandle<()> { |
| 83 | tokio::spawn(async move { |
| 84 | let http = http_client(); |
| 85 | loop { |
| 86 | tokio::select! { |
| 87 | () = tokio::time::sleep(TICK) => {} |
| 88 | _ = stop.wait_for(|stopped| *stopped) => break, |
| 89 | } |
| 90 | if let Err(error) = process_due(&store, &key, &issuer, &http, &now_stamp()).await { |
| 91 | tracing::error!(error = %error, "back-channel pass failed"); |
| 92 | } |
| 93 | } |
| 94 | }) |
| 95 | } |
| 96 | |
| 97 | |
| 98 | |
| 99 | pub async fn process_due( |
| 100 | store: &Store, |
| 101 | key: &[u8; 32], |
| 102 | issuer: &str, |
| 103 | http: &reqwest::Client, |
| 104 | now: &str, |
| 105 | ) -> im_core::Result<usize> { |
| 106 | let due = store.due_deliveries(now, BATCH).await?; |
| 107 | |
| 108 | |
| 109 | let mut pending = Vec::with_capacity(due.len()); |
| 110 | for job in &due { |
| 111 | pending.push(deliver(store, key, issuer, http, job)); |
| 112 | } |
| 113 | let attempts: Vec<Attempt> = stream::iter(pending) |
| 114 | .buffered(DELIVERY_CONCURRENCY) |
| 115 | .collect() |
| 116 | .await; |
| 117 | for (job, attempt) in due.iter().zip(&attempts) { |
| 118 | match attempt { |
| 119 | Attempt::Delivered => tracing::info!(row = %job.id, "back-channel logout delivered"), |
| 120 | Attempt::Retry { |
| 121 | attempts, |
| 122 | next, |
| 123 | error, |
| 124 | } => tracing::warn!( |
| 125 | row = %job.id, attempts, next = %next, error = %error, |
| 126 | "back-channel logout failed; retry scheduled" |
| 127 | ), |
| 128 | Attempt::Abandon { attempts, error } => tracing::error!( |
| 129 | row = %job.id, attempts, error = %error, |
| 130 | "back-channel logout abandoned" |
| 131 | ), |
| 132 | } |
| 133 | |
| 134 | |
| 135 | if let Err(error) = store.record_attempt(&job.id, attempt, &now_stamp()).await { |
| 136 | tracing::error!(row = %job.id, error = %error, "back-channel attempt could not be recorded"); |
| 137 | } |
| 138 | } |
| 139 | Ok(due.len()) |
| 140 | } |
| 141 | |
| 142 | |
| 143 | async fn deliver( |
| 144 | store: &Store, |
| 145 | key: &[u8; 32], |
| 146 | issuer: &str, |
| 147 | http: &reqwest::Client, |
| 148 | job: &Delivery, |
| 149 | ) -> Attempt { |
| 150 | let attempts = job.attempts + 1; |
| 151 | let client = match store.client_by_id(&job.client_id).await { |
| 152 | Ok(Some(client)) => client, |
| 153 | Ok(None) => return abandon(attempts, "the client no longer exists"), |
| 154 | Err(error) => return failure(job, attempts, &error.to_string()), |
| 155 | }; |
| 156 | let Some(uri) = client.backchannel_logout_uri.clone() else { |
| 157 | return abandon(attempts, "the client has no back-channel logout URI"); |
| 158 | }; |
| 159 | let token = match logout_token(store, key, issuer, &client, job).await { |
| 160 | Ok(token) => token, |
| 161 | Err(error) => return failure(job, attempts, &error.to_string()), |
| 162 | }; |
| 163 | match http |
| 164 | .post(&uri) |
| 165 | .form(&[("logout_token", token.as_str())]) |
| 166 | .send() |
| 167 | .await |
| 168 | { |
| 169 | Ok(response) if matches!(response.status().as_u16(), 200 | 204) => Attempt::Delivered, |
| 170 | Ok(response) => failure( |
| 171 | job, |
| 172 | attempts, |
| 173 | &format!("the client answered {}", response.status()), |
| 174 | ), |
| 175 | Err(error) => failure(job, attempts, &describe(&error)), |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | |
| 180 | fn failure(job: &Delivery, attempts: i64, error: &str) -> Attempt { |
| 181 | let window_over = |
| 182 | stamp_plus(&job.created_at, RETRY_WINDOW).is_none_or(|deadline| now_stamp() >= deadline); |
| 183 | if window_over { |
| 184 | return abandon(attempts, &format!("{error}; given up after 24 hours")); |
| 185 | } |
| 186 | Attempt::Retry { |
| 187 | attempts, |
| 188 | next: stamp_after(backoff(attempts)), |
| 189 | error: error.to_owned(), |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | fn abandon(attempts: i64, error: &str) -> Attempt { |
| 194 | Attempt::Abandon { |
| 195 | attempts, |
| 196 | error: error.to_owned(), |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | |
| 201 | fn describe(error: &reqwest::Error) -> String { |
| 202 | if error.is_timeout() { |
| 203 | "the client did not answer within 10 seconds".to_owned() |
| 204 | } else if error.is_connect() { |
| 205 | "the client could not be reached".to_owned() |
| 206 | } else { |
| 207 | "the delivery failed".to_owned() |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | |
| 212 | async fn logout_token( |
| 213 | store: &Store, |
| 214 | key: &[u8; 32], |
| 215 | issuer: &str, |
| 216 | client: &Client, |
| 217 | job: &Delivery, |
| 218 | ) -> im_core::Result<String> { |
| 219 | let now = unix_now(); |
| 220 | let mut claims = json!({ |
| 221 | "iss": issuer, |
| 222 | "aud": client.id, |
| 223 | "iat": now, |
| 224 | "exp": now + LOGOUT_TOKEN_TTL, |
| 225 | "jti": job.jti, |
| 226 | "events": { LOGOUT_EVENT: {} }, |
| 227 | "sub": job.sub, |
| 228 | }); |
| 229 | if let (Some(sid), Some(object)) = (&job.sid, claims.as_object_mut()) { |
| 230 | object.insert("sid".into(), Value::String(sid.clone())); |
| 231 | } |
| 232 | signing::sign(store, key, &claims).await |
| 233 | } |
| 234 | |
| 235 | #[cfg(test)] |
| 236 | mod tests { |
| 237 | use super::*; |
| 238 | use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine as _}; |
| 239 | use im_core::model::amr; |
| 240 | use im_core::store::backchannel::EndReason; |
| 241 | use im_core::store::clients::NewClient; |
| 242 | use im_core::store::sessions::{NewSession, SESSION_IDLE, SignInState}; |
| 243 | use im_core::time::stamp_after; |
| 244 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 245 | use tokio::net::{TcpListener, TcpStream}; |
| 246 | |
| 247 | |
| 248 | async fn read_body(stream: &mut TcpStream) -> String { |
| 249 | let mut buf = Vec::new(); |
| 250 | let mut chunk = [0u8; 1024]; |
| 251 | loop { |
| 252 | let n = stream.read(&mut chunk).await.expect("read"); |
| 253 | if n == 0 { |
| 254 | break; |
| 255 | } |
| 256 | buf.extend_from_slice(&chunk[..n]); |
| 257 | if let Some(head_end) = buf.windows(4).position(|w| w == b"\r\n\r\n") { |
| 258 | let head = String::from_utf8_lossy(&buf[..head_end]).to_ascii_lowercase(); |
| 259 | let length = head |
| 260 | .lines() |
| 261 | .find_map(|line| line.strip_prefix("content-length:")) |
| 262 | .and_then(|value| value.trim().parse::<usize>().ok()) |
| 263 | .unwrap_or(0); |
| 264 | if buf.len() >= head_end + 4 + length { |
| 265 | return String::from_utf8_lossy(&buf[head_end + 4..head_end + 4 + length]) |
| 266 | .into_owned(); |
| 267 | } |
| 268 | } |
| 269 | } |
| 270 | String::from_utf8_lossy(&buf).into_owned() |
| 271 | } |
| 272 | |
| 273 | |
| 274 | |
| 275 | async fn server(statuses: Vec<u16>) -> (String, tokio::task::JoinHandle<Vec<String>>) { |
| 276 | let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); |
| 277 | let addr = listener.local_addr().expect("address"); |
| 278 | let handle = tokio::spawn(async move { |
| 279 | let mut bodies = Vec::new(); |
| 280 | for status in statuses { |
| 281 | let (mut stream, _) = listener.accept().await.expect("accept"); |
| 282 | bodies.push(read_body(&mut stream).await); |
| 283 | let answer = format!( |
| 284 | "HTTP/1.1 {status} test\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" |
| 285 | ); |
| 286 | stream.write_all(answer.as_bytes()).await.expect("write"); |
| 287 | } |
| 288 | bodies |
| 289 | }); |
| 290 | (format!("http://{addr}/auth/backchannel-logout"), handle) |
| 291 | } |
| 292 | |
| 293 | #[tokio::test] |
| 294 | async fn a_failed_delivery_is_retried_until_the_client_answers() { |
| 295 | let (_dir, state) = crate::boot::test_state().await; |
| 296 | signing::maintain(&state.store, &state.key) |
| 297 | .await |
| 298 | .expect("signing key"); |
| 299 | let (uri, received) = server(vec![500, 200]).await; |
| 300 | let client = state |
| 301 | .store |
| 302 | .create_client(&NewClient { |
| 303 | name: "Board", |
| 304 | secret_hash: "secret", |
| 305 | redirect_uris: &[], |
| 306 | post_logout_redirect_uris: &[], |
| 307 | backchannel_logout_uri: Some(&uri), |
| 308 | allowed_scopes: "openid", |
| 309 | service_key: Some("iz"), |
| 310 | }) |
| 311 | .await |
| 312 | .expect("client"); |
| 313 | let user = state |
| 314 | .store |
| 315 | .create_user("ada@example.com", "Ada", "hash", false) |
| 316 | .await |
| 317 | .expect("user"); |
| 318 | let session = state |
| 319 | .store |
| 320 | .create_session( |
| 321 | &NewSession { |
| 322 | user_id: &user.id, |
| 323 | decided_on: SignInState::of(&user), |
| 324 | token_hash: "token", |
| 325 | csrf_token: "csrf", |
| 326 | amr: amr::PASSWORD, |
| 327 | ip: None, |
| 328 | user_agent: None, |
| 329 | idle: SESSION_IDLE, |
| 330 | max_age: std::time::Duration::from_secs(3600), |
| 331 | }, |
| 332 | 10, |
| 333 | ) |
| 334 | .await |
| 335 | .expect("session") |
| 336 | .expect("not refused") |
| 337 | .session; |
| 338 | state |
| 339 | .store |
| 340 | .touch_client_session(&session.id, &client.id) |
| 341 | .await |
| 342 | .expect("client session"); |
| 343 | assert!( |
| 344 | state |
| 345 | .store |
| 346 | .end_session(&user.id, &session.id, EndReason::Logout) |
| 347 | .await |
| 348 | .expect("end") |
| 349 | ); |
| 350 | let http = http_client(); |
| 351 | let issuer = state.config.base_url.clone(); |
| 352 | |
| 353 | |
| 354 | let first = process_due(&state.store, &state.key, &issuer, &http, &now_stamp()) |
| 355 | .await |
| 356 | .expect("first pass"); |
| 357 | assert_eq!(first, 1); |
| 358 | let row = state.store.backchannel_rows().await.expect("rows")[0].clone(); |
| 359 | assert_eq!(row.state, "pending"); |
| 360 | assert_eq!(row.attempts, 1); |
| 361 | assert!( |
| 362 | row.last_error.as_deref().is_some_and(|e| e.contains("500")), |
| 363 | "{:?}", |
| 364 | row.last_error |
| 365 | ); |
| 366 | |
| 367 | |
| 368 | let later = stamp_after(std::time::Duration::from_secs(60)); |
| 369 | assert_eq!( |
| 370 | process_due(&state.store, &state.key, &issuer, &http, &later) |
| 371 | .await |
| 372 | .expect("second pass"), |
| 373 | 1 |
| 374 | ); |
| 375 | let row = state |
| 376 | .store |
| 377 | .backchannel_row(&row.id) |
| 378 | .await |
| 379 | .expect("row") |
| 380 | .expect("present"); |
| 381 | assert_eq!(row.state, "sent"); |
| 382 | |
| 383 | |
| 384 | let bodies = received.await.expect("server"); |
| 385 | assert_eq!(bodies.len(), 2); |
| 386 | let token = bodies[1].strip_prefix("logout_token=").expect("form field"); |
| 387 | let payload = token.split('.').nth(1).expect("payload"); |
| 388 | let claims: serde_json::Value = |
| 389 | serde_json::from_slice(&BASE64_URL_SAFE_NO_PAD.decode(payload).expect("base64")) |
| 390 | .expect("json"); |
| 391 | assert_eq!(claims["aud"], client.id.as_str()); |
| 392 | assert_eq!(claims["sid"], session.id.as_str()); |
| 393 | assert_eq!(claims["sub"], user.id.as_str()); |
| 394 | assert!(claims["events"][LOGOUT_EVENT].is_object()); |
| 395 | assert!(claims.get("nonce").is_none()); |
| 396 | } |
| 397 | } |