Files
buzz/crates/buzz-push-gateway/src/authority.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

1259 lines
42 KiB
Rust

//! Durable installation authority and relay delegation state machine.
//!
//! App Attest authenticates the app instance and exact request transcript. It
//! does not prove an Apple-issued binding between that key and the APNs token;
//! accepting the directly submitted token is the protocol's explicit bootstrap
//! assumption.
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::Mutex;
use thiserror::Error;
use uuid::Uuid;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Challenge {
pub id: Uuid,
pub value: [u8; 32],
pub created_at: i64,
pub expires_at: i64,
}
/// Challenge issuance is intentionally bounded inside the durable authority
/// store so the public unauthenticated route cannot amplify database writes
/// across gateway replicas.
pub(crate) const CHALLENGE_QUOTA_WINDOW_SECONDS: i64 = 60;
pub(crate) const CHALLENGE_QUOTA_MAX_REQUESTS: usize = 600;
/// The platform whose push service wakes an installation. It lives only in
/// gateway state: it is derived from the enrollment attestation type and never
/// appears in a grant, a lease, or any relay-visible value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Platform {
Ios,
Android,
}
impl Platform {
/// The value stored in `push_gateway_installations.platform`.
pub fn as_str(self) -> &'static str {
match self {
Platform::Ios => "ios",
Platform::Android => "android",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value {
"ios" => Some(Platform::Ios),
"android" => Some(Platform::Android),
_ => None,
}
}
}
/// `app_attest_key_id` and `app_attest_public_key` hold the attested key's
/// identifier and SEC1 public key on both platforms (the column names predate
/// Android). `assertion_counter` only advances for iOS: Keystore keys have no
/// signature counter.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NewInstallation {
pub id: Uuid,
pub platform: Platform,
pub app_attest_key_id: Vec<u8>,
pub app_attest_public_key: Vec<u8>,
pub assertion_counter: u32,
pub token_ciphertext: Vec<u8>,
pub token_fingerprint: [u8; 32],
pub endpoint_epoch: i64,
pub expires_at: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Installation {
pub id: Uuid,
pub platform: Platform,
pub app_attest_key_id: Vec<u8>,
pub app_attest_public_key: Vec<u8>,
pub assertion_counter: u32,
pub token_ciphertext: Vec<u8>,
pub token_fingerprint: [u8; 32],
pub endpoint_epoch: i64,
pub expires_at: i64,
pub revoked: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Delegation {
pub id: Uuid,
pub installation_id: Uuid,
pub relay_pubkey: String,
pub endpoint_epoch: i64,
pub generation: i64,
pub not_before: i64,
pub expires_at: i64,
pub revoked: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeliveryAuthority {
pub delegation_id: Uuid,
pub installation_id: Uuid,
pub platform: Platform,
pub relay_pubkey: String,
pub token_ciphertext: Vec<u8>,
pub endpoint_epoch: i64,
pub generation: i64,
pub expires_at: i64,
}
#[derive(Debug)]
pub struct DeliveryPermit {
pub authority: DeliveryAuthority,
pub relay_pubkey: String,
pub request_id: Uuid,
}
impl DeliveryPermit {
pub fn new(authority: DeliveryAuthority, relay_pubkey: String, request_id: Uuid) -> Self {
Self {
authority,
relay_pubkey,
request_id,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeliveryDisposition {
Terminal,
Retryable,
}
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
pub enum AuthorityError {
#[error("authority state rejected the request")]
Rejected,
#[error("installation authority is already live")]
Conflict,
#[error("authority request rate exceeded")]
RateLimited,
#[error("authority store unavailable")]
Unavailable,
/// The request id was admitted by an attempt that has not finished yet.
/// The caller should retry later: the first attempt may still fail
/// retryably and release the id.
#[error("delivery request is still in flight")]
InFlight,
}
/// Every mutating method is an atomic store operation. Implementations must
/// serialize installation assertion counters and delegation generations.
#[async_trait]
pub trait AuthorityStore: Send + Sync {
/// Readiness must fail closed when durable authority cannot participate.
async fn ready(&self) -> Result<(), AuthorityError>;
async fn put_challenge(&self, challenge: Challenge) -> Result<(), AuthorityError>;
async fn consume_challenge(
&self,
id: Uuid,
value: [u8; 32],
now: i64,
) -> Result<(), AuthorityError>;
async fn create_installation(
&self,
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<Installation, AuthorityError>;
/// 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.
async fn matching_installation(
&self,
app_attest_key_id: &[u8],
token_fingerprint: [u8; 32],
endpoint_epoch: i64,
expires_at: i64,
now: i64,
) -> Result<Option<Installation>, AuthorityError>;
async fn installation(&self, id: Uuid, now: i64) -> Result<Installation, AuthorityError>;
/// Load an unexpired installation for authenticated revocation retry,
/// including its terminal tombstone.
async fn installation_for_revocation(
&self,
id: Uuid,
now: i64,
) -> Result<Installation, AuthorityError>;
async fn advance_assertion_counter(
&self,
installation_id: Uuid,
previous: u32,
next: u32,
) -> Result<(), AuthorityError>;
async fn upsert_delegation(&self, delegation: Delegation) -> Result<(), AuthorityError>;
async fn rotate_endpoint(
&self,
installation_id: Uuid,
expected_epoch: i64,
new_epoch: i64,
token_ciphertext: Vec<u8>,
token_fingerprint: [u8; 32],
) -> Result<(), AuthorityError>;
/// Revoke a delegation only when `expected_generation` is current,
/// retaining that generation as the replacement watermark. Repeating the
/// exact revocation succeeds so clients can recover from a lost response.
async fn revoke_delegation(
&self,
installation_id: Uuid,
relay_pubkey: &str,
expected_generation: i64,
) -> Result<(), AuthorityError>;
async fn revoke_installation(
&self,
installation_id: Uuid,
expected_epoch: i64,
new_epoch: i64,
) -> Result<(), AuthorityError>;
/// Atomically validate and lock installation then delegation authority,
/// reserve quota/replay state, and commit. That durable commit is the
/// delivery send-begin linearization point seen by revocation.
#[allow(clippy::too_many_arguments)]
async fn authorize_delivery(
&self,
delegation_id: Uuid,
relay_pubkey: &str,
endpoint_epoch: i64,
generation: i64,
event_id: &str,
request_id: Uuid,
request_expires_at: i64,
quota_window_seconds: i64,
quota_max_deliveries: i64,
now: i64,
) -> Result<DeliveryPermit, AuthorityError>;
/// Admission records the request id as in flight. A replay of it fails
/// with `InFlight` until this call settles it: terminal outcomes retain the
/// id as finished (later replays are `Rejected`), retryable outcomes
/// release it. The one-use auth event admitted by `authorize_delivery` is
/// always retained. If the gateway dies before finishing, the id stays in
/// flight until its request expires, so the relay keeps retrying until its
/// attempt limit or the request expiry, whichever comes first.
async fn finish_delivery(
&self,
permit: DeliveryPermit,
disposition: DeliveryDisposition,
) -> Result<(), AuthorityError>;
/// Delete only data whose safety retention window has elapsed.
async fn reap_expired(&self, now: i64) -> Result<(), AuthorityError>;
}
#[derive(Default)]
struct MemoryState {
challenges: HashMap<Uuid, Challenge>,
installations: HashMap<Uuid, Installation>,
token_owners: HashMap<[u8; 32], Uuid>,
delegations: HashMap<(Uuid, String), Delegation>,
delegation_ids: HashMap<Uuid, (Uuid, String)>,
delivery_auth_replays: HashMap<(String, String), i64>,
/// Request id to (expires_at, finished).
delivery_request_replays: HashMap<(String, Uuid), (i64, bool)>,
endpoint_quotas: HashMap<[u8; 32], (i64, i64)>,
}
/// Executable reference store used by conformance tests. Production uses the
/// PostgreSQL implementation; this lock deliberately gives the model a single
/// linearization point for every authority transition.
#[derive(Default)]
pub struct MemoryAuthorityStore(Mutex<MemoryState>);
#[async_trait]
impl AuthorityStore for MemoryAuthorityStore {
async fn ready(&self) -> Result<(), AuthorityError> {
self.0
.lock()
.map(|_| ())
.map_err(|_| AuthorityError::Unavailable)
}
async fn put_challenge(&self, challenge: Challenge) -> Result<(), AuthorityError> {
let mut s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
let window_start = challenge
.created_at
.saturating_sub(CHALLENGE_QUOTA_WINDOW_SECONDS);
if s.challenges
.values()
.filter(|existing| existing.created_at >= window_start)
.count()
>= CHALLENGE_QUOTA_MAX_REQUESTS
{
return Err(AuthorityError::RateLimited);
}
if s.challenges.insert(challenge.id, challenge).is_some() {
return Err(AuthorityError::Rejected);
}
Ok(())
}
async fn consume_challenge(
&self,
id: Uuid,
value: [u8; 32],
now: i64,
) -> Result<(), AuthorityError> {
let mut s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
let challenge = s.challenges.remove(&id).ok_or(AuthorityError::Rejected)?;
if challenge.value != value || challenge.expires_at < now {
return Err(AuthorityError::Rejected);
}
Ok(())
}
async fn create_installation(
&self,
n: NewInstallation,
now: i64,
) -> Result<(), AuthorityError> {
let mut s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
s.create_installation(n, now)
}
async fn enroll_installation(
&self,
challenge_id: Uuid,
challenge: [u8; 32],
n: NewInstallation,
now: i64,
) -> Result<Installation, AuthorityError> {
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);
}
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 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<Installation, AuthorityError> {
let s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
let i = s
.installations
.get(&id)
.filter(|i| !i.revoked && i.expires_at >= now)
.ok_or(AuthorityError::Rejected)?;
Ok(i.clone())
}
async fn installation_for_revocation(
&self,
id: Uuid,
now: i64,
) -> Result<Installation, AuthorityError> {
let s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
let i = s
.installations
.get(&id)
.filter(|i| i.expires_at >= now)
.ok_or(AuthorityError::Rejected)?;
Ok(i.clone())
}
async fn matching_installation(
&self,
key_id: &[u8],
fingerprint: [u8; 32],
epoch: i64,
expires_at: i64,
now: i64,
) -> Result<Option<Installation>, AuthorityError> {
let s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
Ok(s.matching_installation(key_id, fingerprint, epoch, expires_at, now))
}
async fn advance_assertion_counter(
&self,
id: Uuid,
previous: u32,
next: u32,
) -> Result<(), AuthorityError> {
if next <= previous {
return Err(AuthorityError::Rejected);
}
let mut s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
let i = s
.installations
.get_mut(&id)
.ok_or(AuthorityError::Rejected)?;
if i.assertion_counter != previous {
return Err(AuthorityError::Rejected);
}
i.assertion_counter = next;
Ok(())
}
async fn upsert_delegation(&self, d: Delegation) -> Result<(), AuthorityError> {
let mut s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
let installation = s
.installations
.get(&d.installation_id)
.ok_or(AuthorityError::Rejected)?;
if installation.revoked
|| installation.endpoint_epoch != d.endpoint_epoch
|| d.generation < 1
|| d.not_before >= d.expires_at
{
return Err(AuthorityError::Rejected);
}
let key = (d.installation_id, d.relay_pubkey.clone());
if s.delegations
.get(&key)
.is_some_and(|old| d.generation <= old.generation)
|| s.delegation_ids.contains_key(&d.id)
{
return Err(AuthorityError::Rejected);
}
let installation = s
.installations
.get_mut(&d.installation_id)
.ok_or(AuthorityError::Rejected)?;
installation.expires_at = installation.expires_at.max(d.expires_at);
s.delegation_ids.insert(d.id, key.clone());
s.delegations.insert(key, d);
Ok(())
}
async fn rotate_endpoint(
&self,
id: Uuid,
expected: i64,
new: i64,
ciphertext: Vec<u8>,
fingerprint: [u8; 32],
) -> Result<(), AuthorityError> {
if new != expected.checked_add(1).ok_or(AuthorityError::Rejected)? {
return Err(AuthorityError::Rejected);
}
let mut s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
let old_fingerprint = {
let i = s.installations.get(&id).ok_or(AuthorityError::Rejected)?;
if i.revoked || i.endpoint_epoch != expected {
return Err(AuthorityError::Rejected);
}
i.token_fingerprint
};
let token_key = fingerprint;
if s.token_owners
.get(&token_key)
.is_some_and(|owner| *owner != id)
{
return Err(AuthorityError::Rejected);
}
s.token_owners.remove(&old_fingerprint);
s.token_owners.insert(token_key, id);
let i = s
.installations
.get_mut(&id)
.ok_or(AuthorityError::Rejected)?;
i.endpoint_epoch = new;
i.token_ciphertext = ciphertext;
i.token_fingerprint = fingerprint;
Ok(())
}
async fn revoke_delegation(
&self,
id: Uuid,
relay: &str,
expected_generation: i64,
) -> Result<(), AuthorityError> {
let mut s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
let key = (id, relay.to_owned());
let old = s
.delegations
.get_mut(&key)
.ok_or(AuthorityError::Rejected)?;
if expected_generation != old.generation {
return Err(AuthorityError::Rejected);
}
if old.revoked {
return Ok(());
}
old.revoked = true;
Ok(())
}
async fn revoke_installation(
&self,
id: Uuid,
expected: i64,
new: i64,
) -> Result<(), AuthorityError> {
if new != expected.checked_add(1).ok_or(AuthorityError::Rejected)? {
return Err(AuthorityError::Rejected);
}
let mut s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
let i = s
.installations
.get_mut(&id)
.ok_or(AuthorityError::Rejected)?;
if i.revoked && i.endpoint_epoch == new {
return Ok(());
}
if i.revoked || i.endpoint_epoch != expected {
return Err(AuthorityError::Rejected);
}
i.endpoint_epoch = new;
i.revoked = true;
Ok(())
}
async fn authorize_delivery(
&self,
delegation_id: Uuid,
relay: &str,
epoch: i64,
generation: i64,
event_id: &str,
request_id: Uuid,
request_expires_at: i64,
quota_window_seconds: i64,
quota_max_deliveries: i64,
now: i64,
) -> Result<DeliveryPermit, AuthorityError> {
let mut s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
let key = s
.delegation_ids
.get(&delegation_id)
.cloned()
.ok_or(AuthorityError::Rejected)?;
let d = s.delegations.get(&key).ok_or(AuthorityError::Rejected)?;
let i = s
.installations
.get(&d.installation_id)
.ok_or(AuthorityError::Rejected)?;
if d.revoked
|| i.revoked
|| d.id != delegation_id
|| d.relay_pubkey != relay
|| d.endpoint_epoch != epoch
|| d.generation != generation
|| i.endpoint_epoch != epoch
|| now < d.not_before
|| now > d.expires_at
|| now > i.expires_at
|| request_expires_at < now
|| request_expires_at > d.expires_at
{
return Err(AuthorityError::Rejected);
}
let authority = DeliveryAuthority {
delegation_id,
installation_id: i.id,
platform: i.platform,
relay_pubkey: relay.to_owned(),
token_ciphertext: i.token_ciphertext.clone(),
endpoint_epoch: epoch,
generation,
expires_at: d.expires_at,
};
let fingerprint = i.token_fingerprint;
let auth_key = (relay.to_owned(), event_id.to_owned());
let request_key = (relay.to_owned(), request_id);
match s.delivery_request_replays.get(&request_key) {
Some((_, false)) => return Err(AuthorityError::InFlight),
Some((_, true)) => return Err(AuthorityError::Rejected),
None => {}
}
if s.delivery_auth_replays.contains_key(&auth_key) {
return Err(AuthorityError::Rejected);
}
let quota = s.endpoint_quotas.entry(fingerprint).or_insert((now, 0));
if now.saturating_sub(quota.0) >= quota_window_seconds {
*quota = (now, 0);
}
if quota.1 >= quota_max_deliveries {
return Err(AuthorityError::RateLimited);
}
quota.1 += 1;
s.delivery_auth_replays.insert(auth_key, request_expires_at);
s.delivery_request_replays
.insert(request_key, (request_expires_at, false));
Ok(DeliveryPermit::new(authority, relay.to_owned(), request_id))
}
async fn finish_delivery(
&self,
permit: DeliveryPermit,
disposition: DeliveryDisposition,
) -> Result<(), AuthorityError> {
let mut s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
let key = (permit.relay_pubkey, permit.request_id);
match disposition {
DeliveryDisposition::Retryable => {
s.delivery_request_replays.remove(&key);
}
DeliveryDisposition::Terminal => {
if let Some((_, finished)) = s.delivery_request_replays.get_mut(&key) {
*finished = true;
}
}
}
Ok(())
}
async fn reap_expired(&self, now: i64) -> Result<(), AuthorityError> {
let mut s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
s.challenges
.retain(|_, challenge| challenge.expires_at >= now);
s.delivery_auth_replays
.retain(|_, expires_at| *expires_at >= now);
s.delivery_request_replays
.retain(|_, (expires_at, _)| *expires_at >= now);
s.endpoint_quotas
.retain(|_, (started_at, _)| now.saturating_sub(*started_at) < 86_400);
Ok(())
}
}
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::<Vec<_>>();
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::<Vec<_>>();
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<Installation> {
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::*;
async fn admitted(
store: &MemoryAuthorityStore,
event: &str,
request: Uuid,
) -> Result<DeliveryPermit, AuthorityError> {
store
.authorize_delivery(
Uuid::from_u128(2),
&"11".repeat(32),
1,
1,
event,
request,
1_100,
60,
10,
1_000,
)
.await
}
async fn store() -> MemoryAuthorityStore {
let store = MemoryAuthorityStore::default();
store
.create_installation(
NewInstallation {
platform: Platform::Ios,
id: Uuid::from_u128(1),
app_attest_key_id: vec![1],
app_attest_public_key: vec![2; 33],
assertion_counter: 0,
token_ciphertext: vec![3],
token_fingerprint: [4; 32],
endpoint_epoch: 1,
expires_at: 2_000,
},
1_000,
)
.await
.unwrap();
store
.upsert_delegation(Delegation {
id: Uuid::from_u128(2),
installation_id: Uuid::from_u128(1),
relay_pubkey: "11".repeat(32),
endpoint_epoch: 1,
generation: 1,
not_before: 900,
expires_at: 1_500,
revoked: false,
})
.await
.unwrap();
store
}
#[tokio::test]
async fn exact_enrollment_replay_recovers_committed_installation() {
let store = store().await;
let recovered = store
.matching_installation(&[1], [4; 32], 1, 2_000, 1_001)
.await
.unwrap()
.expect("exact replay finds the committed installation");
assert_eq!(recovered.id, Uuid::from_u128(1));
assert!(store
.matching_installation(&[1], [5; 32], 1, 2_000, 1_001,)
.await
.unwrap()
.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();
for offset in 0..CHALLENGE_QUOTA_MAX_REQUESTS {
store
.put_challenge(Challenge {
id: Uuid::from_u128(offset as u128 + 1),
value: [offset as u8; 32],
created_at: 1_000,
expires_at: 1_300,
})
.await
.expect("requests within the quota are admitted");
}
assert_eq!(
store
.put_challenge(Challenge {
id: Uuid::new_v4(),
value: [0; 32],
created_at: 1_000,
expires_at: 1_300,
})
.await,
Err(AuthorityError::RateLimited)
);
store
.put_challenge(Challenge {
id: Uuid::new_v4(),
value: [0; 32],
created_at: 1_061,
expires_at: 1_361,
})
.await
.expect("quota reopens after the rolling window");
}
#[tokio::test]
async fn exhausted_delivery_quota_is_rate_limited_without_consuming_fences() {
let store = store().await;
let deliver = |event: String, request: Uuid, now: i64| {
let store = &store;
async move {
store
.authorize_delivery(
Uuid::from_u128(2),
&"11".repeat(32),
1,
1,
&event,
request,
now + 100,
60,
2,
now,
)
.await
}
};
deliver("22".repeat(32), Uuid::new_v4(), 1_000)
.await
.unwrap();
deliver("33".repeat(32), Uuid::new_v4(), 1_000)
.await
.unwrap();
let (event, request) = ("44".repeat(32), Uuid::new_v4());
assert_eq!(
deliver(event.clone(), request, 1_000).await.err(),
Some(AuthorityError::RateLimited)
);
{
let s = store.0.lock().unwrap();
assert_eq!(s.delivery_auth_replays.len(), 2);
assert_eq!(s.delivery_request_replays.len(), 2);
assert_eq!(s.endpoint_quotas.values().next().unwrap().1, 2);
}
deliver(event, request, 1_060)
.await
.expect("the rate-limited attempt left its auth event and request id unused");
}
#[tokio::test]
async fn authenticated_delegation_renews_installation_lifetime() {
let store = store().await;
store
.upsert_delegation(Delegation {
id: Uuid::from_u128(3),
installation_id: Uuid::from_u128(1),
relay_pubkey: "11".repeat(32),
endpoint_epoch: 1,
generation: 2,
not_before: 1_900,
expires_at: 2_500,
revoked: false,
})
.await
.expect("new delegation renews its installation");
assert_eq!(
store
.installation(Uuid::from_u128(1), 2_400)
.await
.expect("renewed installation remains live")
.expires_at,
2_500
);
assert_eq!(
store
.upsert_delegation(Delegation {
id: Uuid::from_u128(4),
installation_id: Uuid::from_u128(1),
relay_pubkey: "11".repeat(32),
endpoint_epoch: 1,
generation: 2,
not_before: 2_000,
expires_at: 3_000,
revoked: false,
})
.await,
Err(AuthorityError::Rejected)
);
assert_eq!(
store.installation(Uuid::from_u128(1), 2_600).await,
Err(AuthorityError::Rejected),
"a rejected delegation must not extend installation authority"
);
}
#[tokio::test]
async fn expired_installation_can_be_replaced_but_live_installation_cannot() {
let store = store().await;
let replacement = |id| NewInstallation {
platform: Platform::Ios,
id,
app_attest_key_id: vec![1],
app_attest_public_key: vec![5; 33],
assertion_counter: 0,
token_ciphertext: vec![6],
token_fingerprint: [4; 32],
endpoint_epoch: 1,
expires_at: 3_000,
};
assert_eq!(
store
.create_installation(replacement(Uuid::from_u128(5)), 1_999)
.await,
Err(AuthorityError::Conflict)
);
store
.create_installation(replacement(Uuid::from_u128(5)), 2_001)
.await
.expect("expired token and App Attest ownership can be replaced");
assert!(store.installation(Uuid::from_u128(1), 2_001).await.is_err());
assert!(store.installation(Uuid::from_u128(5), 2_001).await.is_ok());
assert!(store
.authorize_delivery(
Uuid::from_u128(2),
&"11".repeat(32),
1,
1,
&"77".repeat(32),
Uuid::new_v4(),
2_100,
60,
10,
2_001,
)
.await
.is_err());
}
#[tokio::test]
async fn retry_releases_request_id_but_burns_auth_event() {
let store = store().await;
let request = Uuid::new_v4();
let first_event = "22".repeat(32);
let permit = admitted(&store, &first_event, request).await.unwrap();
store
.finish_delivery(permit, DeliveryDisposition::Retryable)
.await
.unwrap();
assert!(admitted(&store, &first_event, Uuid::new_v4())
.await
.is_err());
admitted(&store, &"33".repeat(32), request)
.await
.expect("fresh auth event may retry stable request id");
}
#[tokio::test]
async fn replay_of_unfinished_request_is_in_flight_until_it_finishes() {
let store = store().await;
let request = Uuid::new_v4();
let permit = admitted(&store, &"22".repeat(32), request).await.unwrap();
assert_eq!(
admitted(&store, &"33".repeat(32), request).await.err(),
Some(AuthorityError::InFlight)
);
store
.finish_delivery(permit, DeliveryDisposition::Terminal)
.await
.unwrap();
assert_eq!(
admitted(&store, &"44".repeat(32), request).await.err(),
Some(AuthorityError::Rejected)
);
}
#[tokio::test]
async fn terminal_outcome_burns_request_id() {
let store = store().await;
let request = Uuid::new_v4();
let permit = admitted(&store, &"22".repeat(32), request).await.unwrap();
store
.finish_delivery(permit, DeliveryDisposition::Terminal)
.await
.unwrap();
assert!(admitted(&store, &"33".repeat(32), request).await.is_err());
}
#[tokio::test]
async fn delegation_revocation_requires_the_current_generation() {
let store = store().await;
assert_eq!(
store
.revoke_delegation(Uuid::from_u128(1), &"11".repeat(32), 0)
.await,
Err(AuthorityError::Rejected)
);
assert_eq!(
store
.revoke_delegation(Uuid::from_u128(1), &"11".repeat(32), 2)
.await,
Err(AuthorityError::Rejected)
);
admitted(&store, &"44".repeat(32), Uuid::new_v4())
.await
.expect("rejected revocations must leave generation 1 active");
store
.revoke_delegation(Uuid::from_u128(1), &"11".repeat(32), 1)
.await
.expect("the current generation can be revoked");
store
.revoke_delegation(Uuid::from_u128(1), &"11".repeat(32), 1)
.await
.expect("the exact revocation is idempotent after response loss");
assert!(admitted(&store, &"55".repeat(32), Uuid::new_v4())
.await
.is_err());
let replacement = |id, generation| Delegation {
id,
installation_id: Uuid::from_u128(1),
relay_pubkey: "11".repeat(32),
endpoint_epoch: 1,
generation,
not_before: 900,
expires_at: 1_500,
revoked: false,
};
assert_eq!(
store
.upsert_delegation(replacement(Uuid::from_u128(3), 1))
.await,
Err(AuthorityError::Rejected)
);
store
.upsert_delegation(replacement(Uuid::from_u128(4), 2))
.await
.expect("only a strictly newer generation can reactivate the delegation");
store
.authorize_delivery(
Uuid::from_u128(4),
&"11".repeat(32),
1,
2,
&"66".repeat(32),
Uuid::new_v4(),
1_100,
60,
10,
1_000,
)
.await
.expect("generation 2 authority is active");
}
#[tokio::test]
async fn installation_revocation_is_authenticated_and_idempotent() {
let store = store().await;
let id = Uuid::from_u128(1);
let before = store.installation(id, 1_000).await.unwrap();
store
.revoke_installation(id, 1, 2)
.await
.expect("the current endpoint epoch can be revoked");
let tombstone = store
.installation_for_revocation(id, 1_000)
.await
.expect("revocation retry can authenticate against the tombstone");
assert!(tombstone.revoked);
store
.advance_assertion_counter(id, before.assertion_counter, before.assertion_counter + 1)
.await
.expect("an authenticated tombstone retry can advance its assertion counter");
store
.revoke_installation(id, 1, 2)
.await
.expect("the exact installation revocation is idempotent");
store
.create_installation(
NewInstallation {
platform: Platform::Ios,
id: Uuid::from_u128(5),
app_attest_key_id: vec![1],
app_attest_public_key: vec![5; 33],
assertion_counter: 0,
token_ciphertext: vec![6],
token_fingerprint: [4; 32],
endpoint_epoch: 1,
expires_at: 3_000,
},
1_001,
)
.await
.expect("a replacement can reuse ownership without deleting the tombstone");
assert!(
store
.installation_for_revocation(id, 1_001)
.await
.expect("replacement preserves the prior revocation tombstone")
.revoked
);
assert_eq!(
store.revoke_installation(id, 2, 3).await,
Err(AuthorityError::Rejected)
);
}
}