Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions gateway/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions gateway/examples/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
16 changes: 16 additions & 0 deletions gateway/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
#[serde(default)]
pub sandbox_key_path: Option<PathBuf>,
/// Overrides the APNs host, for tests.
#[serde(default)]
pub base_url: Option<String>,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
{
Expand Down
109 changes: 69 additions & 40 deletions gateway/src/platform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String>,
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<ApnsKey>)>,
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<Option<(std::time::Instant, String)>>,
}

impl ApnsKey {
fn load(team_id: &str, key_id: &str, path: &std::path::Path) -> Result<Self, PlatformError> {
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()
}
}
Expand All @@ -90,45 +134,30 @@ impl Apns {
config: &crate::config::ApnsConfig,
alert_title: String,
) -> Result<Self, PlatformError> {
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
Expand All @@ -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);
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
Expand Down
87 changes: 87 additions & 0 deletions gateway/tests/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}),
Expand Down Expand Up @@ -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;
Expand Down
Loading