//! Wake-up (`docs/PROTOCOL.md` ยง6, `.agents/features/wake-up.md`): the push routes and the one //! request the relay sends, against a push server on loopback. Tokens and ids are generated per test. use axum::body::{Body, Bytes}; use axum::http::{header, HeaderMap, Method, Request, StatusCode}; use http_body_util::BodyExt; use std::sync::atomic::{AtomicI64, AtomicU16, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; use tabellarius_protocol::*; use tabellarius_relay::http::{router, AppState, Clock}; use tabellarius_relay::store::Store; use tabellarius_relay::wake::Waker; use tower::ServiceExt; const T0: i64 = 1_794_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, } impl Mailbox { fn new() -> Self { Self { id: MailboxId::from_bytes(random()), post: Token::from_bytes(random()), fetch: Token::from_bytes(random()), } } fn path(&self, rest: &str) -> String { format!("/v0/mailboxes/{}/{rest}", self.id.to_wire()) } } /// What reached the push server: path, headers, body. #[derive(Clone)] struct Seen { path: String, headers: HeaderMap, body: Vec, } /// A push server on loopback that records every request and answers with `status`. struct PushServer { port: u16, seen: Arc>>, status: Arc, } impl PushServer { async fn start() -> Self { let seen = Arc::new(Mutex::new(Vec::new())); let status = Arc::new(AtomicU16::new(201)); let (s, st) = (Arc::clone(&seen), Arc::clone(&status)); let app = axum::Router::new().fallback( move |uri: axum::http::Uri, headers: HeaderMap, body: Bytes| { let (s, st) = (Arc::clone(&s), Arc::clone(&st)); async move { s.lock().expect("seen").push(Seen { path: uri.to_string(), headers, body: body.to_vec(), }); StatusCode::from_u16(st.load(Ordering::SeqCst)).expect("status") } }, ); let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await .expect("bind"); let port = listener.local_addr().expect("addr").port(); tokio::spawn(async move { let _ = axum::serve(listener, app).await; }); Self { port, seen, status } } fn endpoint(&self, path: &str) -> String { format!("http://127.0.0.1:{}{path}", self.port) } fn seen(&self) -> Vec { self.seen.lock().expect("seen").clone() } /// Waits up to 5 s for `n` requests. async fn wait_for(&self, n: usize) -> Vec { for _ in 0..100 { if self.seen().len() >= n { break; } tokio::time::sleep(Duration::from_millis(50)).await; } self.seen() } /// Gives a wake that should not happen a second to show up anyway. async fn quiet(&self) -> Vec { tokio::time::sleep(Duration::from_secs(1)).await; self.seen() } } struct Relay { app: axum::Router, store: Arc, now: Arc, } impl Relay { /// `loopback`: the relay was started with `--push-loopback`, as tests must be to reach a local /// push server. fn new(loopback: bool) -> 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 app = router(AppState::with_waker( Arc::clone(&store), clock, Waker::new(loopback), )); Self { app, store, now } } async fn call( &self, method: Method, path: &str, auth: Option<&Token>, body: Vec, ) -> StatusCode { 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 body = resp.into_body().collect().await.expect("body").to_bytes(); assert!( status != StatusCode::NOT_FOUND || body.is_empty(), "a 404 has no body" ); status } async fn mailbox(&self) -> Mailbox { let m = Mailbox::new(); 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, StatusCode::CREATED ); m } async fn set_push(&self, m: &Mailbox, token: &Token, endpoint: &str) -> StatusCode { let body = format!(r#"{{"endpoint":"{endpoint}"}}"#).into_bytes(); self.call(Method::PUT, &m.path("push"), Some(token), body) .await } async fn clear_push(&self, m: &Mailbox, token: &Token) -> StatusCode { self.call(Method::DELETE, &m.path("push"), Some(token), vec![]) .await } async fn post(&self, m: &Mailbox, token: &Token, blob: &[u8]) -> StatusCode { self.call(Method::POST, &m.path("blobs"), Some(token), blob.to_vec()) .await } fn advance(&self, secs: i64) { self.now.fetch_add(secs, Ordering::SeqCst); } } #[tokio::test(flavor = "multi_thread")] async fn only_the_owner_sets_or_clears_where_to_be_woken() { let relay = Relay::new(true); let push = PushServer::start().await; let m = relay.mailbox().await; let endpoint = push.endpoint("/up/a"); // The post token is the contact's: it cannot say where the owner is woken. assert_eq!( relay.set_push(&m, &m.post, &endpoint).await, StatusCode::NOT_FOUND ); assert_eq!( relay.set_push(&Mailbox::new(), &m.fetch, &endpoint).await, StatusCode::NOT_FOUND ); assert_eq!( relay .call(Method::PUT, &m.path("push"), Some(&m.fetch), b"{}".to_vec()) .await, StatusCode::BAD_REQUEST ); assert_eq!( relay .set_push(&m, &m.fetch, "http://push.example.cz/up") .await, StatusCode::BAD_REQUEST ); assert_eq!( relay.set_push(&m, &m.fetch, &endpoint).await, StatusCode::NO_CONTENT ); assert_eq!( relay.store.push_endpoint(&m.id).expect("read"), Some(endpoint) ); assert_eq!(relay.clear_push(&m, &m.post).await, StatusCode::NOT_FOUND); assert_eq!(relay.clear_push(&m, &m.fetch).await, StatusCode::NO_CONTENT); assert_eq!(relay.store.push_endpoint(&m.id).expect("read"), None); // Clearing what is not there is not an error. assert_eq!(relay.clear_push(&m, &m.fetch).await, StatusCode::NO_CONTENT); } #[tokio::test(flavor = "multi_thread")] async fn a_relay_facing_the_internet_refuses_loopback_endpoints() { let relay = Relay::new(false); let m = relay.mailbox().await; assert_eq!( relay.set_push(&m, &m.fetch, "http://127.0.0.1:9/up").await, StatusCode::BAD_REQUEST ); assert_eq!(relay.store.push_endpoint(&m.id).expect("read"), None); } #[tokio::test(flavor = "multi_thread")] async fn a_post_wakes_with_a_constant_and_nothing_of_the_mailbox_or_the_blob() { let relay = Relay::new(true); let push = PushServer::start().await; let m = relay.mailbox().await; assert_eq!( relay .set_push(&m, &m.fetch, &push.endpoint("/upToken123?up=1")) .await, StatusCode::NO_CONTENT ); let canary = b"CANARY-wake-7f3a9c"; assert_eq!(relay.post(&m, &m.post, canary).await, StatusCode::CREATED); let seen = push.wait_for(1).await; assert_eq!(seen.len(), 1, "one wake"); let wake = &seen[0]; assert_eq!(wake.path, "/upToken123?up=1"); assert_eq!(wake.body, WAKE_BODY); assert_eq!(wake.headers.get("ttl").expect("TTL"), "86400"); assert_eq!(wake.headers.get("urgency").expect("Urgency"), "normal"); // Nothing of the mailbox, its tokens or the blob, anywhere in the request. let mut everything = wake.path.clone().into_bytes(); for (name, value) in &wake.headers { everything.extend_from_slice(name.as_str().as_bytes()); everything.extend_from_slice(value.as_bytes()); } everything.extend_from_slice(&wake.body); let text = String::from_utf8_lossy(&everything); for secret in [ m.id.to_wire(), m.post.to_wire(), m.fetch.to_wire(), blob_hash(canary).to_wire(), ] { assert!(!text.contains(&secret), "the wake carries {secret}"); } assert!(!text.contains("CANARY"), "the wake carries the blob"); assert!(!text.contains("authorization"), "no token goes out"); } #[tokio::test(flavor = "multi_thread")] async fn a_mailbox_is_woken_at_most_once_a_minute() { let relay = Relay::new(true); let push = PushServer::start().await; let m = relay.mailbox().await; relay.set_push(&m, &m.fetch, &push.endpoint("/up/a")).await; for _ in 0..3 { assert_eq!(relay.post(&m, &m.post, b"x").await, StatusCode::CREATED); } assert_eq!(push.wait_for(1).await.len(), 1); relay.advance(WAKE_EVERY_SECS - 1); relay.post(&m, &m.post, b"y").await; assert_eq!(push.quiet().await.len(), 1, "within the minute"); relay.advance(1); relay.post(&m, &m.post, b"z").await; assert_eq!(push.wait_for(2).await.len(), 2, "after the minute"); // Another mailbox has its own minute. let other = relay.mailbox().await; relay .set_push(&other, &other.fetch, &push.endpoint("/up/b")) .await; relay.post(&other, &other.post, b"w").await; let seen = push.wait_for(3).await; assert_eq!(seen.len(), 3); assert_eq!(seen[2].path, "/up/b"); } #[tokio::test(flavor = "multi_thread")] async fn nothing_wakes_without_a_stored_post_or_without_an_endpoint() { let relay = Relay::new(true); let push = PushServer::start().await; let m = relay.mailbox().await; // No endpoint: a post wakes nobody. relay.post(&m, &m.post, b"before").await; relay.set_push(&m, &m.fetch, &push.endpoint("/up/a")).await; // A refused post wakes nobody: a stranger, or the owner's fetch token. assert_eq!( relay.post(&m, &Token::from_bytes(random()), b"x").await, StatusCode::NOT_FOUND ); assert_eq!(relay.post(&m, &m.fetch, b"x").await, StatusCode::NOT_FOUND); let too_big = vec![0u8; MAX_BLOB_BYTES + 1]; assert_ne!(relay.post(&m, &m.post, &too_big).await, StatusCode::CREATED); assert!(push.quiet().await.is_empty()); // Cleared: nothing either. relay.clear_push(&m, &m.fetch).await; relay.post(&m, &m.post, b"after").await; assert!(push.quiet().await.is_empty()); } #[tokio::test(flavor = "multi_thread")] async fn an_endpoint_the_push_server_says_is_gone_is_removed() { let relay = Relay::new(true); let push = PushServer::start().await; let m = relay.mailbox().await; let endpoint = push.endpoint("/up/a"); relay.set_push(&m, &m.fetch, &endpoint).await; // A failure that is not "gone" keeps it. push.status.store(500, Ordering::SeqCst); relay.post(&m, &m.post, b"x").await; push.wait_for(1).await; tokio::time::sleep(Duration::from_millis(300)).await; assert_eq!( relay.store.push_endpoint(&m.id).expect("read"), Some(endpoint) ); push.status.store(410, Ordering::SeqCst); relay.advance(WAKE_EVERY_SECS); relay.post(&m, &m.post, b"y").await; push.wait_for(2).await; let mut gone = false; for _ in 0..50 { gone = relay.store.push_endpoint(&m.id).expect("read").is_none(); if gone { break; } tokio::time::sleep(Duration::from_millis(50)).await; } assert!(gone, "410: the endpoint is removed"); } /// A raw listener that only counts connections: proves whether the relay connected at all. async fn counting_listener() -> (u16, Arc) { let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await .expect("bind"); let port = listener.local_addr().expect("addr").port(); let count = Arc::new(AtomicUsize::new(0)); let c = Arc::clone(&count); tokio::spawn(async move { while let Ok((conn, _)) = listener.accept().await { c.fetch_add(1, Ordering::SeqCst); drop(conn); } }); (port, count) } #[tokio::test(flavor = "multi_thread")] async fn an_https_endpoint_on_a_local_address_is_never_connected_to() { // `https://127.0.0.1` passes the endpoint's syntax, so only the resolver stands in the way. for (loopback, expected) in [(false, 0), (true, 1)] { let relay = Relay::new(loopback); let (port, count) = counting_listener().await; let m = relay.mailbox().await; assert_eq!( relay .set_push(&m, &m.fetch, &format!("https://127.0.0.1:{port}/up")) .await, StatusCode::NO_CONTENT ); relay.post(&m, &m.post, b"x").await; tokio::time::sleep(Duration::from_secs(1)).await; assert_eq!( count.load(Ordering::SeqCst), expected, "with --push-loopback {loopback}" ); } } #[tokio::test(flavor = "multi_thread")] async fn a_redirect_from_the_push_server_is_not_followed() { let relay = Relay::new(true); let push = PushServer::start().await; let m = relay.mailbox().await; // The push server answers 303 to a second path on itself: following it would show up there. let target = push.endpoint("/second"); let redirecting = axum::Router::new().fallback(move || { let target = target.clone(); async move { (StatusCode::SEE_OTHER, [(header::LOCATION, target)]) } }); let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await .expect("bind"); let port = listener.local_addr().expect("addr").port(); tokio::spawn(async move { let _ = axum::serve(listener, redirecting).await; }); relay .set_push(&m, &m.fetch, &format!("http://127.0.0.1:{port}/first")) .await; relay.post(&m, &m.post, b"x").await; assert!(push.quiet().await.is_empty(), "the redirect was followed"); } #[test] fn a_gone_endpoint_does_not_remove_the_one_set_since() { let store = Store::open_in_memory().expect("store"); let m = Mailbox::new(); store .create_mailbox( &CreateMailbox { id: m.id, post_token_hash: m.post.hash(), fetch_token_hash: m.fetch.hash(), }, T0, ) .expect("mailbox"); let newer = PushEndpoint::parse("https://push.invalid/newer").expect("endpoint"); store.set_push(&m.id, &m.fetch, Some(&newer)).expect("set"); store .drop_push_if(&m.id, "https://push.invalid/older") .expect("drop"); assert_eq!( store.push_endpoint(&m.id).expect("read").as_deref(), Some("https://push.invalid/newer") ); }