Files
buzz/crates/buzz-push-gateway/src/http_android_tests.rs
Tom Brow 309f5827b1 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>
2026-11-24 22:24:53 -08:00

733 lines
25 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 {
gateway_with(
with_android.then(|| Arc::new(TestAttestationVerifier) as _),
signed_calls_per_window,
)
}
fn gateway_with(
attestation: Option<Arc<dyn AndroidAttestationVerifier>>,
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: attestation.map(|attestation| AndroidRuntime {
attestation,
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;
}
/// 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<u8>],
client_data: &[u8],
) -> Result<crate::android_attestation::VerifiedAndroidKey, AndroidAttestationError> {
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"]
);
}