//! What the relay does for calls (`.agents/features/calls-relay.md`): the long-poll on the fetch route, short-lived //! TURN credentials, and nothing of either stored. Tokens, ids and the TURN secret are generated per test. use axum::body::Body; use axum::http::{header, Method, Request, StatusCode}; use base64::Engine as _; use hmac::{Hmac, Mac}; use http_body_util::BodyExt; use sha1::Sha1; use std::sync::atomic::{AtomicI64, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant}; use tabellarius_protocol::*; use tabellarius_relay::http::{router, AppState, Clock}; use tabellarius_relay::store::Store; use tabellarius_relay::turn::Turn; use tower::ServiceExt; const T0: i64 = 1_796_000_000; fn random() -> [u8; N] { let mut b = [0u8; N]; getrandom::fill(&mut b).expect("system randomness"); b } struct Mailbox { id: MailboxId, post: Token, fetch: Token, } struct Relay { app: axum::Router, _store: Arc, now: Arc, } impl Relay { fn new(turn: Option, max_waiters: usize) -> Self { let store = Arc::new(Store::open_in_memory().expect("store")); let now = Arc::new(AtomicI64::new(T0)); let n = Arc::clone(&now); let clock: Clock = Arc::new(move || n.load(Ordering::SeqCst)); let mut state = AppState::new(Arc::clone(&store), clock).with_max_waiters(max_waiters); if let Some(t) = turn { state = state.with_turn(t); } Self { app: router(state), _store: store, now, } } async fn call( &self, method: Method, path: &str, auth: Option<&Token>, body: Vec, ) -> (StatusCode, Vec) { let mut req = Request::builder().method(method).uri(path); if let Some(t) = auth { req = req.header(header::AUTHORIZATION, t.to_bearer()); } let resp = self .app .clone() .oneshot(req.body(Body::from(body)).expect("request")) .await .expect("infallible"); let status = resp.status(); let bytes = resp .into_body() .collect() .await .expect("body") .to_bytes() .to_vec(); (status, bytes) } async fn mailbox(&self) -> Mailbox { let m = Mailbox { id: MailboxId::from_bytes(random()), post: Token::from_bytes(random()), fetch: Token::from_bytes(random()), }; let body = serde_json::to_vec(&CreateMailbox { id: m.id, post_token_hash: m.post.hash(), fetch_token_hash: m.fetch.hash(), }) .expect("json"); assert_eq!( self.call(Method::POST, "/v0/mailboxes", None, body).await.0, StatusCode::CREATED ); m } async fn post(&self, m: &Mailbox, bytes: &[u8]) -> StatusCode { self.call( Method::POST, &format!("/v0/mailboxes/{}/blobs", m.id.to_wire()), Some(&m.post), bytes.to_vec(), ) .await .0 } async fn fetch(&self, m: &Mailbox, token: &Token, wait: Option) -> (StatusCode, usize) { let q = wait.map(|w| format!("?wait={w}")).unwrap_or_default(); let (status, body) = self .call( Method::GET, &format!("/v0/mailboxes/{}/blobs{q}", m.id.to_wire()), Some(token), vec![], ) .await; let n = if status == StatusCode::OK { serde_json::from_slice::(&body) .expect("json") .blobs .len() } else { 0 }; (status, n) } async fn turn(&self, m: &Mailbox, token: &Token) -> (StatusCode, Vec) { self.call( Method::POST, &format!("/v0/mailboxes/{}/turn", m.id.to_wire()), Some(token), vec![], ) .await } } // --- the long-poll --- #[tokio::test(flavor = "multi_thread")] async fn a_long_poll_answers_as_soon_as_a_blob_arrives() { let relay = Arc::new(Relay::new(None, 1024)); let m = Arc::new(relay.mailbox().await); let (r, mm) = (Arc::clone(&relay), Arc::clone(&m)); let started = Instant::now(); let waiting = tokio::spawn(async move { r.fetch(&mm, &mm.fetch, Some(25)).await }); tokio::time::sleep(Duration::from_millis(300)).await; assert!( !waiting.is_finished(), "nothing waiting, so the request is held" ); assert_eq!(relay.post(&m, b"ring").await, StatusCode::CREATED); let (status, n) = waiting.await.expect("task"); assert_eq!((status, n), (StatusCode::OK, 1)); assert!( started.elapsed() < Duration::from_secs(2), "answered on arrival, not after the wait: {:?}", started.elapsed() ); } #[tokio::test(flavor = "multi_thread")] async fn a_long_poll_with_nothing_arriving_answers_empty_after_the_wait() { let relay = Relay::new(None, 1024); let m = relay.mailbox().await; let started = Instant::now(); assert_eq!( relay.fetch(&m, &m.fetch, Some(1)).await, (StatusCode::OK, 0) ); let took = started.elapsed(); assert!( took >= Duration::from_millis(900) && took < Duration::from_secs(3), "held about a second: {took:?}" ); } #[tokio::test(flavor = "multi_thread")] async fn a_post_to_another_mailbox_does_not_end_the_wait() { let relay = Arc::new(Relay::new(None, 1024)); let (a, b) = (Arc::new(relay.mailbox().await), relay.mailbox().await); let (r, aa) = (Arc::clone(&relay), Arc::clone(&a)); let waiting = tokio::spawn(async move { r.fetch(&aa, &aa.fetch, Some(2)).await }); tokio::time::sleep(Duration::from_millis(200)).await; relay.post(&b, b"not for a").await; tokio::time::sleep(Duration::from_millis(500)).await; assert!(!waiting.is_finished(), "b's blob must not wake a's waiter"); assert_eq!(waiting.await.expect("task"), (StatusCode::OK, 0)); } #[tokio::test(flavor = "multi_thread")] async fn a_waiting_blob_is_answered_at_once_and_a_wrong_token_is_never_held() { let relay = Relay::new(None, 1024); let m = relay.mailbox().await; relay.post(&m, b"already here").await; let started = Instant::now(); assert_eq!( relay.fetch(&m, &m.fetch, Some(25)).await, (StatusCode::OK, 1) ); assert_eq!( relay.fetch(&m, &m.post, Some(25)).await.0, StatusCode::NOT_FOUND, "the post token cannot fetch" ); assert!( started.elapsed() < Duration::from_secs(1), "neither was held" ); } #[tokio::test(flavor = "multi_thread")] async fn a_wait_longer_than_the_limit_is_held_the_limit_at_most() { assert_eq!(MAX_WAIT_SECS, 25); assert_eq!( tabellarius_relay::http::clamp_wait(Some(3600)), Duration::from_secs(25) ); assert_eq!( tabellarius_relay::http::clamp_wait(Some(5)), Duration::from_secs(5) ); assert_eq!(tabellarius_relay::http::clamp_wait(None), Duration::ZERO); } #[tokio::test(flavor = "multi_thread")] async fn over_the_cap_a_long_poll_is_answered_at_once() { let relay = Arc::new(Relay::new(None, 1)); let m = Arc::new(relay.mailbox().await); let (r, mm) = (Arc::clone(&relay), Arc::clone(&m)); let first = tokio::spawn(async move { r.fetch(&mm, &mm.fetch, Some(2)).await }); tokio::time::sleep(Duration::from_millis(200)).await; let started = Instant::now(); assert_eq!( relay.fetch(&m, &m.fetch, Some(25)).await, (StatusCode::OK, 0) ); assert!( started.elapsed() < Duration::from_millis(500), "the second waiter is over the cap" ); assert_eq!(first.await.expect("task"), (StatusCode::OK, 0)); } // --- TURN credentials --- fn turn() -> (Turn, Vec) { let secret = random::<32>().to_vec(); ( Turn::new( secret.clone(), vec![ "turn:turn.test:3478?transport=udp".into(), "turn:turn.test:3478?transport=tcp".into(), ], ), secret, ) } #[tokio::test(flavor = "multi_thread")] async fn without_a_turn_secret_there_is_no_turn_route() { let relay = Relay::new(None, 1024); let m = relay.mailbox().await; assert_eq!(relay.turn(&m, &m.fetch).await.0, StatusCode::NOT_FOUND); } #[tokio::test(flavor = "multi_thread")] async fn turn_credentials_are_coturns_rest_pair_valid_ten_minutes() { let (t, secret) = turn(); let relay = Relay::new(Some(t), 1024); let m = relay.mailbox().await; let (status, body) = relay.turn(&m, &m.fetch).await; assert_eq!(status, StatusCode::OK); let c: TurnCredentials = serde_json::from_slice(&body).expect("json"); let (expiry, rand) = c.username.split_once(':').expect("expiry:random"); assert_eq!( expiry.parse::().expect("number"), T0 + TURN_TTL_SECS as i64 ); assert!(rand.len() >= 16, "a random part, no mailbox in it"); assert!( !c.username.contains(&m.id.to_wire()) && !String::from_utf8_lossy(&body).contains(&m.id.to_wire()) ); let mut mac = Hmac::::new_from_slice(&secret).expect("key"); mac.update(c.username.as_bytes()); assert_eq!( c.password, base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes()) ); assert_eq!(c.ttl, TURN_TTL_SECS); assert_eq!(c.urls.len(), 2); // Two requests give two different usernames. let again: TurnCredentials = serde_json::from_slice(&relay.turn(&m, &m.fetch).await.1).expect("json"); assert_ne!(again.username, c.username); } #[tokio::test(flavor = "multi_thread")] async fn only_the_fetch_token_gets_turn_credentials_and_only_thirty_an_hour() { let (t, _) = turn(); let relay = Relay::new(Some(t), 1024); let m = relay.mailbox().await; assert_eq!(relay.turn(&m, &m.post).await.0, StatusCode::NOT_FOUND); assert_eq!( relay.turn(&m, &Token::from_bytes(random())).await.0, StatusCode::NOT_FOUND ); for i in 0..TURN_PER_HOUR { assert_eq!( relay.turn(&m, &m.fetch).await.0, StatusCode::OK, "credential {i}" ); } assert_eq!( relay.turn(&m, &m.fetch).await.0, StatusCode::TOO_MANY_REQUESTS ); relay.now.fetch_add(3600, Ordering::SeqCst); assert_eq!( relay.turn(&m, &m.fetch).await.0, StatusCode::OK, "a new hour" ); // Another mailbox has its own count. let other = relay.mailbox().await; assert_eq!(relay.turn(&other, &other.fetch).await.0, StatusCode::OK); } #[tokio::test(flavor = "multi_thread")] async fn turn_credentials_and_long_polls_store_nothing() { let dir = tempfile::tempdir().expect("dir"); let path = dir.path().join("relay.db"); let (t, secret) = turn(); let store = Arc::new(Store::open(&path).expect("store")); let clock: Clock = Arc::new(|| T0); let app = router(AppState::new(Arc::clone(&store), clock).with_turn(t)); let relay = Relay { app, _store: store, now: Arc::new(AtomicI64::new(T0)), }; let m = relay.mailbox().await; let before = std::fs::read(&path).expect("db"); let (_, body) = relay.turn(&m, &m.fetch).await; let c: TurnCredentials = serde_json::from_slice(&body).expect("json"); relay.fetch(&m, &m.fetch, Some(1)).await; drop(relay); let after = std::fs::read(&path).expect("db"); assert_eq!(before, after, "the database did not change"); for needle in [c.username.as_bytes(), c.password.as_bytes(), &secret[..]] { assert!( !after.windows(needle.len()).any(|w| w == needle), "nothing of the TURN pair or the secret on disk" ); } } #[test] fn the_turn_flags_come_together_or_not_at_all() { use tabellarius_relay::parse_args; let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::>(); let a = parse_args(s(&[ "--turn-secret-file", "/run/turn", "--turn-url", "turn:t.test:3478?transport=udp", "--turn-url", "turn:t.test:3478?transport=tcp", ])) .expect("valid"); assert_eq!( a.turn_secret_file.as_deref(), Some(std::path::Path::new("/run/turn")) ); assert_eq!(a.turn_urls.len(), 2); assert!( parse_args(s(&["--turn-secret-file", "/run/turn"])).is_err(), "a secret without a URL" ); assert!( parse_args(s(&["--turn-url", "turn:t.test:3478"])).is_err(), "a URL without a secret" ); assert!( parse_args(s(&[ "--turn-secret-file", "/run/turn", "--turn-url", "https://t.test" ])) .is_err(), "not a TURN URL" ); assert!(parse_args(s(&[])) .expect("defaults") .turn_secret_file .is_none()); }