//! Thin glue over `web-push-native`, which does the cryptography: the RFC 8291 message encryption //! (aes128gcm content coding, RFC 8188) and the RFC 8292 VAPID authorization (an ES256 JWT). The //! crate is RustCrypto based and pure Rust. This module only converts the base64url values that //! browsers and the database hold into the types the crate takes, and builds the request. use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use p256::elliptic_curve::sec1::ToEncodedPoint; use web_push_native::jwt_simple::algorithms::ES256KeyPair; use web_push_native::{Auth, WebPushBuilder, p256}; use forge_core::{Error, Result}; /// The uncompressed P-256 point length: 0x04 followed by X and Y. const POINT_LEN: usize = 65; /// Decodes base64url, with or without padding. pub fn decode_b64(text: &str) -> Result> { URL_SAFE_NO_PAD .decode(text.trim_end_matches('=')) .map_err(|_| Error::Invalid("not base64url".into())) } /// Encodes base64url without padding, the form push services and browsers use. pub fn encode_b64(bytes: &[u8]) -> String { URL_SAFE_NO_PAD.encode(bytes) } /// A new VAPID private key (32 bytes) from the system RNG. pub fn new_vapid_private() -> [u8; 32] { let mut out = [0u8; 32]; out.copy_from_slice(&ES256KeyPair::generate().to_bytes()); out } /// The key pair the VAPID signature is made with, from its 32-byte private scalar. pub fn vapid_key_pair(private: &[u8; 32]) -> Result { ES256KeyPair::from_bytes(private).map_err(|_| Error::Crypto("bad VAPID key".into())) } /// The public key of a VAPID private key, as the uncompressed point in base64url. This is the /// `applicationServerKey` the browser subscribes with. pub fn vapid_public_key(private: &[u8; 32]) -> Result { let secret = p256::SecretKey::from_slice(private).map_err(|_| Error::Crypto("bad VAPID key".into()))?; let point = secret.public_key().to_encoded_point(false); Ok(encode_b64(point.as_bytes())) } /// Builds the POST for one push: the body is encrypted for the browser's key and auth secret, /// and the request carries the VAPID `Authorization` for `endpoint`'s origin. `subject` is the /// contact URL (`mailto:` or `https:`). pub fn push_request( endpoint: &str, p256dh: &[u8], auth: &[u8], subject: &str, key_pair: &ES256KeyPair, payload: Vec, ) -> Result>> { if p256dh.len() != POINT_LEN { return Err(Error::Invalid( "the browser key is not a P-256 point".into(), )); } let ua_public = p256::PublicKey::from_sec1_bytes(p256dh) .map_err(|_| Error::Invalid("the browser key is not on the curve".into()))?; if auth.len() != 16 { return Err(Error::Invalid( "the browser auth secret is not 16 bytes".into(), )); } let ua_auth = Auth::clone_from_slice(auth); let uri: http::Uri = endpoint .parse() .map_err(|_| Error::Invalid("bad push endpoint".into()))?; WebPushBuilder::new(uri, ua_public, ua_auth) .with_vapid(key_pair, subject) .build(payload) .map_err(|e| Error::Crypto(format!("web push encryption failed: {e}"))) } #[cfg(test)] mod tests { use super::*; use p256::elliptic_curve::sec1::ToEncodedPoint; #[test] fn a_browser_key_that_is_not_a_point_is_refused() { let key_pair = vapid_key_pair(&new_vapid_private()).expect("key"); let auth = [7u8; 16]; let not_a_point = [4u8; 65]; assert!( push_request( "https://push.example.test/x", ¬_a_point, &auth, "mailto:tahinli@example.test", &key_pair, b"hi".to_vec() ) .is_err() ); assert!( push_request( "https://push.example.test/x", &[0x04; 10], &auth, "mailto:tahinli@example.test", &key_pair, b"hi".to_vec() ) .is_err() ); } #[test] fn the_request_is_an_encrypted_vapid_post_to_the_endpoint() { let private = new_vapid_private(); let key_pair = vapid_key_pair(&private).expect("key"); let browser = p256::SecretKey::from_slice(&new_vapid_private()).expect("scalar"); let point = browser .public_key() .to_encoded_point(false) .as_bytes() .to_vec(); let auth = [9u8; 16]; let endpoint = "https://push.example.test/send/abc"; let payload = br#"{"title":"tahinli/forge#1"}"#.to_vec(); let request = push_request( endpoint, &point, &auth, "mailto:tahinli@example.test", &key_pair, payload.clone(), ) .expect("request"); assert_eq!(request.method(), http::Method::POST); assert_eq!(request.uri().to_string(), endpoint); assert_eq!(request.headers()["content-encoding"], "aes128gcm"); assert_eq!(request.headers()["ttl"], "43200"); // The VAPID header names the push service's origin and carries the instance's public key. let auth_header = request.headers()["authorization"] .to_str() .expect("ascii") .to_owned(); assert!(auth_header.starts_with("vapid "), "{auth_header}"); assert!(auth_header.contains(&format!( "k={}", vapid_public_key(&private).expect("public") ))); let token = auth_header .split("t=") .nth(1) .and_then(|rest| rest.split(',').next()) .expect("token"); let claims = token.split('.').nth(1).expect("claims"); let claims = decode_b64(claims).expect("base64"); let claims: serde_json::Value = serde_json::from_slice(&claims).expect("json"); assert_eq!(claims["aud"], "https://push.example.test"); assert_eq!(claims["sub"], "mailto:tahinli@example.test"); // The body is encrypted: it is longer than the plaintext and does not contain it. let body = request.body(); assert!(body.len() > payload.len()); assert!(!body.windows(payload.len()).any(|w| w == payload.as_slice())); } #[test] fn the_public_key_is_the_uncompressed_point() { let public = vapid_public_key(&new_vapid_private()).expect("public"); assert_eq!(decode_b64(&public).expect("b64").len(), POINT_LEN); } }