forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

backchannel.rs397 lines, 14.9 KiBHistoryRawDownload
1//! The back-channel logout worker (contracts.md 2.5). It delivers the outbox rows that `im-core` queued
2//! when an `im` session ended: it signs a logout token for each row and POSTs it to the client's
3//! `backchannel_logout_uri` as the form field `logout_token`.
4//!
5//! A delivery is done on `200` or `204`. Anything else, or no answer within ten seconds, is a failure and
6//! the row is retried after the backoff of contracts.md 2.5 (10 s, 30 s, 1 min, 5 min, then every 15 min)
7//! until 24 hours after the row was queued; then it is abandoned and logged. Redirects are never
8//! followed. A failure never affects the logout that queued the row: that already committed.
9//!
10//! Due rows are delivered a few at a time (see [`DELIVERY_CONCURRENCY`]), so one slow client does not hold up
11//! the others. Their outcomes are recorded in the order the rows were due.
12//!
13//! The token carries `iss`, `aud` (the client), `iat`, `exp` (two minutes), the row's `jti`, the logout
14//! `events`, `sub` and `sid` (when the row names a session). It carries no `nonce`. Every attempt of a
15//! row re-signs the token with fresh `iat` and `exp` but the same `jti`, so a repeat is recognisable as one
16//! logout (contracts.md 2.5).
17
18use std::sync::Arc;
19use std::time::Duration;
20
21use futures_util::{StreamExt, stream};
22use im_core::model::Client;
23use im_core::store::Store;
24use im_core::store::backchannel::{Attempt, Delivery};
25use im_core::time::{now_stamp, stamp_after, stamp_plus, unix_now};
26use serde_json::{Value, json};
27use tokio::sync::watch;
28
29use crate::oidc::signing;
30
31/// The event name of a logout token (OpenID Back-Channel Logout 1.0).
32pub const LOGOUT_EVENT: &str = "http://schemas.openid.net/event/backchannel-logout";
33
34/// How long a client has to answer one delivery.
35pub const DELIVERY_TIMEOUT: Duration = Duration::from_secs(10);
36
37/// Lifetime of a logout token, in seconds (contracts.md 2.5: two minutes).
38const LOGOUT_TOKEN_TTL: i64 = 2 * 60;
39
40/// How long a row is retried before it is abandoned (contracts.md 2.5: 24 hours).
41pub const RETRY_WINDOW: Duration = Duration::from_secs(24 * 60 * 60);
42
43/// How often the worker looks for due rows.
44const TICK: Duration = Duration::from_secs(5);
45
46/// The most rows one pass delivers.
47const BATCH: i64 = 20;
48
49/// How many deliveries run at once. Each waits up to [`DELIVERY_TIMEOUT`] on its client, so they run together
50/// and the pass takes about as long as its slowest client, not the sum of all of them.
51pub const DELIVERY_CONCURRENCY: usize = 8;
52
53/// How long to wait before the next try after `failures` failed tries (contracts.md 2.5).
54pub 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/// The HTTP client of the worker: ten-second timeouts and no redirects, so a logout is never sent
65/// to another host.
66pub 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/// Runs [`process_due`] every few seconds until `stop` is set. Failures are logged and the next pass
76/// tries again.
77pub 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/// Delivers every row due at `now`, oldest first, and records each outcome. Returns how many rows were
98/// attempted.
99pub 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 // The deliveries are built in a loop and polled `DELIVERY_CONCURRENCY` at a time. `buffered` keeps the
108 // order of `due`, so the outcomes are recorded oldest first.
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 // A failed write must not hold up the rows after it: they were already sent, and an unrecorded row
134 // is sent again on the next pass. The failure is logged and the loop goes on.
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/// One attempt for one row. Every failure path returns an [`Attempt`]; nothing here is fatal.
143async 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/// A failed attempt: retried after the backoff, or abandoned when the retry window has passed.
180fn 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
193fn abandon(attempts: i64, error: &str) -> Attempt {
194 Attempt::Abandon {
195 attempts,
196 error: error.to_owned(),
197 }
198}
199
200/// A short description of a transport error, for the log and the row. Never the token.
201fn 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/// Signs the logout token of one row for `client` (contracts.md 2.5).
212async 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)]
236mod 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 /// Reads one HTTP request from `stream` and returns its body.
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 /// A local server that answers successive connections with the given statuses. Returns its URL and
274 /// a handle that yields the request bodies it received.
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 // The first pass meets the 500: the row waits for its first backoff.
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 // Once the backoff has passed, the second pass gets the 200.
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 // Both deliveries carried a logout token for this client and session, without a nonce.
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}