1#![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
64pub use mid_issuer::{
67 AttestedBy, ClaimValue, EmbeddedGenesisRoster, EmbeddedRosterChainEntry,
68 EmbeddedVerificationMethod, MidJwtPayload, VerificationMethod,
69};
70
71use sha2::{Digest, Sha256};
72use std::collections::BTreeMap;
73
74#[derive(Debug, Clone)]
81pub struct VerifyConfig {
82 pub expected_audience: String,
87 pub expected_nonce: String,
91 pub max_iat_skew_secs: u64,
97 pub now_unix_secs: u64,
102}
103
104#[derive(Debug, Clone)]
108pub struct VerifiedMid {
109 pub did: String,
112 pub genesis_roster_hash: [u8; 32],
117 pub current_version: u64,
121 pub claims: BTreeMap<String, ClaimValue>,
124 pub iat: u64,
126 pub exp: u64,
128 pub aud: String,
131 pub roster_hashes: Vec<(u64, [u8; 32])>,
136}
137
138impl VerifiedMid {
139 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 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 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
183pub fn verify_mid_response(jwt: &str, config: &VerifyConfig) -> Result<VerifiedMid, VerifyError> {
193 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 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 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 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#[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 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 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 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 fn did(&self) -> String {
320 keys::did_from_pubkey(self.genesis.signing_key.verifying_key())
321 }
322
323 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 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 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 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 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 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 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 #[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 #[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 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 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 let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
583
584 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 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 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 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 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 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 #[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 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 #[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 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 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 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 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 #[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 #[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 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}