Files
buzz/crates/buzz-push-gateway/src/http_android_tests.rs
Tom Brow 25b58ab98f feat(push-gateway): verify Android Key Attestation (#9562)
## What and why

Ticket 3 of the Android push plan ([design PR
#9555](https://github.com/block/buzz/pull/9555)). The gateway now
verifies Android Key Attestation at enrollment instead of rejecting
every Android chain, and rate limits signed installation calls per
attested key.

Stacked on [#9560](https://github.com/block/buzz/pull/9560) (Android
enrollment and FCM wakes). This PR's base is that branch; it will be
retargeted once that merges.

- **Chain.** It must end at a configured Google attestation root
(Google's [published hardware
roots](https://developer.android.com/privacy-and-security/security-key-attestation#root_certificate)
are built in, pinned by public key), with valid signatures and issuer
links, CA issuers above the attestation key certificate, and no SHA-1
signatures. The attestation key certificate itself is exempt from the CA
flags, because some factory keyboxes issue it with CA:FALSE and
digitalSignature only (Google's Sony Xperia 10 III sample); a Keystore
leaf still cannot act as an issuer, since the extension is refused above
the leaf. Validity is enforced for Remote Key Provisioning chains;
Google tells verifiers to keep trusting the long-expired factory chains,
which the revocation list covers instead. The attestation extension must
be in the leaf and nowhere else. The leaf key must be EC P-256; it
becomes the installation's signing key.
- **KeyDescription.** Attestation and KeyMint security levels must be
TrustedEnvironment or StrongBox. The challenge must equal SHA-256 of the
enrollment transcript. Key properties (generated, EC, P-256, sign-only)
and the root of trust come only from the hardware-enforced list. The
bootloader must be locked, and the boot state Verified, or SelfSigned
with a verified boot key on an operator-configured list. The application
id (the one software-enforced value) must name exactly the configured
package with a configured signing digest.
- **Revocation.** A background task fetches Google's status list at
startup and then on its cache lifetime (5 minutes to 1 day), with a 30
second timeout, an 8 MiB size cap, capped exponential backoff and
jitter. Any REVOKED or SUSPENDED serial in the chain is rejected. With
no list yet, or a list older than the grace period, enrollment fails
closed. Enrollment reads an in-memory snapshot and never waits on a
fetch.
- **Rate limit.** Signed installation calls (delegate, revoke
delegation, rotate endpoint, revoke installation, on both platforms) are
limited per attested key. A call is counted only after its signature
verifies, so forged requests cannot spend another installation's
allowance. Counters are in memory per replica, bounded to 100,000 keys.
- **Dependencies.** None added. `x509-parser` gains its `verify-aws`
feature, which uses the `aws-lc-rs` the crate already depends on.

## Configuration

All optional; Android stays off unless the ticket 2 settings are
present. Documented in `docs/push-gateway-deployment.md` and
`.env.example` with example values only, and passed through
`deploy/charts/buzz-push-gateway` (disabled by default, schema-checked,
covered by `tests/runtime-options.sh`).

- `BUZZ_PUSH_ANDROID_BOOT_KEY_DIGESTS`: SHA-256 digests of verified boot
keys accepted with a SelfSigned boot state. Empty by default, so a
default gateway accepts stock Android only.
- `BUZZ_PUSH_ANDROID_ATTESTATION_ROOTS_PATH`: PEM bundle replacing the
built-in roots, for a reviewed root rollout. In the chart,
`android.attestationRoots.secretName` and `secretKey` mount it from a
Secret; an empty name keeps the built-in roots.
- `BUZZ_PUSH_ANDROID_REVOCATION_GRACE_SECONDS`: default 604800 (7 days),
minimum 3600.
- `BUZZ_PUSH_SIGNED_CALL_WINDOW_SECONDS` and
`BUZZ_PUSH_SIGNED_CALL_MAX_CALLS`: defaults 60 and 30.

## Tests

- `cargo test -p buzz-push-gateway` (all pass, 18 ignored), `cargo fmt
--all --check`, `cargo clippy -p buzz-push-gateway --all-targets -- -D
warnings`, and the chart tests (`render.sh`, `release-contract.sh`).
- Key Attestation chains are generated in the tests with a test root
injected as the configured root, and run through the production
verifier. One table rejects: unlocked bootloader, Unverified, Failed,
SelfSigned with an unlisted key, boot key only in the software list (two
variants), key properties only in the software list, extra key purposes,
wrong curve, wrong package, two packages, wrong signing digest, wrong
challenge, software-backed key (two variants), unknown root, forged leaf
signature, expired provisioned intermediate, extension repeated above
the leaf, non-P-256 leaf, a CA:FALSE certificate issuing the attestation
key certificate. Another accepts Verified with any boot key, SelfSigned
with a listed key, StrongBox and TrustedEnvironment, an expired factory
intermediate, and a CA:FALSE, digitalSignature attestation key
certificate. Revoked leaf, intermediate and root, a missing list and a
stale list are rejected. The status list parser and refresh (backoff,
cap, keeping the last list through failures) run against a scripted fake
source; no test touches the network.
- The per-key rate limit runs through the public router: forged calls do
not spend the allowance, the fourth authentic call is refused whatever
its kind, and another installation is unaffected.
- Break check: disabling the locked-bootloader guard and the rate limit
turned `rejected_attestations` and the rate limit test red; restored.

## Not here

The app side (ticket 7) generates the Keystore key and sends the chain.
The end to end run on a physical Android phone against a test gateway is
also still to do.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
2026-11-17 19:18:35 -08:00

671 lines
22 KiB
Rust

//! Android installations through the public router: enrollment with the
//! test-only attestation verifier, Keystore-signed installation calls, and
//! delivery through a fake FCM sender. Transcripts are built with the
//! production types, so a drift in them fails here.
use super::*;
use crate::{
android_attestation::testing::TestAttestationVerifier,
authority::MemoryAuthorityStore,
grant::{GrantKey, GrantKeyring},
token::{TokenKey, TokenKeyring},
};
use axum::{body::Body, http::Request};
use nostr::{EventBuilder, Keys, Kind, Tag};
use p256::ecdsa::{signature::Signer, Signature, SigningKey};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::sync::Mutex;
use tower::ServiceExt;
const NOW: i64 = 1_750_000_000;
const FCM_TOKEN: &str = "cExample-token:APA91bExample_token-1";
const ROTATED_FCM_TOKEN: &str = "dExample-token:APA91bExample_token-2";
const DELIVERY_URL: &str = "https://push.example/v1/deliveries";
fn fixed_now() -> i64 {
NOW
}
/// Records every wake the gateway hands to the FCM boundary.
#[derive(Default)]
struct FakeFcm(Mutex<Vec<(String, DeliveryAttempt)>>);
#[async_trait::async_trait]
impl PushTransport for FakeFcm {
async fn send(&self, attempt: DeliveryAttempt, endpoint: &str) -> DeliveryOutcome {
self.0.lock().unwrap().push((endpoint.to_owned(), attempt));
DeliveryOutcome::Accepted
}
}
struct NeverApns;
#[async_trait::async_trait]
impl PushTransport for NeverApns {
async fn send(&self, _: DeliveryAttempt, _: &str) -> DeliveryOutcome {
panic!("an Android installation never reaches APNs")
}
}
struct Gateway {
app: Router,
fcm: Arc<FakeFcm>,
grant_keyring: Arc<GrantKeyring>,
}
fn gateway(with_android: bool) -> Gateway {
gateway_limited(with_android, 1_000)
}
fn gateway_limited(with_android: bool, 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());
let (app, _) = router(AppState {
grant_keyring: grant_keyring.clone(),
authority: Arc::new(MemoryAuthorityStore::default()),
token_keyring: Arc::new(
TokenKeyring::new(vec![TokenKey::new("test", &[2; 32]).unwrap()]).unwrap(),
),
application: Arc::new(ApplicationRuntime {
app_attest: Arc::new(
AppAttestVerifier::new(
"TEAMID.com.example.buzz".into(),
include_bytes!("../tests/fixtures/apple-app-attestation-root.pem").to_vec(),
)
.unwrap(),
),
transport: Arc::new(NeverApns),
android: with_android.then(|| AndroidRuntime {
attestation: Arc::new(TestAttestationVerifier),
transport: fcm.clone(),
}),
}),
max_grant_lifetime_seconds: 600,
max_installation_lifetime_seconds: 600,
endpoint_quota_window_seconds: 60,
endpoint_quota_max_deliveries: 10,
signed_calls: Arc::new(crate::signed_call_limiter::SignedCallLimiter::new(
60,
signed_calls_per_window,
)),
now: fixed_now,
accepting: Arc::new(AtomicBool::new(true)),
});
Gateway {
app,
fcm,
grant_keyring,
}
}
async fn post(app: &Router, path: &str, body: &Value) -> (StatusCode, Value) {
let response = app
.clone()
.oneshot(
Request::post(path)
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(body).unwrap()))
.unwrap(),
)
.await
.unwrap();
let status = response.status();
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
(
status,
serde_json::from_slice(&bytes).unwrap_or(Value::Null),
)
}
/// One issued enrollment challenge.
struct Challenge {
id: uuid::Uuid,
text: String,
}
async fn challenge(app: &Router) -> Challenge {
let (status, body) = post(app, "/v1/installations/challenges", &json!({"v": 1})).await;
assert_eq!(status, StatusCode::OK);
Challenge {
id: body["challenge_id"].as_str().unwrap().parse().unwrap(),
text: body["challenge"].as_str().unwrap().to_owned(),
}
}
/// The phone: an attested Keystore key.
struct Phone {
key: SigningKey,
}
impl Phone {
fn new(seed: u8) -> Self {
Self {
key: SigningKey::from_slice(&[seed; 32]).unwrap(),
}
}
fn public_key(&self) -> Vec<u8> {
self.key
.verifying_key()
.to_sec1_point(false)
.as_ref()
.to_vec()
}
fn key_id(&self) -> String {
STANDARD.encode(Sha256::digest(self.public_key()))
}
/// A signature over `transcript`, as Keystore's SHA256withECDSA makes one.
fn sign(&self, transcript: &str) -> String {
let signature: Signature = self.key.sign(transcript.as_bytes());
STANDARD.encode(signature.to_der().as_bytes())
}
/// The test verifier's chain: the key and the attested challenge.
fn chain(&self, transcript: &str) -> Vec<String> {
vec![
STANDARD.encode(self.public_key()),
STANDARD.encode(Sha256::digest(transcript.as_bytes())),
]
}
}
/// The transcript whose digest the phone uses as the attestation challenge.
/// It takes no key: a Keystore key is generated from this digest.
fn enroll_transcript(ch: &Challenge, endpoint: &str) -> String {
transcript(
ANDROID_ENROLL_DOMAIN,
&AndroidEnrollTranscript {
v: 1,
audience: ENROLL_AUDIENCE,
challenge_id: ch.id,
challenge: &ch.text,
endpoint,
endpoint_epoch: 1,
expires_at: NOW + 600,
},
)
.unwrap()
}
fn enroll_body(phone: &Phone, ch: &Challenge, endpoint: &str) -> Value {
json!({
"v": 1, "challenge_id": ch.id, "challenge": ch.text,
"android_attestation": phone.chain(&enroll_transcript(ch, endpoint)),
"endpoint": endpoint, "endpoint_epoch": 1, "expires_at": NOW + 600,
})
}
async fn enroll(g: &Gateway, phone: &Phone) -> uuid::Uuid {
let ch = challenge(&g.app).await;
let (status, body) = post(
&g.app,
"/v1/installations",
&enroll_body(phone, &ch, FCM_TOKEN),
)
.await;
assert_eq!(status, StatusCode::CREATED, "{body}");
body["installation_handle"]
.as_str()
.unwrap()
.parse()
.unwrap()
}
/// An installation call after enrollment.
#[derive(Clone)]
enum Call {
Delegate {
relay: String,
epoch: i64,
generation: i64,
},
Rotate {
epoch: i64,
endpoint: &'static str,
},
RevokeDelegation {
relay: String,
generation: i64,
},
RevokeInstallation {
epoch: i64,
},
}
/// The route, the request fields before `assertion`, and the exact transcript
/// the call's assertion signs.
fn prepare(call: &Call, handle: uuid::Uuid, ch: &Challenge) -> (&'static str, Value, String) {
let common = |extra: Value| {
let mut body = json!({
"v": 1, "challenge_id": ch.id, "challenge": ch.text, "installation_handle": handle,
});
body.as_object_mut()
.unwrap()
.extend(extra.as_object().unwrap().clone());
body
};
match call {
Call::Delegate {
relay,
epoch,
generation,
} => (
"/v1/delegations",
common(
json!({"endpoint_epoch": epoch, "generation": generation, "relay_pubkey": relay,
"not_before": NOW, "expires_at": NOW + 300}),
),
transcript(
"buzz.push.delegate.v1",
&DelegateTranscript {
v: 1,
audience: DELEGATE_AUDIENCE,
challenge_id: ch.id,
challenge: &ch.text,
installation_handle: handle,
endpoint_epoch: *epoch,
generation: *generation,
relay_pubkey: relay,
not_before: NOW,
expires_at: NOW + 300,
},
)
.unwrap(),
),
Call::Rotate { epoch, endpoint } => (
"/v1/installations/endpoint",
common(
json!({"endpoint_epoch": epoch, "new_endpoint_epoch": epoch + 1, "endpoint": endpoint}),
),
transcript(
"buzz.push.rotate-endpoint.v1",
&RotateTranscript {
v: 1,
audience: ROTATE_ENDPOINT_AUDIENCE,
challenge_id: ch.id,
challenge: &ch.text,
installation_handle: handle,
endpoint_epoch: *epoch,
new_endpoint_epoch: epoch + 1,
endpoint,
},
)
.unwrap(),
),
Call::RevokeDelegation { relay, generation } => (
"/v1/delegations/revoke",
common(json!({"relay_pubkey": relay, "generation": generation})),
transcript(
"buzz.push.revoke-delegation.v1",
&RevokeDelegationTranscript {
v: 1,
audience: REVOKE_DELEGATION_AUDIENCE,
challenge_id: ch.id,
challenge: &ch.text,
installation_handle: handle,
relay_pubkey: relay,
generation: *generation,
},
)
.unwrap(),
),
Call::RevokeInstallation { epoch } => (
"/v1/installations/revoke",
common(json!({"endpoint_epoch": epoch, "new_endpoint_epoch": epoch + 1})),
transcript(
"buzz.push.revoke-installation.v1",
&RevokeInstallationTranscript {
v: 1,
audience: REVOKE_INSTALLATION_AUDIENCE,
challenge_id: ch.id,
challenge: &ch.text,
installation_handle: handle,
endpoint_epoch: *epoch,
new_endpoint_epoch: epoch + 1,
},
)
.unwrap(),
),
}
}
/// Send `call` with a fresh challenge, signed by `signer` over the transcript
/// of `signed_call` (the same call unless a test alters it).
async fn send_call(
g: &Gateway,
handle: uuid::Uuid,
call: &Call,
signed_call: &Call,
signer: &Phone,
) -> (StatusCode, Value) {
let ch = challenge(&g.app).await;
let (path, mut body, _) = prepare(call, handle, &ch);
let (_, _, signed) = prepare(signed_call, handle, &ch);
body["assertion"] = signer.sign(&signed).into();
post(&g.app, path, &body).await
}
async fn call_ok(g: &Gateway, handle: uuid::Uuid, call: &Call, phone: &Phone) -> Value {
let (status, body) = send_call(g, handle, call, call, phone).await;
assert!(status.is_success(), "{status} {body}");
body
}
async fn deliver_wake(g: &Gateway, relay: &Keys, grant: &str) -> StatusCode {
let body = serde_json::to_vec(&json!({
"v": 1, "endpoint_grant": grant, "request_id": uuid::Uuid::new_v4(), "expires_at": NOW + 60,
}))
.unwrap();
let event = EventBuilder::new(Kind::HttpAuth, "")
.tags([
Tag::parse(["u", DELIVERY_URL]).unwrap(),
Tag::parse(["method", "POST"]).unwrap(),
Tag::parse(["payload", &hex::encode(Sha256::digest(&body))]).unwrap(),
])
.sign_with_keys(relay)
.unwrap();
let auth = format!(
"Nostr {}",
STANDARD.encode(serde_json::to_vec(&event).unwrap())
);
g.app
.clone()
.oneshot(
Request::post(DELIVERY_PATH)
.header("authorization", auth)
.body(Body::from(body))
.unwrap(),
)
.await
.unwrap()
.status()
}
fn sent_tokens(g: &Gateway) -> Vec<String> {
g.fcm
.0
.lock()
.unwrap()
.iter()
.map(|(t, _)| t.clone())
.collect()
}
#[tokio::test]
async fn android_installation_journey() {
let g = gateway(true);
let phone = Phone::new(7);
let relay = Keys::generate();
let relay_hex = relay.public_key().to_hex();
let handle = enroll(&g, &phone).await;
let delegate = |epoch, generation| Call::Delegate {
relay: relay_hex.clone(),
epoch,
generation,
};
let grant = call_ok(&g, handle, &delegate(1, 1), &phone).await["endpoint_grant"]
.as_str()
.unwrap()
.to_owned();
// The grant the relay stores names no platform.
let opened = g.grant_keyring.open(&grant).unwrap();
assert!(!serde_json::to_string(&opened)
.unwrap()
.to_lowercase()
.contains("android"));
assert_eq!(deliver_wake(&g, &relay, &grant).await, StatusCode::OK);
assert_eq!(sent_tokens(&g), [FCM_TOKEN]);
// The wake expires with the delivery request.
assert_eq!(g.fcm.0.lock().unwrap()[0].1.expires_at, NOW + 60);
// Rotating the endpoint retires the epoch-1 grant; the relay's renewed
// delegation wakes the new token.
let rotate = Call::Rotate {
epoch: 1,
endpoint: ROTATED_FCM_TOKEN,
};
call_ok(&g, handle, &rotate, &phone).await;
assert_eq!(
deliver_wake(&g, &relay, &grant).await,
StatusCode::NOT_FOUND
);
let renewed = call_ok(&g, handle, &delegate(2, 2), &phone).await["endpoint_grant"]
.as_str()
.unwrap()
.to_owned();
assert_eq!(deliver_wake(&g, &relay, &renewed).await, StatusCode::OK);
assert_eq!(sent_tokens(&g), [FCM_TOKEN, ROTATED_FCM_TOKEN]);
// Revoking the delegation stops wakes; revoking the installation ends it.
let revoke_delegation = Call::RevokeDelegation {
relay: relay_hex.clone(),
generation: 2,
};
call_ok(&g, handle, &revoke_delegation, &phone).await;
assert_eq!(
deliver_wake(&g, &relay, &renewed).await,
StatusCode::NOT_FOUND
);
call_ok(&g, handle, &Call::RevokeInstallation { epoch: 2 }, &phone).await;
let (status, _) = send_call(&g, handle, &delegate(2, 3), &delegate(2, 3), &phone).await;
assert_eq!(status, StatusCode::NOT_FOUND);
assert_eq!(sent_tokens(&g), [FCM_TOKEN, ROTATED_FCM_TOKEN]);
}
#[tokio::test]
async fn android_signed_calls_reject_wrong_key_altered_transcript_and_reused_challenge() {
let g = gateway(true);
let (phone, other) = (Phone::new(7), Phone::new(9));
let relay = "aa".repeat(32);
let handle = enroll(&g, &phone).await;
let delegate = |generation| Call::Delegate {
relay: relay.clone(),
epoch: 1,
generation,
};
// Each call, and a different call of the same kind whose transcript is
// signed instead.
let rows = [
(delegate(1), delegate(2)),
(
Call::Rotate {
epoch: 1,
endpoint: ROTATED_FCM_TOKEN,
},
Call::Rotate {
epoch: 1,
endpoint: "eExample-other:token",
},
),
(
Call::RevokeDelegation {
relay: relay.clone(),
generation: 1,
},
Call::RevokeDelegation {
relay: relay.clone(),
generation: 2,
},
),
(
Call::RevokeInstallation { epoch: 1 },
Call::RevokeInstallation { epoch: 5 },
),
];
for (call, altered) in &rows {
// Signed by a key other than the one attested at enrollment.
let (status, _) = send_call(&g, handle, call, call, &other).await;
assert_eq!(status, StatusCode::UNAUTHORIZED, "wrong key");
// The right key, over a transcript that is not the request's.
let (status, _) = send_call(&g, handle, call, altered, &phone).await;
assert_eq!(status, StatusCode::UNAUTHORIZED, "altered transcript");
// An assertion in the iOS format is not an Android signature.
let ch = challenge(&g.app).await;
let (path, mut body, _) = prepare(call, handle, &ch);
body["assertion"] = STANDARD.encode(b"\xa2\x6fauthenticatorData").into();
assert_eq!(post(&g.app, path, &body).await.0, StatusCode::UNAUTHORIZED);
}
// None of the rejections changed the installation or used up the key.
let ch = challenge(&g.app).await;
let (path, mut body, signed) = prepare(&delegate(1), handle, &ch);
body["assertion"] = phone.sign(&signed).into();
assert_eq!(post(&g.app, path, &body).await.0, StatusCode::CREATED);
// Replaying the identical signed request fails: the challenge is single use.
assert_eq!(post(&g.app, path, &body).await.0, StatusCode::NOT_FOUND);
// A fresh signature over a new transcript but the consumed challenge fails too.
let mut resigned = body.clone();
resigned["generation"] = 2.into();
let (_, _, signed) = prepare(
&delegate(2),
handle,
&Challenge {
id: ch.id,
text: ch.text.clone(),
},
);
resigned["assertion"] = phone.sign(&signed).into();
assert_eq!(post(&g.app, path, &resigned).await.0, StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn android_enrollment_derives_platform_from_the_attestation_and_rejects_bad_ones() {
let g = gateway(true);
let phone = Phone::new(7);
let enroll_status = |g: &Gateway, body: Value| {
let app = g.app.clone();
async move { post(&app, "/v1/installations", &body).await.0 }
};
let ch = challenge(&g.app).await;
let good = enroll_body(&phone, &ch, FCM_TOKEN);
// Exactly one attestation must be present.
let mut both = good.clone();
both["attestation"] = STANDARD.encode(b"x").into();
let mut neither = good.clone();
neither
.as_object_mut()
.unwrap()
.remove("android_attestation");
for body in [both, neither] {
assert_eq!(enroll_status(&g, body).await, StatusCode::BAD_REQUEST);
}
// A gateway without Android configuration accepts no Android enrollment.
let plain = gateway(false);
let plain_ch = challenge(&plain.app).await;
let status = enroll_status(&plain, enroll_body(&phone, &plain_ch, FCM_TOKEN)).await;
assert_eq!(status, StatusCode::BAD_REQUEST);
// FCM tokens are opaque ASCII, not hex, and bounded.
for endpoint in [
"",
"has space",
"bad/char",
&"a".repeat(MAX_FCM_TOKEN_BYTES + 1),
] {
let mut body = good.clone();
body["endpoint"] = endpoint.into();
assert_eq!(
enroll_status(&g, body).await,
StatusCode::BAD_REQUEST,
"{endpoint}"
);
}
// The gateway derives the key id from the attested key, so an Android
// enrollment carries none.
let mut with_key_id = good.clone();
with_key_id["key_id"] = phone.key_id().into();
assert_eq!(
enroll_status(&g, with_key_id).await,
StatusCode::BAD_REQUEST
);
// The attestation must bind this exact transcript, prove an uncompressed
// P-256 point and stay within the chain bounds.
let other_transcript = enroll_transcript(&ch, ROTATED_FCM_TOKEN);
let mut wrong_binding = good.clone();
wrong_binding["android_attestation"] = phone.chain(&other_transcript).into();
let mut not_a_point = good.clone();
not_a_point["android_attestation"] = json!([
STANDARD.encode([4u8; 65]),
STANDARD.encode(Sha256::digest(enroll_transcript(&ch, FCM_TOKEN).as_bytes())),
]);
// One key has one id: the same key as a compressed point would get a
// second id, and a second rate-limit bucket.
let mut compressed = good.clone();
compressed["android_attestation"] = json!([
STANDARD.encode(phone.key.verifying_key().to_sec1_point(true).as_ref()),
STANDARD.encode(Sha256::digest(enroll_transcript(&ch, FCM_TOKEN).as_bytes())),
]);
let mut long_chain = good.clone();
long_chain["android_attestation"] =
vec![STANDARD.encode(b"c"); MAX_ANDROID_CHAIN_CERTIFICATES + 1].into();
for body in [wrong_binding, not_a_point, compressed, long_chain] {
assert_eq!(enroll_status(&g, body).await, StatusCode::UNAUTHORIZED);
}
// The accepted enrollment, and its exact replay after a lost response,
// name one installation.
let first = post(&g.app, "/v1/installations", &good).await;
let replay = post(&g.app, "/v1/installations", &good).await;
assert_eq!(
(first.0, replay.0),
(StatusCode::CREATED, StatusCode::CREATED)
);
assert_eq!(
first.1["installation_handle"],
replay.1["installation_handle"]
);
}
#[tokio::test]
async fn signed_installation_calls_are_limited_per_attested_key() {
let g = gateway_limited(true, 3);
let (phone, other, forger) = (Phone::new(7), Phone::new(8), Phone::new(9));
let relay = "aa".repeat(32);
let handle = enroll(&g, &phone).await;
let delegate = |generation| Call::Delegate {
relay: relay.clone(),
epoch: 1,
generation,
};
let revoke = Call::RevokeDelegation {
relay: relay.clone(),
generation: 1,
};
// Forged calls fail authentication before they are counted, so they
// cannot spend the installation's allowance.
for _ in 0..5 {
let (status, _) = send_call(&g, handle, &delegate(1), &delegate(1), &forger).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
}
call_ok(&g, handle, &delegate(1), &phone).await;
call_ok(&g, handle, &revoke, &phone).await;
call_ok(&g, handle, &delegate(2), &phone).await;
// The fourth authentic call in the window is refused, whichever kind.
for call in [Call::RevokeInstallation { epoch: 1 }, delegate(3)] {
let (status, body) = send_call(&g, handle, &call, &call, &phone).await;
assert_eq!(status, StatusCode::TOO_MANY_REQUESTS, "{body}");
}
// Another installation has its own allowance.
let other_handle = {
let ch = challenge(&g.app).await;
let (status, body) = post(
&g.app,
"/v1/installations",
&enroll_body(&other, &ch, ROTATED_FCM_TOKEN),
)
.await;
assert_eq!(status, StatusCode::CREATED, "{body}");
body["installation_handle"]
.as_str()
.unwrap()
.parse()
.unwrap()
};
call_ok(&g, other_handle, &delegate(1), &other).await;
}