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 std::collections::BTreeMap;
72
73#[derive(Debug, Clone)]
80pub struct VerifyConfig {
81 pub expected_audience: String,
86 pub expected_nonce: String,
90 pub max_iat_skew_secs: u64,
96 pub now_unix_secs: u64,
101}
102
103#[derive(Debug, Clone)]
107pub struct VerifiedMid {
108 pub did: String,
111 pub genesis_roster_hash: [u8; 32],
116 pub current_version: u64,
120 pub claims: BTreeMap<String, ClaimValue>,
123 pub iat: u64,
125 pub exp: u64,
127 pub aud: String,
130 pub roster_hashes: Vec<(u64, [u8; 32])>,
135}
136
137impl VerifiedMid {
138 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 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 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
182pub 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
202pub 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 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 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 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 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#[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 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 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 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 fn did(&self) -> String {
353 keys::did_from_pubkey(self.genesis.signing_key.verifying_key())
354 }
355
356 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 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 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 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 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 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 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 #[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 #[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 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 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 let jwt = mint_jwt(&snapshot, &signer, "https://acme.com", "nonce-abc", 1_716_700_000);
616
617 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 verify_mid_response(&good, &config).unwrap();
638 verify_mid_response(&good, &config).unwrap();
639
640 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 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 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 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 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 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 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 #[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 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 #[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 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 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 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 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 #[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 #[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 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}