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