diff --git a/gateway/README.md b/gateway/README.md index 5f82d73..da93784 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -37,7 +37,12 @@ the real server's wake round; not yet against Apple or Google. with `Retry-After`. Budgets are fixed hourly windows, so a server can briefly send up to twice its budget across a window boundary. A wallet with two servers gets two budgets; Apple may then throttle some wakes, - which wallets must tolerate anyway (spec §5.4). + which wallets must tolerate anyway (spec §5.4). The wallet API is also + limited per client address (an IPv4 address or an IPv6 /64): 60 + subscriptions and 60 revocations an hour by default. The counters hold + salted hashes of addresses, in memory only, and are never logged. + Behind a proxy, list it in `trusted_proxies` so its `X-Forwarded-For` + names the client; from anyone else that header is ignored. - **Blind.** Only `aes128gcm` bodies are accepted, and they are forwarded unchanged, base64url in the `lz` field. Payment alerts show a fixed, generic title (`alert_title`); the app's Notification Service Extension @@ -52,7 +57,7 @@ gateway. The reference one takes: ``` POST /v0/subscriptions -{ "platform": "apns" | "fcm", +{ "platform": "apns" | "apns-sandbox" | "fcm", "token": "", "server_key": "" } → 201 { "endpoint": "https:///wp/", @@ -66,6 +71,17 @@ Authorization: Bearer 503 revocation list full, try later ``` +Both answer `429` with `Retry-After` past the per-address limits. + +`apns-sandbox` is for development builds (Xcode), whose device tokens +work only in Apple's development environment. The gateway accepts it +when `[apns] allow_sandbox = true`, and sends those pushes there with the +same auth key; `apns` goes to the environment `sandbox` picks +(production by default). So one gateway serves development, TestFlight +and App Store builds. The app knows which it is from its +`aps-environment` entitlement. Turning `allow_sandbox` off later makes +existing `apns-sandbox` endpoints answer `410`. + The wallet registers the endpoint with the server (`POST /v0/devices`) and keeps `revoke_secret` on the device; the server never sees it. A wallet connected to two servers subscribes twice. Before `expires`, the wallet @@ -145,8 +161,10 @@ revocations. - **Abuse of the open wallet API.** Anyone can subscribe and then revoke, so the revocation list could be filled; past 1,000,000 entries, - revocations get `503` until old ones expire. Put a per-address rate limit - in front of the gateway. App attestation would close this properly. + revocations get `503` until old ones expire. The per-address limits + make that slow (at 60 an hour, about 17,000 address-hours), not + impossible for someone with many addresses. App attestation (App + Attest, Play Integrity) would close it properly. - **Several gateway instances.** Rate limits live in memory per instance, and the revocation list is a local file. Run one instance, or share the list. diff --git a/gateway/examples/config.toml b/gateway/examples/config.toml index fe9ab84..9230a5f 100644 --- a/gateway/examples/config.toml +++ b/gateway/examples/config.toml @@ -1,5 +1,8 @@ # Example gateway configuration. TLS is terminated in front of the gateway. listen = "127.0.0.1:8090" +# Proxies whose X-Forwarded-For names the client, for the per-address +# limits. Only these; from anyone else the header is ignored. +trusted_proxies = [] # Endpoints are built on this origin, and servers' VAPID tokens must name it. public_origin = "https://push.example-wallet.app" # Holds the endpoint-sealing keys and the revocation list. Losing it @@ -17,7 +20,12 @@ key_id = "KEY1234567" key_path = "/etc/lz-gateway/AuthKey_KEY1234567.p8" # The wallet app's bundle id. topic = "app.example.wallet" +# Where "apns" subscriptions go: false for production (TestFlight, App +# Store builds). sandbox = false +# Also accept "apns-sandbox" subscriptions from development (Xcode) builds, +# sent to Apple's development environment with the same key. +allow_sandbox = false [fcm] project_id = "example-wallet" @@ -29,3 +37,6 @@ credentials_path = "/etc/lz-gateway/fcm-service-account.json" background_per_hour = 3 alerts_per_hour = 20 per_server_per_minute = 100000 +# The open wallet API, per client address (IPv4 address or IPv6 /64). +subscriptions_per_address_per_hour = 60 +revocations_per_address_per_hour = 60 diff --git a/gateway/src/config.rs b/gateway/src/config.rs index c6d351d..0cd3579 100644 --- a/gateway/src/config.rs +++ b/gateway/src/config.rs @@ -1,6 +1,6 @@ //! Gateway configuration, read from a TOML file. -use std::net::SocketAddr; +use std::net::{IpAddr, SocketAddr}; use std::path::PathBuf; use serde::Deserialize; @@ -10,6 +10,11 @@ use serde::Deserialize; pub struct Config { /// Address to listen on. TLS is terminated in front of the gateway. pub listen: SocketAddr, + /// Proxies in front of the gateway whose `X-Forwarded-For` names the + /// client. Used for the per-address limits on the wallet API only, and + /// never logged. + #[serde(default)] + pub trusted_proxies: Vec, /// This gateway's public origin, for example `https://push.example.app`. /// Endpoints are built on it, and VAPID tokens must name it as `aud`. pub public_origin: String, @@ -49,12 +54,21 @@ pub struct ApnsConfig { pub key_path: PathBuf, /// The app's bundle id (`apns-topic`). pub topic: String, - /// Use the development APNs environment. + /// Send `apns` subscriptions to the development APNs environment. #[serde(default)] pub sandbox: bool, + /// Also accept `apns-sandbox` subscriptions, from development builds + /// (Xcode), and send them to the development environment, so one + /// gateway serves both kinds of build. The same auth key works in + /// both. Leave it off for a gateway that only release builds use. + #[serde(default)] + pub allow_sandbox: bool, /// Overrides the APNs host, for tests. #[serde(default)] pub base_url: Option, + /// Overrides the development APNs host for `apns-sandbox`, for tests. + #[serde(default)] + pub sandbox_base_url: Option, } impl ApnsConfig { @@ -65,6 +79,14 @@ impl ApnsConfig { (None, false) => "https://api.push.apple.com".into(), } } + + /// Where `apns-sandbox` subscriptions go, when allowed. + pub fn sandbox_url(&self) -> Option { + self.allow_sandbox.then(|| match &self.sandbox_base_url { + Some(u) => u.trim_end_matches('/').to_owned(), + None => "https://api.sandbox.push.apple.com".into(), + }) + } } #[derive(Debug, Clone, Deserialize)] @@ -100,6 +122,16 @@ pub struct LimitsConfig { /// All pushes signed by one server key, per minute. #[serde(default = "default_per_server")] pub per_server_per_minute: u32, + /// Subscriptions created per client address (an IPv4 address or an + /// IPv6 /64) per hour. A wallet subscribes once per server and renews + /// every few months, but carrier NAT puts many phones on one IPv4 + /// address. + #[serde(default = "default_per_address")] + pub subscriptions_per_address_per_hour: u32, + /// Revocations per client address per hour. They fill the revocation + /// list, which holds at most 1,000,000. + #[serde(default = "default_per_address")] + pub revocations_per_address_per_hour: u32, } fn default_background() -> u32 { @@ -111,6 +143,9 @@ fn default_alert() -> u32 { fn default_per_server() -> u32 { 100_000 } +fn default_per_address() -> u32 { + 60 +} impl Default for LimitsConfig { fn default() -> Self { @@ -118,6 +153,8 @@ impl Default for LimitsConfig { background_per_hour: default_background(), alerts_per_hour: default_alert(), per_server_per_minute: default_per_server(), + subscriptions_per_address_per_hour: default_per_address(), + revocations_per_address_per_hour: default_per_address(), } } } @@ -134,6 +171,8 @@ pub enum ConfigError { NoPlatform, #[error("endpoint_lifetime_days must be 1 to 365")] Lifetime, + #[error("[limits] per-address limits must be at least 1")] + Limits, } impl Config { @@ -163,6 +202,11 @@ impl Config { if !(1..=crate::keys::MAX_LIFETIME_DAYS).contains(&self.endpoint_lifetime_days) { return Err(ConfigError::Lifetime); } + if self.limits.subscriptions_per_address_per_hour == 0 + || self.limits.revocations_per_address_per_hour == 0 + { + return Err(ConfigError::Limits); + } Ok(()) } } diff --git a/gateway/src/lib.rs b/gateway/src/lib.rs index e1879b0..941b5d3 100644 --- a/gateway/src/lib.rs +++ b/gateway/src/lib.rs @@ -11,13 +11,13 @@ //! - **Bound.** Each subscription accepts pushes signed by one server key //! ([`vapid`]); there is no admission list. //! - **Rate-limited** per device, with background and alert budgets apart, -//! and per server key ([`limits`]). +//! and per server key; the wallet API per client address ([`limits`]). //! - **Blind.** Payloads are forwarded as received: encrypted to the //! device. Nothing logs device tokens, endpoints, or payloads. //! //! Wallet API (vendor-internal, not part of the Lantern Zero spec): //! - `POST /v0/subscriptions` with -//! `{"platform": "apns" | "fcm", "token": "...", "server_key": ""}` +//! `{"platform": "apns" | "apns-sandbox" | "fcm", "token": "...", "server_key": ""}` //! returns `201 {"endpoint": "https:///wp/", //! "expires": , "revoke_secret": ""}`. //! - `DELETE /v0/subscriptions/` with @@ -31,12 +31,14 @@ pub mod revoke; pub mod seal; pub mod vapid; +use std::net::{IpAddr, SocketAddr}; use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; use axum::Router; use axum::body::Bytes; -use axum::extract::{DefaultBodyLimit, Path as UrlPath, State}; +use axum::extract::connect_info::IntoMakeServiceWithConnectInfo; +use axum::extract::{ConnectInfo, DefaultBodyLimit, Path as UrlPath, State}; use axum::http::{HeaderMap, StatusCode, header}; use axum::response::{IntoResponse, Response}; use axum::routing::{delete, post}; @@ -48,7 +50,7 @@ use subtle::ConstantTimeEq as _; use zeroize::Zeroizing; use crate::keys::KeyRing; -use crate::limits::{Limits, Window}; +use crate::limits::{ClientKey, Limits, Window}; use crate::platform::{Apns, Delivery, Fcm, Kind, Push}; use crate::revoke::{RevokeError, Revoked}; use crate::seal::{MAX_TOKEN_LEN, Platform, Sealer, Subscription}; @@ -66,6 +68,7 @@ pub struct AppState { pub sealer: Sealer, pub revoked: Arc, pub limits: Limits, + pub client_key: ClientKey, pub apns: Option, pub fcm: Option, } @@ -111,16 +114,49 @@ impl AppState { background: Window::new(l.background_per_hour, 3600), alert: Window::new(l.alerts_per_hour, 3600), per_server: Window::new(l.per_server_per_minute, 60), + subscribe: Window::new(l.subscriptions_per_address_per_hour, 3600), + revoke: Window::new(l.revocations_per_address_per_hour, 3600), }; Ok(Arc::new(Self { sealer: Sealer::new(&ring), revoked, limits, + client_key: ClientKey::default(), apns, fcm, config, })) } + + /// The client's address, for the per-address limits only: the peer, + /// or the last `X-Forwarded-For` entry when the peer is a trusted + /// proxy (as the relay does). + fn client_ip(&self, peer: IpAddr, headers: &HeaderMap) -> IpAddr { + if !self.config.trusted_proxies.contains(&peer) { + return peer; + } + headers + .get_all("x-forwarded-for") + .iter() + .filter_map(|v| v.to_str().ok()) + .flat_map(|v| v.split(',')) + .next_back() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(peer) + } + + /// Counts a wallet API call against its client's hourly budget. + fn limit_client(&self, w: &Window, peer: SocketAddr, headers: &HeaderMap) -> Option { + let key = self.client_key.of(self.client_ip(peer.ip(), headers)); + w.hit(key, now_unix()).err().map(|retry| { + ( + StatusCode::TOO_MANY_REQUESTS, + [(header::RETRY_AFTER, retry.to_string())], + "rate limited", + ) + .into_response() + }) + } } pub fn router(state: Arc) -> Router { @@ -132,6 +168,12 @@ pub fn router(state: Arc) -> Router { .with_state(state) } +/// [`router`] as a service that knows each peer's address, which the +/// per-address limits need. Serve this, not the bare router. +pub fn app(state: Arc) -> IntoMakeServiceWithConnectInfo { + router(state).into_make_service_with_connect_info::() +} + /// Lowercase hex. pub(crate) fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() @@ -159,19 +201,32 @@ struct SubscribeRequest { } /// Creates a subscription bound to `server_key` (spec §4.1). -async fn subscribe(State(state): State>, body: Bytes) -> Response { +async fn subscribe( + State(state): State>, + ConnectInfo(peer): ConnectInfo, + headers: HeaderMap, + body: Bytes, +) -> Response { + if let Some(r) = state.limit_client(&state.limits.subscribe, peer, &headers) { + return r; + } let Ok(req) = serde_json::from_slice::(&body) else { return error(StatusCode::BAD_REQUEST, "malformed request"); }; let platform = match req.platform.as_str() { "apns" if state.apns.is_some() => Platform::Apns, + "apns-sandbox" if state.apns.as_ref().is_some_and(Apns::allows_sandbox) => { + Platform::ApnsSandbox + } "fcm" if state.fcm.is_some() => Platform::Fcm, - "apns" | "fcm" => return error(StatusCode::BAD_REQUEST, "platform not configured"), + "apns" | "apns-sandbox" | "fcm" => { + return error(StatusCode::BAD_REQUEST, "platform not configured"); + } _ => return error(StatusCode::BAD_REQUEST, "unknown platform"), }; let token = match platform { // APNs device tokens are hex. - Platform::Apns => { + Platform::Apns | Platform::ApnsSandbox => { let t = req.token.trim(); if t.len() % 2 != 0 || t.len() < 32 || t.len() > 2 * MAX_TOKEN_LEN { return error(StatusCode::BAD_REQUEST, "invalid token"); @@ -228,9 +283,13 @@ async fn subscribe(State(state): State>, body: Bytes) -> Response /// Revokes a subscription (spec §4.1): later pushes to it get `410`. async fn revoke( State(state): State>, + ConnectInfo(peer): ConnectInfo, UrlPath(opaque): UrlPath, headers: HeaderMap, ) -> Response { + if let Some(r) = state.limit_client(&state.limits.revoke, peer, &headers) { + return r; + } let now = now_unix(); let Some(sub) = state.sealer.open(&opaque) else { return error(StatusCode::NOT_FOUND, "no such subscription"); @@ -375,7 +434,8 @@ async fn push( topic, }; let delivery = match (sub.platform, &state.apns, &state.fcm) { - (Platform::Apns, Some(apns), _) => apns.send(&sub.token, &p, now).await, + (Platform::Apns, Some(apns), _) => apns.send(&sub.token, &p, now, false).await, + (Platform::ApnsSandbox, Some(apns), _) => apns.send(&sub.token, &p, now, true).await, (Platform::Fcm, _, Some(fcm)) => fcm.send(&sub.token, &p).await, // The platform was configured when this endpoint was made, but // isn't any more: the endpoint can never work again. diff --git a/gateway/src/limits.rs b/gateway/src/limits.rs index 4d3c333..38971f4 100644 --- a/gateway/src/limits.rs +++ b/gateway/src/limits.rs @@ -1,13 +1,22 @@ -//! Per-device and per-server-key rate limits (spec §5.3). +//! Per-device and per-server-key rate limits (spec §5.3), and per-address +//! limits on the wallet API. //! //! Binding stops other servers from pushing to a device, but not the //! device's own server from pushing too often. Background wakes and //! visible payment alerts get separate hourly budgets per device; a server //! key also has an overall per-minute budget. +//! +//! The wallet API is open, so subscribing and revoking are also limited +//! per client address ([`ClientKey`]), mainly so nobody can cheaply fill +//! the revocation list. Those tables hold only salted hashes of addresses, +//! in memory: a restart forgets them, and nothing logs them. use std::collections::HashMap; +use std::net::IpAddr; use std::sync::Mutex; +use sha2::{Digest, Sha256}; + /// A fixed-window counter: at most `limit` hits per `window_secs` per key. #[derive(Debug)] pub struct Window { @@ -62,6 +71,52 @@ pub struct Limits { pub background: Window, pub alert: Window, pub per_server: Window, + /// Per client address, per hour. + pub subscribe: Window, + pub revoke: Window, +} + +/// Hashes client addresses for the per-address windows: an IPv4 address, +/// or an IPv6 /64, since one host usually holds a whole /64 (as the relay +/// counts, relay/src/limits.rs). Salted per process, so the tables don't +/// hold addresses, and a hash from one run means nothing in the next. +pub struct ClientKey { + salt: [u8; 32], +} + +impl std::fmt::Debug for ClientKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ClientKey()") + } +} + +impl Default for ClientKey { + fn default() -> Self { + let mut salt = [0u8; 32]; + rand::fill(&mut salt); + Self { salt } + } +} + +impl ClientKey { + pub fn of(&self, ip: IpAddr) -> [u8; 32] { + let ip = match ip { + IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(ip), + v4 => v4, + }; + let bytes = match ip { + IpAddr::V4(v4) => v4.to_ipv6_mapped().octets(), + IpAddr::V6(v6) => { + let mut b = [0u8; 16]; + b[..8].copy_from_slice(&v6.octets()[..8]); + b + } + }; + let mut h = Sha256::new(); + h.update(self.salt); + h.update(bytes); + h.finalize().into() + } } #[cfg(test)] @@ -79,6 +134,22 @@ mod tests { assert_eq!(w.hit([1; 32], t + 3600), Ok(())); } + #[test] + fn client_keys_count_ipv6_per_64_and_mapped_ipv4_as_ipv4() { + let k = ClientKey::default(); + let of = |s: &str| k.of(s.parse().unwrap()); + assert_eq!(of("2001:db8:1:2::1"), of("2001:db8:1:2:ffff::9")); + assert_ne!(of("2001:db8:1:2::1"), of("2001:db8:1:3::1")); + assert_eq!(of("::ffff:192.0.2.1"), of("192.0.2.1")); + assert_ne!(of("192.0.2.1"), of("192.0.2.2")); + // Salted: another run hashes the same address differently. + assert_ne!( + ClientKey::default().of("192.0.2.1".parse().unwrap()), + of("192.0.2.1") + ); + assert_eq!(format!("{k:?}"), "ClientKey()"); + } + #[test] fn forgets_keys_from_past_windows() { let w = Window::new(1, 60); diff --git a/gateway/src/main.rs b/gateway/src/main.rs index 7f1216f..09a7de6 100644 --- a/gateway/src/main.rs +++ b/gateway/src/main.rs @@ -9,7 +9,7 @@ use std::path::PathBuf; use std::process::ExitCode; use lz_gateway::config::Config; -use lz_gateway::{AppState, router}; +use lz_gateway::{AppState, app}; #[tokio::main] async fn main() -> ExitCode { @@ -72,7 +72,7 @@ async fn main() -> ExitCode { } }; tracing::info!(%listen, "serving"); - match axum::serve(listener, router(state)) + match axum::serve(listener, app(state)) .with_graceful_shutdown(shutdown_signal()) .await { diff --git a/gateway/src/platform.rs b/gateway/src/platform.rs index 5605aac..127d368 100644 --- a/gateway/src/platform.rs +++ b/gateway/src/platform.rs @@ -55,6 +55,8 @@ pub enum Delivery { pub struct Apns { http: reqwest::Client, base_url: String, + /// For `apns-sandbox` subscriptions, when `allow_sandbox` is on. + sandbox_url: Option, topic: String, team_id: String, key_id: String, @@ -67,6 +69,7 @@ impl std::fmt::Debug for Apns { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Apns") .field("base_url", &self.base_url) + .field("sandbox_url", &self.sandbox_url) .finish_non_exhaustive() } } @@ -93,6 +96,7 @@ impl Apns { Ok(Self { http, base_url: config.base_url(), + sandbox_url: config.sandbox_url(), topic: config.topic.clone(), team_id: config.team_id.clone(), key_id: config.key_id.clone(), @@ -122,7 +126,29 @@ impl Apns { t } - pub async fn send(&self, device_token: &[u8], push: &Push<'_>, now_unix: u64) -> Delivery { + /// Whether `apns-sandbox` subscriptions are accepted. + pub fn allows_sandbox(&self) -> bool { + self.sandbox_url.is_some() + } + + /// Sends to the configured environment, or with `sandbox` to the + /// development one (`apns-sandbox`). A sandbox push without + /// `allow_sandbox` any more is `Gone`: that endpoint can't work again. + pub async fn send( + &self, + device_token: &[u8], + push: &Push<'_>, + now_unix: u64, + sandbox: bool, + ) -> Delivery { + let base_url = if sandbox { + match &self.sandbox_url { + Some(u) => u, + None => return Delivery::Gone, + } + } else { + &self.base_url + }; let hex = crate::hex(device_token); let lz = URL_SAFE_NO_PAD.encode(push.body); let (push_type, priority, payload) = match push.kind { @@ -147,7 +173,7 @@ impl Apns { }; let mut req = self .http - .post(format!("{}/3/device/{hex}", self.base_url)) + .post(format!("{base_url}/3/device/{hex}")) .header( "authorization", format!("bearer {}", self.provider_token(now_unix)), diff --git a/gateway/src/seal.rs b/gateway/src/seal.rs index 7c7f6e7..96c8958 100644 --- a/gateway/src/seal.rs +++ b/gateway/src/seal.rs @@ -37,6 +37,8 @@ const MAX_OPAQUE: usize = 1024; pub enum Platform { Apns, Fcm, + /// APNs, development environment (`[apns] allow_sandbox`). + ApnsSandbox, } impl Platform { @@ -44,6 +46,7 @@ impl Platform { match self { Platform::Apns => 1, Platform::Fcm => 2, + Platform::ApnsSandbox => 3, } } @@ -51,6 +54,7 @@ impl Platform { match c { 1 => Some(Platform::Apns), 2 => Some(Platform::Fcm), + 3 => Some(Platform::ApnsSandbox), _ => None, } } diff --git a/gateway/tests/gateway.rs b/gateway/tests/gateway.rs index 5da130e..eeac069 100644 --- a/gateway/tests/gateway.rs +++ b/gateway/tests/gateway.rs @@ -9,7 +9,7 @@ use axum::http::{HeaderMap, StatusCode}; use base64::Engine as _; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use lz_gateway::config::{ApnsConfig, Config, FcmConfig, LimitsConfig}; -use lz_gateway::{AppState, router}; +use lz_gateway::{AppState, app}; use lz_server::webpush::Vapid; use p256::pkcs8::EncodePrivateKey; use serde_json::{Value, json}; @@ -66,6 +66,8 @@ impl Platform { struct Harness { origin: String, apns: Platform, + /// Apple's development environment, for `apns-sandbox`. + apns_sandbox: Platform, fcm: Platform, apns_public: p256::PublicKey, server: Vapid, @@ -85,7 +87,13 @@ fn temp_dir(tag: &str) -> std::path::PathBuf { } async fn harness_with(limits: LimitsConfig) -> Harness { + harness_custom(|c| c.limits = limits).await +} + +/// A gateway with `tweak` applied to the test config. +async fn harness_custom(tweak: impl FnOnce(&mut Config)) -> Harness { let (apns_url, apns) = Platform::start().await; + let (apns_sandbox_url, apns_sandbox) = Platform::start().await; let (fcm_url, fcm) = Platform::start().await; let dir = temp_dir("gw"); // A throwaway APNs auth key, as Apple's `.p8` file would hold it. @@ -102,8 +110,9 @@ async fn harness_with(limits: LimitsConfig) -> Harness { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let origin = format!("http://{}", listener.local_addr().unwrap()); - let config = Config { + let mut config = Config { listen: listener.local_addr().unwrap(), + trusted_proxies: Vec::new(), public_origin: origin.clone(), data_dir: dir.join("data"), endpoint_lifetime_days: 90, @@ -114,7 +123,9 @@ async fn harness_with(limits: LimitsConfig) -> Harness { key_path, topic: "app.example.wallet".into(), sandbox: false, + allow_sandbox: true, base_url: Some(apns_url), + sandbox_base_url: Some(apns_sandbox_url), }), fcm: Some(FcmConfig { project_id: "example-wallet".into(), @@ -122,15 +133,17 @@ async fn harness_with(limits: LimitsConfig) -> Harness { static_access_token: Some("test-access-token".into()), base_url: fcm_url, }), - limits, + limits: LimitsConfig::default(), }; + tweak(&mut config); config.validate().unwrap(); let data_dir = config.data_dir.clone(); let state = AppState::new(config.clone()).unwrap(); - let task = tokio::spawn(async move { axum::serve(listener, router(state)).await.unwrap() }); + let task = tokio::spawn(async move { axum::serve(listener, app(state)).await.unwrap() }); Harness { origin, apns, + apns_sandbox, fcm, apns_public: apns_key.public_key(), server: Vapid::from_secret(&[0x22; 32]).unwrap(), @@ -169,8 +182,7 @@ impl Harness { let listener = tokio::net::TcpListener::bind(self.config.listen) .await .unwrap(); - self.task = - tokio::spawn(async move { axum::serve(listener, router(state)).await.unwrap() }); + self.task = tokio::spawn(async move { axum::serve(listener, app(state)).await.unwrap() }); // Pooled connections would still reach the old instance's tasks. self.http = reqwest::Client::new(); } @@ -484,6 +496,7 @@ async fn rate_limits_per_device_with_separate_alert_budget() { background_per_hour: 3, alerts_per_hour: 2, per_server_per_minute: 1000, + ..LimitsConfig::default() }) .await; let endpoint = h.endpoint("apns", APNS_TOKEN).await; @@ -545,6 +558,120 @@ async fn rate_limits_per_device_with_separate_alert_budget() { assert_eq!(h.apns.take().len(), 6); } +#[tokio::test] +async fn sandbox_subscriptions_go_to_the_development_environment() { + let h = harness().await; + let release = h.endpoint("apns", APNS_TOKEN).await; + let dev = h.endpoint("apns-sandbox", APNS_TOKEN).await; + for e in [&release, &dev] { + assert_eq!(h.push(&h.server, e, "normal", &[1; 10]).await.status(), 201); + } + let (prod_seen, dev_seen) = (h.apns.take(), h.apns_sandbox.take()); + assert_eq!((prod_seen.len(), dev_seen.len()), (1, 1)); + assert_eq!(dev_seen[0].0, format!("/3/device/{APNS_TOKEN}")); + // The same auth key and topic in both environments. + assert_eq!(dev_seen[0].1["apns-topic"], "app.example.wallet"); + assert!( + dev_seen[0].1["authorization"] + .to_str() + .unwrap() + .starts_with("bearer ") + ); +} + +#[tokio::test] +async fn sandbox_subscriptions_need_allow_sandbox() { + let mut h = harness().await; + let dev = h.endpoint("apns-sandbox", APNS_TOKEN).await; + h.config.apns.as_mut().unwrap().allow_sandbox = false; + h.restart().await; + let r = h + .subscribe("apns-sandbox", APNS_TOKEN, &h.server.public_b64) + .await; + assert_eq!(r.status(), 400); + // An endpoint made while it was allowed can't work any more: the + // server drops the device. + assert_eq!( + h.push(&h.server, &dev, "normal", &[1; 10]).await.status(), + 410 + ); + assert!(h.apns_sandbox.take().is_empty()); +} + +#[tokio::test] +async fn limits_subscribing_and_revoking_per_address() { + let h = harness_with(LimitsConfig { + subscriptions_per_address_per_hour: 2, + revocations_per_address_per_hour: 1, + ..LimitsConfig::default() + }) + .await; + let a = h.subscription("apns", APNS_TOKEN).await; + let f = h.subscription("fcm", FCM_TOKEN).await; + let r = h.subscribe("apns", APNS_TOKEN, &h.server.public_b64).await; + assert_eq!(r.status(), 429); + assert!( + r.headers()["retry-after"] + .to_str() + .unwrap() + .parse::() + .unwrap() + <= 3600 + ); + // The peer isn't a trusted proxy, so a forged X-Forwarded-For changes + // nothing. + let r = h + .http + .post(format!("{}/v0/subscriptions", h.origin)) + .header("x-forwarded-for", "192.0.2.9") + .body( + json!({ "platform": "apns", "token": APNS_TOKEN, "server_key": h.server.public_b64 }) + .to_string(), + ) + .send() + .await + .unwrap(); + assert_eq!(r.status(), 429); + + let endpoint = a["endpoint"].as_str().unwrap(); + let secret = a["revoke_secret"].as_str().unwrap(); + assert_eq!(h.revoke(endpoint, Some(secret)).await, 204); + assert_eq!(h.revoke(endpoint, Some(secret)).await, 429); + // Pushes aren't counted per address: servers push from one address. + let fcm_endpoint = f["endpoint"].as_str().unwrap(); + for _ in 0..3 { + assert_eq!( + h.push(&h.server, fcm_endpoint, "high", &[1; 10]) + .await + .status(), + 201 + ); + } +} + +#[tokio::test] +async fn trusted_proxies_name_the_client() { + let h = harness_custom(|c| { + c.trusted_proxies = vec!["127.0.0.1".parse().unwrap()]; + c.limits.subscriptions_per_address_per_hour = 1; + }) + .await; + let from = |ip: &'static str| { + h.http + .post(format!("{}/v0/subscriptions", h.origin)) + .header("x-forwarded-for", format!("203.0.113.50, {ip}")) + .body(json!({ "platform": "apns", "token": APNS_TOKEN, "server_key": h.server.public_b64 }).to_string()) + .send() + }; + assert_eq!(from("192.0.2.1").await.unwrap().status(), 201); + assert_eq!(from("192.0.2.1").await.unwrap().status(), 429); + // The last entry is the proxy's; earlier ones are the client's to forge. + assert_eq!(from("192.0.2.2").await.unwrap().status(), 201); + // IPv6 counts per /64. + assert_eq!(from("2001:db8:1:2::1").await.unwrap().status(), 201); + assert_eq!(from("2001:db8:1:2::99").await.unwrap().status(), 429); +} + #[tokio::test] async fn maps_platform_answers_for_the_server() { let h = harness().await;