Files
buzz/crates/buzz-push-gateway/src/model.rs
Tom Brow 6b4a398829 feat(push-gateway): enroll Android installations and send FCM wakes (#9560)
## What and why

Ticket 2 of the Android push plan ([design PR
#9555](https://github.com/block/buzz/pull/9555)). The gateway now
enrolls Android installations and wakes them through FCM, next to the
existing iOS path.

Builds on [#9557](https://github.com/block/buzz/pull/9557)
(platform-neutral `/v1/deliveries` route), now merged.

- **Platform.** The enrollment request has no platform field. The
gateway derives it from which attestation is present (App Attest object
or Android attestation chain) and records it in a new
`push_gateway_installations.platform` column (`ios` or `android`). It
lives only in gateway state; the relay never sees it.
- **Android enrollment transcript.** Key Attestation fixes the challenge
at key generation, so the client signs nothing at enrollment and sends
no `key_id`. The attestation challenge must equal SHA-256 of a canonical
JSON transcript under domain `buzz.push.enroll.android.v1` with `v`,
`audience`, `challenge_id`, `challenge`, `endpoint`, `endpoint_epoch`
and `expires_at`. The gateway derives the key id as SHA-256 of the
attested 65-byte uncompressed P-256 key. A request whose `key_id`
presence doesn't match its platform gets 400. The iOS transcript
(`buzz.push.enroll.v1`) is unchanged.
- **Signed calls.** iOS keeps App Attest assertions. After enrollment,
an Android installation signs every call (delegate, revoke delegation,
rotate endpoint, revoke installation) with its attested Keystore key:
ECDSA P-256, DER, over the same transcript bytes iOS signs. High-S
signatures are accepted since Keystore does not normalize. There is no
counter; the single-use challenge inside the transcript is the replay
protection.
- **FCM sender.** HTTP v1, high priority, data-only, compiled-in payload
(no relay-supplied bytes), one constant collapse key, TTL from the
delivery expiry. OAuth access tokens come from the service account key
(RS256 JWT bearer). Outcomes map onto the existing delivery outcome
classes and metrics (`push_gateway_fcm_*`).
- **Token refresh.** A cached token keeps serving until it expires. Once
it is due for refresh, one background task fetches a new one, so a wake
never waits on a refresh while a valid token exists. A failed fetch
keeps the current token and backs off 5 s before the next attempt. Only
a cold cache (no unexpired token) makes a wake wait on the token
request, single-flighted. A 401 discards the cached token only if it is
still the one FCM refused, so a late 401 can't drop a newer token.
- **Retries.** 429 and `QUOTA_EXCEEDED` retry after at least 60 s (FCM's
hint if longer). 500, 502, 503 and 504 retry.
- **Attestation seam.** Android Key Attestation verification sits behind
a trait. Tests use a test-only verifier compiled under `cfg(test)`, so
production configuration cannot select it. The production verifier fails
closed: a gateway configured for Android starts but rejects every
Android enrollment until ticket 3.
- **Migration.** Expand-only `ADD COLUMN platform TEXT NOT NULL DEFAULT
'ios' CHECK (...)`: the deployed gateway's inserts stay valid and
existing rows become iOS. `SET LOCAL lock_timeout` (5 s) and
`statement_timeout` (30 s) bound the table lock wait and the CHECK
validation scan. No triggers, functions, foreign keys or backfills.
Mirrored as gateway `0007` and relay `0093` plus `schema/tables/public`,
per docs/database.md.

## Configuration

All four are optional and must be supplied together (a partial set fails
startup). Documented in `docs/push-gateway-deployment.md` and
`.env.example` with example values only.

- `BUZZ_PUSH_ANDROID_PACKAGE_NAME`
- `BUZZ_PUSH_ANDROID_SIGNING_CERT_DIGESTS`
- `BUZZ_PUSH_FCM_PROJECT_ID`
- `BUZZ_PUSH_FCM_SERVICE_ACCOUNT_PATH`

## Tests

- `cargo test -p buzz-push-gateway` (92 passed, 18 ignored; 94 passed
with `personal-dev-app-attest`; iOS rows unchanged), `cargo fmt
--check`, `cargo clippy -p buzz-push-gateway -p buzz-db --all-targets --
-D warnings`.
- New HTTP tests with a fake FCM sender: Android enroll, delegate,
deliver, rotate endpoint and revoke; signed-call rows for wrong key,
altered transcript and reused challenge; platform derivation and bad
attestations.
- Postgres (ignored, run locally): gateway migration test (existing and
old-gateway inserts become `ios`, bad value rejected); relay
`admin_schema_parity_between_desired_state_and_migrations` now covers
`push_gateway_installations` columns, indexes and constraints; the
`runtime::migration::postgres_tests` set passes single-threaded.
- Break check: making signature verification always succeed turned two
tests red (the signed-call rejection rows and the signature unit test);
restored.
- Token cache tests against a local fake token endpoint with a
controlled clock: a due refresh keeps serving the valid token even when
it fails; a late 401 does not discard a refreshed token; a queued
background refresh honors a foreground failure's backoff. The FCM
response table covers 429 with and without an error body, and 502/504
HTML pages.
- Android enrollment rows: `key_id` present on Android (400), wrong
transcript binding, a 65-byte non-point key, an over-long chain, and
exact replay.
- Break checks for every new guard (no background refresh, blocking
while due, failure dropping the token, unconditional 401 clear, no quota
floor, no 502/504 retry, the queued-refresh backoff check, Android
requiring `key_id`, skipping the P-256 point check): each turned at
least one test red; restored.

## Not here (ticket 3)

Real Key Attestation verification (Google roots, revocation list, boot
state, boot-key list, app identity). Per-key rate limiting is also left
for ticket 3, since it did not fall out of this change. The Helm chart
does not pass the Android settings yet.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
2026-11-17 10:11:17 -07:00

185 lines
6.3 KiB
Rust

//! Closed wire types for the stateful gateway.
use serde::{Deserialize, Serialize};
pub const MAX_REQUEST_BYTES: usize = 8 * 1024;
/// Maximum decoded Apple App Attest object accepted by the verifier.
pub const MAX_APP_ATTESTATION_BYTES: usize = 16 * 1024;
/// Enrollment carries the maximum App Attest object as standard base64 plus a
/// bounded APNs endpoint and the closed JSON envelope. Other gateway requests
/// remain subject to `MAX_REQUEST_BYTES`.
pub const MAX_ENROLL_REQUEST_BYTES: usize = MAX_APP_ATTESTATION_BYTES.div_ceil(3) * 4
+ MAX_ENDPOINT_HEX_BYTES * 2
+ MAX_ANDROID_CHAIN_CERTIFICATES * 8
+ 1024;
pub const MAX_GRANT_BYTES: usize = 4096;
pub const MAX_ENDPOINT_HEX_BYTES: usize = 512;
/// Maximum FCM registration token length. It shares the token-custody limit
/// (`MAX_ENDPOINT_HEX_BYTES` plaintext bytes), well above real tokens.
pub const MAX_FCM_TOKEN_BYTES: usize = MAX_ENDPOINT_HEX_BYTES;
/// Maximum certificates in an Android Key Attestation chain.
pub const MAX_ANDROID_CHAIN_CERTIFICATES: usize = 8;
/// Maximum decoded size of a whole Android attestation chain, matching the App
/// Attest object limit.
pub const MAX_ANDROID_ATTESTATION_BYTES: usize = MAX_APP_ATTESTATION_BYTES;
/// Maximum decoded ECDSA P-256 DER signature accepted from an Android key.
pub const MAX_ANDROID_SIGNATURE_BYTES: usize = 80;
pub const APNS_RECONNECT_PAYLOAD: &[u8] =
br#"{"aps":{"alert":{"body":"Reconnect to your relay now"},"sound":"default","mutable-content":1}}"#;
pub const WIRE_VERSION: u8 = 1;
/// Relay request. It deliberately has no application-payload field:
/// the gateway emits one compiled-in APNs reconnect payload for every delivery.
/// `endpoint_grant` is opaque authenticated ciphertext minted by the gateway
/// sealing key and persisted with the relay-owned lease.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DeliveryRequest {
pub v: u8,
pub endpoint_grant: String,
pub request_id: uuid::Uuid,
pub expires_at: i64,
}
/// Opaque delivery capability plaintext. It contains no APNs token: the random
/// delegation id resolves through durable authority state, while the remaining
/// fields are authenticated fences that make stale or cross-relay use fail.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EndpointGrant {
pub v: u8,
pub delegation_id: uuid::Uuid,
pub relay_pubkey: String,
pub endpoint_epoch: i64,
pub generation: i64,
pub expires_at: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InstallationChallengeRequest {
pub v: u8,
}
#[derive(Debug, Clone, Serialize)]
pub struct InstallationChallengeResponse {
pub challenge_id: uuid::Uuid,
pub challenge: String,
pub expires_at: i64,
}
/// Direct app enrollment. It carries exactly one attestation, and the gateway
/// derives the installation's platform from which one is present; there is no
/// platform field. `attestation` is Apple's App Attest CBOR object. `android_attestation`
/// is a Key Attestation certificate chain, leaf first, of base64 DER
/// certificates. `key_id` is the App Attest key identifier, required on iOS
/// and absent on Android: a Keystore key is generated from the attestation
/// challenge, so its id cannot be in the transcript that challenge binds, and
/// the gateway takes it as the SHA-256 of the attested public key. The attested key is
/// the installation authority; no second application signing key is introduced.
/// `endpoint` is a lowercase-hex APNs token on iOS and an FCM registration
/// token on Android.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InstallationEnrollRequest {
pub v: u8,
pub challenge_id: uuid::Uuid,
pub challenge: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attestation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub android_attestation: Option<Vec<String>>,
pub endpoint: String,
pub endpoint_epoch: i64,
pub expires_at: i64,
}
#[derive(Debug, Clone, Serialize)]
pub struct InstallationEnrollResponse {
pub installation_handle: uuid::Uuid,
pub endpoint_epoch: i64,
pub expires_at: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DelegationRequest {
pub v: u8,
pub challenge_id: uuid::Uuid,
pub challenge: String,
pub installation_handle: uuid::Uuid,
pub endpoint_epoch: i64,
pub generation: i64,
pub relay_pubkey: String,
pub not_before: i64,
pub expires_at: i64,
pub assertion: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct DelegationResponse {
pub endpoint_grant: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RotateEndpointRequest {
pub v: u8,
pub challenge_id: uuid::Uuid,
pub challenge: String,
pub installation_handle: uuid::Uuid,
pub endpoint_epoch: i64,
pub new_endpoint_epoch: i64,
pub endpoint: String,
pub assertion: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RevokeDelegationRequest {
pub v: u8,
pub challenge_id: uuid::Uuid,
pub challenge: String,
pub installation_handle: uuid::Uuid,
pub relay_pubkey: String,
pub generation: i64,
pub assertion: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RevokeInstallationRequest {
pub v: u8,
pub challenge_id: uuid::Uuid,
pub challenge: String,
pub installation_handle: uuid::Uuid,
pub endpoint_epoch: i64,
pub new_endpoint_epoch: i64,
pub assertion: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct MutationResponse {
pub status: &'static str,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "status", deny_unknown_fields)]
pub enum DeliveryResponse {
Accepted,
InvalidEndpoint {
generation: i64,
invalid_at: Option<i64>,
},
Retry {
retry_after_seconds: Option<i64>,
},
}
#[derive(Debug, Clone, Serialize)]
pub struct ErrorBody {
pub error: &'static str,
}