diff --git a/crates/buzz-push-gateway/src/android_attestation.rs b/crates/buzz-push-gateway/src/android_attestation.rs index d0d700c0b5..5c5a129700 100644 --- a/crates/buzz-push-gateway/src/android_attestation.rs +++ b/crates/buzz-push-gateway/src/android_attestation.rs @@ -35,6 +35,10 @@ pub struct VerifiedAndroidKey { pub enum AndroidAttestationError { #[error("invalid Android attestation")] Invalid, + /// The gateway cannot judge the chain right now (no fresh revocation + /// list yet, as after a restart). Not the client's fault: retry later. + #[error("Android attestation cannot be checked yet")] + Unavailable, } /// Verifies an Android Key Attestation chain (DER certificates, leaf first). diff --git a/crates/buzz-push-gateway/src/android_attestation/key_attestation.rs b/crates/buzz-push-gateway/src/android_attestation/key_attestation.rs index 0db89616b0..82f039080b 100644 --- a/crates/buzz-push-gateway/src/android_attestation/key_attestation.rs +++ b/crates/buzz-push-gateway/src/android_attestation/key_attestation.rs @@ -61,6 +61,11 @@ pub struct KeyAttestationPolicy { #[error("invalid Android attestation roots")] pub struct RootsError; +/// Rejection reasons that say the gateway's revocation list, not the chain, +/// is the problem. +const LIST_UNAVAILABLE: &str = "revocation_list_unavailable"; +const LIST_STALE: &str = "revocation_list_stale"; + /// Verifies Android Key Attestation chains offline against pinned roots and /// the in-memory revocation list. pub struct KeyAttestationVerifier { @@ -146,8 +151,8 @@ impl KeyAttestationVerifier { self.revocations .check(&serials, now) .map_err(|failure| match failure { - super::revocation::RevocationFailure::Unavailable => "revocation_list_unavailable", - super::revocation::RevocationFailure::Stale => "revocation_list_stale", + super::revocation::RevocationFailure::Unavailable => LIST_UNAVAILABLE, + super::revocation::RevocationFailure::Stale => LIST_STALE, super::revocation::RevocationFailure::Listed => "certificate_revoked", })?; let description = attestation_extension(&certs)?; @@ -330,7 +335,12 @@ impl AndroidAttestationVerifier for KeyAttestationVerifier { reason, "Android Key Attestation rejected" ); - AndroidAttestationError::Invalid + match reason { + // The gateway's own list is missing or stale: a verdict on + // this chain must wait for the next refresh. + LIST_UNAVAILABLE | LIST_STALE => AndroidAttestationError::Unavailable, + _ => AndroidAttestationError::Invalid, + } }) } } diff --git a/crates/buzz-push-gateway/src/android_attestation/key_attestation_tests.rs b/crates/buzz-push-gateway/src/android_attestation/key_attestation_tests.rs index 41b6b34e2d..f425aa830c 100644 --- a/crates/buzz-push-gateway/src/android_attestation/key_attestation_tests.rs +++ b/crates/buzz-push-gateway/src/android_attestation/key_attestation_tests.rs @@ -874,6 +874,25 @@ fn the_trait_rejects_without_saying_why() { .is_err()); } +#[test] +fn the_trait_defers_rather_than_rejects_without_a_fresh_list() { + let generated = generate(&Spec::default(), &Pki::default(), TRANSCRIPT); + let stale = Arc::new(RevocationList::new(3600)); + stale.replace(HashSet::new(), NOW - 3601); + for list in [Arc::new(RevocationList::new(86_400)), stale] { + assert!(matches!( + verifier(&generated, policy(), list).verify(&generated.chain, TRANSCRIPT), + Err(AndroidAttestationError::Unavailable) + )); + } + // A listed certificate is the chain's fault, so it is still a rejection. + assert!(matches!( + verifier(&generated, policy(), fresh_list(&[LEAF_SERIAL])) + .verify(&generated.chain, TRANSCRIPT), + Err(AndroidAttestationError::Invalid) + )); +} + #[test] fn google_roots_load_and_pin_both_keys() { let verifier = KeyAttestationVerifier::new( diff --git a/crates/buzz-push-gateway/src/authority.rs b/crates/buzz-push-gateway/src/authority.rs index ac5dbecad4..18a236a710 100644 --- a/crates/buzz-push-gateway/src/authority.rs +++ b/crates/buzz-push-gateway/src/authority.rs @@ -164,6 +164,20 @@ pub trait AuthorityStore: Send + Sync { installation: NewInstallation, now: i64, ) -> Result<(), AuthorityError>; + /// Consume an enrollment challenge and create its installation in one + /// atomic step, so the challenge is never spent without the installation. + /// When the challenge is already spent, return the exact live installation + /// (as [`AuthorityStore::matching_installation`] matches it) that spent + /// it: a replay that raced the original request recovers its handle + /// instead of a refusal that would make the client discard its key. + /// Without either, the request is rejected. + async fn enroll_installation( + &self, + challenge_id: Uuid, + challenge: [u8; 32], + installation: NewInstallation, + now: i64, + ) -> Result; /// Return an exact live installation previously committed for the same /// attested enrollment request. This is the idempotency seam used when a /// client loses the successful response and replays the signed request. @@ -313,62 +327,48 @@ impl AuthorityStore for MemoryAuthorityStore { now: i64, ) -> Result<(), AuthorityError> { let mut s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?; - let token_key = n.token_fingerprint; - if s.installations.contains_key(&n.id) { + s.create_installation(n, now) + } + + async fn enroll_installation( + &self, + challenge_id: Uuid, + challenge: [u8; 32], + n: NewInstallation, + now: i64, + ) -> Result { + let mut s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?; + let found = s + .challenges + .get(&challenge_id) + .filter(|c| c.value == challenge) + .map(|c| c.expires_at); + if found.is_some_and(|expires_at| expires_at < now) { + // Like PostgreSQL: an expired challenge is retired by the refusal, + // so a request that read its clock earlier cannot spend it later. + s.challenges.remove(&challenge_id); return Err(AuthorityError::Rejected); } - let matching = s - .installations - .values() - .filter(|installation| { - installation.app_attest_key_id == n.app_attest_key_id - || installation.token_fingerprint == n.token_fingerprint - }) - .map(|installation| installation.id) - .collect::>(); - if matching.iter().any(|id| { - s.installations - .get(id) - .is_some_and(|installation| !installation.revoked && installation.expires_at >= now) - }) { - // App identity and token possession never supersede a live installation. - return Err(AuthorityError::Conflict); + if found.is_none() { + return s + .matching_installation( + &n.app_attest_key_id, + n.token_fingerprint, + n.endpoint_epoch, + n.expires_at, + now, + ) + .ok_or(AuthorityError::Rejected); } - let replaced = matching - .into_iter() - .filter(|id| { - s.installations - .get(id) - .is_some_and(|installation| installation.expires_at < now) - }) - .collect::>(); - for id in replaced { - if let Some(old) = s.installations.remove(&id) { - s.token_owners.remove(&old.token_fingerprint); - } - s.delegations - .retain(|(installation_id, _), _| *installation_id != id); - s.delegation_ids - .retain(|_, (installation_id, _)| *installation_id != id); - } - s.token_owners.insert(token_key, n.id); - s.installations.insert( - n.id, - Installation { - id: n.id, - platform: n.platform, - app_attest_key_id: n.app_attest_key_id, - app_attest_public_key: n.app_attest_public_key, - assertion_counter: n.assertion_counter, - - token_ciphertext: n.token_ciphertext, - token_fingerprint: n.token_fingerprint, - endpoint_epoch: n.endpoint_epoch, - expires_at: n.expires_at, - revoked: false, - }, - ); - Ok(()) + let id = n.id; + // Like the PostgreSQL transaction, a refused creation leaves the + // challenge unspent. + s.create_installation(n, now)?; + s.challenges.remove(&challenge_id); + s.installations + .get(&id) + .cloned() + .ok_or(AuthorityError::Unavailable) } async fn installation(&self, id: Uuid, now: i64) -> Result { @@ -404,17 +404,7 @@ impl AuthorityStore for MemoryAuthorityStore { now: i64, ) -> Result, AuthorityError> { let s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?; - Ok(s.installations - .values() - .find(|installation| { - !installation.revoked - && installation.expires_at >= now - && installation.app_attest_key_id == key_id - && installation.token_fingerprint == fingerprint - && installation.endpoint_epoch == epoch - && installation.expires_at == expires_at - }) - .cloned()) + Ok(s.matching_installation(key_id, fingerprint, epoch, expires_at, now)) } async fn advance_assertion_counter( @@ -663,6 +653,89 @@ impl AuthorityStore for MemoryAuthorityStore { } } +impl MemoryState { + fn create_installation(&mut self, n: NewInstallation, now: i64) -> Result<(), AuthorityError> { + let s = self; + let token_key = n.token_fingerprint; + if s.installations.contains_key(&n.id) { + return Err(AuthorityError::Rejected); + } + let matching = s + .installations + .values() + .filter(|installation| { + installation.app_attest_key_id == n.app_attest_key_id + || installation.token_fingerprint == n.token_fingerprint + }) + .map(|installation| installation.id) + .collect::>(); + if matching.iter().any(|id| { + s.installations + .get(id) + .is_some_and(|installation| !installation.revoked && installation.expires_at >= now) + }) { + // App identity and token possession never supersede a live installation. + return Err(AuthorityError::Conflict); + } + let replaced = matching + .into_iter() + .filter(|id| { + s.installations + .get(id) + .is_some_and(|installation| installation.expires_at < now) + }) + .collect::>(); + for id in replaced { + if let Some(old) = s.installations.remove(&id) { + s.token_owners.remove(&old.token_fingerprint); + } + s.delegations + .retain(|(installation_id, _), _| *installation_id != id); + s.delegation_ids + .retain(|_, (installation_id, _)| *installation_id != id); + } + s.token_owners.insert(token_key, n.id); + s.installations.insert( + n.id, + Installation { + id: n.id, + platform: n.platform, + app_attest_key_id: n.app_attest_key_id, + app_attest_public_key: n.app_attest_public_key, + assertion_counter: n.assertion_counter, + + token_ciphertext: n.token_ciphertext, + token_fingerprint: n.token_fingerprint, + endpoint_epoch: n.endpoint_epoch, + expires_at: n.expires_at, + revoked: false, + }, + ); + Ok(()) + } + + fn matching_installation( + &self, + key_id: &[u8], + fingerprint: [u8; 32], + epoch: i64, + expires_at: i64, + now: i64, + ) -> Option { + self.installations + .values() + .find(|installation| { + !installation.revoked + && installation.expires_at >= now + && installation.app_attest_key_id == key_id + && installation.token_fingerprint == fingerprint + && installation.endpoint_epoch == epoch + && installation.expires_at == expires_at + }) + .cloned() + } +} + #[cfg(test)] mod tests { use super::*; @@ -742,6 +815,101 @@ mod tests { .is_none()); } + fn enrollment(id: u128, fingerprint: u8) -> NewInstallation { + NewInstallation { + platform: Platform::Android, + id: Uuid::from_u128(id), + app_attest_key_id: vec![9], + app_attest_public_key: vec![8; 65], + assertion_counter: 0, + token_ciphertext: vec![7], + token_fingerprint: [fingerprint; 32], + endpoint_epoch: 1, + expires_at: 2_000, + } + } + + async fn enrollment_challenge(store: &MemoryAuthorityStore, id: u128) { + store + .put_challenge(Challenge { + id: Uuid::from_u128(id), + value: [6; 32], + created_at: 1_000, + expires_at: 1_300, + }) + .await + .unwrap(); + } + + #[tokio::test] + async fn enrollment_replay_of_a_spent_challenge_recovers_the_installation_that_spent_it() { + let store = MemoryAuthorityStore::default(); + enrollment_challenge(&store, 20).await; + let created = store + .enroll_installation(Uuid::from_u128(20), [6; 32], enrollment(21, 5), 1_000) + .await + .unwrap(); + assert_eq!(created.id, Uuid::from_u128(21)); + + // The replay mints a new candidate id; it gets the committed one. + let replayed = store + .enroll_installation(Uuid::from_u128(20), [6; 32], enrollment(22, 5), 1_001) + .await + .unwrap(); + assert_eq!(replayed, created); + assert_eq!( + store + .enroll_installation(Uuid::from_u128(20), [6; 32], enrollment(23, 6), 1_001) + .await, + Err(AuthorityError::Rejected), + "a spent challenge pays for nothing but its own installation" + ); + } + + #[tokio::test] + async fn refused_enrollment_leaves_its_challenge_unspent() { + let store = MemoryAuthorityStore::default(); + store + .create_installation(enrollment(30, 5), 1_000) + .await + .unwrap(); + enrollment_challenge(&store, 31).await; + // Same token, different key: the live installation wins. + let mut other_key = enrollment(32, 5); + other_key.app_attest_key_id = vec![10]; + assert_eq!( + store + .enroll_installation(Uuid::from_u128(31), [6; 32], other_key, 1_000) + .await, + Err(AuthorityError::Conflict) + ); + assert_eq!( + store + .consume_challenge(Uuid::from_u128(31), [6; 32], 1_000) + .await, + Ok(()) + ); + } + + #[tokio::test] + async fn expired_replay_first_retires_the_challenge() { + let store = MemoryAuthorityStore::default(); + enrollment_challenge(&store, 40).await; + assert_eq!( + store + .enroll_installation(Uuid::from_u128(40), [6; 32], enrollment(41, 6), 1_301) + .await, + Err(AuthorityError::Rejected) + ); + // A slower original that read its clock inside the window. + assert_eq!( + store + .enroll_installation(Uuid::from_u128(40), [6; 32], enrollment(42, 6), 1_299) + .await, + Err(AuthorityError::Rejected) + ); + } + #[tokio::test] async fn challenge_issuance_is_bounded_per_window() { let store = MemoryAuthorityStore::default(); diff --git a/crates/buzz-push-gateway/src/http.rs b/crates/buzz-push-gateway/src/http.rs index 18869d3fee..7fa8c9ec60 100644 --- a/crates/buzz-push-gateway/src/http.rs +++ b/crates/buzz-push-gateway/src/http.rs @@ -1,6 +1,6 @@ //! Stateful installation, delegation, delivery, and health APIs. use crate::{ - android_attestation::{self, AndroidAttestationVerifier}, + android_attestation::{self, AndroidAttestationError, AndroidAttestationVerifier}, apns::{DeliveryAttempt, DeliveryOutcome, PushTransport}, app_attest::AppAttestVerifier, authority::{ @@ -330,8 +330,8 @@ async fn enroll(State(s): State, body: Bytes) -> Response { None => return error(StatusCode::BAD_REQUEST, "invalid_request"), }; let verified = match verify_enrollment_attestation(&s, &r, signed.as_bytes()) { - Some(value) => value, - None => return error(StatusCode::UNAUTHORIZED, "invalid_attestation"), + Ok(value) => value, + Err(response) => return response, }; let fingerprint = endpoint_fingerprint(platform, &token); match s @@ -360,23 +360,15 @@ async fn enroll(State(s): State, body: Bytes) -> Response { Ok(None) => {} Err(e) => return authority_error(e), } - if let Err(e) = s - .authority - .consume_challenge(r.challenge_id, challenge, now) - .await - { - return authority_error(e); - } let ciphertext = match s.token_keyring.seal(&token) { Ok(v) => v, Err(_) => return error(StatusCode::SERVICE_UNAVAILABLE, "temporarily_unavailable"), }; - let id = uuid::Uuid::new_v4(); let n = NewInstallation { - id, + id: uuid::Uuid::new_v4(), platform, app_attest_key_id: verified.key_id, - app_attest_public_key: verified.public_key, + app_attest_public_key: verified.public_key.clone(), assertion_counter: 0, token_ciphertext: ciphertext, @@ -384,18 +376,26 @@ async fn enroll(State(s): State, body: Bytes) -> Response { endpoint_epoch: 1, expires_at: r.expires_at, }; - if let Err(e) = s.authority.create_installation(n, now).await { - return authority_error(e); + // One atomic step, so a replay racing this request either waits for its + // installation or finds the challenge unspent, never a spent challenge + // with nothing behind it. + match s + .authority + .enroll_installation(r.challenge_id, challenge, n, now) + .await + { + Ok(installation) if installation.app_attest_public_key == verified.public_key => ( + StatusCode::CREATED, + Json(InstallationEnrollResponse { + installation_handle: installation.id, + endpoint_epoch: installation.endpoint_epoch, + expires_at: installation.expires_at, + }), + ) + .into_response(), + Ok(_) => installation_conflict(), + Err(e) => authority_error(e), } - ( - StatusCode::CREATED, - Json(InstallationEnrollResponse { - installation_handle: id, - endpoint_epoch: 1, - expires_at: r.expires_at, - }), - ) - .into_response() } /// The attested key an enrollment proved, on either platform. @@ -405,26 +405,44 @@ struct VerifiedKey { } /// Verify the enrollment's one attestation against the exact transcript. -/// `None` rejects it; the response never says why (rejections are logged). +/// A rejection answers 401 and never says why (rejections are logged). When +/// the gateway cannot judge an Android chain yet (no fresh revocation list, +/// as right after a restart), it answers a retryable 503 instead, so the +/// client keeps its key and replays the same request later. +#[allow(clippy::result_large_err)] // Response is the natural error type for axum handlers fn verify_enrollment_attestation( s: &AppState, r: &InstallationEnrollRequest, transcript: &[u8], -) -> Option { +) -> Result { + let rejected = || error(StatusCode::UNAUTHORIZED, "invalid_attestation"); if let Some(attestation) = &r.attestation { + let key_id = r.key_id.as_deref().ok_or_else(rejected)?; let verified = s .application .app_attest - .verify_attestation(attestation, r.key_id.as_deref()?, transcript) - .ok()?; - return Some(VerifiedKey { + .verify_attestation(attestation, key_id, transcript) + .map_err(|_| rejected())?; + return Ok(VerifiedKey { key_id: verified.key_id, public_key: verified.public_key, }); } - let android = s.application.android.as_ref()?; - let chain = decode_android_chain(r.android_attestation.as_deref()?)?; - let proven = android.attestation.verify(&chain, transcript).ok()?; + let android = s.application.android.as_ref().ok_or_else(rejected)?; + let chain = r + .android_attestation + .as_deref() + .and_then(decode_android_chain) + .ok_or_else(rejected)?; + let proven = android + .attestation + .verify(&chain, transcript) + .map_err(|e| match e { + AndroidAttestationError::Unavailable => { + error(StatusCode::SERVICE_UNAVAILABLE, "temporarily_unavailable") + } + AndroidAttestationError::Invalid => rejected(), + })?; use sha2::{Digest, Sha256}; // The key must be a P-256 point. Its id is its digest; the attestation // challenge binds the key to this transcript. @@ -434,6 +452,7 @@ fn verify_enrollment_attestation( key_id: Sha256::digest(&proven.public_key).to_vec(), public_key: proven.public_key, }) + .ok_or_else(rejected) } /// Decode a bounded Key Attestation chain of base64 DER certificates. diff --git a/crates/buzz-push-gateway/src/http_android_tests.rs b/crates/buzz-push-gateway/src/http_android_tests.rs index 7114d15b53..4f012ae1b1 100644 --- a/crates/buzz-push-gateway/src/http_android_tests.rs +++ b/crates/buzz-push-gateway/src/http_android_tests.rs @@ -58,6 +58,16 @@ fn gateway(with_android: bool) -> Gateway { } fn gateway_limited(with_android: bool, signed_calls_per_window: i64) -> Gateway { + gateway_with( + with_android.then(|| Arc::new(TestAttestationVerifier) as _), + signed_calls_per_window, + ) +} + +fn gateway_with( + attestation: Option>, + signed_calls_per_window: i64, +) -> Gateway { let fcm = Arc::new(FakeFcm::default()); let grant_keyring = Arc::new(GrantKeyring::new(vec![GrantKey::new("test", &[1; 32]).unwrap()]).unwrap()); @@ -76,8 +86,8 @@ fn gateway_limited(with_android: bool, signed_calls_per_window: i64) -> Gateway .unwrap(), ), transport: Arc::new(NeverApns), - android: with_android.then(|| AndroidRuntime { - attestation: Arc::new(TestAttestationVerifier), + android: attestation.map(|attestation| AndroidRuntime { + attestation, transport: fcm.clone(), }), }), @@ -668,3 +678,55 @@ async fn signed_installation_calls_are_limited_per_attested_key() { }; call_ok(&g, other_handle, &delegate(1), &other).await; } + +/// The test verifier behind a revocation list that may not be loaded yet, as +/// right after a gateway restart. +struct ListGatedVerifier { + list_loaded: AtomicBool, +} + +impl AndroidAttestationVerifier for ListGatedVerifier { + fn verify( + &self, + chain: &[Vec], + client_data: &[u8], + ) -> Result { + if !self.list_loaded.load(Ordering::SeqCst) { + return Err(AndroidAttestationError::Unavailable); + } + TestAttestationVerifier.verify(chain, client_data) + } +} + +#[tokio::test] +async fn enrollment_waits_out_a_missing_revocation_list_without_spending_anything() { + let verifier = Arc::new(ListGatedVerifier { + list_loaded: AtomicBool::new(false), + }); + let g = gateway_with(Some(verifier.clone()), 1_000); + let phone = Phone::new(7); + let ch = challenge(&g.app).await; + let body = enroll_body(&phone, &ch, FCM_TOKEN); + + // A fresh enrollment before the first list: retryable, challenge unspent. + let (status, reply) = post(&g.app, "/v1/installations", &body).await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE, "{reply}"); + assert_eq!(reply["error"], "temporarily_unavailable"); + verifier.list_loaded.store(true, Ordering::SeqCst); + let (status, created) = post(&g.app, "/v1/installations", &body).await; + assert_eq!(status, StatusCode::CREATED, "{created}"); + + // A restart empties the list again. The exact replay of the committed + // enrollment (a lost response) is retryable, not an attestation refusal + // that would make the phone discard the key the installation holds. + verifier.list_loaded.store(false, Ordering::SeqCst); + let (status, _) = post(&g.app, "/v1/installations", &body).await; + assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); + verifier.list_loaded.store(true, Ordering::SeqCst); + let (status, replayed) = post(&g.app, "/v1/installations", &body).await; + assert_eq!(status, StatusCode::CREATED); + assert_eq!( + replayed["installation_handle"], + created["installation_handle"] + ); +} diff --git a/crates/buzz-push-gateway/src/http_delivery_tests.rs b/crates/buzz-push-gateway/src/http_delivery_tests.rs index b28df01703..e6a8749ab9 100644 --- a/crates/buzz-push-gateway/src/http_delivery_tests.rs +++ b/crates/buzz-push-gateway/src/http_delivery_tests.rs @@ -639,6 +639,17 @@ impl AuthorityStore for FailingFinishStore { ) -> Result<(), AuthorityError> { self.0.create_installation(installation, now).await } + async fn enroll_installation( + &self, + challenge_id: Uuid, + challenge: [u8; 32], + installation: NewInstallation, + now: i64, + ) -> Result { + self.0 + .enroll_installation(challenge_id, challenge, installation, now) + .await + } async fn matching_installation( &self, app_attest_key_id: &[u8], diff --git a/crates/buzz-push-gateway/src/postgres.rs b/crates/buzz-push-gateway/src/postgres.rs index c21915b4af..c5b6085037 100644 --- a/crates/buzz-push-gateway/src/postgres.rs +++ b/crates/buzz-push-gateway/src/postgres.rs @@ -99,6 +99,104 @@ fn bytes32(v: Vec) -> Result<[u8; 32], AuthorityError> { v.try_into().map_err(|_| AuthorityError::Unavailable) } +/// Create an installation inside `tx`, replacing only expired installations +/// that share its key or token. A live one is a conflict. +async fn insert_installation( + tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, + n: NewInstallation, + now: i64, +) -> Result<(), AuthorityError> { + let now_at = at(now)?; + let existing = sqlx::query( + "SELECT id,expires_at,revoked_at FROM push_gateway_installations WHERE app_attest_key_id=$1 OR token_fingerprint=$2 FOR UPDATE", + ) + .bind(&n.app_attest_key_id) + .bind(n.token_fingerprint.to_vec()) + .fetch_all(&mut **tx) + .await + .map_err(db)?; + if existing.iter().any(|row| { + let revoked = row.try_get::>, _>("revoked_at"); + let expires = row.try_get::, _>("expires_at"); + match (revoked, expires) { + (Ok(None), Ok(expires_at)) => expires_at >= now_at, + (Ok(Some(_)), Ok(_)) => false, + _ => true, + } + }) { + return Err(AuthorityError::Conflict); + } + let replaced = existing + .iter() + .map(|row| { + Ok(( + row.try_get::("id").map_err(db)?, + row.try_get::, _>("expires_at").map_err(db)?, + )) + }) + .collect::, _>>()?; + let expired = replaced + .into_iter() + .filter_map(|(id, expires_at)| (expires_at < now_at).then_some(id)) + .collect::>(); + if !expired.is_empty() { + sqlx::query("DELETE FROM push_gateway_delegations WHERE installation_id = ANY($1)") + .bind(&expired) + .execute(&mut **tx) + .await + .map_err(db)?; + sqlx::query("DELETE FROM push_gateway_installations WHERE id = ANY($1)") + .bind(&expired) + .execute(&mut **tx) + .await + .map_err(db)?; + } + let result = sqlx::query("INSERT INTO push_gateway_installations(id,app_attest_key_id,app_attest_public_key,assertion_counter,token_ciphertext,token_fingerprint,endpoint_epoch,expires_at,platform) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT DO NOTHING") + .bind(n.id).bind(n.app_attest_key_id).bind(n.app_attest_public_key).bind(i64::from(n.assertion_counter)).bind(n.token_ciphertext).bind(n.token_fingerprint.to_vec()).bind(n.endpoint_epoch).bind(at(n.expires_at)?).bind(n.platform.as_str()).execute(&mut **tx).await.map_err(db)?; + if result.rows_affected() != 1 { + return Err(AuthorityError::Conflict); + } + Ok(()) +} + +/// The exact live installation an enrollment request committed, if any. +async fn matching_installation_in<'e>( + executor: impl sqlx::PgExecutor<'e>, + key_id: &[u8], + token_fingerprint: [u8; 32], + endpoint_epoch: i64, + expires_at: i64, + now: i64, +) -> Result, AuthorityError> { + let r = sqlx::query("SELECT * FROM push_gateway_installations WHERE app_attest_key_id=$1 AND token_fingerprint=$2 AND endpoint_epoch=$3 AND expires_at=$4 AND revoked_at IS NULL AND expires_at >= $5") + .bind(key_id) + .bind(token_fingerprint.to_vec()) + .bind(endpoint_epoch) + .bind(at(expires_at)?) + .bind(at(now)?) + .fetch_optional(executor) + .await + .map_err(db)?; + r.map(|r| { + let id = r.try_get("id").map_err(db)?; + Ok(Installation { + id, + platform: platform_column(&r)?, + app_attest_key_id: r.try_get("app_attest_key_id").map_err(db)?, + app_attest_public_key: r.try_get("app_attest_public_key").map_err(db)?, + assertion_counter: u32::try_from(r.try_get::("assertion_counter").map_err(db)?) + .map_err(|_| AuthorityError::Unavailable)?, + + token_ciphertext: r.try_get("token_ciphertext").map_err(db)?, + token_fingerprint: bytes32(r.try_get("token_fingerprint").map_err(db)?)?, + endpoint_epoch: r.try_get("endpoint_epoch").map_err(db)?, + expires_at: ts(r.try_get("expires_at").map_err(db)?), + revoked: false, + }) + }) + .transpose() +} + #[async_trait] impl AuthorityStore for PostgresAuthorityStore { async fn ready(&self) -> Result<(), AuthorityError> { @@ -185,58 +283,70 @@ impl AuthorityStore for PostgresAuthorityStore { now: i64, ) -> Result<(), AuthorityError> { let mut tx = self.pool.begin().await.map_err(db)?; - let now_at = at(now)?; - let existing = sqlx::query( - "SELECT id,expires_at,revoked_at FROM push_gateway_installations WHERE app_attest_key_id=$1 OR token_fingerprint=$2 FOR UPDATE", + insert_installation(&mut tx, n, now).await?; + tx.commit().await.map_err(db) + } + async fn enroll_installation( + &self, + challenge_id: Uuid, + challenge: [u8; 32], + n: NewInstallation, + now: i64, + ) -> Result { + use sha2::{Digest, Sha256}; + let mut tx = self.pool.begin().await.map_err(db)?; + // Spend the matching challenge before judging its expiry. A concurrent + // request that already spent it holds this row until its transaction + // ends, so the DELETE waits for that outcome: after a commit the row is + // gone and the lookup below sees the committed installation; after a + // rollback (including a cancelled request) the row is back and its + // expiry decides. Filtering on expiry in the DELETE would skip a + // locked row that crossed its deadline and answer "rejected" while the + // earlier request could still commit. + let expires_at: Option> = sqlx::query_scalar( + "DELETE FROM push_gateway_challenges WHERE id=$1 AND challenge_hash=$2 RETURNING expires_at", ) - .bind(&n.app_attest_key_id) - .bind(n.token_fingerprint.to_vec()) - .fetch_all(&mut *tx) + .bind(challenge_id) + .bind(Sha256::digest(challenge).to_vec()) + .fetch_optional(&mut *tx) .await .map_err(db)?; - if existing.iter().any(|row| { - let revoked = row.try_get::>, _>("revoked_at"); - let expires = row.try_get::, _>("expires_at"); - match (revoked, expires) { - (Ok(None), Ok(expires_at)) => expires_at >= now_at, - (Ok(Some(_)), Ok(_)) => false, - _ => true, - } - }) { - return Err(AuthorityError::Conflict); - } - let replaced = existing - .iter() - .map(|row| { - Ok(( - row.try_get::("id").map_err(db)?, - row.try_get::, _>("expires_at").map_err(db)?, - )) - }) - .collect::, _>>()?; - let expired = replaced - .into_iter() - .filter_map(|(id, expires_at)| (expires_at < now_at).then_some(id)) - .collect::>(); - if !expired.is_empty() { - sqlx::query("DELETE FROM push_gateway_delegations WHERE installation_id = ANY($1)") - .bind(&expired) - .execute(&mut *tx) - .await - .map_err(db)?; - sqlx::query("DELETE FROM push_gateway_installations WHERE id = ANY($1)") - .bind(&expired) - .execute(&mut *tx) - .await - .map_err(db)?; - } - let result = sqlx::query("INSERT INTO push_gateway_installations(id,app_attest_key_id,app_attest_public_key,assertion_counter,token_ciphertext,token_fingerprint,endpoint_epoch,expires_at,platform) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT DO NOTHING") - .bind(n.id).bind(n.app_attest_key_id).bind(n.app_attest_public_key).bind(i64::from(n.assertion_counter)).bind(n.token_ciphertext).bind(n.token_fingerprint.to_vec()).bind(n.endpoint_epoch).bind(at(n.expires_at)?).bind(n.platform.as_str()).execute(&mut *tx).await.map_err(db)?; - if result.rows_affected() != 1 { - return Err(AuthorityError::Conflict); + let Some(expires_at) = expires_at else { + // Read committed: this statement sees what the request that spent + // the challenge committed while the DELETE waited. + return matching_installation_in( + &mut *tx, + &n.app_attest_key_id, + n.token_fingerprint, + n.endpoint_epoch, + n.expires_at, + now, + ) + .await? + .ok_or(AuthorityError::Rejected); + }; + if ts(expires_at) < now { + // Retire the expired challenge before refusing, so a slower + // request for it that read its clock earlier cannot spend it after + // this refusal. + tx.commit().await.map_err(db)?; + return Err(AuthorityError::Rejected); } + let created = Installation { + id: n.id, + platform: n.platform, + app_attest_key_id: n.app_attest_key_id.clone(), + app_attest_public_key: n.app_attest_public_key.clone(), + assertion_counter: n.assertion_counter, + token_ciphertext: n.token_ciphertext.clone(), + token_fingerprint: n.token_fingerprint, + endpoint_epoch: n.endpoint_epoch, + expires_at: n.expires_at, + revoked: false, + }; + insert_installation(&mut tx, n, now).await?; tx.commit().await.map_err(db)?; - Ok(()) + Ok(created) } async fn installation(&self, id: Uuid, now: i64) -> Result { let r = sqlx::query("SELECT * FROM push_gateway_installations WHERE id=$1 AND revoked_at IS NULL AND expires_at >= $2") @@ -291,41 +401,20 @@ impl AuthorityStore for PostgresAuthorityStore { async fn matching_installation( &self, key_id: &[u8], - token_fingerprint: [u8; 32], endpoint_epoch: i64, expires_at: i64, now: i64, ) -> Result, AuthorityError> { - let r = sqlx::query("SELECT * FROM push_gateway_installations WHERE app_attest_key_id=$1 AND token_fingerprint=$2 AND endpoint_epoch=$3 AND expires_at=$4 AND revoked_at IS NULL AND expires_at >= $5") - .bind(key_id) - .bind(token_fingerprint.to_vec()) - .bind(endpoint_epoch) - .bind(at(expires_at)?) - .bind(at(now)?) - .fetch_optional(&self.pool) - .await - .map_err(db)?; - r.map(|r| { - let id = r.try_get("id").map_err(db)?; - Ok(Installation { - id, - platform: platform_column(&r)?, - app_attest_key_id: r.try_get("app_attest_key_id").map_err(db)?, - app_attest_public_key: r.try_get("app_attest_public_key").map_err(db)?, - assertion_counter: u32::try_from( - r.try_get::("assertion_counter").map_err(db)?, - ) - .map_err(|_| AuthorityError::Unavailable)?, - - token_ciphertext: r.try_get("token_ciphertext").map_err(db)?, - token_fingerprint: bytes32(r.try_get("token_fingerprint").map_err(db)?)?, - endpoint_epoch: r.try_get("endpoint_epoch").map_err(db)?, - expires_at: ts(r.try_get("expires_at").map_err(db)?), - revoked: false, - }) - }) - .transpose() + matching_installation_in( + &self.pool, + key_id, + token_fingerprint, + endpoint_epoch, + expires_at, + now, + ) + .await } async fn advance_assertion_counter( &self, @@ -1088,6 +1177,205 @@ mod postgres_tests { drop_schema(&schema).await; } + async fn seed_enrollment_challenge(store: &PostgresAuthorityStore, id: Uuid, now: i64) { + store + .put_challenge(Challenge { + id, + value: [6; 32], + created_at: now, + expires_at: now + 300, + }) + .await + .expect("issue enrollment challenge"); + } + + fn enrollment(id: Uuid, now: i64) -> NewInstallation { + NewInstallation { + platform: Platform::Android, + id, + app_attest_key_id: vec![9], + app_attest_public_key: vec![8; 65], + assertion_counter: 0, + token_ciphertext: vec![7], + token_fingerprint: [5; 32], + endpoint_epoch: 1, + expires_at: now + 600, + } + } + + // An enrollment whose challenge is spent but whose installation has not + // committed yet, raced by an exact replay (a client retry after a + // timeout). The replay must wait for the outcome, never answer "not + // authorized" while the first request can still commit, including when + // the challenge expires between the two attempts. + #[tokio::test] + #[ignore = "requires PostgreSQL"] + async fn enrollment_replay_waits_for_an_uncommitted_enrollment() { + for (commits, replay_delay) in [(true, 0), (false, 0), (true, 301), (false, 301)] { + let (pool, schema) = full_schema(3).await; + let store = PostgresAuthorityStore::new(pool.clone()); + let now = Utc::now().timestamp(); + let replay_at = now + replay_delay; + let challenge_id = Uuid::new_v4(); + seed_enrollment_challenge(&store, challenge_id, now).await; + + // The original request: challenge spent, installation pending. + let mut original = pool.begin().await.expect("begin original enrollment"); + let original_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()") + .fetch_one(&mut *original) + .await + .expect("read original pid"); + let spent = sqlx::query("DELETE FROM push_gateway_challenges WHERE id=$1") + .bind(challenge_id) + .execute(&mut *original) + .await + .expect("spend challenge"); + assert_eq!(spent.rows_affected(), 1); + let original_id = Uuid::new_v4(); + insert_installation(&mut original, enrollment(original_id, now), now) + .await + .expect("stage original installation"); + + let replay_store = store.clone(); + let replay_id = Uuid::new_v4(); + let replay = tokio::spawn(async move { + replay_store + .enroll_installation( + challenge_id, + [6; 32], + enrollment(replay_id, now), + replay_at, + ) + .await + }); + // Finish the original only once the replay is blocked on its row + // lock, so every case exercises the race rather than a replay that + // has not reached the database yet. + let mut waited = 0; + loop { + let blocked: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid))", + ) + .bind(original_pid) + .fetch_one(&pool) + .await + .expect("read lock waiters"); + if blocked > 0 { + break; + } + waited += 1; + assert!( + waited < 400, + "the replay never waited on the original request's challenge row \ + (commits={commits}, replay_delay={replay_delay})" + ); + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + assert!(!replay.is_finished()); + let expected = if commits { + original.commit().await.expect("commit original"); + Some(original_id) + } else { + // A cancelled request rolls back, and its challenge with it. + original.rollback().await.expect("roll back original"); + // The restored challenge is live only if it has not expired. + (replay_delay == 0).then_some(replay_id) + }; + let result = replay.await.expect("replay task"); + match expected { + Some(expected) => { + let installation = result.expect("the replay recovers an installation"); + assert_eq!(installation.id, expected); + assert!(store.installation(expected, replay_at).await.is_ok()); + } + None => { + assert_eq!(result.map(|i| i.id), Err(AuthorityError::Rejected)); + let installations: i64 = + sqlx::query_scalar("SELECT count(*) FROM push_gateway_installations") + .fetch_one(&pool) + .await + .expect("count installations"); + assert_eq!(installations, 0); + } + } + + pool.close().await; + drop_schema(&schema).await; + } + } + + // An expired replay that reaches the store before a slower original + // request (which read its clock inside the window) retires the challenge, + // so both are refused and nothing holds the token. + #[tokio::test] + #[ignore = "requires PostgreSQL"] + async fn expired_replay_first_retires_the_challenge() { + let (pool, schema) = full_schema(1).await; + let store = PostgresAuthorityStore::new(pool.clone()); + let now = Utc::now().timestamp(); + let challenge_id = Uuid::new_v4(); + seed_enrollment_challenge(&store, challenge_id, now).await; + + let replay = store + .enroll_installation( + challenge_id, + [6; 32], + enrollment(Uuid::new_v4(), now), + now + 301, + ) + .await; + assert_eq!(replay.map(|i| i.id), Err(AuthorityError::Rejected)); + let original = store + .enroll_installation( + challenge_id, + [6; 32], + enrollment(Uuid::new_v4(), now), + now + 299, + ) + .await; + assert_eq!(original.map(|i| i.id), Err(AuthorityError::Rejected)); + let installations: i64 = + sqlx::query_scalar("SELECT count(*) FROM push_gateway_installations") + .fetch_one(&pool) + .await + .expect("count installations"); + assert_eq!(installations, 0); + + pool.close().await; + drop_schema(&schema).await; + } + + #[tokio::test] + #[ignore = "requires PostgreSQL"] + async fn refused_enrollment_leaves_its_challenge_unspent() { + let (pool, schema) = full_schema(1).await; + let store = PostgresAuthorityStore::new(pool.clone()); + let now = Utc::now().timestamp(); + store + .create_installation(enrollment(Uuid::new_v4(), now), now) + .await + .expect("live installation holds the token"); + let challenge_id = Uuid::new_v4(); + seed_enrollment_challenge(&store, challenge_id, now).await; + // Same token, different key: the live installation wins. + let mut other_key = enrollment(Uuid::new_v4(), now); + other_key.app_attest_key_id = vec![10]; + assert_eq!( + store + .enroll_installation(challenge_id, [6; 32], other_key, now) + .await + .map(|i| i.id), + Err(AuthorityError::Conflict) + ); + store + .consume_challenge(challenge_id, [6; 32], now) + .await + .expect("the refused enrollment left its challenge unspent"); + + pool.close().await; + drop_schema(&schema).await; + } + // The schema has no foreign keys, so these tests prove the reference // checks run in the gateway's own transactions. #[tokio::test] diff --git a/docs/nips/NIP-PL.md b/docs/nips/NIP-PL.md index 443f9ec3fc..b374673053 100644 --- a/docs/nips/NIP-PL.md +++ b/docs/nips/NIP-PL.md @@ -277,7 +277,7 @@ The opaque string returned as `endpoint_grant` by `POST /v1/delegations` is the ### Common HTTP and value rules -All routes below accept only `POST`. Clients MUST send `Content-Type: application/json`; bodies are UTF-8 JSON and MUST be at most 8192 bytes, except `POST /v1/installations`, whose body MUST be at most 23896 bytes. That installation-only ceiling is derived from the maximum permitted base64-encoded 16384-byte App Attest object, the maximum 512-byte APNs endpoint encoded as hex, and 1024 bytes for the remaining closed envelope. A body over its applicable limit is rejected with HTTP `413` before JSON parsing. Every request object is closed: unknown members, duplicate members at any depth, missing or incorrectly typed members, trailing non-whitespace data, or a `v` other than integer `1` are `400 {"error":"invalid_request"}`. Integers are signed JSON integers in the ranges stated below. Unix times are integer seconds. UUIDs use the canonical lowercase hyphenated representation. Relay pubkeys are exactly 64 lowercase hexadecimal characters. APNs endpoints are non-empty, even-length lowercase hexadecimal strings encoding at most 512 bytes. Challenges are exactly 32 bytes encoded as unpadded URL-safe base64. `key_id`, `attestation`, and `assertion` use padded or unpadded standard base64 as accepted by Apple's App Attest API; decoded key ids are exactly 32 bytes, attestations are 1..16384 bytes, and assertions are 1..1024 bytes. An `endpoint_grant`, including its key-id prefix, MUST be at most 4096 bytes. +All routes below accept only `POST`. Clients MUST send `Content-Type: application/json`; bodies are UTF-8 JSON and MUST be at most 8192 bytes, except `POST /v1/installations`, whose body MUST be at most 23960 bytes. That installation-only ceiling is derived from the maximum permitted base64-encoded 16384-byte App Attest object, the maximum 512-byte APNs endpoint encoded as hex, 64 bytes of array framing for an Android attestation chain of at most 8 certificates, and 1024 bytes for the remaining closed envelope. A body over its applicable limit is rejected with HTTP `413` before JSON parsing. Every request object is closed: unknown members, duplicate members at any depth, missing or incorrectly typed members, trailing non-whitespace data, or a `v` other than integer `1` are `400 {"error":"invalid_request"}`. Integers are signed JSON integers in the ranges stated below. Unix times are integer seconds. UUIDs use the canonical lowercase hyphenated representation. Relay pubkeys are exactly 64 lowercase hexadecimal characters. APNs endpoints are non-empty, even-length lowercase hexadecimal strings encoding at most 512 bytes. Challenges are exactly 32 bytes encoded as unpadded URL-safe base64. `key_id`, `attestation`, and `assertion` use padded or unpadded standard base64 as accepted by Apple's App Attest API; decoded key ids are exactly 32 bytes, attestations are 1..16384 bytes, and assertions are 1..1024 bytes. An `endpoint_grant`, including its key-id prefix, MUST be at most 4096 bytes. Handler responses are UTF-8 `application/json`. Closed error bodies are `{"error":"invalid_request"}`, `{"error":"invalid_attestation"}`, `{"error":"not_authorized"}`, `{"error":"invalid_auth"}`, `{"error":"invalid_grant"}`, `{"error":"installation_conflict"}`, `{"error":"rate_limited"}`, `{"error":"temporarily_unavailable"}`, `{"error":"configuration_fault"}`, or `{"error":"not_ready"}`. Authority, custody, and quota rejection MUST NOT reveal whether an installation, delegation, or endpoint exists. Delivery grant, authority, and replay failures collapse to `404 invalid_grant`; endpoint quota exhaustion uses `429 rate_limited`; storage failures use `503 temporarily_unavailable`. @@ -286,10 +286,10 @@ Handler responses are UTF-8 `application/json`. Closed error bodies are `{"error Every App Attest operation signs a **transcript**, not the received request bytes. Transcript bytes are UTF-8 bytes of: ``` - + "\\n" + + || 0x0a || ``` -The JSON object has no insignificant whitespace and members appear in the exact order shown below. Strings use JSON escaping for quotation mark, reverse solidus, and U+0000..U+001F; all authority-bearing strings admitted by this profile are ASCII. UUID strings are canonical lowercase-hyphenated. Integers use shortest decimal notation. The fixed `audience` value is part of the signed object and prevents cross-route use. For enrollment, these exact transcript bytes are the App Attest `clientData` supplied to attestation verification. For every assertion route, `clientDataHash = SHA-256(transcript bytes)` is verified by App Attest. The separately stored challenge must equal the request `challenge`, is single-use, expires after 300 seconds, and is consumed only after successful cryptographic verification. Assertion `signCount` MUST strictly increase atomically for the installation. +`||` is byte concatenation and `0x0a` is a single line feed byte (U+000A), not the two characters reverse solidus and `n`. The JSON object has no insignificant whitespace and members appear in the exact order shown below. Strings use JSON escaping for quotation mark, reverse solidus, and U+0000..U+001F; all authority-bearing strings admitted by this profile are ASCII. UUID strings are canonical lowercase-hyphenated. Integers use shortest decimal notation. The fixed `audience` value is part of the signed object and prevents cross-route use. For enrollment, these exact transcript bytes are the App Attest `clientData` supplied to attestation verification. For every assertion route, `clientDataHash = SHA-256(transcript bytes)` is verified by App Attest. The separately stored challenge must equal the request `challenge`, is single-use, expires after 300 seconds, and is consumed only after successful cryptographic verification. Assertion `signCount` MUST strictly increase atomically for the installation. ### Challenge @@ -327,10 +327,34 @@ The gateway verifies Apple's attestation chain, configured application identifie {"installation_handle":"","endpoint_epoch":1,"expires_at":} ``` -The client MUST durably journal the exact attested enrollment request before its first send and retain it until delegation state is durable. If that exact request is replayed after the installation commit, the gateway MUST return the same success response after re-verifying the attestation, even though the challenge was already consumed. Idempotency requires exact equality of attested key, profile, endpoint fingerprint, epoch, and expiration, and the recovered public key MUST equal the committed key; any mismatch remains indistinguishable from other authority rejection. This recovery rule grants no authority beyond replaying the already authenticated request. +The client MUST durably journal the exact attested enrollment request before its first send and retain it until it has durably stored the returned `installation_handle`, which it MUST do before its first delegation request. If that exact request is replayed after the installation commit, the gateway MUST return the same success response after re-verifying the attestation, even though the challenge was already consumed. Replay recovery lasts only while the installation keeps the expiration it was enrolled with: a delegation that extends it ends recovery, and a later replay of the enrollment, while that request is otherwise still valid, is `404 not_authorized`. Idempotency requires exact equality of attested key, profile, endpoint fingerprint, epoch, and expiration, and the recovered public key MUST equal the committed key; any mismatch remains indistinguishable from other authority rejection. This recovery rule grants no authority beyond replaying the already authenticated request. + +Consuming the challenge and committing the installation are one atomic step: a challenge is never spent without the installation it pays for, and a refused creation leaves it unspent. An exact replay that races an enrollment still in progress waits for its outcome and returns the committed installation, or enrolls itself if that attempt rolled back; it never receives `404` while the original can still commit, even when the challenge's expiry passes while it waits. After a rollback, the restored challenge's expiry decides as usual. A request that finds its challenge expired retires it before answering `404`, so a slower request for the same challenge cannot spend it afterwards. Invalid attestation is `401 invalid_attestation`; a consumed or expired challenge is `404 not_authorized`. After successful attestation verification, a key or token owned by a different live installation is `409 installation_conflict`; the conflicting request does not replace existing live authority. A fresh verified enrollment may replace expired or revoked ownership so an app that missed its renewal window can recover. +### Android installation enrollment + +`POST /v1/installations` also enrolls an Android installation when the gateway has an Android application configured; otherwise an Android request is `400 invalid_request`. The gateway derives the platform from which attestation the request carries: exactly one of `attestation` (iOS, with `key_id`) or `android_attestation` (Android, without `key_id`) MUST be present. Request members, in any request order: + +```json +{"v":1,"challenge_id":"","challenge":"","android_attestation":["", ...],"endpoint":"","endpoint_epoch":1,"expires_at":} +``` + +`android_attestation` is the Android Key Attestation certificate chain, leaf first: 1..8 padded standard-base64 DER certificates whose decoded total is at most 16384 bytes. `endpoint` is the FCM registration token as issued: 1..512 bytes of ASCII letters, digits, `:`, `_` and `-`. The `expires_at` rule is the same as for iOS. + +A Keystore key is generated from its attestation challenge, so the transcript holds only values known before the key exists and has no `key_id`. The exact transcript is domain `buzz.push.enroll.android.v1` followed by this ordered object: + +```json +{"v":1,"audience":"https://push.buzz.xyz/v1/installations","challenge_id":"","challenge":"","endpoint":"","endpoint_epoch":1,"expires_at":} +``` + +The client generates a hardware-backed, sign-only ECDSA P-256 key whose attestation challenge is `SHA-256(transcript bytes)`, and sends the key's certificate chain. The gateway follows Google's Key Attestation verification guidance: the chain ends at a pinned Google hardware attestation root, every signature verifies, no certificate appears on Google's attestation status list, and the attestation extension appears only in the leaf. From the attestation extension it requires TEE or StrongBox security levels, the challenge above, and, from the hardware-enforced list, an EC P-256 key generated in hardware for signing only, a locked bootloader, and a verified boot state (or a self-signed one whose boot key the gateway is configured to accept). The application id MUST name exactly the configured package and include an accepted signing certificate digest. The installation's key is the leaf's P-256 public key; its key id is `SHA-256` of the uncompressed SEC1 point. Success, replay idempotency, `409 installation_conflict`, and `404 not_authorized` follow the iOS rules above, with the attested public key and FCM token in place of the App Attest key and APNs token. + +A rejected chain is `401 invalid_attestation`. When the gateway cannot check a chain yet, because it has not fetched the attestation status list since starting or its newest list is older than the configured grace period, enrollment is `503 temporarily_unavailable` and spends nothing; the client keeps its key and replays the same request later. + +**Signed installation calls.** Delegation, endpoint rotation, and both revocations use the same routes, requests, transcripts, and challenge rules as iOS below. For an Android installation, the request's `assertion` member carries a padded standard-base64 DER ECDSA P-256 signature (Keystore `SHA256withECDSA`, at most 80 decoded bytes) over the exact transcript bytes, verified against the enrolled key. Either form of `s` is accepted. There is no counter; the single-use challenge inside the transcript is the replay protection. On endpoint rotation, `endpoint` is an FCM registration token as defined above. + ### Relay delegation and capability issuance `POST /v1/delegations`