diff --git a/.env.example b/.env.example index b18765b79e..b4e7827944 100644 --- a/.env.example +++ b/.env.example @@ -101,7 +101,7 @@ BUZZ_PUSH_GATEWAY_DELIVERY_URL=https://push.buzz.xyz/v1/deliveries/apns # BUZZ_PUSH_ANDROID_PACKAGE_NAME=com.example.buzz # BUZZ_PUSH_ANDROID_SIGNING_CERT_DIGESTS=<64-hex-char SHA-256 of the app signing certificate>[,...] # BUZZ_PUSH_FCM_PROJECT_ID=example-project -# BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH=/etc/buzz-push/fcm-service-account.json +# BUZZ_PUSH_FCM_CREDENTIALS_PATH=/etc/buzz-push/fcm-credentials.json # Optional Android attestation settings. Boot keys are SHA-256 digests of verified # boot keys accepted with a self-signed boot state; empty accepts stock Android only. # BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS=<64-hex-char digest>[,...] diff --git a/Cargo.lock b/Cargo.lock index 4d70e1a38b..b280ac24f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1414,6 +1414,7 @@ dependencies = [ "p256", "percent-encoding", "proptest", + "quick-xml 0.38.4", "rand 0.10.1", "reqwest 0.13.4", "rustls-pki-types", diff --git a/crates/buzz-push-gateway/Cargo.toml b/crates/buzz-push-gateway/Cargo.toml index bb8c467fc2..4e904303a5 100644 --- a/crates/buzz-push-gateway/Cargo.toml +++ b/crates/buzz-push-gateway/Cargo.toml @@ -23,6 +23,7 @@ personal-dev-app-attest = [] aes-gcm = "0.10" aws-lc-rs = { version = "1", default-features = false } minicbor = { version = "0.25", features = ["std", "half"] } +quick-xml = { version = "0.38", features = ["serialize"] } p256 = { version = "0.14", features = ["ecdsa"] } rustls-pki-types = { version = "1", features = ["std"] } webpki = { package = "rustls-webpki", version = "0.103.9", default-features = false, features = ["aws-lc-rs", "alloc"] } diff --git a/crates/buzz-push-gateway/src/aws_credentials.rs b/crates/buzz-push-gateway/src/aws_credentials.rs new file mode 100644 index 0000000000..87d8937235 --- /dev/null +++ b/crates/buzz-push-gateway/src/aws_credentials.rs @@ -0,0 +1,238 @@ +//! The gateway's AWS identity, for signing the federation subject token. +//! +//! Three sources, chosen once at startup from the environment in this order: +//! +//! 1. Static `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` / +//! `AWS_SESSION_TOKEN`. +//! 2. IAM roles for service accounts: `AWS_ROLE_ARN` and +//! `AWS_WEB_IDENTITY_TOKEN_FILE`, exchanged at STS +//! `AssumeRoleWithWebIdentity`. +//! 3. EKS Pod Identity: `AWS_CONTAINER_CREDENTIALS_FULL_URI` and +//! `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE`, read from the agent's +//! credentials endpoint. +//! +//! EC2 instance metadata is deliberately unsupported: pods cannot reach it. +//! Nothing is fetched at startup, and credentials are fetched on every mint +//! (about once an hour), so no AWS credential is cached here. + +use std::{fmt, path::PathBuf}; + +use reqwest::StatusCode; +use serde::Deserialize; +use url::{Host, Url}; + +use crate::fcm::{FcmError, MintFailure}; + +const ROLE_SESSION_NAME: &str = "buzz-push-gateway"; +const STS_API_VERSION: &str = "2011-06-15"; +/// The EKS Pod Identity Agent's link-local addresses. +const POD_IDENTITY_IPV4: [u8; 4] = [169, 254, 170, 23]; +const POD_IDENTITY_IPV6: [u16; 8] = [0xfd00, 0x0ec2, 0, 0, 0, 0, 0, 0x23]; + +#[derive(Clone, PartialEq, Eq)] +pub struct AwsCredentials { + pub access_key_id: String, + pub secret_access_key: String, + pub session_token: Option, +} + +impl fmt::Debug for AwsCredentials { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("AwsCredentials").finish_non_exhaustive() + } +} + +#[derive(Debug)] +pub enum AwsCredentialSource { + Static(AwsCredentials), + WebIdentity { + role_arn: String, + token_file: PathBuf, + /// The STS endpoint to post `AssumeRoleWithWebIdentity` to. + sts_url: String, + }, + PodIdentity { + url: String, + token_file: Option, + }, +} + +#[derive(Deserialize)] +#[serde(rename_all = "PascalCase")] +struct ContainerCredentials { + access_key_id: String, + secret_access_key: String, + token: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "PascalCase")] +struct AssumeRoleWithWebIdentityResponse { + assume_role_with_web_identity_result: AssumeRoleResult, +} +#[derive(Deserialize)] +#[serde(rename_all = "PascalCase")] +struct AssumeRoleResult { + credentials: StsCredentials, +} +#[derive(Deserialize)] +#[serde(rename_all = "PascalCase")] +struct StsCredentials { + access_key_id: String, + secret_access_key: String, + session_token: String, +} + +impl AwsCredentialSource { + /// Pick the source named by the environment `get` reads. `sts_url` is + /// where a web identity token is exchanged. Fails when no supported + /// source is configured or its settings are incomplete. + pub fn from_lookup( + get: impl Fn(&str) -> Option, + sts_url: String, + ) -> Result { + let get = |name: &str| get(name).filter(|value| !value.is_empty()); + if let Some(access_key_id) = get("AWS_ACCESS_KEY_ID") { + let secret_access_key = get("AWS_SECRET_ACCESS_KEY").ok_or(FcmError::Configuration( + "AWS_ACCESS_KEY_ID is set without AWS_SECRET_ACCESS_KEY", + ))?; + return Ok(Self::Static(AwsCredentials { + access_key_id, + secret_access_key, + session_token: get("AWS_SESSION_TOKEN"), + })); + } + if let Some(token_file) = get("AWS_WEB_IDENTITY_TOKEN_FILE") { + let role_arn = get("AWS_ROLE_ARN").ok_or(FcmError::Configuration( + "AWS_WEB_IDENTITY_TOKEN_FILE is set without AWS_ROLE_ARN", + ))?; + return Ok(Self::WebIdentity { + role_arn, + token_file: token_file.into(), + sts_url, + }); + } + if let Some(url) = get("AWS_CONTAINER_CREDENTIALS_FULL_URI") { + validate_pod_identity_url(&url)?; + return Ok(Self::PodIdentity { + url, + token_file: get("AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE").map(Into::into), + }); + } + Err(FcmError::Configuration( + "no AWS credentials: set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, or \ + AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE, or \ + AWS_CONTAINER_CREDENTIALS_FULL_URI", + )) + } + + /// The caller's current AWS credentials. + pub(crate) async fn credentials( + &self, + client: &reqwest::Client, + ) -> Result { + match self { + Self::Static(credentials) => Ok(credentials.clone()), + Self::WebIdentity { + role_arn, + token_file, + sts_url, + } => { + // The kubelet rotates the projected token: read it every time. + let token = read_secret_file(token_file)?; + let body = url::form_urlencoded::Serializer::new(String::new()) + .append_pair("Action", "AssumeRoleWithWebIdentity") + .append_pair("Version", STS_API_VERSION) + .append_pair("RoleArn", role_arn) + .append_pair("RoleSessionName", ROLE_SESSION_NAME) + .append_pair("WebIdentityToken", &token) + .finish(); + let response = client + .post(sts_url) + .header( + reqwest::header::CONTENT_TYPE, + "application/x-www-form-urlencoded", + ) + .body(body) + .send() + .await + .map_err(|_| MintFailure::unavailable("aws web identity", None))?; + let text = response_text(response, "aws web identity").await?; + let parsed: AssumeRoleWithWebIdentityResponse = quick_xml::de::from_str(&text) + .map_err(|_| MintFailure::unavailable("aws web identity", None))?; + let c = parsed.assume_role_with_web_identity_result.credentials; + Ok(AwsCredentials { + access_key_id: c.access_key_id, + secret_access_key: c.secret_access_key, + session_token: Some(c.session_token), + }) + } + Self::PodIdentity { url, token_file } => { + let mut request = client.get(url); + if let Some(path) = token_file { + request = + request.header(reqwest::header::AUTHORIZATION, read_secret_file(path)?); + } + let response = request + .send() + .await + .map_err(|_| MintFailure::unavailable("aws pod identity", None))?; + let text = response_text(response, "aws pod identity").await?; + let c: ContainerCredentials = serde_json::from_str(&text) + .map_err(|_| MintFailure::unavailable("aws pod identity", None))?; + Ok(AwsCredentials { + access_key_id: c.access_key_id, + secret_access_key: c.secret_access_key, + session_token: Some(c.token), + }) + } + } + } +} + +/// An unreadable token file is a deployment fault that retrying will not fix. +fn read_secret_file(path: &PathBuf) -> Result { + std::fs::read_to_string(path) + .map(|content| content.trim_end().to_owned()) + .map_err(|_| MintFailure::rejected("aws token file", None)) +} + +async fn response_text( + response: reqwest::Response, + hop: &'static str, +) -> Result { + let status = response.status(); + if status.is_server_error() || status == StatusCode::TOO_MANY_REQUESTS { + return Err(MintFailure::unavailable(hop, Some(status.as_u16()))); + } + if !status.is_success() { + return Err(MintFailure::rejected(hop, Some(status.as_u16()))); + } + response + .text() + .await + .map_err(|_| MintFailure::unavailable(hop, None)) +} + +/// The authorization token is a credential, so it may only travel over https +/// or to a loopback or Pod Identity Agent address, as the AWS SDKs require. +fn validate_pod_identity_url(value: &str) -> Result<(), FcmError> { + let url = Url::parse(value).map_err(|_| { + FcmError::Configuration("AWS_CONTAINER_CREDENTIALS_FULL_URI is not a valid URL") + })?; + let trusted = match (url.scheme(), url.host()) { + ("https", Some(_)) => true, + ("http", Some(Host::Ipv4(ip))) => ip.is_loopback() || ip.octets() == POD_IDENTITY_IPV4, + ("http", Some(Host::Ipv6(ip))) => ip.is_loopback() || ip.segments() == POD_IDENTITY_IPV6, + ("http", Some(Host::Domain(domain))) => domain == "localhost", + _ => false, + }; + if trusted { + Ok(()) + } else { + Err(FcmError::Configuration( + "AWS_CONTAINER_CREDENTIALS_FULL_URI must be https, or http to loopback or the \ + EKS Pod Identity Agent", + )) + } +} diff --git a/crates/buzz-push-gateway/src/aws_sigv4.rs b/crates/buzz-push-gateway/src/aws_sigv4.rs new file mode 100644 index 0000000000..7e06039cbf --- /dev/null +++ b/crates/buzz-push-gateway/src/aws_sigv4.rs @@ -0,0 +1,224 @@ +//! The AWS subject token Google's workload identity federation accepts: a +//! SigV4-signed STS `GetCallerIdentity` request, serialized as Google +//! documents it. Google's token service replays the request to STS, so STS +//! vouches for the caller's AWS identity without any long-lived key. +//! +//! Only the one request shape Google defines is implemented: a bodiless POST +//! to the `sts` service. + +use aws_lc_rs::{ + digest::{digest, SHA256}, + hmac, +}; +use chrono::DateTime; +use thiserror::Error; +use url::Url; + +use crate::aws_credentials::AwsCredentials; + +const SERVICE: &str = "sts"; +const ALGORITHM: &str = "AWS4-HMAC-SHA256"; + +/// The request could not be signed. It carries no credential material. +#[derive(Debug, Error)] +pub enum SigningError { + #[error("the STS verification URL is not an absolute URL with a host")] + Url, + #[error("the request time is outside the representable range")] + Time, +} + +/// Build Google's URL-encoded subject token for `credentials`. +/// +/// `url_template` is the credential file's `regional_cred_verification_url` +/// with its `{region}` placeholder, and `audience` the file's `audience`. +pub fn subject_token( + url_template: &str, + region: &str, + audience: &str, + credentials: &AwsCredentials, + now: i64, +) -> Result { + let request_url = url_template.replace("{region}", region); + let parsed = Url::parse(&request_url).map_err(|_| SigningError::Url)?; + let host = match (parsed.host_str().ok_or(SigningError::Url)?, parsed.port()) { + (host, Some(port)) => format!("{host}:{port}"), + (host, None) => host.to_owned(), + }; + let time = DateTime::from_timestamp(now, 0).ok_or(SigningError::Time)?; + let amz_date = time.format("%Y%m%dT%H%M%SZ").to_string(); + let date = &amz_date[..8]; + + // Sorted by lowercase name, as SigV4 requires. + let mut headers = vec![ + ("host", host), + ("x-amz-date", amz_date.clone()), + ("x-goog-cloud-target-resource", audience.to_owned()), + ]; + if let Some(token) = &credentials.session_token { + headers.push(("x-amz-security-token", token.clone())); + } + headers.sort_by(|a, b| a.0.cmp(b.0)); + let signed_headers = headers + .iter() + .map(|(name, _)| *name) + .collect::>() + .join(";"); + let canonical_headers: String = headers + .iter() + .map(|(name, value)| format!("{name}:{}\n", value.trim())) + .collect(); + + let mut query: Vec<(String, String)> = parsed + .query_pairs() + .map(|(k, v)| (uri_encode(&k), uri_encode(&v))) + .collect(); + query.sort(); + let canonical_query = query + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect::>() + .join("&"); + let payload_hash = hex::encode(digest(&SHA256, b"").as_ref()); + let canonical_request = format!( + "POST\n{}\n{canonical_query}\n{canonical_headers}\n{signed_headers}\n{payload_hash}", + parsed.path() + ); + + let scope = format!("{date}/{region}/{SERVICE}/aws4_request"); + let string_to_sign = format!( + "{ALGORITHM}\n{amz_date}\n{scope}\n{}", + hex::encode(digest(&SHA256, canonical_request.as_bytes()).as_ref()) + ); + let mut key = hmac_sha256( + format!("AWS4{}", credentials.secret_access_key).as_bytes(), + date.as_bytes(), + ); + for part in [region, SERVICE, "aws4_request"] { + key = hmac_sha256(&key, part.as_bytes()); + } + let signature = hex::encode(hmac_sha256(&key, string_to_sign.as_bytes())); + let authorization = format!( + "{ALGORITHM} Credential={}/{scope}, SignedHeaders={signed_headers}, Signature={signature}", + credentials.access_key_id + ); + + // Google's serialization: Authorization first, then every signed header. + let mut serialized = vec![serde_json::json!({"key": "Authorization", "value": authorization})]; + serialized.extend( + headers + .iter() + .map(|(name, value)| serde_json::json!({"key": name, "value": value})), + ); + let token = serde_json::json!({ + "url": request_url, + "method": "POST", + "headers": serialized, + }); + Ok(uri_encode(&token.to_string())) +} + +fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec { + hmac::sign(&hmac::Key::new(hmac::HMAC_SHA256, key), data) + .as_ref() + .to_vec() +} + +/// Percent-encode everything except SigV4's unreserved characters. This is +/// also `encodeURIComponent`'s output for the ASCII JSON Google's token holds, +/// apart from the characters `encodeURIComponent` leaves alone (`!'()*`), +/// which Google's token service decodes either way. +fn uri_encode(value: &str) -> String { + let mut out = String::with_capacity(value.len()); + for byte in value.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + out.push(byte as char) + } + _ => out.push_str(&format!("%{byte:02X}")), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const AUDIENCE: &str = "//iam.googleapis.com/projects/123456789/locations/global/workloadIdentityPools/example-pool/providers/example-aws"; + const URL: &str = + "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"; + /// 2015-08-30T12:36:00Z, AWS's SigV4 documentation date. + const NOW: i64 = 1_440_938_160; + + fn credentials(session_token: Option<&str>) -> AwsCredentials { + AwsCredentials { + access_key_id: "AKIDEXAMPLE".into(), + secret_access_key: "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY".into(), + session_token: session_token.map(Into::into), + } + } + + fn decoded(token: &str) -> serde_json::Value { + let json: Vec = url::form_urlencoded::parse(format!("x={token}").as_bytes()) + .next() + .unwrap() + .1 + .bytes() + .collect(); + serde_json::from_slice(&json).unwrap() + } + + /// The signatures were computed by an independent implementation (a + /// Python hashlib/hmac script following the SigV4 specification), not by + /// this module. + #[test] + fn subject_token_matches_known_answer_with_session_token() { + let token = subject_token( + URL, + "us-east-1", + AUDIENCE, + &credentials(Some("EXAMPLETOKEN")), + NOW, + ) + .unwrap(); + assert!(!token.contains(['{', '"', ' ', ':', '/']), "{token}"); + assert_eq!( + decoded(&token), + serde_json::json!({ + "url": "https://sts.us-east-1.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15", + "method": "POST", + "headers": [ + {"key": "Authorization", "value": "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/sts/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token;x-goog-cloud-target-resource, Signature=a04e017a1fa273c71fc30f2633c72fba1736281950c42041d49495ba6e69611f"}, + {"key": "host", "value": "sts.us-east-1.amazonaws.com"}, + {"key": "x-amz-date", "value": "20150830T123600Z"}, + {"key": "x-amz-security-token", "value": "EXAMPLETOKEN"}, + {"key": "x-goog-cloud-target-resource", "value": AUDIENCE}, + ], + }) + ); + } + + #[test] + fn subject_token_matches_known_answer_without_session_token() { + let token = subject_token(URL, "us-east-1", AUDIENCE, &credentials(None), NOW).unwrap(); + let token = decoded(&token); + assert_eq!( + token["headers"][0]["value"], + "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/sts/aws4_request, SignedHeaders=host;x-amz-date;x-goog-cloud-target-resource, Signature=de946cd9ee4a1b9b4fef72f8258d35ba32e7c6e62954b0a297eb2843cf63fcdd" + ); + assert_eq!(token["headers"].as_array().unwrap().len(), 4); + } + + #[test] + fn unsignable_requests_fail() { + assert!(matches!( + subject_token("not a url", "us-east-1", AUDIENCE, &credentials(None), NOW), + Err(SigningError::Url) + )); + assert!(matches!( + subject_token(URL, "us-east-1", AUDIENCE, &credentials(None), i64::MAX), + Err(SigningError::Time) + )); + } +} diff --git a/crates/buzz-push-gateway/src/config.rs b/crates/buzz-push-gateway/src/config.rs index ad7e578361..638cd0c791 100644 --- a/crates/buzz-push-gateway/src/config.rs +++ b/crates/buzz-push-gateway/src/config.rs @@ -30,8 +30,9 @@ pub struct AndroidConfig { pub signing_cert_digests: Vec<[u8; 32]>, /// Firebase project that owns the app's FCM registration tokens. pub fcm_project_id: String, - /// Mounted service account key JSON the gateway uses to call FCM HTTP v1. - pub fcm_service_account_path: PathBuf, + /// Mounted Google credential JSON (service account key or AWS workload + /// identity federation config) the gateway uses to call FCM HTTP v1. + pub fcm_credentials_path: PathBuf, /// Verified boot keys (SHA-256 digests) accepted when the hardware reports /// a SelfSigned boot state. Empty, the default, accepts stock Android only. pub boot_key_digests: Vec<[u8; 32]>, @@ -178,7 +179,7 @@ const ANDROID_SETTINGS: [&str; 4] = [ "BUZZ_PUSH_ANDROID_PACKAGE_NAME", "BUZZ_PUSH_ANDROID_SIGNING_CERT_DIGESTS", "BUZZ_PUSH_FCM_PROJECT_ID", - "BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH", + "BUZZ_PUSH_FCM_CREDENTIALS_PATH", ]; const ANDROID_OPTIONAL_SETTINGS: [&str; 3] = [ @@ -257,7 +258,7 @@ fn parse_android(e: &HashMap) -> Result, C package_name: package_name.to_owned(), signing_cert_digests, fcm_project_id: required(ANDROID_SETTINGS[2])?.to_owned(), - fcm_service_account_path: PathBuf::from(required(ANDROID_SETTINGS[3])?), + fcm_credentials_path: PathBuf::from(required(ANDROID_SETTINGS[3])?), boot_key_digests, attestation_roots_path: e .get(ANDROID_OPTIONAL_SETTINGS[1]) @@ -549,8 +550,8 @@ mod tests { ), ("BUZZ_PUSH_FCM_PROJECT_ID".into(), "example-project".into()), ( - "BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH".into(), - "/fcm/service-account.json".into(), + "BUZZ_PUSH_FCM_CREDENTIALS_PATH".into(), + "/fcm/credentials.json".into(), ), ]); env diff --git a/crates/buzz-push-gateway/src/fcm.rs b/crates/buzz-push-gateway/src/fcm.rs index d3ecc4ad14..7307dd0a84 100644 --- a/crates/buzz-push-gateway/src/fcm.rs +++ b/crates/buzz-push-gateway/src/fcm.rs @@ -5,7 +5,10 @@ //! to live derived from the delivery's expiry: no relay-supplied bytes reach it. use std::{ - sync::Arc, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, time::{Duration, Instant}, }; @@ -18,6 +21,7 @@ use thiserror::Error; use tokio::sync::Mutex; use crate::apns::{DeliveryAttempt, DeliveryOutcome, PushTransport}; +use crate::fcm_federation::FederatedMinter; /// The one collapse key every wake carries. FCM replaces a wake it is still /// holding for an unreachable phone, so a phone coming back online gets one @@ -38,6 +42,8 @@ const ACCESS_TOKEN_REFRESH_MARGIN_SECONDS: i64 = 120; const TOKEN_FAILURE_BACKOFF: Duration = Duration::from_secs(5); /// FCM asks senders to wait at least a minute after a quota error. const QUOTA_RETRY_FLOOR_SECONDS: i64 = 60; +/// The whole of one token mint, however many requests it chains. +const MINT_DEADLINE: Duration = Duration::from_secs(15); /// Service account setup failure. It carries no credential material. #[derive(Debug, Error)] @@ -45,6 +51,10 @@ pub enum FcmError { /// The service account key is missing a field, malformed or not RSA. #[error("invalid FCM service account credential")] Credential, + /// The credential file or the environment it depends on is unusable. The + /// reason is a fixed message and carries no credential material. + #[error("invalid FCM credential configuration: {0}")] + Configuration(&'static str), } #[derive(Deserialize)] @@ -79,13 +89,63 @@ impl TokenState { } /// The ways a delivery cannot obtain an access token. -enum TokenFault { +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum TokenFault { /// The token endpoint answered but refused the credential. Rejected, /// The token endpoint could not be reached or is unhealthy. Unavailable, } +/// A failed mint: the fault class deliveries see, and which hop failed, for +/// the one log line operators get. It carries no credential material. +#[derive(Debug)] +pub(crate) struct MintFailure { + pub(crate) fault: TokenFault, + pub(crate) hop: &'static str, + pub(crate) status: Option, +} + +impl MintFailure { + pub(crate) fn rejected(hop: &'static str, status: Option) -> Self { + Self { + fault: TokenFault::Rejected, + hop, + status, + } + } + + pub(crate) fn unavailable(hop: &'static str, status: Option) -> Self { + Self { + fault: TokenFault::Unavailable, + hop, + status, + } + } +} + +/// What mints an OAuth access token. Everything else about a token (caching, +/// refresh, backoff) is `TokenSource`'s and identical for both. +enum TokenMinter { + /// Sign a JWT with a service account key and exchange it at `token_uri`. + ServiceAccount(ServiceAccountMinter), + /// Exchange the pod's AWS identity through Google workload identity + /// federation. + Federated(FederatedMinter), +} + +/// A freshly minted token and the seconds Google says it stays valid. +pub(crate) struct MintedToken { + pub(crate) value: String, + pub(crate) lifetime_seconds: i64, +} + +struct ServiceAccountMinter { + client_email: String, + token_uri: String, + key: KeyPair, +} + /// Direct HTTP/1.1+2 FCM HTTP v1 transport authenticated by a service account. pub struct FcmTransport { client: reqwest::Client, @@ -93,15 +153,17 @@ pub struct FcmTransport { tokens: Arc, } -/// The service account's OAuth access tokens. A cached token is served until +/// The gateway's OAuth access tokens. A cached token is served until /// it expires; a replacement is fetched by one background task from /// `refresh_at`, so deliveries wait on Google's token endpoint only when no /// unexpired token exists (cold start, expiry or a refused token). struct TokenSource { client: reqwest::Client, - client_email: String, - token_uri: String, - key: KeyPair, + minter: TokenMinter, + /// Bounds one whole mint. + deadline: Duration, + /// The first mint's result is logged once. + first_mint_logged: AtomicBool, now: fn() -> i64, /// Never held across a network call. state: Mutex, @@ -110,30 +172,49 @@ struct TokenSource { } impl FcmTransport { - /// Build the production transport for `project_id` from a Google service - /// account key JSON. - pub fn service_account(project_id: &str, key_json: &[u8]) -> Result { - Self::with_endpoints(project_id, key_json, FCM_BASE_URL, || { - chrono::Utc::now().timestamp() - }) + /// Build the production transport for `project_id` from a Google + /// credential JSON: a service account key (`"type": "service_account"`) + /// or an AWS workload identity federation config + /// (`"type": "external_account"`). Nothing is fetched here. + pub fn from_credentials(project_id: &str, credentials_json: &[u8]) -> Result { + Self::with_endpoints( + project_id, + credentials_json, + FCM_BASE_URL, + || chrono::Utc::now().timestamp(), + |name| std::env::var(name).ok(), + ) } + /// `env` reads the process environment the federated minter takes its AWS + /// region and credentials from. fn with_endpoints( project_id: &str, - key_json: &[u8], + credentials_json: &[u8], base_url: &str, now: fn() -> i64, + env: impl Fn(&str) -> Option, ) -> Result { - let account: ServiceAccountKey = - serde_json::from_slice(key_json).map_err(|_| FcmError::Credential)?; - if project_id.is_empty() || account.client_email.is_empty() || account.token_uri.is_empty() - { + if project_id.is_empty() { return Err(FcmError::Credential); } - let key = KeyPair::from_pkcs8(&pkcs8_der(&account.private_key)?) - .map_err(|_| FcmError::Credential)?; + let credentials: serde_json::Value = + serde_json::from_slice(credentials_json).map_err(|_| FcmError::Credential)?; + let minter = match credentials.get("type").and_then(|t| t.as_str()) { + Some("service_account") => TokenMinter::ServiceAccount(service_account_minter( + serde_json::from_value(credentials).map_err(|_| FcmError::Credential)?, + )?), + Some("external_account") => { + TokenMinter::Federated(FederatedMinter::from_config(credentials, FCM_SCOPE, env)?) + } + _ => { + return Err(FcmError::Configuration( + "the credential file's type must be service_account or external_account", + )) + } + }; let client = reqwest::Client::builder() - .timeout(Duration::from_secs(15)) + .timeout(MINT_DEADLINE) .build() .map_err(|_| FcmError::Credential)?; Ok(Self { @@ -141,9 +222,9 @@ impl FcmTransport { send_url: format!("{base_url}/v1/projects/{project_id}/messages:send"), tokens: Arc::new(TokenSource { client, - client_email: account.client_email, - token_uri: account.token_uri, - key, + minter, + deadline: MINT_DEADLINE, + first_mint_logged: AtomicBool::new(false), now, state: Mutex::new(TokenState::default()), fetch: Mutex::new(()), @@ -152,6 +233,19 @@ impl FcmTransport { } } +fn service_account_minter(account: ServiceAccountKey) -> Result { + if account.client_email.is_empty() || account.token_uri.is_empty() { + return Err(FcmError::Credential); + } + let key = + KeyPair::from_pkcs8(&pkcs8_der(&account.private_key)?).map_err(|_| FcmError::Credential)?; + Ok(ServiceAccountMinter { + client_email: account.client_email, + token_uri: account.token_uri, + key, + }) +} + impl TokenSource { /// Short-lived OAuth access token. async fn access_token(self: &Arc) -> Result { @@ -201,6 +295,7 @@ impl TokenSource { /// Request a token and record the result. Callers hold `fetch`. async fn fetch_token(&self) -> Result { let result = self.request_access_token((self.now)()).await; + self.log_mint(&result); let mut state = self.state.lock().await; match result { Ok(token) => { @@ -209,13 +304,37 @@ impl TokenSource { state.failed_at = None; Ok(value) } - Err(fault) => { + Err(failure) => { state.failed_at = Some(Instant::now()); - Err(fault) + Err(failure.fault) } } } + /// Log the first successful mint once, and every failed one, so a broken + /// setup (or a federation binding removed after startup) shows in the logs. + /// The failure backoff bounds how often a failure can log. + fn log_mint(&self, result: &Result) { + let credential = match self.minter { + TokenMinter::ServiceAccount(_) => "service_account", + TokenMinter::Federated(_) => "external_account", + }; + match result { + Ok(_) => { + if !self.first_mint_logged.swap(true, Ordering::Relaxed) { + tracing::info!(credential, "first FCM access token minted"); + } + } + Err(failure) => tracing::warn!( + credential, + hop = failure.hop, + status = failure.status, + fault = ?failure.fault, + "FCM access token mint failed" + ), + } + } + /// Drop the cached token if it is still `refused`, so a late 401 for an /// older token cannot discard a newer one. async fn discard(&self, refused: &str) { @@ -225,16 +344,39 @@ impl TokenSource { } } - async fn request_access_token(&self, now: i64) -> Result { + async fn request_access_token(&self, now: i64) -> Result { + let minted = tokio::time::timeout(self.deadline, self.mint(now)) + .await + .map_err(|_| MintFailure::unavailable("deadline", None))??; + let lifetime = minted + .lifetime_seconds + .clamp(0, ACCESS_TOKEN_LIFETIME_SECONDS); + Ok(CachedToken { + value: minted.value, + refresh_at: now + lifetime - ACCESS_TOKEN_REFRESH_MARGIN_SECONDS, + expires_at: now + lifetime, + }) + } + + async fn mint(&self, now: i64) -> Result { + match &self.minter { + TokenMinter::ServiceAccount(minter) => minter.mint(&self.client, now).await, + TokenMinter::Federated(minter) => minter.mint(&self.client, now).await, + } + } +} + +impl ServiceAccountMinter { + async fn mint(&self, client: &reqwest::Client, now: i64) -> Result { + const HOP: &str = "service account token"; let assertion = self .signed_assertion(now) - .map_err(|_| TokenFault::Rejected)?; + .map_err(|_| MintFailure::rejected(HOP, None))?; let body = url::form_urlencoded::Serializer::new(String::new()) .append_pair("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer") .append_pair("assertion", &assertion) .finish(); - let response = self - .client + let response = client .post(&self.token_uri) .header( reqwest::header::CONTENT_TYPE, @@ -243,13 +385,13 @@ impl TokenSource { .body(body) .send() .await - .map_err(|_| TokenFault::Unavailable)?; + .map_err(|_| MintFailure::unavailable(HOP, None))?; let status = response.status(); if status.is_server_error() || status == StatusCode::TOO_MANY_REQUESTS { - return Err(TokenFault::Unavailable); + return Err(MintFailure::unavailable(HOP, Some(status.as_u16()))); } if !status.is_success() { - return Err(TokenFault::Rejected); + return Err(MintFailure::rejected(HOP, Some(status.as_u16()))); } #[derive(Deserialize)] struct TokenResponse { @@ -259,15 +401,13 @@ impl TokenSource { let token = response .json::() .await - .map_err(|_| TokenFault::Unavailable)?; + .map_err(|_| MintFailure::unavailable(HOP, None))?; if token.access_token.is_empty() { - return Err(TokenFault::Rejected); + return Err(MintFailure::rejected(HOP, None)); } - let lifetime = token.expires_in.clamp(0, ACCESS_TOKEN_LIFETIME_SECONDS); - Ok(CachedToken { + Ok(MintedToken { value: token.access_token, - refresh_at: now + lifetime - ACCESS_TOKEN_REFRESH_MARGIN_SECONDS, - expires_at: now + lifetime, + lifetime_seconds: token.expires_in, }) } @@ -469,6 +609,7 @@ mod tests { .private_key_to_pem_pkcs8() .unwrap(); serde_json::to_vec(&serde_json::json!({ + "type": "service_account", "client_email": "gateway@example-project.iam.example.org", "private_key": String::from_utf8(pem).unwrap(), "token_uri": token_uri, @@ -514,6 +655,7 @@ mod tests { &service_account(&format!("{base}/token")), &base, || NOW, + |_| None, ) .unwrap(); (transport, fake) @@ -665,6 +807,7 @@ mod tests { &service_account(&format!("{base}/token")), &base, now, + |_| None, ) .unwrap(); (Arc::new(transport), server) @@ -877,13 +1020,37 @@ mod tests { fn malformed_service_account_fails_as_a_credential_error() { for key in [ &b""[..], - b"{}", - br#"{"client_email":"a","private_key":"nope","token_uri":"b"}"#, + br#"{"type":"service_account"}"#, + br#"{"type":"service_account","client_email":"a","private_key":"nope","token_uri":"b"}"#, ] { assert!(matches!( - FcmTransport::with_endpoints("example-project", key, FCM_BASE_URL, || NOW), + FcmTransport::with_endpoints("example-project", key, FCM_BASE_URL, || NOW, |_| None), Err(FcmError::Credential) )); } } + + #[test] + fn credential_type_must_be_service_account_or_external_account() { + for key in [ + &b"{}"[..], + br#"{"type":"authorized_user"}"#, + br#"{"type":7}"#, + ] { + assert!(matches!( + FcmTransport::with_endpoints( + "example-project", + key, + FCM_BASE_URL, + || NOW, + |_| None + ), + Err(FcmError::Configuration(_)) + )); + } + } } + +#[cfg(test)] +#[path = "fcm_federation_tests.rs"] +mod federation_tests; diff --git a/crates/buzz-push-gateway/src/fcm_federation.rs b/crates/buzz-push-gateway/src/fcm_federation.rs new file mode 100644 index 0000000000..b046e23e2d --- /dev/null +++ b/crates/buzz-push-gateway/src/fcm_federation.rs @@ -0,0 +1,229 @@ +//! Keyless FCM access tokens: Google workload identity federation from AWS. +//! +//! The credential file is Google's standard `external_account` config for an +//! AWS provider. Minting chains three hops under one deadline: +//! +//! 1. the pod's AWS credentials ([`crate::aws_credentials`]), +//! 2. Google STS, trading a SigV4-signed `GetCallerIdentity` subject token +//! ([`crate::aws_sigv4`]) for a federated access token, +//! 3. the service account's `generateAccessToken`, trading that for an access +//! token carrying the FCM scope. +//! +//! The file's IMDS fields (`region_url`, `url`, `imdsv2_session_token_url`) +//! are accepted and ignored: pods cannot reach instance metadata, so the +//! region and credentials come from the environment. + +use chrono::DateTime; +use reqwest::StatusCode; +use serde::Deserialize; +use url::Url; + +use crate::{ + aws_credentials::AwsCredentialSource, + aws_sigv4, + fcm::{FcmError, MintFailure, MintedToken}, +}; + +const CLOUD_PLATFORM_SCOPE: &str = "https://www.googleapis.com/auth/cloud-platform"; +const AWS_ENVIRONMENT_ID: &str = "aws1"; + +#[derive(Deserialize)] +struct ExternalAccount { + audience: String, + subject_token_type: String, + token_url: String, + service_account_impersonation_url: Option, + credential_source: CredentialSource, +} + +/// Google's AWS credential source. `region_url`, `url` and +/// `imdsv2_session_token_url` only matter to instance metadata lookups. +#[derive(Deserialize)] +struct CredentialSource { + environment_id: Option, + regional_cred_verification_url: Option, +} + +pub(crate) struct FederatedMinter { + audience: String, + subject_token_type: String, + token_url: String, + impersonation_url: String, + verification_url: String, + region: String, + /// The scope the impersonated token carries. + scope: &'static str, + aws: AwsCredentialSource, +} + +impl FederatedMinter { + /// Validate an `external_account` config and the AWS environment it needs. + /// `env` reads that environment. Nothing is fetched. + pub(crate) fn from_config( + config: serde_json::Value, + scope: &'static str, + env: impl Fn(&str) -> Option, + ) -> Result { + let file: ExternalAccount = serde_json::from_value(config).map_err(|_| { + FcmError::Configuration( + "an external_account credential needs audience, subject_token_type, token_url \ + and credential_source", + ) + })?; + if file.credential_source.environment_id.as_deref() != Some(AWS_ENVIRONMENT_ID) { + return Err(FcmError::Configuration( + "only the AWS credential source (environment_id aws1) is supported", + )); + } + let verification_url = file + .credential_source + .regional_cred_verification_url + .filter(|url| url.contains("{region}")) + .ok_or(FcmError::Configuration( + "credential_source.regional_cred_verification_url with a {region} placeholder \ + is required", + ))?; + let impersonation_url = + file.service_account_impersonation_url + .ok_or(FcmError::Configuration( + "service_account_impersonation_url is required: FCM needs the service account \ + access token", + ))?; + if file.audience.is_empty() || file.subject_token_type.is_empty() { + return Err(FcmError::Configuration( + "audience and subject_token_type must not be empty", + )); + } + for url in [&file.token_url, &impersonation_url] { + Url::parse(url).map_err(|_| { + FcmError::Configuration( + "token_url and service_account_impersonation_url must be URLs", + ) + })?; + } + let region = ["AWS_REGION", "AWS_DEFAULT_REGION"] + .iter() + .find_map(|name| env(name).filter(|value| !value.is_empty())) + .ok_or(FcmError::Configuration( + "AWS_REGION or AWS_DEFAULT_REGION is required", + ))?; + // The region-scoped STS endpoint doubles as the web identity exchange + // endpoint, so no partition suffix is assumed. + let signing_url = + Url::parse(&verification_url.replace("{region}", ®ion)).map_err(|_| { + FcmError::Configuration("regional_cred_verification_url is not a valid URL") + })?; + let host = signing_url.host_str().ok_or(FcmError::Configuration( + "regional_cred_verification_url has no host", + ))?; + let sts_url = match signing_url.port() { + Some(port) => format!("{}://{host}:{port}/", signing_url.scheme()), + None => format!("{}://{host}/", signing_url.scheme()), + }; + Ok(Self { + audience: file.audience, + subject_token_type: file.subject_token_type, + token_url: file.token_url, + impersonation_url, + verification_url, + region, + scope, + aws: AwsCredentialSource::from_lookup(env, sts_url)?, + }) + } + + pub(crate) async fn mint( + &self, + client: &reqwest::Client, + now: i64, + ) -> Result { + let credentials = self.aws.credentials(client).await?; + let subject_token = aws_sigv4::subject_token( + &self.verification_url, + &self.region, + &self.audience, + &credentials, + now, + ) + .map_err(|_| MintFailure::rejected("aws signing", None))?; + + const STS_HOP: &str = "google sts"; + let body = url::form_urlencoded::Serializer::new(String::new()) + .append_pair( + "grant_type", + "urn:ietf:params:oauth:grant-type:token-exchange", + ) + .append_pair( + "requested_token_type", + "urn:ietf:params:oauth:token-type:access_token", + ) + .append_pair("subject_token_type", &self.subject_token_type) + .append_pair("audience", &self.audience) + .append_pair("scope", CLOUD_PLATFORM_SCOPE) + .append_pair("subject_token", &subject_token) + .finish(); + let response = client + .post(&self.token_url) + .header( + reqwest::header::CONTENT_TYPE, + "application/x-www-form-urlencoded", + ) + .body(body) + .send() + .await + .map_err(|_| MintFailure::unavailable(STS_HOP, None))?; + #[derive(Deserialize)] + struct FederatedToken { + access_token: String, + } + let federated: FederatedToken = decode(response, STS_HOP).await?; + if federated.access_token.is_empty() { + return Err(MintFailure::rejected(STS_HOP, None)); + } + + const IMPERSONATION_HOP: &str = "service account impersonation"; + let response = client + .post(&self.impersonation_url) + .bearer_auth(&federated.access_token) + .json(&serde_json::json!({ "scope": [self.scope] })) + .send() + .await + .map_err(|_| MintFailure::unavailable(IMPERSONATION_HOP, None))?; + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct ImpersonatedToken { + access_token: String, + expire_time: String, + } + let token: ImpersonatedToken = decode(response, IMPERSONATION_HOP).await?; + if token.access_token.is_empty() { + return Err(MintFailure::rejected(IMPERSONATION_HOP, None)); + } + let expires_at = DateTime::parse_from_rfc3339(&token.expire_time) + .map_err(|_| MintFailure::unavailable(IMPERSONATION_HOP, None))? + .timestamp(); + Ok(MintedToken { + value: token.access_token, + lifetime_seconds: expires_at.saturating_sub(now), + }) + } +} + +/// Decode a Google token response. 5xx and 429 mean Google is unhealthy; any +/// other failure status means it refused the credential. +async fn decode( + response: reqwest::Response, + hop: &'static str, +) -> Result { + let status = response.status(); + if status.is_server_error() || status == StatusCode::TOO_MANY_REQUESTS { + return Err(MintFailure::unavailable(hop, Some(status.as_u16()))); + } + if !status.is_success() { + return Err(MintFailure::rejected(hop, Some(status.as_u16()))); + } + response + .json() + .await + .map_err(|_| MintFailure::unavailable(hop, None)) +} diff --git a/crates/buzz-push-gateway/src/fcm_federation_tests.rs b/crates/buzz-push-gateway/src/fcm_federation_tests.rs new file mode 100644 index 0000000000..20fb017d8c --- /dev/null +++ b/crates/buzz-push-gateway/src/fcm_federation_tests.rs @@ -0,0 +1,770 @@ +//! Federated token minting, driven through `TokenSource` against fake AWS +//! credential, Google STS and impersonation servers. No real credential or +//! network is involved. + +use super::*; +use crate::aws_credentials::AwsCredentialSource; +use axum::{ + body::Bytes, + extract::State, + http::{HeaderMap, StatusCode as Status}, + routing::{get, post}, + Router, +}; +use std::{ + collections::HashMap, + sync::{Arc, Mutex}, +}; + +const NOW: i64 = 1_750_000_000; +const FCM_SCOPE_URL: &str = "https://www.googleapis.com/auth/firebase.messaging"; + +/// One fake hop: the response it gives and how long it takes to give it. +#[derive(Clone)] +struct Hop { + response: (u16, String), + delay: Duration, +} + +impl Hop { + fn ok(body: impl Into) -> Self { + Self { + response: (200, body.into()), + delay: Duration::ZERO, + } + } +} + +struct Fake { + aws: Hop, + web_identity: Hop, + sts: Hop, + impersonation: Hop, + /// Request count and last (headers, body) per hop, by path. + requests: HashMap<&'static str, Vec<(HeaderMap, String)>>, +} + +type Shared = Arc>; + +fn expire_time(at: i64) -> String { + chrono::DateTime::from_timestamp(at, 0) + .unwrap() + .to_rfc3339() +} + +fn impersonated(n: usize, expires_at: i64) -> String { + serde_json::json!({"accessToken": format!("fcm-{n}"), "expireTime": expire_time(expires_at)}) + .to_string() +} + +fn new_fake() -> Shared { + Arc::new(Mutex::new(Fake { + aws: Hop::ok( + r#"{"AccessKeyId":"AKIDPOD","SecretAccessKey":"pod-secret","Token":"pod-session","Expiration":"2030-01-01T00:00:00Z"}"#, + ), + web_identity: Hop::ok( + "\ + \ + AKIDIRSAirsa-secret\ + irsa-session2030-01-01T00:00:00Z\ + ", + ), + sts: Hop::ok(r#"{"access_token":"federated-1","token_type":"Bearer","expires_in":3599}"#), + impersonation: Hop::ok(impersonated(1, NOW + 3600)), + requests: HashMap::new(), + })) +} + +async fn serve_hop( + fake: &Shared, + name: &'static str, + headers: HeaderMap, + body: Bytes, + pick: fn(&Fake) -> Hop, +) -> (Status, String) { + let hop = { + let mut f = fake.lock().unwrap(); + f.requests + .entry(name) + .or_default() + .push((headers, String::from_utf8(body.to_vec()).unwrap())); + pick(&f) + }; + tokio::time::sleep(hop.delay).await; + (Status::from_u16(hop.response.0).unwrap(), hop.response.1) +} + +fn app(fake: Shared) -> Router { + Router::new() + .route( + "/aws", + get(|State(f): State, h: HeaderMap| async move { + serve_hop(&f, "aws", h, Bytes::new(), |f| f.aws.clone()).await + }), + ) + .route( + "/", + post( + |State(f): State, h: HeaderMap, b: Bytes| async move { + serve_hop(&f, "web_identity", h, b, |f| f.web_identity.clone()).await + }, + ), + ) + .route( + "/google/sts", + post( + |State(f): State, h: HeaderMap, b: Bytes| async move { + serve_hop(&f, "sts", h, b, |f| f.sts.clone()).await + }, + ), + ) + .route( + "/google/impersonate", + post( + |State(f): State, h: HeaderMap, b: Bytes| async move { + serve_hop(&f, "impersonation", h, b, |f| f.impersonation.clone()).await + }, + ), + ) + .route( + "/v1/projects/example-project/messages:send", + post( + |State(f): State, h: HeaderMap, b: Bytes| async move { + serve_hop(&f, "send", h, b, |_| Hop::ok("{}")).await + }, + ), + ) + .with_state(fake) +} + +async fn serve_fake(fake: &Shared) -> String { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let app = app(fake.clone()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + base +} + +/// A Google `external_account` config for an AWS provider whose Google hops +/// are served at `base`. +fn config(base: &str) -> serde_json::Value { + serde_json::json!({ + "type": "external_account", + "audience": "//iam.googleapis.com/projects/1/locations/global/workloadIdentityPools/example-pool/providers/example-aws", + "subject_token_type": "urn:ietf:params:aws:token-type:aws4_request", + "token_url": format!("{base}/google/sts"), + "service_account_impersonation_url": format!("{base}/google/impersonate"), + "credential_source": { + "environment_id": "aws1", + "region_url": "http://169.254.169.254/latest/meta-data/placement/availability-zone", + "url": "http://169.254.169.254/latest/meta-data/iam/security-credentials", + "regional_cred_verification_url": + format!("{base}/sts/{{region}}?Action=GetCallerIdentity&Version=2011-06-15"), + }, + }) +} + +/// Environment for the EKS Pod Identity source, with the token in `token_file`. +fn pod_env(base: &str, token_file: &std::path::Path) -> HashMap { + HashMap::from([ + ("AWS_REGION".to_owned(), "us-east-1".to_owned()), + ( + "AWS_CONTAINER_CREDENTIALS_FULL_URI".to_owned(), + format!("{base}/aws"), + ), + ( + "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE".to_owned(), + token_file.to_str().unwrap().to_owned(), + ), + ]) +} + +/// A file in the system temp directory, deleted when dropped. +struct TempFile(std::path::PathBuf); + +impl std::ops::Deref for TempFile { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for TempFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +/// Write `content` to a fresh file that lives as long as the returned guard. +fn temp_file(content: &str) -> TempFile { + let path = std::env::temp_dir().join(format!("buzz-fcm-test-{}", uuid::Uuid::new_v4())); + std::fs::write(&path, content).unwrap(); + TempFile(path) +} + +fn federated( + base: &str, + env: HashMap, + now: fn() -> i64, +) -> Result { + FcmTransport::with_endpoints( + "example-project", + &serde_json::to_vec(&config(base)).unwrap(), + base, + now, + move |name| env.get(name).cloned(), + ) +} + +fn count(fake: &Shared, hop: &str) -> usize { + fake.lock() + .unwrap() + .requests + .get(hop) + .map_or(0, |requests| requests.len()) +} + +fn last(fake: &Shared, hop: &str) -> (HeaderMap, String) { + fake.lock().unwrap().requests[hop].last().unwrap().clone() +} + +fn form(body: &str) -> HashMap { + url::form_urlencoded::parse(body.as_bytes()) + .into_owned() + .collect() +} + +fn attempt() -> DeliveryAttempt { + DeliveryAttempt { + request_id: uuid::Uuid::nil(), + expires_at: NOW + 600, + } +} + +#[tokio::test] +async fn a_send_mints_through_aws_google_sts_and_impersonation_once() { + let fake = new_fake(); + let base = serve_fake(&fake).await; + let token_file = temp_file("pod-identity-token\n"); + let transport = federated(&base, pod_env(&base, &token_file), || NOW).unwrap(); + // Building the transport called nothing. + assert_eq!(count(&fake, "aws") + count(&fake, "sts"), 0); + + for _ in 0..2 { + assert_eq!( + transport.send(attempt(), "registration-token").await, + DeliveryOutcome::Accepted + ); + } + // One mint serves both sends. + for hop in ["aws", "sts", "impersonation"] { + assert_eq!(count(&fake, hop), 1, "{hop}"); + } + assert_eq!( + last(&fake, "aws").0["authorization"], + "pod-identity-token", + "the agent token file's content, without its trailing newline" + ); + + let sts = form(&last(&fake, "sts").1); + assert_eq!( + sts["grant_type"], + "urn:ietf:params:oauth:grant-type:token-exchange" + ); + assert_eq!( + sts["requested_token_type"], + "urn:ietf:params:oauth:token-type:access_token" + ); + assert_eq!( + sts["subject_token_type"], + "urn:ietf:params:aws:token-type:aws4_request" + ); + assert_eq!( + sts["scope"], + "https://www.googleapis.com/auth/cloud-platform" + ); + let audience = config(&base)["audience"].as_str().unwrap().to_owned(); + assert_eq!(sts["audience"], audience); + let subject: serde_json::Value = serde_json::from_str( + &url::form_urlencoded::parse(format!("x={}", sts["subject_token"]).as_bytes()) + .next() + .unwrap() + .1, + ) + .unwrap(); + assert_eq!(subject["method"], "POST"); + assert_eq!( + subject["url"], + format!("{base}/sts/us-east-1?Action=GetCallerIdentity&Version=2011-06-15") + ); + let headers: HashMap = subject["headers"] + .as_array() + .unwrap() + .iter() + .map(|h| { + ( + h["key"].as_str().unwrap().to_owned(), + h["value"].as_str().unwrap().to_owned(), + ) + }) + .collect(); + assert_eq!(headers["x-goog-cloud-target-resource"], audience); + assert_eq!(headers["x-amz-security-token"], "pod-session"); + assert!(headers["Authorization"].starts_with("AWS4-HMAC-SHA256 Credential=AKIDPOD/20250615/us-east-1/sts/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token;x-goog-cloud-target-resource, Signature=")); + + let (impersonation_headers, impersonation_body) = last(&fake, "impersonation"); + assert_eq!(impersonation_headers["authorization"], "Bearer federated-1"); + assert_eq!( + serde_json::from_str::(&impersonation_body).unwrap(), + serde_json::json!({"scope": [FCM_SCOPE_URL]}) + ); + assert_eq!(FCM_SCOPE_URL, FCM_SCOPE); + for (headers, _) in &fake.lock().unwrap().requests["send"] { + assert_eq!(headers["authorization"], "Bearer fcm-1"); + } +} + +#[tokio::test] +async fn web_identity_and_static_credentials_sign_the_subject_token() { + // IRSA: the token file's content is exchanged at the STS endpoint derived + // from the verification URL, and the assumed role signs. + let fake = new_fake(); + let base = serve_fake(&fake).await; + let token_file = temp_file("projected-web-identity-token\n"); + let env = HashMap::from([ + ("AWS_REGION".to_owned(), "us-east-1".to_owned()), + ( + "AWS_ROLE_ARN".to_owned(), + "arn:aws:iam::123456789012:role/example".to_owned(), + ), + ( + "AWS_WEB_IDENTITY_TOKEN_FILE".to_owned(), + token_file.to_str().unwrap().to_owned(), + ), + ]); + let transport = federated(&base, env, || NOW).unwrap(); + assert_eq!(transport.tokens.access_token().await.ok().unwrap(), "fcm-1"); + let web = form(&last(&fake, "web_identity").1); + assert_eq!(web["Action"], "AssumeRoleWithWebIdentity"); + assert_eq!(web["RoleArn"], "arn:aws:iam::123456789012:role/example"); + assert_eq!(web["WebIdentityToken"], "projected-web-identity-token"); + assert_eq!(count(&fake, "aws"), 0); + let subject = form(&last(&fake, "sts").1)["subject_token"].clone(); + assert!(subject.contains("AKIDIRSA"), "{subject}"); + assert!(subject.contains("irsa-session"), "{subject}"); + + // Static keys need no endpoint at all. + let fake = new_fake(); + let base = serve_fake(&fake).await; + let env = HashMap::from([ + ("AWS_DEFAULT_REGION".to_owned(), "us-east-1".to_owned()), + ("AWS_ACCESS_KEY_ID".to_owned(), "AKIDSTATIC".to_owned()), + ( + "AWS_SECRET_ACCESS_KEY".to_owned(), + "static-secret".to_owned(), + ), + ]); + let transport = federated(&base, env, || NOW).unwrap(); + assert_eq!(transport.tokens.access_token().await.ok().unwrap(), "fcm-1"); + let subject = form(&last(&fake, "sts").1)["subject_token"].clone(); + assert!(subject.contains("AKIDSTATIC"), "{subject}"); + assert!(!subject.contains("x-amz-security-token"), "{subject}"); + assert_eq!(count(&fake, "aws") + count(&fake, "web_identity"), 0); +} + +#[tokio::test] +async fn each_hop_failure_is_classified_rejected_or_unavailable() { + type Set = fn(&mut Fake, Hop); + let aws: Set = |f, hop| f.aws = hop; + let sts: Set = |f, hop| f.sts = hop; + let impersonation: Set = |f, hop| f.impersonation = hop; + let status = |code: u16| Hop { + response: (code, "{}".into()), + delay: Duration::ZERO, + }; + let rows: [(&str, Set, Hop, TokenFault); 21] = [ + ("aws 500", aws, status(500), TokenFault::Unavailable), + ("aws 429", aws, status(429), TokenFault::Unavailable), + ("aws 403", aws, status(403), TokenFault::Rejected), + ( + "aws garbage", + aws, + Hop::ok("not json"), + TokenFault::Unavailable, + ), + ("sts 500", sts, status(500), TokenFault::Unavailable), + ("sts 503", sts, status(503), TokenFault::Unavailable), + ("sts 429", sts, status(429), TokenFault::Unavailable), + ("sts 400", sts, status(400), TokenFault::Rejected), + ("sts 401", sts, status(401), TokenFault::Rejected), + ("sts 403", sts, status(403), TokenFault::Rejected), + ( + "sts garbage", + sts, + Hop::ok("not json"), + TokenFault::Unavailable, + ), + ( + "sts empty token", + sts, + Hop::ok(r#"{"access_token":""}"#), + TokenFault::Rejected, + ), + ( + "impersonation 500", + impersonation, + status(500), + TokenFault::Unavailable, + ), + ( + "impersonation 429", + impersonation, + status(429), + TokenFault::Unavailable, + ), + ( + "impersonation 400", + impersonation, + status(400), + TokenFault::Rejected, + ), + ( + "impersonation 403", + impersonation, + status(403), + TokenFault::Rejected, + ), + ( + "impersonation garbage", + impersonation, + Hop::ok("not json"), + TokenFault::Unavailable, + ), + ( + "impersonation empty token", + impersonation, + Hop::ok(r#"{"accessToken":"","expireTime":"2030-01-01T00:00:00Z"}"#), + TokenFault::Rejected, + ), + ( + "impersonation bad expireTime", + impersonation, + Hop::ok(r#"{"accessToken":"t","expireTime":"soon"}"#), + TokenFault::Unavailable, + ), + ( + "impersonation missing expireTime", + impersonation, + Hop::ok(r#"{"accessToken":"t"}"#), + TokenFault::Unavailable, + ), + ("aws unreachable", aws, status(200), TokenFault::Unavailable), + ]; + for (label, set, hop, expected) in rows { + let fake = new_fake(); + set(&mut fake.lock().unwrap(), hop); + let base = serve_fake(&fake).await; + let token_file = temp_file("token"); + let mut env = pod_env(&base, &token_file); + if label == "aws unreachable" { + // Nothing listens on a port that was just released. + let closed = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = closed.local_addr().unwrap().port(); + drop(closed); + env.insert( + "AWS_CONTAINER_CREDENTIALS_FULL_URI".into(), + format!("http://127.0.0.1:{port}/aws"), + ); + } + let transport = federated(&base, env, || NOW).unwrap(); + let result = transport.tokens.access_token().await; + assert_eq!(result.err(), Some(expected), "{label}"); + // A hop that failed stops the chain: later hops are never called. + if label.starts_with("aws") { + assert_eq!(count(&fake, "sts"), 0, "{label}"); + } + if label.starts_with("sts") { + assert_eq!(count(&fake, "impersonation"), 0, "{label}"); + } + } +} + +#[tokio::test] +async fn an_unreadable_aws_token_file_is_rejected_not_retried() { + let fake = new_fake(); + let base = serve_fake(&fake).await; + let missing = std::env::temp_dir().join(format!("buzz-fcm-missing-{}", uuid::Uuid::new_v4())); + let transport = federated(&base, pod_env(&base, &missing), || NOW).unwrap(); + assert_eq!( + transport.tokens.access_token().await.err(), + Some(TokenFault::Rejected) + ); + assert_eq!(count(&fake, "aws"), 0); +} + +#[tokio::test] +async fn a_failed_hop_keeps_the_valid_cached_token_and_lifetime_comes_from_expire_time() { + use std::sync::atomic::{AtomicI64, Ordering}; + static CLOCK: AtomicI64 = AtomicI64::new(NOW); + fn clock() -> i64 { + CLOCK.load(Ordering::SeqCst) + } + let fake = new_fake(); + // expireTime says 30 minutes, not the usual hour. + fake.lock().unwrap().impersonation = Hop::ok(impersonated(1, NOW + 1800)); + let base = serve_fake(&fake).await; + let token_file = temp_file("token"); + let transport = Arc::new(federated(&base, pod_env(&base, &token_file), clock).unwrap()); + assert_eq!( + transport.send(attempt(), "registration-token").await, + DeliveryOutcome::Accepted + ); + + // The refresh margin is measured from expireTime: due 120 s before it. + CLOCK.store(NOW + 1800 - 119, Ordering::SeqCst); + fake.lock().unwrap().impersonation.response = (503, "{}".into()); + assert_eq!( + transport.send(attempt(), "registration-token").await, + DeliveryOutcome::Accepted, + "the valid token serves while its refresh runs" + ); + for _ in 0..500 { + if count(&fake, "impersonation") == 2 { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert_eq!( + count(&fake, "impersonation"), + 2, + "the refresh was attempted" + ); + // The background refresh holds `fetch` until it has recorded its failure. + drop(transport.tokens.fetch.lock().await); + assert_eq!( + transport.send(attempt(), "registration-token").await, + DeliveryOutcome::Accepted + ); + for (headers, _) in &fake.lock().unwrap().requests["send"] { + assert_eq!( + headers["authorization"], "Bearer fcm-1", + "the token was kept" + ); + } + assert_eq!( + count(&fake, "impersonation"), + 2, + "backoff stops a retry storm" + ); + + // Once the kept token expires, the recorded failure fails fast. + CLOCK.store(NOW + 1800, Ordering::SeqCst); + assert_eq!( + transport.send(attempt(), "registration-token").await, + DeliveryOutcome::Retry { + retry_after_seconds: None + } + ); +} + +#[tokio::test] +async fn one_deadline_bounds_the_whole_chain_of_hops() { + let delayed = |fake: &Shared| { + let f = &mut *fake.lock().unwrap(); + for hop in [&mut f.aws, &mut f.sts, &mut f.impersonation] { + hop.delay = Duration::from_millis(250); + } + }; + let build = |base: &str, deadline: Duration| { + let token_file = temp_file("token"); + let mut transport = federated(base, pod_env(base, &token_file), || NOW).unwrap(); + Arc::get_mut(&mut transport.tokens).unwrap().deadline = deadline; + // The token file must outlive the mint, so it travels with the transport. + (transport, token_file) + }; + + // Three 250 ms hops fit a 5 s deadline... + let fake = new_fake(); + delayed(&fake); + let base = serve_fake(&fake).await; + let (transport, _token_file) = build(&base, Duration::from_secs(5)); + assert_eq!(transport.tokens.access_token().await.ok().unwrap(), "fcm-1"); + + // ...but no single hop outlasts a 375 ms deadline, yet the chain does: + // it fires during the second hop, so impersonation is never reached. + let fake = new_fake(); + delayed(&fake); + let base = serve_fake(&fake).await; + let (transport, _token_file) = build(&base, Duration::from_millis(375)); + assert_eq!( + transport.tokens.access_token().await.err(), + Some(TokenFault::Unavailable) + ); + assert_eq!(count(&fake, "aws"), 1); + assert_eq!(count(&fake, "impersonation"), 0); +} + +fn rejected(config: serde_json::Value, env: &HashMap) -> Option<&'static str> { + let env = env.clone(); + match FcmTransport::with_endpoints( + "example-project", + &serde_json::to_vec(&config).unwrap(), + FCM_BASE_URL, + || NOW, + move |name| env.get(name).cloned(), + ) { + Ok(_) => None, + Err(FcmError::Configuration(reason)) => Some(reason), + Err(other) => panic!("expected a configuration error, got {other}"), + } +} + +#[tokio::test] +async fn startup_validates_the_file_and_environment_without_calling_anyone() { + let fake = new_fake(); + let base = serve_fake(&fake).await; + let token_file = temp_file("token"); + let env = pod_env(&base, &token_file); + assert_eq!(rejected(config(&base), &env), None); + assert_eq!( + fake.lock().unwrap().requests.len(), + 0, + "startup must not call AWS or Google" + ); + + let edit = |change: &dyn Fn(&mut serde_json::Value)| { + let mut value = config(&base); + change(&mut value); + value + }; + let without = |key: &'static str| edit(&move |v| drop(v.as_object_mut().unwrap().remove(key))); + let source = |value: serde_json::Value| edit(&move |v| v["credential_source"] = value.clone()); + let cases = [ + ( + "no impersonation url", + without("service_account_impersonation_url"), + ), + ("no audience", without("audience")), + ("no token url", without("token_url")), + ("empty audience", edit(&|v| v["audience"] = "".into())), + ("bad token url", edit(&|v| v["token_url"] = "nope".into())), + ("file source", source(serde_json::json!({"file": "/token"}))), + ( + "url source", + source( + serde_json::json!({"url": "https://example.org/token", "format": {"type": "text"}}), + ), + ), + ( + "executable source", + source(serde_json::json!({"executable": {"command": "x"}})), + ), + ( + "other environment", + source( + serde_json::json!({"environment_id": "aws2", "regional_cred_verification_url": "https://sts.{region}.example.org"}), + ), + ), + ( + "no verification url", + source(serde_json::json!({"environment_id": "aws1"})), + ), + ( + "no region placeholder", + source( + serde_json::json!({"environment_id": "aws1", "regional_cred_verification_url": "https://sts.example.org?Action=GetCallerIdentity"}), + ), + ), + ]; + for (label, config) in cases { + assert!(rejected(config, &env).is_some(), "{label} must be rejected"); + } + + let without_env = |name: &str| { + let mut env = env.clone(); + env.remove(name); + env + }; + let env_cases = [ + ("no region", without_env("AWS_REGION")), + ( + "no credentials", + HashMap::from([("AWS_REGION".to_owned(), "us-east-1".to_owned())]), + ), + ( + "access key without secret", + HashMap::from([ + ("AWS_REGION".to_owned(), "us-east-1".to_owned()), + ("AWS_ACCESS_KEY_ID".to_owned(), "AKID".to_owned()), + ]), + ), + ( + "web identity without role", + HashMap::from([ + ("AWS_REGION".to_owned(), "us-east-1".to_owned()), + ( + "AWS_WEB_IDENTITY_TOKEN_FILE".to_owned(), + "/token".to_owned(), + ), + ]), + ), + ( + "token over plain http to a remote host", + HashMap::from([ + ("AWS_REGION".to_owned(), "us-east-1".to_owned()), + ( + "AWS_CONTAINER_CREDENTIALS_FULL_URI".to_owned(), + "http://credentials.example.org/v1".to_owned(), + ), + ]), + ), + ]; + for (label, env) in env_cases { + assert!( + rejected(config(&base), &env).is_some(), + "{label} must be rejected" + ); + } + + // The EKS Pod Identity Agent's own address is accepted over http. + let mut agent = env.clone(); + agent.insert( + "AWS_CONTAINER_CREDENTIALS_FULL_URI".into(), + "http://169.254.170.23/v1/credentials".into(), + ); + assert_eq!(rejected(config(&base), &agent), None); +} + +#[test] +fn the_aws_credential_source_is_chosen_by_precedence() { + let pick = |pairs: &[(&str, &str)]| { + let env: HashMap = pairs + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect(); + AwsCredentialSource::from_lookup(move |n| env.get(n).cloned(), "https://sts/".into()).map( + |source| match source { + AwsCredentialSource::Static(_) => "static", + AwsCredentialSource::WebIdentity { .. } => "web identity", + AwsCredentialSource::PodIdentity { .. } => "pod identity", + }, + ) + }; + let all = [ + ("AWS_ACCESS_KEY_ID", "AKID"), + ("AWS_SECRET_ACCESS_KEY", "secret"), + ("AWS_ROLE_ARN", "arn"), + ("AWS_WEB_IDENTITY_TOKEN_FILE", "/t"), + ( + "AWS_CONTAINER_CREDENTIALS_FULL_URI", + "https://agent.example.org/c", + ), + ]; + assert_eq!(pick(&all).unwrap(), "static"); + assert_eq!(pick(&all[2..]).unwrap(), "web identity"); + assert_eq!(pick(&all[4..]).unwrap(), "pod identity"); + // Only instance metadata style settings are not a source. + assert!(pick(&[("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "/v2/credentials")]).is_err()); + // Empty values count as unset. + assert!(pick(&[("AWS_ACCESS_KEY_ID", "")]).is_err()); +} diff --git a/crates/buzz-push-gateway/src/lib.rs b/crates/buzz-push-gateway/src/lib.rs index 25e8efdd03..e8263776b6 100644 --- a/crates/buzz-push-gateway/src/lib.rs +++ b/crates/buzz-push-gateway/src/lib.rs @@ -3,8 +3,11 @@ pub mod android_attestation; pub mod apns; pub mod app_attest; pub mod authority; +pub mod aws_credentials; +pub mod aws_sigv4; pub mod config; pub mod fcm; +pub(crate) mod fcm_federation; pub mod grant; pub mod http; pub mod metrics; diff --git a/crates/buzz-push-gateway/src/main.rs b/crates/buzz-push-gateway/src/main.rs index 605527bc4d..27ac1d2dbc 100644 --- a/crates/buzz-push-gateway/src/main.rs +++ b/crates/buzz-push-gateway/src/main.rs @@ -68,9 +68,9 @@ async fn main() -> Result<(), Box> { .android .as_ref() .map(|android| -> Result<_, Box> { - let fcm = FcmTransport::service_account( + let fcm = FcmTransport::from_credentials( &android.fcm_project_id, - &fs::read(&android.fcm_service_account_path)?, + &fs::read(&android.fcm_credentials_path)?, )?; let roots = match &android.attestation_roots_path { Some(path) => fs::read_to_string(path)?, diff --git a/deploy/charts/buzz-push-gateway/templates/deployment.yaml b/deploy/charts/buzz-push-gateway/templates/deployment.yaml index f9e14abcc9..feeb1a6ab7 100644 --- a/deploy/charts/buzz-push-gateway/templates/deployment.yaml +++ b/deploy/charts/buzz-push-gateway/templates/deployment.yaml @@ -62,7 +62,7 @@ spec: - { name: BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS, value: {{ join "," .Values.android.bootKeyDigests | quote }} } - { name: BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS, value: {{ .Values.android.revocationGraceSeconds | int64 | quote }} } - { name: BUZZ_PUSH_FCM_PROJECT_ID, value: {{ .Values.android.fcmProjectId | quote }} } - - { name: BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH, value: /run/buzz/fcm/service-account.json } + - { name: BUZZ_PUSH_FCM_CREDENTIALS_PATH, value: /run/buzz/fcm/credentials.json } {{- if .Values.android.attestationRoots.secretName }} - { name: BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH, value: /run/buzz/android-attestation/roots.pem } {{- end }} @@ -91,7 +91,7 @@ spec: secret: { secretName: {{ .Values.application.apnsCert.secretName }}, defaultMode: 0400, items: [{ key: {{ .Values.application.apnsCert.secretKey }}, path: identity.pem }] } {{- if .Values.android.enabled }} - name: fcm - secret: { secretName: {{ .Values.android.fcmServiceAccount.secretName }}, defaultMode: 0400, items: [{ key: {{ .Values.android.fcmServiceAccount.secretKey }}, path: service-account.json }] } + secret: { secretName: {{ .Values.android.fcmCredentials.secretName }}, defaultMode: 0400, items: [{ key: {{ .Values.android.fcmCredentials.secretKey }}, path: credentials.json }] } {{- with .Values.android.attestationRoots }} {{- if .secretName }} - name: android-attestation-roots diff --git a/deploy/charts/buzz-push-gateway/tests/runtime-options.sh b/deploy/charts/buzz-push-gateway/tests/runtime-options.sh index 30610c63b6..42d433cbbe 100644 --- a/deploy/charts/buzz-push-gateway/tests/runtime-options.sh +++ b/deploy/charts/buzz-push-gateway/tests/runtime-options.sh @@ -47,7 +47,7 @@ digest=$(printf 'ab%.0s' {1..32}) helm template push "$chart" --set android.enabled=true \ --set "android.signingCertDigests[0]=$digest" >"$out/android.yaml" for needle in BUZZ_PUSH_ANDROID_PACKAGE_NAME "$digest" BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS \ - BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH; do + BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS BUZZ_PUSH_FCM_CREDENTIALS_PATH; do grep -q "$needle" "$out/android.yaml" || { echo "Android render lacks $needle" >&2; exit 1; } done if grep -q 'ATTESTATION_ROOTS\|android-attestation' "$out/android.yaml"; then diff --git a/deploy/charts/buzz-push-gateway/values.schema.json b/deploy/charts/buzz-push-gateway/values.schema.json index 97be3568b1..2625a93a0e 100644 --- a/deploy/charts/buzz-push-gateway/values.schema.json +++ b/deploy/charts/buzz-push-gateway/values.schema.json @@ -396,7 +396,7 @@ "bootKeyDigests", "revocationGraceSeconds", "fcmProjectId", - "fcmServiceAccount", + "fcmCredentials", "attestationRoots" ], "properties": { @@ -430,7 +430,7 @@ "type": "string", "minLength": 1 }, - "fcmServiceAccount": { + "fcmCredentials": { "$ref": "#/$defs/apnsCert" }, "attestationRoots": { diff --git a/deploy/charts/buzz-push-gateway/values.yaml b/deploy/charts/buzz-push-gateway/values.yaml index 56edf82a42..950e56db66 100644 --- a/deploy/charts/buzz-push-gateway/values.yaml +++ b/deploy/charts/buzz-push-gateway/values.yaml @@ -47,9 +47,15 @@ android: # before Android enrollment fails closed. revocationGraceSeconds: 604800 fcmProjectId: example-project - fcmServiceAccount: + # Secret holding Google's credential JSON: a service account key, or an AWS + # workload identity federation config (type external_account) for keyless + # access. Federation also needs AWS_REGION and AWS credentials in the pod. + # As shipped, the chart supports IRSA, whose webhook injects both. EKS Pod + # Identity also needs a region and a NetworkPolicy egress rule to the agent + # (169.254.170.23/32, TCP 80), which this chart does not add. + fcmCredentials: secretName: buzz-push-gateway - secretKey: fcm-service-account.json + secretKey: fcm-credentials.json # Optional PEM bundle replacing the built-in Google attestation roots, for a # reviewed root rollout. Empty secretName keeps the built-in roots. attestationRoots: diff --git a/docs/push-gateway-deployment.md b/docs/push-gateway-deployment.md index c675a487d0..3e5908a595 100644 --- a/docs/push-gateway-deployment.md +++ b/docs/push-gateway-deployment.md @@ -44,7 +44,35 @@ sees it. | `BUZZ_PUSH_ANDROID_PACKAGE_NAME` | Exact Android application package, for example `com.example.buzz`. | | `BUZZ_PUSH_ANDROID_SIGNING_CERT_DIGESTS` | Comma-separated SHA-256 digests (64 hex characters each) of the app's accepted signing certificates. | | `BUZZ_PUSH_FCM_PROJECT_ID` | Firebase project that owns the app's registration tokens, for example `example-project`. | -| `BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH` | Read-only mounted service account key JSON the gateway uses to call FCM. Never commit it. | +| `BUZZ_PUSH_FCM_CREDENTIALS_PATH` | Read-only mounted Google credential JSON the gateway uses to call FCM, dispatched on its `type`: `service_account` (a key file) or `external_account` (keyless, see below). Never commit it. | + +### Keyless FCM credentials + +Projects that forbid service account keys use Google workload identity +federation from AWS. Point `BUZZ_PUSH_FCM_CREDENTIALS_PATH` at the standard +`external_account` config for an AWS provider (`gcloud iam +workload-identity-pools create-cred-config` writes it, with +`--service-account` so it carries `service_account_impersonation_url`, which is +required). Only the AWS credential source (`environment_id` `aws1`) is +supported; the file's instance metadata fields are ignored. + +The pod also needs `AWS_REGION` (or `AWS_DEFAULT_REGION`) and one source of AWS +credentials: IAM roles for service accounts (`AWS_ROLE_ARN` and +`AWS_WEB_IDENTITY_TOKEN_FILE`), EKS Pod Identity +(`AWS_CONTAINER_CREDENTIALS_FULL_URI` and optionally +`AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE`), or static `AWS_ACCESS_KEY_ID`, +`AWS_SECRET_ACCESS_KEY` and `AWS_SESSION_TOKEN`. If several are present, static +keys win, then web identity, then Pod Identity. EC2 +instance metadata is not used. Startup validates the file and these settings but +calls neither AWS nor Google. The first successful token mint is logged once, +and every failed mint logs its hop and status. The pod must reach the regional +STS endpoint and Google's STS and IAM Credentials APIs. + +The Helm chart supports IRSA as shipped: the EKS webhook injects the region and +web identity settings. Pod Identity works in the gateway, but the chart neither +sets `AWS_REGION` nor lets its NetworkPolicy reach the Pod Identity agent, so +with that chart you must supply the region and an egress rule to +`169.254.170.23/32` on TCP port 80 yourself. The wake is a high-priority, data-only FCM message with a compiled-in payload, one constant collapse key and a time to live taken from the delivery's expiry. @@ -96,7 +124,7 @@ get no push; there is no software fallback. With the Helm chart, set `android.enabled=true` together with `android.packageName`, `android.signingCertDigests`, `android.fcmProjectId` and -the Secret holding the service account key. `android.bootKeyDigests` and +the Secret holding the Google credential JSON. `android.bootKeyDigests` and `android.revocationGraceSeconds` map to the settings above. To replace the built-in roots, name a Secret holding the PEM bundle in `android.attestationRoots.secretName` (and its key in `secretKey`); the chart