Skip to main content

adk_surface/mobile/
vapid.rs

1//! The kernel's own push key and the VAPID token it signs (spec 3.3 §5.4; RFC 8292).
2//!
3//! The key is a P-256 key kept in the kernel home, readable by its owner only, so pushes come
4//! from the person's own kernel and no relay holds a key. A VAPID token is an ES256 JWT for one
5//! push service origin, valid 12 hours, re-signed at most once an hour per origin.
6
7use std::collections::HashMap;
8use std::fmt;
9use std::path::Path;
10use std::sync::{Arc, Mutex};
11
12use adk_core::Clock;
13use base64ct::{Base64UrlUnpadded, Encoding as _};
14use chrono::{DateTime, Duration, Utc};
15use p256::ecdsa::signature::Signer as _;
16use p256::ecdsa::{Signature, SigningKey};
17use sha2::{Digest as _, Sha256};
18
19use super::error::MobileError;
20
21/// How long a VAPID token is valid.
22const TOKEN_LIFETIME: Duration = Duration::hours(12);
23/// How long a signed token is reused for its origin.
24const RESIGN_AFTER: Duration = Duration::hours(1);
25
26/// The kernel's push key (spec 3.3 §5.4): a P-256 key, kept at `<home>/push.key`, that signs
27/// the VAPID token of every push and that phones subscribe with. Its `Debug` shows only its
28/// id.
29///
30/// Replicas share one key with `adk-rust up --push-key <file>`; each subscription remembers the
31/// id of the key it was made with, and a replica sends only with that key.
32///
33/// # Example
34///
35/// ```rust
36/// use adk_surface::mobile::PushKey;
37///
38/// let home = tempfile::tempdir().unwrap();
39/// let path = home.path().join(PushKey::FILE);
40/// let key = PushKey::load_or_create(&path).unwrap();
41/// assert_eq!(key.id(), PushKey::load_or_create(&path).unwrap().id());
42/// assert_eq!(format!("{key:?}"), format!("PushKey({})", key.id()));
43/// ```
44#[derive(Clone)]
45pub struct PushKey {
46    signing: SigningKey,
47    public: String,
48    id: String,
49}
50
51impl fmt::Debug for PushKey {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        write!(f, "PushKey({})", self.id)
54    }
55}
56
57impl PushKey {
58    /// The key's file name in the kernel home.
59    pub const FILE: &'static str = "push.key";
60
61    /// A new random key from the operating system's generator.
62    ///
63    /// # Errors
64    ///
65    /// Returns [`MobileError::PushKey`] when the generator is unavailable.
66    pub fn generate() -> Result<Self, MobileError> {
67        loop {
68            let mut bytes = [0u8; 32];
69            getrandom::fill(&mut bytes).map_err(|error| MobileError::PushKey {
70                reason: format!("the operating system's random source failed: {error}"),
71            })?;
72            // A value outside the curve's order is astronomically rare; draw again.
73            if let Ok(key) = Self::from_bytes(bytes) {
74                return Ok(key);
75            }
76        }
77    }
78
79    /// The key with this secret scalar.
80    ///
81    /// # Errors
82    ///
83    /// Returns [`MobileError::PushKey`] when the bytes are not a P-256 secret key.
84    pub fn from_bytes(bytes: [u8; 32]) -> Result<Self, MobileError> {
85        let signing = SigningKey::from_bytes(&bytes.into()).map_err(|_| MobileError::PushKey {
86            reason: "the bytes are not a P-256 secret key".into(),
87        })?;
88        let point = signing.verifying_key().to_encoded_point(false);
89        let public = Base64UrlUnpadded::encode_string(point.as_bytes());
90        let digest = Sha256::digest(point.as_bytes());
91        let id = Base64UrlUnpadded::encode_string(&digest[..12]);
92        Ok(Self { signing, public, id })
93    }
94
95    /// The key in the file at `path`, or a new one written there, readable only by its owner
96    /// on Unix (mode `0600`). The file holds 64 hex digits. An empty file gets a new key and
97    /// keeps its permissions, so a caller can create it owner-only first.
98    ///
99    /// # Errors
100    ///
101    /// Returns [`MobileError::PushKey`] when the file cannot be read or created, or does not
102    /// hold a key.
103    pub fn load_or_create(path: &Path) -> Result<Self, MobileError> {
104        let unusable = |error: std::io::Error| MobileError::PushKey {
105            reason: format!("{}: {error}", path.display()),
106        };
107        match std::fs::read_to_string(path) {
108            Ok(text) if text.trim().is_empty() => {
109                let key = Self::generate()?;
110                let mut file = std::fs::OpenOptions::new()
111                    .write(true)
112                    .truncate(true)
113                    .open(path)
114                    .map_err(unusable)?;
115                key.write_to(&mut file).map_err(unusable)?;
116                return Ok(key);
117            }
118            Ok(text) => return Self::parse(path, &text),
119            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
120            Err(error) => return Err(unusable(error)),
121        }
122        let key = Self::generate()?;
123        if let Some(parent) = path.parent() {
124            std::fs::create_dir_all(parent).map_err(unusable)?;
125        }
126        let mut options = std::fs::OpenOptions::new();
127        options.write(true).create_new(true);
128        #[cfg(unix)]
129        std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
130        match options.open(path) {
131            Ok(mut file) => {
132                key.write_to(&mut file).map_err(unusable)?;
133                Ok(key)
134            }
135            // Another kernel created it first: use that one.
136            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
137                Self::parse(path, &std::fs::read_to_string(path).map_err(unusable)?)
138            }
139            Err(error) => Err(unusable(error)),
140        }
141    }
142
143    fn write_to(&self, file: &mut std::fs::File) -> std::io::Result<()> {
144        use std::io::Write as _;
145        let bytes = self.signing.to_bytes();
146        let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
147        writeln!(file, "{hex}")?;
148        file.sync_all()
149    }
150
151    fn parse(path: &Path, text: &str) -> Result<Self, MobileError> {
152        let text = text.trim();
153        let invalid = || MobileError::PushKey {
154            reason: format!("{} does not hold 64 hex digits", path.display()),
155        };
156        if text.len() != 64 || !text.is_ascii() {
157            return Err(invalid());
158        }
159        let mut bytes = [0u8; 32];
160        for (index, byte) in bytes.iter_mut().enumerate() {
161            *byte =
162                u8::from_str_radix(&text[index * 2..index * 2 + 2], 16).map_err(|_| invalid())?;
163        }
164        Self::from_bytes(bytes)
165    }
166
167    /// The key's id: what a subscription records, so a replica sends only with its key.
168    pub fn id(&self) -> &str {
169        &self.id
170    }
171
172    /// The public key a phone subscribes with (`applicationServerKey`): the uncompressed point,
173    /// base64url without padding.
174    pub fn public_key(&self) -> &str {
175        &self.public
176    }
177
178    fn sign(&self, message: &[u8]) -> Vec<u8> {
179        let signature: Signature = self.signing.sign(message);
180        signature.to_bytes().to_vec()
181    }
182}
183
184/// Signs and caches the VAPID token of each push service origin.
185#[derive(Clone)]
186pub(crate) struct Vapid {
187    key: PushKey,
188    subject: String,
189    clock: Arc<dyn Clock>,
190    signed: Arc<Mutex<Signed>>,
191}
192
193/// Each origin's token and when it was signed.
194type Signed = HashMap<String, (String, DateTime<Utc>)>;
195
196impl fmt::Debug for Vapid {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        f.debug_struct("Vapid").field("key", &self.key).field("subject", &self.subject).finish()
199    }
200}
201
202impl Vapid {
203    /// A signer with `key`, naming `subject` (a `mailto:` or https URL) as the contact.
204    pub(crate) fn new(key: PushKey, subject: String, clock: Arc<dyn Clock>) -> Self {
205        Self { key, subject, clock, signed: Arc::default() }
206    }
207
208    pub(crate) fn key(&self) -> &PushKey {
209        &self.key
210    }
211
212    /// The `Authorization` header of a push to `origin` (`https://host[:port]`).
213    pub(crate) fn authorization(&self, origin: &str) -> String {
214        format!("vapid t={}, k={}", self.token(origin), self.key.public_key())
215    }
216
217    /// The token for `origin`, signed again once the cached one is an hour old.
218    fn token(&self, origin: &str) -> String {
219        let now = self.clock.now();
220        let mut signed = self.signed.lock().unwrap_or_else(|e| e.into_inner());
221        if let Some((token, at)) = signed.get(origin)
222            && now - *at < RESIGN_AFTER
223            && now >= *at
224        {
225            return token.clone();
226        }
227        let header = Base64UrlUnpadded::encode_string(br#"{"typ":"JWT","alg":"ES256"}"#);
228        let claims = serde_json::json!({
229            "aud": origin,
230            "exp": (now + TOKEN_LIFETIME).timestamp(),
231            "sub": self.subject,
232        });
233        let claims = Base64UrlUnpadded::encode_string(claims.to_string().as_bytes());
234        let input = format!("{header}.{claims}");
235        let signature = Base64UrlUnpadded::encode_string(&self.key.sign(input.as_bytes()));
236        let token = format!("{input}.{signature}");
237        signed.insert(origin.to_string(), (token.clone(), now));
238        token
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use adk_core::ManualClock;
245    use chrono::TimeZone as _;
246    use p256::ecdsa::VerifyingKey;
247    use p256::ecdsa::signature::Verifier as _;
248
249    use super::*;
250
251    fn clock() -> Arc<ManualClock> {
252        Arc::new(ManualClock::new(Utc.with_ymd_and_hms(2026, 10, 24, 18, 0, 0).unwrap()))
253    }
254
255    /// The signed input, the claims, the signature and the public key of a header.
256    fn parts(header: &str) -> (String, serde_json::Value, Vec<u8>, String) {
257        let (token, key) = header
258            .strip_prefix("vapid t=")
259            .and_then(|rest| rest.split_once(", k="))
260            .expect("vapid t=…, k=…");
261        let (input, signature) = token.rsplit_once('.').unwrap();
262        let claims = input.split_once('.').unwrap().1;
263        let claims =
264            serde_json::from_slice(&Base64UrlUnpadded::decode_vec(claims).unwrap()).unwrap();
265        (
266            input.to_string(),
267            claims,
268            Base64UrlUnpadded::decode_vec(signature).unwrap(),
269            key.to_string(),
270        )
271    }
272
273    /// The token is ES256 over its header and claims, for the push service's origin, valid
274    /// 12 hours, naming the contact (RFC 8292 §2).
275    #[test]
276    fn a_token_is_es256_for_the_origin() {
277        let clock = clock();
278        let key = PushKey::generate().unwrap();
279        let vapid = Vapid::new(key.clone(), "https://home.example.ts.net".into(), clock.clone());
280        let (input, claims, signature, public) =
281            parts(&vapid.authorization("https://web.push.apple.com"));
282        assert_eq!(public, key.public_key());
283        assert_eq!(claims["aud"], "https://web.push.apple.com");
284        assert_eq!(claims["sub"], "https://home.example.ts.net");
285        assert_eq!(claims["exp"], (clock.now() + Duration::hours(12)).timestamp());
286        let verifying = VerifyingKey::from_sec1_bytes(
287            &Base64UrlUnpadded::decode_vec(key.public_key()).unwrap(),
288        )
289        .unwrap();
290        let signature = Signature::from_slice(&signature).unwrap();
291        verifying.verify(input.as_bytes(), &signature).unwrap();
292    }
293
294    /// One signature per origin per hour.
295    #[test]
296    fn a_token_is_reused_for_an_hour_per_origin() {
297        let clock = clock();
298        let vapid = Vapid::new(
299            PushKey::generate().unwrap(),
300            "mailto:ana@example.com".into(),
301            clock.clone(),
302        );
303        let apple = vapid.authorization("https://web.push.apple.com");
304        let google = vapid.authorization("https://fcm.googleapis.com");
305        assert_ne!(apple, google);
306        clock.advance(std::time::Duration::from_secs(59 * 60));
307        assert_eq!(vapid.authorization("https://web.push.apple.com"), apple);
308        clock.advance(std::time::Duration::from_secs(60));
309        assert_ne!(vapid.authorization("https://web.push.apple.com"), apple);
310    }
311
312    #[test]
313    fn a_key_file_that_is_not_a_key_is_refused() {
314        let home = tempfile::tempdir().unwrap();
315        let path = home.path().join(PushKey::FILE);
316        std::fs::write(&path, "not a key\n").unwrap();
317        let error = PushKey::load_or_create(&path).unwrap_err();
318        assert!(matches!(error, MobileError::PushKey { .. }), "{error:?}");
319    }
320
321    #[cfg(unix)]
322    #[test]
323    fn a_new_key_file_is_its_owner_s_only() {
324        use std::os::unix::fs::PermissionsExt as _;
325        let home = tempfile::tempdir().unwrap();
326        let path = home.path().join(PushKey::FILE);
327        PushKey::load_or_create(&path).unwrap();
328        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
329        assert_eq!(mode, 0o600);
330    }
331}