From 4d71637511dc69f1d280a281e5727411bd4d5503 Mon Sep 17 00:00:00 2001 From: Gregory Fong Date: Fri, 13 Nov 2026 21:52:00 -0800 Subject: [PATCH] gateway: an optional separate APNs key for apns-sandbox Apple limits a key to one app only if it covers a single environment, so a vendor that scopes its keys holds a production key and a sandbox key. [apns] sandbox_key_id and sandbox_key_path sign apns-sandbox pushes; without them the main key signs both, as before. Co-Authored-By: Claude Opus 5.5 --- gateway/README.md | 5 ++ gateway/examples/config.toml | 4 ++ gateway/src/config.rs | 16 +++++ gateway/src/platform.rs | 109 ++++++++++++++++++++++------------- gateway/tests/gateway.rs | 87 ++++++++++++++++++++++++++++ 5 files changed, 181 insertions(+), 40 deletions(-) diff --git a/gateway/README.md b/gateway/README.md index da93784..378b6d7 100644 --- a/gateway/README.md +++ b/gateway/README.md @@ -82,6 +82,11 @@ 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`. +Apple limits a key to one app only if the key covers one environment. +To use such keys, give the production one as `key_id` and `key_path` +and the sandbox one as `sandbox_key_id` and `sandbox_key_path`. Without +those, a key for both environments signs both. + 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 diff --git a/gateway/examples/config.toml b/gateway/examples/config.toml index 9230a5f..8233307 100644 --- a/gateway/examples/config.toml +++ b/gateway/examples/config.toml @@ -26,6 +26,10 @@ sandbox = false # Also accept "apns-sandbox" subscriptions from development (Xcode) builds, # sent to Apple's development environment with the same key. allow_sandbox = false +# Optional: a separate key for "apns-sandbox", for Apple keys limited to +# this app (Apple then allows one environment per key). +# sandbox_key_id = "KEY7654321" +# sandbox_key_path = "/etc/lz-gateway/AuthKey_KEY7654321.p8" [fcm] project_id = "example-wallet" diff --git a/gateway/src/config.rs b/gateway/src/config.rs index 0cd3579..f7c14f8 100644 --- a/gateway/src/config.rs +++ b/gateway/src/config.rs @@ -63,6 +63,14 @@ pub struct ApnsConfig { /// both. Leave it off for a gateway that only release builds use. #[serde(default)] pub allow_sandbox: bool, + /// A separate key for `apns-sandbox`, such as an Apple key limited to + /// this app and the development environment (Apple scopes a key to + /// one app only if it covers one environment). Without it, the main + /// key is used for both. Set both or neither. + #[serde(default)] + pub sandbox_key_id: Option, + #[serde(default)] + pub sandbox_key_path: Option, /// Overrides the APNs host, for tests. #[serde(default)] pub base_url: Option, @@ -173,6 +181,8 @@ pub enum ConfigError { Lifetime, #[error("[limits] per-address limits must be at least 1")] Limits, + #[error("[apns] sandbox_key_id and sandbox_key_path go together, with allow_sandbox")] + SandboxKey, } impl Config { @@ -202,6 +212,12 @@ impl Config { if !(1..=crate::keys::MAX_LIFETIME_DAYS).contains(&self.endpoint_lifetime_days) { return Err(ConfigError::Lifetime); } + if let Some(a) = &self.apns + && (a.sandbox_key_id.is_some() != a.sandbox_key_path.is_some() + || (a.sandbox_key_id.is_some() && !a.allow_sandbox)) + { + return Err(ConfigError::SandboxKey); + } if self.limits.subscriptions_per_address_per_hour == 0 || self.limits.revocations_per_address_per_hour == 0 { diff --git a/gateway/src/platform.rs b/gateway/src/platform.rs index 127d368..cef73f6 100644 --- a/gateway/src/platform.rs +++ b/gateway/src/platform.rs @@ -9,7 +9,7 @@ use std::time::Duration; use base64::Engine as _; use base64::engine::general_purpose::URL_SAFE_NO_PAD; -use p256::ecdsa::signature::Signer; +use p256::ecdsa::signature::Signer as _; use p256::ecdsa::{Signature, SigningKey}; use p256::pkcs8::DecodePrivateKey; use serde_json::json; @@ -55,21 +55,65 @@ pub enum Delivery { pub struct Apns { http: reqwest::Client, base_url: String, - /// For `apns-sandbox` subscriptions, when `allow_sandbox` is on. - sandbox_url: Option, + signer: ApnsKey, + /// For `apns-sandbox` subscriptions, when `allow_sandbox` is on: the + /// development host, and its own key if one is configured. + sandbox: Option<(String, Option)>, topic: String, + alert_title: String, +} + +/// One APNs auth key and its cached provider token. +struct ApnsKey { team_id: String, key_id: String, key: SigningKey, - alert_title: String, token: Mutex>, } +impl ApnsKey { + fn load(team_id: &str, key_id: &str, path: &std::path::Path) -> Result { + let pem = std::fs::read_to_string(path) + .map_err(|e| PlatformError::Read(path.display().to_string(), e))?; + let key = SigningKey::from_pkcs8_pem(&pem).map_err(|_| PlatformError::ApnsKey)?; + Ok(Self { + team_id: team_id.to_owned(), + key_id: key_id.to_owned(), + key, + token: Mutex::new(None), + }) + } + + fn provider_token(&self, now_unix: u64) -> String { + let mut cached = self.token.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((at, t)) = cached.as_ref() + && at.elapsed() < APNS_TOKEN_REFRESH + { + return t.clone(); + } + let header = json!({ "alg": "ES256", "kid": self.key_id }); + let claims = json!({ "iss": self.team_id, "iat": now_unix }); + let input = format!( + "{}.{}", + URL_SAFE_NO_PAD.encode(header.to_string()), + URL_SAFE_NO_PAD.encode(claims.to_string()) + ); + let sig: Signature = self.key.sign(input.as_bytes()); + let t = format!("{input}.{}", URL_SAFE_NO_PAD.encode(sig.to_bytes())); + *cached = Some((std::time::Instant::now(), t.clone())); + t + } + + fn forget_token(&self) { + *self.token.lock().unwrap_or_else(|e| e.into_inner()) = None; + } +} + 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) + .field("sandbox_url", &self.sandbox.as_ref().map(|(u, _)| u)) .finish_non_exhaustive() } } @@ -90,45 +134,30 @@ impl Apns { config: &crate::config::ApnsConfig, alert_title: String, ) -> Result { - let pem = std::fs::read_to_string(&config.key_path) - .map_err(|e| PlatformError::Read(config.key_path.display().to_string(), e))?; - let key = SigningKey::from_pkcs8_pem(&pem).map_err(|_| PlatformError::ApnsKey)?; + let signer = ApnsKey::load(&config.team_id, &config.key_id, &config.key_path)?; + let sandbox = match config.sandbox_url() { + Some(url) => { + let own = match (&config.sandbox_key_id, &config.sandbox_key_path) { + (Some(id), Some(path)) => Some(ApnsKey::load(&config.team_id, id, path)?), + _ => None, + }; + Some((url, own)) + } + None => None, + }; Ok(Self { http, base_url: config.base_url(), - sandbox_url: config.sandbox_url(), + signer, + sandbox, topic: config.topic.clone(), - team_id: config.team_id.clone(), - key_id: config.key_id.clone(), - key, alert_title, - token: Mutex::new(None), }) } - fn provider_token(&self, now_unix: u64) -> String { - let mut cached = self.token.lock().unwrap_or_else(|e| e.into_inner()); - if let Some((at, t)) = cached.as_ref() - && at.elapsed() < APNS_TOKEN_REFRESH - { - return t.clone(); - } - let header = json!({ "alg": "ES256", "kid": self.key_id }); - let claims = json!({ "iss": self.team_id, "iat": now_unix }); - let input = format!( - "{}.{}", - URL_SAFE_NO_PAD.encode(header.to_string()), - URL_SAFE_NO_PAD.encode(claims.to_string()) - ); - let sig: Signature = self.key.sign(input.as_bytes()); - let t = format!("{input}.{}", URL_SAFE_NO_PAD.encode(sig.to_bytes())); - *cached = Some((std::time::Instant::now(), t.clone())); - t - } - /// Whether `apns-sandbox` subscriptions are accepted. pub fn allows_sandbox(&self) -> bool { - self.sandbox_url.is_some() + self.sandbox.is_some() } /// Sends to the configured environment, or with `sandbox` to the @@ -141,13 +170,13 @@ impl Apns { now_unix: u64, sandbox: bool, ) -> Delivery { - let base_url = if sandbox { - match &self.sandbox_url { - Some(u) => u, + let (base_url, signer) = if sandbox { + match &self.sandbox { + Some((u, own)) => (u, own.as_ref().unwrap_or(&self.signer)), None => return Delivery::Gone, } } else { - &self.base_url + (&self.base_url, &self.signer) }; let hex = crate::hex(device_token); let lz = URL_SAFE_NO_PAD.encode(push.body); @@ -176,7 +205,7 @@ impl Apns { .post(format!("{base_url}/3/device/{hex}")) .header( "authorization", - format!("bearer {}", self.provider_token(now_unix)), + format!("bearer {}", signer.provider_token(now_unix)), ) .header("apns-topic", &self.topic) .header("apns-push-type", push_type) @@ -212,7 +241,7 @@ impl Apns { (410, _) | (400, "BadDeviceToken" | "DeviceTokenNotForTopic") => Delivery::Gone, (429, _) => Delivery::RateLimited(retry), (403, "ExpiredProviderToken" | "InvalidProviderToken") => { - *self.token.lock().unwrap_or_else(|e| e.into_inner()) = None; + signer.forget_token(); tracing::warn!(reason, "APNs rejected the provider token"); Delivery::Failed } diff --git a/gateway/tests/gateway.rs b/gateway/tests/gateway.rs index eeac069..7941038 100644 --- a/gateway/tests/gateway.rs +++ b/gateway/tests/gateway.rs @@ -124,6 +124,8 @@ async fn harness_custom(tweak: impl FnOnce(&mut Config)) -> Harness { topic: "app.example.wallet".into(), sandbox: false, allow_sandbox: true, + sandbox_key_id: None, + sandbox_key_path: None, base_url: Some(apns_url), sandbox_base_url: Some(apns_sandbox_url), }), @@ -579,6 +581,91 @@ async fn sandbox_subscriptions_go_to_the_development_environment() { ); } +/// The `kid` of the APNs provider token a fake platform received, after +/// checking its signature with `key`. +fn apns_kid(headers: &HeaderMap, key: &p256::PublicKey) -> String { + use p256::ecdsa::signature::Verifier; + let bearer = headers["authorization"] + .to_str() + .unwrap() + .strip_prefix("bearer ") + .unwrap(); + let parts: Vec<&str> = bearer.split('.').collect(); + let sig = + p256::ecdsa::Signature::from_slice(&URL_SAFE_NO_PAD.decode(parts[2]).unwrap()).unwrap(); + p256::ecdsa::VerifyingKey::from(*key) + .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &sig) + .unwrap(); + let header: Value = serde_json::from_slice(&URL_SAFE_NO_PAD.decode(parts[0]).unwrap()).unwrap(); + header["kid"].as_str().unwrap().to_owned() +} + +#[tokio::test] +async fn a_separate_sandbox_key_signs_sandbox_pushes() { + // Apple limits a key to one app only if it covers one environment, so a + // vendor may hold a production key and a sandbox key. + let dir = temp_dir("sandbox-key"); + let sandbox_key = p256::SecretKey::from_slice(&[0x55; 32]).unwrap(); + let path = dir.join("AuthKey_SANDBOX.p8"); + std::fs::write( + &path, + sandbox_key + .to_pkcs8_pem(Default::default()) + .unwrap() + .as_bytes(), + ) + .unwrap(); + let h = harness_custom(|c| { + let a = c.apns.as_mut().unwrap(); + a.sandbox_key_id = Some("SANDBOX123".into()); + a.sandbox_key_path = Some(path); + }) + .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!(apns_kid(&prod_seen[0].1, &h.apns_public), "KEY1234567"); + assert_eq!( + apns_kid(&dev_seen[0].1, &sandbox_key.public_key()), + "SANDBOX123" + ); +} + +#[test] +fn a_sandbox_key_needs_its_id_path_and_allow_sandbox() { + let mut a = lz_gateway::config::ApnsConfig { + team_id: "TEAM123456".into(), + key_id: "KEY1234567".into(), + key_path: "/k.p8".into(), + topic: "app.example.wallet".into(), + sandbox: false, + allow_sandbox: false, + sandbox_key_id: Some("SANDBOX123".into()), + sandbox_key_path: Some("/s.p8".into()), + base_url: None, + sandbox_base_url: None, + }; + let config = |a: &lz_gateway::config::ApnsConfig| Config { + listen: "127.0.0.1:0".parse().unwrap(), + trusted_proxies: Vec::new(), + public_origin: "https://push.example.test".into(), + data_dir: "/tmp/x".into(), + endpoint_lifetime_days: 90, + alert_title: "New activity".into(), + apns: Some(a.clone()), + fcm: None, + limits: LimitsConfig::default(), + }; + assert!(config(&a).validate().is_err(), "needs allow_sandbox"); + a.allow_sandbox = true; + assert!(config(&a).validate().is_ok()); + a.sandbox_key_path = None; + assert!(config(&a).validate().is_err(), "id without a path"); +} + #[tokio::test] async fn sandbox_subscriptions_need_allow_sandbox() { let mut h = harness().await;