[relay] Calls: a long-poll on the fetch route, TURN credentials for coturn, wakes every 10 s; the module passes the TURN secret by systemd credential
This commit is contained in:
@@ -8,7 +8,7 @@ publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tabellarius-protocol = { path = "../protocol" }
|
||||
axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json"] }
|
||||
axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json", "query"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "signal"] }
|
||||
# Plain SQLite: the relay holds only ciphertext and hashes; nothing in it is readable (PROTOCOL.md §5).
|
||||
rusqlite = { version = "0.41", features = ["bundled"] }
|
||||
@@ -21,6 +21,10 @@ base64 = "0.22"
|
||||
# The wake (`.agents/features/wake-up.md` §2.2): the relay's only outgoing request. rustls with
|
||||
# Mozilla's roots built in; the resolver is the relay's own, which drops every non-global address.
|
||||
ureq = { version = "3", default-features = false, features = ["rustls"] }
|
||||
# TURN credentials for coturn's REST API (`.agents/features/calls-relay.md`): HMAC-SHA1 is what coturn checks.
|
||||
hmac = "0.12"
|
||||
sha1 = "0.10"
|
||||
getrandom = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
getrandom = "0.3"
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
//! The long-poll's waiting room (`.agents/features/calls-relay.md`): who is waiting for which mailbox, in memory
|
||||
//! only, an entry only while someone waits. Nothing here is ever written to disk or logged.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tabellarius_protocol::MailboxId;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
/// Waiters relay-wide before one more is answered at once.
|
||||
pub const MAX_WAITERS: usize = 1024;
|
||||
|
||||
pub struct Arrivals {
|
||||
waiting: Mutex<HashMap<MailboxId, (Arc<Notify>, usize)>>,
|
||||
max: usize,
|
||||
}
|
||||
|
||||
/// One waiter's place; leaving it (drop) removes the entry when nobody else waits for that mailbox.
|
||||
pub struct Place<'a> {
|
||||
arrivals: &'a Arrivals,
|
||||
id: MailboxId,
|
||||
pub notify: Arc<Notify>,
|
||||
}
|
||||
|
||||
impl Arrivals {
|
||||
pub fn new(max: usize) -> Self {
|
||||
Self { waiting: Mutex::new(HashMap::new()), max }
|
||||
}
|
||||
|
||||
/// A place to wait for `id`, or `None` when the relay already holds `max` waiters.
|
||||
pub fn enter(&self, id: MailboxId) -> Option<Place<'_>> {
|
||||
let mut w = self.waiting.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let total: usize = w.values().map(|(_, n)| n).sum();
|
||||
if total >= self.max {
|
||||
return None;
|
||||
}
|
||||
let entry = w.entry(id).or_insert_with(|| (Arc::new(Notify::new()), 0));
|
||||
entry.1 += 1;
|
||||
Some(Place { arrivals: self, id, notify: Arc::clone(&entry.0) })
|
||||
}
|
||||
|
||||
/// A blob arrived for `id`: everyone waiting for it is answered.
|
||||
pub fn arrived(&self, id: &MailboxId) {
|
||||
let w = self.waiting.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((n, _)) = w.get(id) {
|
||||
n.notify_waiters();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Place<'_> {
|
||||
fn drop(&mut self) {
|
||||
let mut w = self.arrivals.waiting.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(entry) = w.get_mut(&self.id) {
|
||||
entry.1 -= 1;
|
||||
if entry.1 == 0 {
|
||||
w.remove(&self.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,24 @@
|
||||
//! The HTTP face of the store. No logging, no connection info: a handler never sees the client's
|
||||
//! address, and nothing here writes a request anywhere.
|
||||
|
||||
use crate::arrivals::{Arrivals, MAX_WAITERS};
|
||||
use crate::store::{Refused, Store};
|
||||
use crate::turn::Turn;
|
||||
use crate::wake::Waker;
|
||||
use axum::body::Bytes;
|
||||
use axum::extract::rejection::BytesRejection;
|
||||
use axum::extract::{DefaultBodyLimit, Path, State};
|
||||
use axum::extract::{DefaultBodyLimit, Path, Query, State};
|
||||
use axum::http::{header, HeaderMap, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{delete, get, post, put};
|
||||
use axum::{Json, Router};
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tabellarius_protocol::{
|
||||
CreateFile, CreateInvite, CreateMailbox, FetchedBlobs, FileId, InviteId, MailboxId,
|
||||
RotatePostToken, SetPush, Sha256Hash, Token, VersionInfo, FILE_CHUNK_BYTES, MAX_BLOB_BYTES,
|
||||
VERSION,
|
||||
RotatePostToken, SetPush, Sha256Hash, Token, TurnCredentials, VersionInfo, FILE_CHUNK_BYTES,
|
||||
MAX_BLOB_BYTES, MAX_WAIT_SECS, VERSION,
|
||||
};
|
||||
|
||||
/// Unix seconds. The server passes the system clock; tests pass their own.
|
||||
@@ -27,6 +30,10 @@ pub struct AppState {
|
||||
pub clock: Clock,
|
||||
/// Wakes a mailbox's owner when a blob arrives (`PROTOCOL.md` §6).
|
||||
pub waker: Arc<Waker>,
|
||||
/// Who is long-polling which mailbox, in memory only (`calls-relay.md`).
|
||||
pub arrivals: Arc<Arrivals>,
|
||||
/// TURN credentials for calls; `None` when the relay was started without a TURN secret.
|
||||
pub turn: Option<Arc<Turn>>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
@@ -40,8 +47,22 @@ impl AppState {
|
||||
store,
|
||||
clock,
|
||||
waker: Arc::new(waker),
|
||||
arrivals: Arc::new(Arrivals::new(MAX_WAITERS)),
|
||||
turn: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands out TURN credentials under this secret and these URLs (`POST /v0/mailboxes/{id}/turn`).
|
||||
pub fn with_turn(mut self, turn: Turn) -> Self {
|
||||
self.turn = Some(Arc::new(turn));
|
||||
self
|
||||
}
|
||||
|
||||
/// At most `max` long-polls held at once, relay-wide (tests set a small one).
|
||||
pub fn with_max_waiters(mut self, max: usize) -> Self {
|
||||
self.arrivals = Arc::new(Arrivals::new(max));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON bodies are small: the largest is an invite with a 16 KiB KeyPackage in base64url.
|
||||
@@ -63,6 +84,7 @@ pub fn router(state: AppState) -> Router {
|
||||
.route("/v0/mailboxes/{id}/blobs/{hash}", delete(acknowledge))
|
||||
.route("/v0/mailboxes/{id}/post-token", put(rotate_post_token))
|
||||
.route("/v0/mailboxes/{id}/push", put(set_push).delete(clear_push))
|
||||
.route("/v0/mailboxes/{id}/turn", post(turn_credentials))
|
||||
.route("/v0/files", post(create_file))
|
||||
.route("/v0/files/{id}", delete(delete_file))
|
||||
.route("/v0/invites", post(create_invite))
|
||||
@@ -141,6 +163,8 @@ async fn post_blob(
|
||||
let token = bearer(&headers)?;
|
||||
let now = (s.clock)();
|
||||
s.store.post(&id, &token, &body, now)?;
|
||||
// Anyone long-polling this mailbox is answered now.
|
||||
s.arrivals.arrived(&id);
|
||||
// Only after the blob is stored under a valid post token; the 201 does not wait for the wake.
|
||||
if let Ok(Some(endpoint)) = s.store.push_endpoint(&id) {
|
||||
s.waker.wake(Arc::clone(&s.store), id, endpoint, now);
|
||||
@@ -148,15 +172,58 @@ async fn post_blob(
|
||||
Ok(StatusCode::CREATED)
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
pub struct Wait {
|
||||
wait: Option<u64>,
|
||||
}
|
||||
|
||||
/// How long a fetch may be held: `?wait=` in seconds, at most [`MAX_WAIT_SECS`]; none means not at all.
|
||||
pub fn clamp_wait(wait: Option<u64>) -> Duration {
|
||||
Duration::from_secs(wait.unwrap_or(0).min(MAX_WAIT_SECS))
|
||||
}
|
||||
|
||||
/// `GET …/blobs[?wait=N]`: the waiting blobs; with `wait` and none waiting, held until one arrives or N seconds
|
||||
/// pass. The token is checked before anything is held, and the place is taken before the store is read, so a blob
|
||||
/// posted in between is never missed.
|
||||
async fn fetch_blobs(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
Query(q): Query<Wait>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<FetchedBlobs>, Status> {
|
||||
let id = mailbox(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
let wait = clamp_wait(q.wait);
|
||||
let place = if wait.is_zero() { None } else { s.arrivals.enter(id) };
|
||||
let Some(place) = place else {
|
||||
return Ok(Json(FetchedBlobs { blobs: s.store.fetch(&id, &token)? }));
|
||||
};
|
||||
let notified = place.notify.notified();
|
||||
tokio::pin!(notified);
|
||||
notified.as_mut().enable();
|
||||
let blobs = s.store.fetch(&id, &token)?;
|
||||
Ok(Json(FetchedBlobs { blobs }))
|
||||
if !blobs.is_empty() {
|
||||
return Ok(Json(FetchedBlobs { blobs }));
|
||||
}
|
||||
let _ = tokio::time::timeout(wait, notified).await;
|
||||
// The place is left when this returns.
|
||||
Ok(Json(FetchedBlobs { blobs: s.store.fetch(&id, &token)? }))
|
||||
}
|
||||
|
||||
/// `POST …/turn` with the fetch token: a TURN REST pair (`calls-relay.md`). 404 without a TURN secret or with a
|
||||
/// wrong token, 429 over [`tabellarius_protocol::TURN_PER_HOUR`]. Nothing is stored.
|
||||
async fn turn_credentials(
|
||||
State(s): State<AppState>,
|
||||
Path(id): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<TurnCredentials>, Status> {
|
||||
let turn = s.turn.as_ref().ok_or(Status(StatusCode::NOT_FOUND))?;
|
||||
let id = mailbox(&id)?;
|
||||
let token = bearer(&headers)?;
|
||||
s.store.authorize_fetch(&id, &token)?;
|
||||
turn.credentials(id, (s.clock)())
|
||||
.map(Json)
|
||||
.ok_or(Status(StatusCode::TOO_MANY_REQUESTS))
|
||||
}
|
||||
|
||||
async fn acknowledge(
|
||||
|
||||
+22
-1
@@ -1,9 +1,11 @@
|
||||
//! The Tabellarius relay: holds ciphertext addressed to a mailbox until its owner fetches and
|
||||
//! acknowledges it. Stores exactly `docs/PROTOCOL.md` §5 and logs no request.
|
||||
|
||||
pub mod arrivals;
|
||||
pub mod http;
|
||||
pub mod join;
|
||||
pub mod store;
|
||||
pub mod turn;
|
||||
pub mod wake;
|
||||
|
||||
use std::net::SocketAddr;
|
||||
@@ -20,6 +22,10 @@ pub struct Args {
|
||||
pub limits: store::Limits,
|
||||
/// `--push-loopback`: accept and wake `http://` loopback push endpoints. Tests only.
|
||||
pub push_loopback: bool,
|
||||
/// `--turn-secret-file <path>`: the secret shared with the TURN server (calls); none means no TURN route.
|
||||
pub turn_secret_file: Option<PathBuf>,
|
||||
/// `--turn-url <url>` (repeatable): the TURN servers named in each credential.
|
||||
pub turn_urls: Vec<String>,
|
||||
}
|
||||
|
||||
/// `--listen <addr:port>`, `--db <path>`, the relay-wide quotas `--max-bytes`, `--max-mailboxes`,
|
||||
@@ -27,11 +33,13 @@ pub struct Args {
|
||||
/// (tests). Anything else is refused with a usage line.
|
||||
pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, String> {
|
||||
let usage = "usage: tabellarius-relay [--listen 127.0.0.1:8470] [--db tabellarius-relay.db] \
|
||||
[--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000] \n [--max-files 10000] [--max-file-bytes 4294967296] [--push-loopback]";
|
||||
[--max-bytes 1073741824] [--max-mailboxes 100000] [--max-invites 10000] \n [--max-files 10000] [--max-file-bytes 4294967296] [--push-loopback] [--turn-secret-file <path> --turn-url <turn:host:port?transport=udp> ...]";
|
||||
let mut listen: SocketAddr = DEFAULT_LISTEN.parse().map_err(|_| usage.to_string())?;
|
||||
let mut db = PathBuf::from(DEFAULT_DB);
|
||||
let mut limits = store::Limits::default();
|
||||
let mut push_loopback = false;
|
||||
let mut turn_secret_file = None;
|
||||
let mut turn_urls = Vec::new();
|
||||
let mut it = args.into_iter();
|
||||
let positive = |v: Option<String>| -> Result<i64, String> {
|
||||
v.and_then(|v| v.parse::<i64>().ok())
|
||||
@@ -46,6 +54,13 @@ pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, Strin
|
||||
"--max-files" => limits.files = positive(it.next())?,
|
||||
"--max-file-bytes" => limits.file_bytes = positive(it.next())?,
|
||||
"--push-loopback" => push_loopback = true,
|
||||
"--turn-secret-file" => {
|
||||
turn_secret_file = Some(it.next().map(PathBuf::from).ok_or_else(|| usage.to_string())?)
|
||||
}
|
||||
"--turn-url" => {
|
||||
let url = it.next().filter(|u| u.starts_with("turn:") || u.starts_with("turns:"));
|
||||
turn_urls.push(url.ok_or_else(|| usage.to_string())?);
|
||||
}
|
||||
"--listen" => {
|
||||
listen = it
|
||||
.next()
|
||||
@@ -61,10 +76,16 @@ pub fn parse_args<I: IntoIterator<Item = String>>(args: I) -> Result<Args, Strin
|
||||
_ => return Err(usage.to_string()),
|
||||
}
|
||||
}
|
||||
// A secret without a URL, or URLs without a secret, is a mistake in the deployment.
|
||||
if turn_secret_file.is_some() != !turn_urls.is_empty() {
|
||||
return Err(usage.to_string());
|
||||
}
|
||||
Ok(Args {
|
||||
listen,
|
||||
db,
|
||||
limits,
|
||||
push_loopback,
|
||||
turn_secret_file,
|
||||
turn_urls,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -65,11 +65,19 @@ async fn main() {
|
||||
});
|
||||
|
||||
let clock: Clock = Arc::new(now);
|
||||
let app = router(AppState::with_waker(
|
||||
store,
|
||||
clock,
|
||||
Waker::new(args.push_loopback),
|
||||
));
|
||||
let mut state = AppState::with_waker(store, clock, Waker::new(args.push_loopback));
|
||||
if let Some(path) = &args.turn_secret_file {
|
||||
// Read once; trailing whitespace from an editor or `echo` is not part of the secret. Never printed.
|
||||
let secret = match std::fs::read(path) {
|
||||
Ok(bytes) if !bytes.trim_ascii().is_empty() => bytes.trim_ascii().to_vec(),
|
||||
_ => {
|
||||
eprintln!("tabellarius-relay: cannot read the TURN secret file");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
state = state.with_turn(tabellarius_relay::turn::Turn::new(secret, args.turn_urls.clone()));
|
||||
}
|
||||
let app = router(state);
|
||||
let shutdown = async {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
};
|
||||
|
||||
@@ -273,6 +273,12 @@ impl Store {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Checks the fetch token and nothing else (TURN credentials, `calls-relay.md`). Reads, writes nothing.
|
||||
pub fn authorize_fetch(&self, id: &MailboxId, token: &Token) -> Result<(), Refused> {
|
||||
let conn = self.conn();
|
||||
Self::authorize(&conn, id, token, Column::Fetch)
|
||||
}
|
||||
|
||||
/// Deletes this mailbox's blob whose SHA-256 is `hash`. Unknown hash = [`Refused::NotFound`].
|
||||
pub fn acknowledge(
|
||||
&self,
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
//! TURN credentials for calls (`.agents/features/calls-relay.md`): coturn's REST API pair under a secret the relay
|
||||
//! and the TURN server share. The secret is never logged or sent; the counters live in memory only.
|
||||
|
||||
use base64::Engine as _;
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha1::Sha1;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
use tabellarius_protocol::{MailboxId, TurnCredentials, TURN_PER_HOUR, TURN_TTL_SECS};
|
||||
|
||||
/// How many mailboxes' hourly counts are remembered before the old ones are pruned.
|
||||
const MAX_COUNTED: usize = 100_000;
|
||||
|
||||
pub struct Turn {
|
||||
secret: Vec<u8>,
|
||||
urls: Vec<String>,
|
||||
/// Per mailbox: the hour's start and how many credentials it got in it.
|
||||
counts: Mutex<HashMap<MailboxId, (i64, u32)>>,
|
||||
}
|
||||
|
||||
impl Turn {
|
||||
pub fn new(secret: Vec<u8>, urls: Vec<String>) -> Self {
|
||||
Self { secret, urls, counts: Mutex::new(HashMap::new()) }
|
||||
}
|
||||
|
||||
/// A fresh pair for `id` at `now`, or `None` when it had [`TURN_PER_HOUR`] this hour.
|
||||
pub fn credentials(&self, id: MailboxId, now: i64) -> Option<TurnCredentials> {
|
||||
{
|
||||
let mut c = self.counts.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if c.len() >= MAX_COUNTED {
|
||||
c.retain(|_, (start, _)| now - *start < 3600);
|
||||
}
|
||||
let entry = c.entry(id).or_insert((now, 0));
|
||||
if !(0..3600).contains(&(now - entry.0)) {
|
||||
*entry = (now, 0);
|
||||
}
|
||||
if entry.1 >= TURN_PER_HOUR {
|
||||
return None;
|
||||
}
|
||||
entry.1 += 1;
|
||||
}
|
||||
let mut nonce = [0u8; 16];
|
||||
getrandom::fill(&mut nonce).ok()?;
|
||||
let username = format!(
|
||||
"{}:{}",
|
||||
now + i64::from(TURN_TTL_SECS),
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(nonce)
|
||||
);
|
||||
let mut mac = Hmac::<Sha1>::new_from_slice(&self.secret).ok()?;
|
||||
mac.update(username.as_bytes());
|
||||
let password = base64::engine::general_purpose::STANDARD.encode(mac.finalize().into_bytes());
|
||||
Some(TurnCredentials { username, password, ttl: TURN_TTL_SECS, urls: self.urls.clone() })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
//! 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<const N: usize>() -> [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<Store>,
|
||||
now: Arc<AtomicI64>,
|
||||
}
|
||||
|
||||
impl Relay {
|
||||
fn new(turn: Option<Turn>, 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<u8>) -> (StatusCode, Vec<u8>) {
|
||||
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<u64>) -> (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::<FetchedBlobs>(&body).expect("json").blobs.len() } else { 0 };
|
||||
(status, n)
|
||||
}
|
||||
async fn turn(&self, m: &Mailbox, token: &Token) -> (StatusCode, Vec<u8>) {
|
||||
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<u8>) {
|
||||
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::<i64>().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::<Sha1>::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::<Vec<_>>();
|
||||
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());
|
||||
}
|
||||
@@ -277,7 +277,9 @@ async fn a_post_wakes_with_a_constant_and_nothing_of_the_mailbox_or_the_blob() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_mailbox_is_woken_at_most_once_a_minute() {
|
||||
async fn a_mailbox_is_woken_at_most_once_every_ten_seconds() {
|
||||
// Ten since 2026-12-03, so a call right after a message still wakes a closed app (calls-relay.md).
|
||||
assert_eq!(WAKE_EVERY_SECS, 10);
|
||||
let relay = Relay::new(true);
|
||||
let push = PushServer::start().await;
|
||||
let m = relay.mailbox().await;
|
||||
@@ -288,10 +290,10 @@ async fn a_mailbox_is_woken_at_most_once_a_minute() {
|
||||
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");
|
||||
assert_eq!(push.quiet().await.len(), 1, "within the ten seconds");
|
||||
relay.advance(1);
|
||||
relay.post(&m, &m.post, b"z").await;
|
||||
assert_eq!(push.wait_for(2).await.len(), 2, "after the minute");
|
||||
assert_eq!(push.wait_for(2).await.len(), 2, "after them");
|
||||
// Another mailbox has its own minute.
|
||||
let other = relay.mailbox().await;
|
||||
relay
|
||||
|
||||
Reference in New Issue
Block a user