Skip to main content

mid_verify/
lib.rs

1//! # `mid-verify` — RP-side mID JWT verifier
2//!
3//! Phase 0 of the [mID Mission](../../../docs/plans/phase%201%20sso_permissionless_mission.md).
4//! Implements the four-step verification from
5//! [ADR 0005 Decision 1](../../../docs/adr/0005-mid-protocol-v1-phase-0-spec-lockin.md):
6//! given a JWS compact-form mID token and a [`VerifyConfig`], run all
7//! cryptographic checks entirely locally and return a [`VerifiedMid`]
8//! that captures the user's DID, current roster version, and disclosed
9//! claims.
10//!
11//! ## The four-step verification
12//!
13//! 1. **Genesis self-signature.** Decode the genesis public key from the
14//!    DID's base58 suffix; verify the genesis roster envelope's
15//!    `self_signed_by_genesis_key` against it.
16//! 2. **Roster chain.** Each chain entry signed by a VM present in the
17//!    prior entry's roster; versions strictly monotonic.
18//! 3. **Current VM in head.** The device that signed this JWT is in the
19//!    head (current) roster.
20//! 4. **JWS outer signature.** Standard ES256 verification against the
21//!    embedded verification method's public key.
22//!
23//! ## Zero MATA runtime calls
24//!
25//! Per ADR 0005, RPs make zero HTTP requests to MATA infrastructure
26//! during verification. Every cryptographic input the verifier needs
27//! travels inside the JWT itself; everything else is RP-local
28//! configuration ([`VerifyConfig`]) or RP-local state (the optional
29//! rollback check the RP runs against its own database AFTER calling
30//! [`verify_mid_response`]).
31//!
32//! ## Usage
33//!
34//! ```ignore
35//! use mid_verify::{verify_mid_response, VerifyConfig};
36//!
37//! let config = VerifyConfig {
38//!     expected_audience: "https://acme.com".to_string(),
39//!     expected_nonce: my_session_nonce.clone(),
40//!     max_iat_skew_secs: 120,
41//!     now_unix_secs: current_wall_clock_secs(),
42//! };
43//!
44//! let verified = verify_mid_response(&incoming_jwt, &config)?;
45//!
46//! // Optional rollback check — look up the highest version this RP has
47//! // seen for this DID in its own database, then:
48//! let last_seen = db.lookup_last_seen_version(&verified.did).await?;
49//! verified.check_rollback(last_seen)?;
50//!
51//! // Persist user, issue session...
52//! ```
53
54#![forbid(unsafe_code)]
55#![warn(missing_docs)]
56
57pub mod checks;
58mod error;
59pub mod keys;
60
61pub use error::VerifyError;
62pub use keys::{did_from_pubkey, multibase_from_pubkey, pubkey_from_did, pubkey_from_multibase};
63
64// Re-export the wire-format types from mid-issuer so RPs only need one
65// `cargo add mid-verify` to access everything they need.
66pub use mid_issuer::{
67    AttestedBy, ClaimValue, EmbeddedGenesisRoster, EmbeddedRosterChainEntry,
68    EmbeddedVerificationMethod, MidJwtPayload, VerificationMethod,
69};
70
71use std::collections::BTreeMap;
72
73// ─── Public API ────────────────────────────────────────────────────────────
74
75/// Configuration the RP supplies to [`verify_mid_response`].
76///
77/// All fields are RP-supplied and reflect RP-local policy. The verifier
78/// never reaches out to MATA infrastructure to populate any of these.
79#[derive(Debug, Clone)]
80pub struct VerifyConfig {
81    /// The RP's bare origin (e.g. `"https://acme.com"`). Must equal the
82    /// JWT's `aud` claim exactly. The wallet sets `aud` from the
83    /// `rp_origin` field in the original sign-in request; this check
84    /// catches a token issued to one RP being replayed at another.
85    pub expected_audience: String,
86    /// The single-use nonce the RP issued for this sign-in session. Must
87    /// equal the JWT's `nonce` claim exactly. The RP fetches this from
88    /// its own per-session store (e.g. the `auth_nonces` table).
89    pub expected_nonce: String,
90    /// Maximum allowed forward clock skew between the wallet's `iat`
91    /// and the verifier's wall clock, in seconds. Tokens with `iat >
92    /// now + max_iat_skew_secs` are rejected as "not yet valid"; this
93    /// guards against forward-dated tokens. 120s is a reasonable
94    /// default.
95    pub max_iat_skew_secs: u64,
96    /// The verifier's current wall-clock time in Unix seconds. Passed
97    /// in by the caller (rather than read here) so the verifier stays a
98    /// pure function — testable with fixed clocks, deterministic in
99    /// production retries.
100    pub now_unix_secs: u64,
101}
102
103/// The result of a successful verification. Carries everything an RP
104/// needs to upsert a user row, issue a session, and (optionally) run a
105/// rollback check.
106#[derive(Debug, Clone)]
107pub struct VerifiedMid {
108    /// The user's DID. Stable across the user's lifetime; the RP's user
109    /// table primary key.
110    pub did: String,
111    /// SHA-256 of the canonical genesis-roster bytes. The RP records
112    /// this on first sight as the user's anchor; on subsequent sign-ins
113    /// the same DID MUST produce the same `genesis_roster_hash` (the
114    /// RP's upsert can guard the invariant).
115    pub genesis_roster_hash: [u8; 32],
116    /// The head roster's version. Monotonically increases as the user
117    /// adds / revokes devices. The RP can record this and reject lower
118    /// versions on subsequent sign-ins to defeat stolen-device replay.
119    pub current_version: u64,
120    /// The claim values the user consented to disclose, exactly as the
121    /// wallet asserted them.
122    pub claims: BTreeMap<String, ClaimValue>,
123    /// The JWT's issued-at, Unix seconds.
124    pub iat: u64,
125    /// The JWT's expiry, Unix seconds.
126    pub exp: u64,
127    /// The JWT's audience — equals `config.expected_audience` after
128    /// successful verify.
129    pub aud: String,
130    /// `(version, SHA-256 of its canonical bytes)` for every roster the token
131    /// carries, genesis first, head last. An RP records the head's pair and
132    /// passes it to [`VerifiedMid::check_continuity`] next time, which is what
133    /// catches a history branched off an older roster.
134    pub roster_hashes: Vec<(u64, [u8; 32])>,
135}
136
137impl VerifiedMid {
138    /// Check that the current roster version is at least as new as the
139    /// last version the RP has seen for this DID.
140    ///
141    /// The RP fetches `last_seen_version` from its own per-DID store
142    /// (typically a `users.last_seen_roster_version` column). Pass
143    /// `None` if this is a DID the RP has never seen — in that case
144    /// the check trivially passes and the RP records the current
145    /// version as the new high-water mark.
146    pub fn check_rollback(&self, last_seen_version: Option<u64>) -> Result<(), VerifyError> {
147        match last_seen_version {
148            Some(seen) if seen > self.current_version => Err(VerifyError::RollbackDetected {
149                current: self.current_version,
150                last_seen: seen,
151            }),
152            _ => Ok(()),
153        }
154    }
155
156    /// The head roster's `(version, hash)`: what an RP records as its mark.
157    pub fn head(&self) -> (u64, [u8; 32]) {
158        *self.roster_hashes.last().expect("a verified token carries at least its genesis roster")
159    }
160
161    /// Check that this token's roster history continues the one the RP saw
162    /// last. `mark` is the `(version, hash)` the RP recorded ([`Self::head`]
163    /// of an earlier token), or `None` for a DID it has never seen.
164    ///
165    /// Refuses an older head ([`VerifyError::RollbackDetected`], as
166    /// [`Self::check_rollback`]) and, unlike it, a history that does not carry
167    /// the recorded roster at the recorded version ([`VerifyError::ForkDetected`]).
168    /// Every token carries its full chain from genesis, so the recorded roster
169    /// must be in it.
170    pub fn check_continuity(&self, mark: Option<(u64, [u8; 32])>) -> Result<(), VerifyError> {
171        let Some((version, hash)) = mark else {
172            return Ok(());
173        };
174        self.check_rollback(Some(version))?;
175        match self.roster_hashes.iter().find(|(v, _)| *v == version) {
176            Some((_, carried)) if *carried == hash => Ok(()),
177            _ => Err(VerifyError::ForkDetected { version }),
178        }
179    }
180}
181
182/// Run the four-step mID verification against `jwt` per [`VerifyConfig`].
183///
184/// On success, returns a [`VerifiedMid`]. On any failure, returns the
185/// specific [`VerifyError`] variant — caller can `match` to log /
186/// respond distinctly.
187///
188/// This function is a pure function of its inputs. It does no I/O,
189/// reads no clock, makes no remote calls. The caller supplies the
190/// wall-clock time via [`VerifyConfig::now_unix_secs`].
191pub fn verify_mid_response(jwt: &str, config: &VerifyConfig) -> Result<VerifiedMid, VerifyError> {
192    verify_inner(
193        jwt,
194        &config.expected_audience,
195        Some(&config.expected_nonce),
196        config.now_unix_secs,
197        config.max_iat_skew_secs,
198    )
199    .map(|(verified, _)| verified)
200}
201
202/// [`verify_mid_response`] for a relying party that reads the nonce out of
203/// the token instead of holding it beside the session: every check except the
204/// nonce comparison, and the token's nonce handed back.
205///
206/// **The caller MUST then prove that nonce is one it issued and consume it**
207/// (single use) -- that is what makes the token fresh. `mid-signin`'s
208/// `Authenticator::authenticate_with_embedded_nonce` does exactly that. It
209/// used to read the nonce in a first pass (decode and parse the payload) and
210/// verify in a second (decode and parse it again); this is the one pass.
211pub fn verify_mid_response_echoed_nonce(
212    jwt: &str,
213    expected_audience: &str,
214    now_unix_secs: u64,
215    max_iat_skew_secs: u64,
216) -> Result<(VerifiedMid, String), VerifyError> {
217    verify_inner(jwt, expected_audience, None, now_unix_secs, max_iat_skew_secs)
218}
219
220fn verify_inner(
221    jwt: &str,
222    expected_audience: &str,
223    expected_nonce: Option<&str>,
224    now_unix_secs: u64,
225    max_iat_skew_secs: u64,
226) -> Result<(VerifiedMid, String), VerifyError> {
227    // 1. Split JWS into segments + decode header/payload.
228    let parts = checks::split_jws(jwt)?;
229    checks::validate_jws_header(&parts.header_bytes)?;
230    let mut payload: MidJwtPayload = serde_json::from_slice(&parts.payload_bytes)?;
231
232    // 2. Metadata checks: audience, nonce, expiry, not-yet-valid.
233    if payload.aud != expected_audience {
234        return Err(VerifyError::AudienceMismatch {
235            expected: expected_audience.to_string(),
236            actual: payload.aud.clone(),
237        });
238    }
239    if expected_nonce.is_some_and(|n| payload.nonce != n) {
240        return Err(VerifyError::NonceMismatch);
241    }
242    if now_unix_secs >= payload.exp {
243        return Err(VerifyError::Expired {
244            exp: payload.exp,
245            now: now_unix_secs,
246        });
247    }
248    if payload.iat > now_unix_secs.saturating_add(max_iat_skew_secs) {
249        return Err(VerifyError::NotYetValid {
250            iat: payload.iat,
251            now: now_unix_secs,
252            max_skew_secs: max_iat_skew_secs,
253        });
254    }
255
256    // 3. The four cryptographic checks. Each is isolated; the
257    //    orchestrator just calls them in order.
258    //    The genesis and chain checks hand back the hashes their signatures
259    //    were verified over: those ARE the roster hashes the RP anchors on
260    //    (step 4), so nothing is canonicalized or hashed twice.
261    let genesis_roster_hash = checks::genesis_verified_hash(&payload)?;
262    let mut roster_hashes = Vec::with_capacity(1 + payload.embedded_roster_chain.len());
263    roster_hashes.push((payload.embedded_genesis_roster.version, genesis_roster_hash));
264    checks::roster_chain_hashes(&payload, &mut roster_hashes)?;
265    checks::check_current_vm_in_head(&payload)?;
266    checks::check_jws_signature(&payload, parts.signing_input, parts.signature_b64)?;
267
268    // 4. current_version for the RP's anchoring + rollback detection; the
269    //    roster hashes came out of step 3.
270    let current_version = payload
271        .embedded_roster_chain
272        .last()
273        .map(|e| e.version)
274        .unwrap_or(payload.embedded_genesis_roster.version);
275
276    let nonce = std::mem::take(&mut payload.nonce);
277    let verified = VerifiedMid {
278        did: payload.iss.clone(),
279        genesis_roster_hash,
280        current_version,
281        claims: payload.claims,
282        iat: payload.iat,
283        exp: payload.exp,
284        aud: payload.aud,
285        roster_hashes,
286    };
287    Ok((verified, nonce))
288}
289
290// ─── Tests ─────────────────────────────────────────────────────────────────
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295    use sha2::{Digest, Sha256};
296    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
297    use kms_client::{DeviceSigner, InMemoryDeviceSigner};
298    use mid_issuer::{
299        build_mid_jwt, AttestedBy, ClaimRequest, ClaimValue, EmbeddedGenesisRoster,
300        EmbeddedRosterChainEntry, EmbeddedVerificationMethod, IdentitySnapshot, RpRequest,
301        VerificationMethod,
302    };
303    use p256::ecdsa::signature::hazmat::PrehashSigner;
304    use p256::ecdsa::{Signature, SigningKey};
305    use std::collections::BTreeMap;
306
307    // ─── Fixture builders ──────────────────────────────────────────────────
308
309    /// Build a deterministic signing key from a seed string (matches
310    /// the mid-issuer test helper).
311    fn make_signing_key(seed: &str) -> SigningKey {
312        let mut hasher = Sha256::new();
313        hasher.update(seed.as_bytes());
314        hasher.update(b"-mid-verify-test-seed");
315        let bytes: [u8; 32] = hasher.finalize().into();
316        SigningKey::from_bytes(&bytes.into()).unwrap()
317    }
318
319    /// A single device's key material. The DID it belongs to is owned
320    /// by [`IdentityFixture`] — a device's `signing_key` is its own,
321    /// but it serves whatever identity it's been added to.
322    struct DeviceKey {
323        device_id: String,
324        signing_key: SigningKey,
325    }
326
327    impl DeviceKey {
328        fn new(seed: &str, device_id: &str) -> Self {
329            Self {
330                device_id: device_id.into(),
331                signing_key: make_signing_key(seed),
332            }
333        }
334    }
335
336    /// A test identity centered on a genesis device. Additional devices
337    /// are added to the SAME DID — they don't bring their own DID.
338    struct IdentityFixture {
339        genesis: DeviceKey,
340    }
341
342    impl IdentityFixture {
343        fn new(genesis_seed: &str, genesis_device_id: &str) -> Self {
344            Self {
345                genesis: DeviceKey::new(genesis_seed, genesis_device_id),
346            }
347        }
348
349        /// The DID derived from the genesis key. Every device added to
350        /// this identity serves this DID — its VM's `controller` is this
351        /// DID, its VM's `id` is `<this_did>#<its_device_id>`.
352        fn did(&self) -> String {
353            keys::did_from_pubkey(self.genesis.signing_key.verifying_key())
354        }
355
356        /// Build a verification method for any device under this identity.
357        fn vm_for(&self, device: &DeviceKey) -> VerificationMethod {
358            let did = self.did();
359            VerificationMethod {
360                id: format!("{did}#{}", device.device_id),
361                vm_type: "EcdsaSecp256r1VerificationKey2019".into(),
362                controller: did,
363                public_key_multibase: keys::multibase_from_pubkey(
364                    device.signing_key.verifying_key(),
365                ),
366            }
367        }
368
369        /// Build the embedded-VM form (the JWT's current_verification_method).
370        fn embedded_vm_for(&self, device: &DeviceKey) -> EmbeddedVerificationMethod {
371            let did = self.did();
372            EmbeddedVerificationMethod {
373                id: format!("{did}#{}", device.device_id),
374                vm_type: "EcdsaSecp256r1VerificationKey2019".into(),
375                controller: did,
376                public_key_multibase: keys::multibase_from_pubkey(
377                    device.signing_key.verifying_key(),
378                ),
379            }
380        }
381    }
382
383    /// Sign the canonical bytes of a genesis roster with the given key,
384    /// returning the base64url-encoded `r || s`.
385    fn sign_genesis(roster: &EmbeddedGenesisRoster, signing_key: &SigningKey) -> String {
386        let canonical = mid_issuer::canonical::genesis_canonical_bytes(roster);
387        let prehash: [u8; 32] = Sha256::digest(&canonical).into();
388        let sig: Signature = signing_key.sign_prehash(&prehash).unwrap();
389        let normalized = sig.normalize_s().unwrap_or(sig);
390        let bytes = normalized.to_bytes();
391        URL_SAFE_NO_PAD.encode(bytes)
392    }
393
394    /// Sign the canonical bytes of a chain entry with the given key.
395    fn sign_chain_entry(entry: &EmbeddedRosterChainEntry, signing_key: &SigningKey) -> String {
396        let canonical = mid_issuer::canonical::chain_entry_canonical_bytes(entry);
397        let prehash: [u8; 32] = Sha256::digest(&canonical).into();
398        let sig: Signature = signing_key.sign_prehash(&prehash).unwrap();
399        let normalized = sig.normalize_s().unwrap_or(sig);
400        let bytes = normalized.to_bytes();
401        URL_SAFE_NO_PAD.encode(bytes)
402    }
403
404    /// Build a single-device identity snapshot (genesis only, no chain).
405    fn fresh_identity(identity: &IdentityFixture) -> IdentitySnapshot {
406        let genesis_vm = identity.vm_for(&identity.genesis);
407        let mut genesis = EmbeddedGenesisRoster {
408            version: 1,
409            did: identity.did(),
410            verification_methods: vec![genesis_vm],
411            signed_at: 1_700_000_000,
412            self_signed_by_genesis_key: String::new(),
413        };
414        genesis.self_signed_by_genesis_key =
415            sign_genesis(&genesis, &identity.genesis.signing_key);
416
417        let mut approved = BTreeMap::new();
418        approved.insert(
419            "did".into(),
420            ClaimValue {
421                value: serde_json::Value::String(identity.did()),
422                attested_by: AttestedBy::SelfAttested,
423                verified_at_signup: None,
424                computed_at: None,
425                formula_version: None,
426            },
427        );
428
429        IdentitySnapshot {
430            did: identity.did(),
431            genesis_roster: genesis,
432            roster_chain: vec![],
433            current_verification_method: identity.embedded_vm_for(&identity.genesis),
434            approved_claims: approved,
435        }
436    }
437
438    /// Build a two-device identity snapshot: genesis + one chain entry
439    /// adding the second device. Signs the chain entry with the genesis
440    /// device's key (the only one in the prior roster).
441    fn two_device_identity(
442        identity: &IdentityFixture,
443        new_device: &DeviceKey,
444    ) -> IdentitySnapshot {
445        let mut base = fresh_identity(identity);
446
447        let mut chain_entry = EmbeddedRosterChainEntry {
448            version: 2,
449            did: identity.did(),
450            verification_methods: vec![
451                identity.vm_for(&identity.genesis),
452                identity.vm_for(new_device),
453            ],
454            signed_at: 1_710_000_000,
455            signed_by_signer_in_prior_roster: String::new(),
456            signer_kid: identity.genesis.device_id.clone(),
457        };
458        chain_entry.signed_by_signer_in_prior_roster =
459            sign_chain_entry(&chain_entry, &identity.genesis.signing_key);
460
461        base.roster_chain.push(chain_entry);
462        base.current_verification_method = identity.embedded_vm_for(new_device);
463        base
464    }
465
466    /// Sign and emit a JWT against the given snapshot. The signer is
467    /// derived from the snapshot's `current_verification_method` —
468    /// caller is responsible for matching the snapshot to the signer.
469    fn mint_jwt(
470        snapshot: &IdentitySnapshot,
471        signer: &dyn DeviceSigner,
472        rp_origin: &str,
473        nonce: &str,
474        iat: u64,
475    ) -> String {
476        let req = RpRequest {
477            rp_origin: rp_origin.into(),
478            nonce: nonce.into(),
479            claims: ClaimRequest {
480                required: vec!["did".into()],
481                optional: vec![],
482                custom: BTreeMap::new(),
483            },
484        };
485        build_mid_jwt(&req, snapshot, signer, iat).expect("mint JWT")
486    }
487
488    fn fresh_config(now: u64, nonce: &str) -> VerifyConfig {
489        VerifyConfig {
490            expected_audience: "https://acme.com".into(),
491            expected_nonce: nonce.into(),
492            max_iat_skew_secs: 120,
493            now_unix_secs: now,
494        }
495    }
496
497    // ─── Happy path ────────────────────────────────────────────────────────
498
499    #[test]
500    fn happy_path_single_device_verifies() {
501        let identity = IdentityFixture::new("device-A", "dev-laptop");
502        let snapshot = fresh_identity(&identity);
503        let signer = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("device-A"));
504
505        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
506        let config = fresh_config(1_716_700_010, "nonce-abc");
507        let verified = verify_mid_response(&jwt, &config).expect("happy path verify");
508
509        assert_eq!(verified.did, identity.did());
510        assert_eq!(verified.current_version, 1);
511        assert_eq!(verified.aud, "https://acme.com");
512        assert_eq!(verified.iat, 1_716_700_000);
513        assert_eq!(verified.exp, 1_716_700_000 + 3600);
514        assert!(verified.claims.contains_key("did"));
515    }
516
517    #[test]
518    fn happy_path_two_devices_chain_verifies() {
519        let identity = IdentityFixture::new("genesis", "dev-laptop");
520        let new_device = DeviceKey::new("new-phone", "dev-phone");
521        let snapshot = two_device_identity(&identity, &new_device);
522        let signer = InMemoryDeviceSigner::new("dev-phone", make_signing_key("new-phone"));
523
524        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
525        let config = fresh_config(1_716_700_010, "nonce-abc");
526        let verified = verify_mid_response(&jwt, &config).expect("two-device verify");
527
528        assert_eq!(verified.did, identity.did());
529        assert_eq!(verified.current_version, 2);
530    }
531
532    // ─── Tamper checks ─────────────────────────────────────────────────────
533
534    #[test]
535    fn tampered_jws_signature_rejected() {
536        let identity = IdentityFixture::new("device-A", "dev-laptop");
537        let snapshot = fresh_identity(&identity);
538        let signer = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("device-A"));
539        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
540        let config = fresh_config(1_716_700_010, "nonce-abc");
541
542        // Flip a bit in the last segment (the signature).
543        let mut parts: Vec<String> = jwt.split('.').map(|s| s.to_string()).collect();
544        let last_idx = parts.len() - 1;
545        let sig_bytes = URL_SAFE_NO_PAD.decode(&parts[last_idx]).unwrap();
546        let mut tampered = sig_bytes.clone();
547        tampered[0] ^= 0x80;
548        parts[last_idx] = URL_SAFE_NO_PAD.encode(tampered);
549        let tampered_jwt = parts.join(".");
550
551        let err = verify_mid_response(&tampered_jwt, &config).unwrap_err();
552        assert!(
553            matches!(err, VerifyError::JwtSignatureInvalid | VerifyError::SignatureWrongLength { .. }),
554            "got {err:?}"
555        );
556    }
557
558    #[test]
559    fn audience_mismatch_rejected() {
560        let identity = IdentityFixture::new("device-A", "dev-laptop");
561        let snapshot = fresh_identity(&identity);
562        let signer = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("device-A"));
563        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
564
565        let mut config = fresh_config(1_716_700_010, "nonce-abc");
566        config.expected_audience = "https://attacker.com".into();
567
568        match verify_mid_response(&jwt, &config) {
569            Err(VerifyError::AudienceMismatch { expected, actual }) => {
570                assert_eq!(expected, "https://attacker.com");
571                assert_eq!(actual, "https://acme.com");
572            }
573            other => panic!("expected AudienceMismatch, got {other:?}"),
574        }
575    }
576
577    #[test]
578    fn nonce_mismatch_rejected() {
579        let identity = IdentityFixture::new("device-A", "dev-laptop");
580        let snapshot = fresh_identity(&identity);
581        let signer = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("device-A"));
582        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
583
584        let config = fresh_config(1_716_700_010, "different-nonce");
585        match verify_mid_response(&jwt, &config) {
586            Err(VerifyError::NonceMismatch) => {}
587            other => panic!("expected NonceMismatch, got {other:?}"),
588        }
589    }
590
591    #[test]
592    fn expired_jwt_rejected() {
593        let identity = IdentityFixture::new("device-A", "dev-laptop");
594        let snapshot = fresh_identity(&identity);
595        let signer = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("device-A"));
596        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
597
598        // Default token lifetime is 3600s. Time-travel past exp.
599        let config = fresh_config(1_716_700_000 + 3601, "nonce-abc");
600        match verify_mid_response(&jwt, &config) {
601            Err(VerifyError::Expired { exp, now }) => {
602                assert_eq!(exp, 1_716_700_000 + 3600);
603                assert_eq!(now, 1_716_700_000 + 3601);
604            }
605            other => panic!("expected Expired, got {other:?}"),
606        }
607    }
608
609    #[test]
610    fn forward_dated_jwt_beyond_skew_rejected() {
611        let identity = IdentityFixture::new("device-A", "dev-laptop");
612        let snapshot = fresh_identity(&identity);
613        let signer = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("device-A"));
614        // Mint with iat far in the future.
615        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
616
617        // Verifier's wall clock is well before iat — beyond the 120s skew.
618        let config = fresh_config(1_716_600_000, "nonce-abc");
619        match verify_mid_response(&jwt, &config) {
620            Err(VerifyError::NotYetValid { iat, now, max_skew_secs }) => {
621                assert_eq!(iat, 1_716_700_000);
622                assert_eq!(now, 1_716_600_000);
623                assert_eq!(max_skew_secs, 120);
624            }
625            other => panic!("expected NotYetValid, got {other:?}"),
626        }
627    }
628
629    #[test]
630    fn a_remembered_roster_signature_admits_nothing_else() {
631        let identity = IdentityFixture::new("device-remember", "dev-laptop");
632        let snapshot = fresh_identity(&identity);
633        let signer = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("device-remember"));
634        let good = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
635        let config = fresh_config(1_716_700_010, "nonce-abc");
636        // Twice: the second passes through the remembered genesis signature.
637        verify_mid_response(&good, &config).unwrap();
638        verify_mid_response(&good, &config).unwrap();
639
640        // The same signature over a roster that differs by one field.
641        let mut moved = snapshot.clone();
642        moved.genesis_roster.signed_at += 1;
643        let jwt = mint_jwt(&moved, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
644        assert!(matches!(
645            verify_mid_response(&jwt, &config).unwrap_err(),
646            VerifyError::GenesisSignatureInvalid
647        ));
648
649        // The same roster with one bit of the remembered signature flipped.
650        let mut flipped = snapshot.clone();
651        let mut sig =
652            URL_SAFE_NO_PAD.decode(&flipped.genesis_roster.self_signed_by_genesis_key).unwrap();
653        sig[0] ^= 0x01;
654        flipped.genesis_roster.self_signed_by_genesis_key = URL_SAFE_NO_PAD.encode(sig);
655        let jwt = mint_jwt(&flipped, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
656        assert!(matches!(
657            verify_mid_response(&jwt, &config).unwrap_err(),
658            VerifyError::GenesisSignatureInvalid
659        ));
660    }
661
662    #[test]
663    fn tampered_genesis_signature_rejected() {
664        let identity = IdentityFixture::new("device-A", "dev-laptop");
665        let mut snapshot = fresh_identity(&identity);
666        // Flip a byte in the genesis signature.
667        let mut sig_bytes =
668            URL_SAFE_NO_PAD.decode(&snapshot.genesis_roster.self_signed_by_genesis_key).unwrap();
669        sig_bytes[0] ^= 0x80;
670        snapshot.genesis_roster.self_signed_by_genesis_key = URL_SAFE_NO_PAD.encode(sig_bytes);
671        let signer = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("device-A"));
672        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
673
674        let config = fresh_config(1_716_700_010, "nonce-abc");
675        let err = verify_mid_response(&jwt, &config).unwrap_err();
676        assert!(
677            matches!(err, VerifyError::GenesisSignatureInvalid),
678            "got {err:?}"
679        );
680    }
681
682    #[test]
683    fn broken_chain_signer_not_in_prior_rejected() {
684        let identity = IdentityFixture::new("genesis", "dev-laptop");
685        let new_device = DeviceKey::new("new-phone", "dev-phone");
686        let mut snapshot = two_device_identity(&identity, &new_device);
687
688        // Forge: claim the chain entry was signed by a non-existent
689        // device. The signature won't even be checked — the lookup
690        // fails first.
691        snapshot.roster_chain[0].signer_kid = "ghost-device".into();
692        snapshot.roster_chain[0].signed_by_signer_in_prior_roster =
693            sign_chain_entry(&snapshot.roster_chain[0], &identity.genesis.signing_key);
694
695        let signer = InMemoryDeviceSigner::new("dev-phone", make_signing_key("new-phone"));
696        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
697
698        let config = fresh_config(1_716_700_010, "nonce-abc");
699        match verify_mid_response(&jwt, &config) {
700            Err(VerifyError::ChainSignerNotInPriorRoster { signer_kid, .. }) => {
701                assert_eq!(signer_kid, "ghost-device");
702            }
703            other => panic!("expected ChainSignerNotInPriorRoster, got {other:?}"),
704        }
705    }
706
707    #[test]
708    fn non_monotonic_chain_version_rejected() {
709        let identity = IdentityFixture::new("genesis", "dev-laptop");
710        let new_device = DeviceKey::new("new-phone", "dev-phone");
711        let mut snapshot = two_device_identity(&identity, &new_device);
712
713        // Roll back the chain entry's version to match the genesis.
714        snapshot.roster_chain[0].version = 1;
715        snapshot.roster_chain[0].signed_by_signer_in_prior_roster =
716            sign_chain_entry(&snapshot.roster_chain[0], &identity.genesis.signing_key);
717
718        let signer = InMemoryDeviceSigner::new("dev-phone", make_signing_key("new-phone"));
719        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
720
721        let config = fresh_config(1_716_700_010, "nonce-abc");
722        match verify_mid_response(&jwt, &config) {
723            Err(VerifyError::ChainVersionNotMonotonic { entry_version, prior_version }) => {
724                assert_eq!(entry_version, 1);
725                assert_eq!(prior_version, 1);
726            }
727            other => panic!("expected ChainVersionNotMonotonic, got {other:?}"),
728        }
729    }
730
731    #[test]
732    fn current_vm_not_in_head_rejected() {
733        let identity = IdentityFixture::new("genesis", "dev-laptop");
734        let snapshot = fresh_identity(&identity);
735        // Build a JWT with a forged current_verification_method that
736        // claims to be a device NOT in the head roster. We have to do
737        // this manually — mid-issuer's build_mid_jwt would reject it
738        // before signing. So we mint a normal JWT, then surgically
739        // replace the embedded VM in the payload.
740
741        let signer = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("genesis"));
742        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
743
744        // Decode + tamper the payload.
745        let parts: Vec<&str> = jwt.split('.').collect();
746        let payload_bytes = URL_SAFE_NO_PAD.decode(parts[1]).unwrap();
747        let mut payload: MidJwtPayload = serde_json::from_slice(&payload_bytes).unwrap();
748        payload.embedded_verification_method.id = format!("{}#ghost", identity.did());
749        let new_payload_bytes = serde_json::to_vec(&payload).unwrap();
750        let new_payload_b64 = URL_SAFE_NO_PAD.encode(new_payload_bytes);
751        let tampered_jwt = format!("{}.{}.{}", parts[0], new_payload_b64, parts[2]);
752
753        let config = fresh_config(1_716_700_010, "nonce-abc");
754        match verify_mid_response(&tampered_jwt, &config) {
755            Err(VerifyError::CurrentVmNotInHeadRoster { vm_id }) => {
756                assert!(vm_id.ends_with("#ghost"));
757            }
758            other => panic!("expected CurrentVmNotInHeadRoster, got {other:?}"),
759        }
760    }
761
762    /// A stranger copies an owner's public roster (every token carries it), keeps a
763    /// rostered device id, puts their own key beside it and signs with that key. The
764    /// id is in the head roster, so only comparing the key catches it.
765    #[test]
766    fn a_rostered_id_with_a_strangers_key_is_rejected() {
767        use p256::ecdsa::signature::hazmat::PrehashSigner;
768
769        let identity = IdentityFixture::new("genesis", "dev-laptop");
770        let snapshot = fresh_identity(&identity);
771        let signer = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("genesis"));
772        let genuine = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
773
774        let parts: Vec<&str> = genuine.split('.').collect();
775        let mut payload: MidJwtPayload =
776            serde_json::from_slice(&URL_SAFE_NO_PAD.decode(parts[1]).unwrap()).unwrap();
777        let attacker = make_signing_key("attacker");
778        payload.embedded_verification_method.public_key_multibase =
779            keys::multibase_from_pubkey(attacker.verifying_key());
780        let payload_b64 = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).unwrap());
781        let signing_input = format!("{}.{}", parts[0], payload_b64);
782        let prehash: [u8; 32] = Sha256::digest(signing_input.as_bytes()).into();
783        let sig: p256::ecdsa::Signature = attacker.sign_prehash(&prehash).unwrap();
784        let forged = format!("{signing_input}.{}", URL_SAFE_NO_PAD.encode(sig.to_bytes()));
785
786        let config = fresh_config(1_716_700_010, "nonce-abc");
787        match verify_mid_response(&forged, &config) {
788            Err(VerifyError::CurrentVmNotInHeadRoster { vm_id }) => {
789                assert!(vm_id.ends_with("#dev-laptop"));
790            }
791            other => panic!("a stranger's key under a rostered id must be refused, got {other:?}"),
792        }
793    }
794
795    /// Append a roster entry at `version` listing `devices`, signed by `signer`.
796    fn push_roster(
797        snapshot: &mut IdentitySnapshot,
798        identity: &IdentityFixture,
799        version: u64,
800        devices: &[&DeviceKey],
801        signer: &DeviceKey,
802    ) {
803        let mut entry = EmbeddedRosterChainEntry {
804            version,
805            did: identity.did(),
806            verification_methods: devices.iter().map(|d| identity.vm_for(d)).collect(),
807            signed_at: 1_710_000_000 + version,
808            signed_by_signer_in_prior_roster: String::new(),
809            signer_kid: signer.device_id.clone(),
810        };
811        entry.signed_by_signer_in_prior_roster = sign_chain_entry(&entry, &signer.signing_key);
812        snapshot.roster_chain.push(entry);
813    }
814
815    /// The phone is added at v2 and removed at v3 by the laptop. The phone then
816    /// signs its own v3′ from v2 that keeps itself. Both histories verify on their
817    /// own; only the roster the RP saw at v3 tells them apart.
818    #[test]
819    fn a_history_branched_off_an_older_roster_is_refused() {
820        let identity = IdentityFixture::new("genesis", "dev-laptop");
821        let phone = DeviceKey::new("new-phone", "dev-phone");
822
823        // The honest history, as the RP saw it last: v3 without the phone.
824        let mut honest = two_device_identity(&identity, &phone);
825        push_roster(&mut honest, &identity, 3, &[&identity.genesis], &identity.genesis);
826        honest.current_verification_method = identity.embedded_vm_for(&identity.genesis);
827        let laptop = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("genesis"));
828        let seen = verify_mid_response(
829            &mint_jwt(&honest, &laptop, "https://acme.com", "n1", 1_716_700_000),
830            &fresh_config(1_716_700_010, "n1"),
831        )
832        .unwrap();
833        let mark = seen.head();
834        assert_eq!(mark.0, 3);
835
836        // The phone's branch: v3′ (and v4′) from v2, keeping itself.
837        let mut forked = two_device_identity(&identity, &phone);
838        push_roster(&mut forked, &identity, 3, &[&identity.genesis, &phone], &phone);
839        let phone_signer = InMemoryDeviceSigner::new("dev-phone", make_signing_key("new-phone"));
840        let v3_prime = verify_mid_response(
841            &mint_jwt(&forked, &phone_signer, "https://acme.com", "n2", 1_716_700_000),
842            &fresh_config(1_716_700_010, "n2"),
843        )
844        .expect("the branch verifies on its own");
845        assert!(v3_prime.check_rollback(Some(mark.0)).is_ok(), "the version-only mark misses it");
846        assert!(matches!(
847            v3_prime.check_continuity(Some(mark)),
848            Err(VerifyError::ForkDetected { version: 3 })
849        ));
850
851        push_roster(&mut forked, &identity, 4, &[&identity.genesis, &phone], &phone);
852        let v4_prime = verify_mid_response(
853            &mint_jwt(&forked, &phone_signer, "https://acme.com", "n3", 1_716_700_000),
854            &fresh_config(1_716_700_010, "n3"),
855        )
856        .unwrap();
857        assert!(matches!(
858            v4_prime.check_continuity(Some(mark)),
859            Err(VerifyError::ForkDetected { version: 3 })
860        ));
861
862        // The honest history continues: v4 on top of v3 passes, and so does v3 itself.
863        push_roster(&mut honest, &identity, 4, &[&identity.genesis], &identity.genesis);
864        let next = verify_mid_response(
865            &mint_jwt(&honest, &laptop, "https://acme.com", "n4", 1_716_700_000),
866            &fresh_config(1_716_700_010, "n4"),
867        )
868        .unwrap();
869        next.check_continuity(Some(mark)).unwrap();
870        seen.check_continuity(Some(mark)).unwrap();
871        // An older head is still a rollback.
872        assert!(matches!(
873            verify_mid_response(
874                &mint_jwt(&two_device_identity(&identity, &phone), &phone_signer, "https://acme.com", "n5", 1_716_700_000),
875                &fresh_config(1_716_700_010, "n5"),
876            )
877            .unwrap()
878            .check_continuity(Some(mark)),
879            Err(VerifyError::RollbackDetected { current: 2, last_seen: 3 })
880        ));
881    }
882
883    #[test]
884    fn a_chain_entry_naming_another_did_is_refused() {
885        let identity = IdentityFixture::new("genesis", "dev-laptop");
886        let phone = DeviceKey::new("new-phone", "dev-phone");
887        let mut snapshot = two_device_identity(&identity, &phone);
888        snapshot.roster_chain[0].did = "did:mata:someone-else".into();
889        snapshot.roster_chain[0].signed_by_signer_in_prior_roster =
890            sign_chain_entry(&snapshot.roster_chain[0], &identity.genesis.signing_key);
891        let signer = InMemoryDeviceSigner::new("dev-phone", make_signing_key("new-phone"));
892        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
893        assert!(matches!(
894            verify_mid_response(&jwt, &fresh_config(1_716_700_010, "nonce-abc")),
895            Err(VerifyError::ChainEntryDidMismatch { entry_version: 2, .. })
896        ));
897    }
898
899    // ─── Rollback detection (caller-side) ──────────────────────────────────
900
901    #[test]
902    fn rollback_passes_when_no_history() {
903        let identity = IdentityFixture::new("device-A", "dev-laptop");
904        let snapshot = fresh_identity(&identity);
905        let signer = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("device-A"));
906        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
907        let verified =
908            verify_mid_response(&jwt, &fresh_config(1_716_700_010, "nonce-abc")).unwrap();
909
910        assert!(verified.check_rollback(None).is_ok());
911    }
912
913    #[test]
914    fn rollback_passes_when_current_equals_last_seen() {
915        let identity = IdentityFixture::new("device-A", "dev-laptop");
916        let snapshot = fresh_identity(&identity);
917        let signer = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("device-A"));
918        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
919        let verified =
920            verify_mid_response(&jwt, &fresh_config(1_716_700_010, "nonce-abc")).unwrap();
921
922        assert!(verified.check_rollback(Some(1)).is_ok());
923    }
924
925    #[test]
926    fn rollback_rejected_when_current_below_last_seen() {
927        let identity = IdentityFixture::new("device-A", "dev-laptop");
928        let snapshot = fresh_identity(&identity);
929        let signer = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("device-A"));
930        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
931        let verified =
932            verify_mid_response(&jwt, &fresh_config(1_716_700_010, "nonce-abc")).unwrap();
933
934        match verified.check_rollback(Some(5)) {
935            Err(VerifyError::RollbackDetected { current, last_seen }) => {
936                assert_eq!(current, 1);
937                assert_eq!(last_seen, 5);
938            }
939            other => panic!("expected RollbackDetected, got {other:?}"),
940        }
941    }
942
943    // ─── Shape checks ──────────────────────────────────────────────────────
944
945    #[test]
946    fn malformed_jws_shape_rejected() {
947        let config = fresh_config(1_716_700_010, "nonce-abc");
948        let err = verify_mid_response("not.a.valid.jws.has.too.many.dots", &config).unwrap_err();
949        assert!(matches!(err, VerifyError::InvalidJwsShape(_)));
950    }
951
952    #[test]
953    fn genesis_roster_hash_is_deterministic() {
954        // Two verifications of the same JWT MUST produce the same hash.
955        let identity = IdentityFixture::new("device-A", "dev-laptop");
956        let snapshot = fresh_identity(&identity);
957        let signer = InMemoryDeviceSigner::new("dev-laptop", make_signing_key("device-A"));
958        let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
959        let config = fresh_config(1_716_700_010, "nonce-abc");
960
961        let v1 = verify_mid_response(&jwt, &config).unwrap();
962        let v2 = verify_mid_response(&jwt, &config).unwrap();
963        assert_eq!(v1.genesis_roster_hash, v2.genesis_roster_hash);
964    }
965}