mirror of
https://github.com/block/buzz.git
synced 2026-11-28 04:01:45 +00:00
fix(push-gateway): keep Android enrollment retryable across replay races and restarts (#9893)
Follow-up to [#9811 enroll Android devices for push](https://github.com/block/buzz/pull/9811), covering the gateway side of its non-blocking review comments. Two enrollment states could make an Android phone discard a key its committed installation still holds, after which its fresh enrollment hits `409 installation_conflict` for the installation's whole lifetime (up to about 30 days of no push). Both now answer in a way the client already treats as "keep the key and retry". - **Enrollment replay racing the original request** ([review comment](https://github.com/block/buzz/pull/9811#discussion_r4648232889)). Enrollment consumed its challenge in one statement and created the installation in another. A client that timed out between them and replayed the same signed request found a spent challenge and no installation, and got `404 not_authorized`. Consuming the challenge and creating the installation are now one transaction. A concurrent replay locks the challenge row before judging its expiry, so it waits even when the challenge expires meanwhile, then returns the installation the first request committed, or enrolls itself if that request rolled back or was cancelled. A request that finds its challenge expired deletes it before answering `404`, so a slower request that read its clock earlier cannot spend it afterwards. A refused creation (`409`) also leaves the challenge unspent. - **Enrollment before the attestation status list loads.** A restarted gateway has no status list until its first refresh (and a list past its grace period is equally unusable), so every Android chain was refused with `401 invalid_attestation`, which the client treats as final. The verifier now reports a missing or stale list as unavailable, and enrollment answers `503 temporarily_unavailable` before spending anything. A listed certificate is still refused. - **NIP-PL** now specifies Android enrollment: the `android_attestation` chain and FCM token request, the `buzz.push.enroll.android.v1` transcript whose SHA-256 is the Keystore attestation challenge, what the gateway checks in the chain, and the SHA256withECDSA signature Android installation calls carry in `assertion`. It also records the two behaviors above, corrects the enrollment body ceiling for the Android chain allowance, names the transcript separator as one LF byte, and says a client stores its installation handle before delegating (replay recovery ends once a delegation extends the installation's expiry). ### Validation Added tests: - [`enrollment_replay_waits_for_an_uncommitted_enrollment`](61c7ef2480/crates/buzz-push-gateway/src/postgres.rs) (PostgreSQL): stages an enrollment whose challenge is spent but whose installation is uncommitted, starts an exact replay, and waits until PostgreSQL shows the replay blocked on it, then checks that the replay recovers the original installation after commit or enrolls itself after rollback, both inside and past the challenge's expiry. `expired_replay_first_retires_the_challenge` and `refused_enrollment_leaves_its_challenge_unspent` cover the other arrival order and the `409` case. - [`enrollment_replay_of_a_spent_challenge_recovers_the_installation_that_spent_it` and `refused_enrollment_leaves_its_challenge_unspent`, `expired_replay_first_retires_the_challenge`](61c7ef2480/crates/buzz-push-gateway/src/authority.rs): the same contract on the in-memory reference store. - [`enrollment_waits_out_a_missing_revocation_list_without_spending_anything`](61c7ef2480/crates/buzz-push-gateway/src/http_android_tests.rs): through the router, a fresh enrollment and a lost-response replay both get `503` while the list is missing, then `201` with the same handle once it loads. - [`the_trait_defers_rather_than_rejects_without_a_fresh_list`](61c7ef2480/crates/buzz-push-gateway/src/android_attestation/key_attestation_tests.rs): the production verifier reports a missing or stale list as unavailable and a listed certificate as invalid. ### Regressions - Enrollment holds one transaction across the challenge delete and the installation insert instead of two short ones. The insert already ran in a transaction with row locks; the only added wait is a replay of the same challenge, which previously failed. - A refused enrollment no longer burns its challenge. The challenge stays single-use for success and still expires after 300 seconds; replaying a refused request only gets the same refusal. - While the status list is missing or stale, Android enrollment answers `503` instead of `401`. Nothing is admitted that wasn't before; clients retry instead of giving up. iOS enrollment and signed calls are unchanged. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
This commit is contained in:
@@ -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:
|
||||
|
||||
```
|
||||
<domain> + "\\n" + <compact ordered JSON object>
|
||||
<domain> || 0x0a || <compact ordered JSON object>
|
||||
```
|
||||
|
||||
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":"<uuid>","endpoint_epoch":1,"expires_at":<unix-seconds>}
|
||||
```
|
||||
|
||||
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":"<uuid>","challenge":"<challenge>","android_attestation":["<standard-base64 DER certificate>", ...],"endpoint":"<FCM registration token>","endpoint_epoch":1,"expires_at":<unix-seconds>}
|
||||
```
|
||||
|
||||
`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":"<uuid>","challenge":"<challenge>","endpoint":"<FCM registration token>","endpoint_epoch":1,"expires_at":<unix-seconds>}
|
||||
```
|
||||
|
||||
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`
|
||||
|
||||
Reference in New Issue
Block a user