-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathverify.rs
More file actions
1821 lines (1632 loc) · 63.6 KB
/
Copy pathverify.rs
File metadata and controls
1821 lines (1632 loc) · 63.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Free-function verification API wrapping [`crate::verifier::Verifier`].
//!
//! **Fail-open duplicity policy**: a diverging shared KEL is reported via
//! `VerificationReport::duplicity_warning` but does not invalidate an
//! attestation whose own signature checks out. Rationale: fail-closed would
//! turn one bad rotation on the identity's shared KEL into a workspace-wide
//! outage for every attestation signed by a current controller — strictly
//! worse than surfacing the fork and letting the user resolve via
//! `auths device remove` on the side they trust. The warning channel is
//! structured (`DuplicityReport`) so downstream policy — CLI status,
//! iOS banner, future CI gates — can decide what to do with it.
use crate::core::{
Attestation, DevicePublicKey, VerifiedAttestation, canonicalize_attestation_data,
};
use crate::error::AttestationError;
use crate::types::{ChainLink, VerificationReport, VerificationStatus};
#[cfg(feature = "native")]
use crate::witness::WitnessVerifyConfig;
use auths_crypto::CryptoProvider;
use auths_keri::{Event, compute_said, find_seal_in_kel};
use chrono::{DateTime, Duration, Utc};
use log::debug;
use serde::Serialize;
/// Maximum allowed clock skew in seconds for timestamp validation.
const MAX_SKEW_SECS: i64 = 5 * 60;
// ---------------------------------------------------------------------------
// Public free functions — backward-compatible, #[cfg(feature = "native")]
// ---------------------------------------------------------------------------
/// Verify an attestation's signatures against the issuer's public key.
///
/// Args:
/// * `att`: The attestation to verify.
/// * `issuer_pk`: Typed issuer public key (Ed25519 or P-256).
#[cfg(feature = "native")]
pub async fn verify_with_keys(
att: &Attestation,
issuer_pk: &DevicePublicKey,
) -> Result<VerifiedAttestation, AttestationError> {
crate::verifier::Verifier::native()
.verify_with_keys(att, issuer_pk)
.await
}
/// Verify an attestation against a specific point in time.
///
/// Args:
/// * `att`: The attestation to verify.
/// * `issuer_pk`: Typed issuer public key (Ed25519 or P-256).
/// * `at`: The reference timestamp for expiry evaluation.
#[cfg(feature = "native")]
pub async fn verify_at_time(
att: &Attestation,
issuer_pk: &DevicePublicKey,
at: DateTime<Utc>,
) -> Result<VerifiedAttestation, AttestationError> {
crate::verifier::Verifier::native()
.verify_at_time(att, issuer_pk, at)
.await
}
/// Verify a chain and validate witness receipts against a quorum threshold.
///
/// Args:
/// * `attestations`: Ordered attestation chain (root first).
/// * `root_pk`: Typed root identity public key (Ed25519 or P-256).
/// * `witness_config`: Witness receipts and quorum threshold to validate.
#[cfg(feature = "native")]
pub async fn verify_chain_with_witnesses(
attestations: &[Attestation],
root_pk: &DevicePublicKey,
witness_config: &WitnessVerifyConfig<'_>,
) -> Result<VerificationReport, AttestationError> {
crate::verifier::Verifier::native()
.verify_chain_with_witnesses(attestations, root_pk, witness_config)
.await
}
/// Verify an ordered attestation chain starting from a known root public key.
///
/// Args:
/// * `attestations`: Ordered attestation chain (root first).
/// * `root_pk`: Typed root identity public key (Ed25519 or P-256).
#[cfg(feature = "native")]
pub async fn verify_chain(
attestations: &[Attestation],
root_pk: &DevicePublicKey,
) -> Result<VerificationReport, AttestationError> {
crate::verifier::Verifier::native()
.verify_chain(attestations, root_pk)
.await
}
/// Verify that a device is authorized under a given identity.
///
/// Args:
/// * `identity_did`: The DID of the authorizing identity.
/// * `device_did`: The device DID to check authorization for.
/// * `attestations`: Pool of attestations to search.
/// * `identity_pk`: Typed identity public key (Ed25519 or P-256).
#[cfg(feature = "native")]
pub async fn verify_device_authorization(
identity_did: &str,
device_did: &crate::types::CanonicalDid,
attestations: &[Attestation],
identity_pk: &DevicePublicKey,
) -> Result<VerificationReport, AttestationError> {
crate::verifier::Verifier::native()
.verify_device_authorization(identity_did, device_did, attestations, identity_pk)
.await
}
use crate::types::CanonicalDid;
/// Checks if a device appears in a list of **already-verified** attestations.
pub fn is_device_listed(
identity_did: &str,
device_did: &CanonicalDid,
attestations: &[VerifiedAttestation],
now: DateTime<Utc>,
) -> bool {
let device_did_str = device_did.to_string();
attestations.iter().any(|verified| {
let att = verified.inner();
if att.issuer != identity_did {
return false;
}
if att.subject.to_string() != device_did_str {
return false;
}
if att.is_revoked() {
return false;
}
if let Some(exp) = att.expires_at
&& now > exp
{
return false;
}
true
})
}
// ---------------------------------------------------------------------------
// Device-link verification — stateless, provider-agnostic
// ---------------------------------------------------------------------------
/// Result of verifying a device's link to a KERI identity.
///
/// Verification failures are expressed as `valid: false` with an error message,
/// not as Rust `Err` values. Only infrastructure errors (bad input, serialization)
/// produce `Err`.
#[derive(Debug, Clone, Serialize)]
pub struct DeviceLinkVerification {
/// Whether the device link verified successfully.
pub valid: bool,
/// Human-readable reason if verification failed.
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
/// The KERI key state after KEL replay (present on success).
#[serde(skip_serializing_if = "Option::is_none")]
pub key_state: Option<auths_keri::KeyState>,
/// Sequence number of the IXN event anchoring the attestation seal (if found).
#[serde(skip_serializing_if = "Option::is_none")]
pub seal_sequence: Option<u128>,
}
impl DeviceLinkVerification {
fn success(key_state: auths_keri::KeyState, seal_sequence: Option<u128>) -> Self {
Self {
valid: true,
error: None,
key_state: Some(key_state),
seal_sequence,
}
}
fn failure(reason: impl Into<String>) -> Self {
Self {
valid: false,
error: Some(reason.into()),
key_state: None,
seal_sequence: None,
}
}
}
/// Verify that a device (`did:key`) is cryptographically linked to a KERI identity.
///
/// Composes: KEL verification, attestation signature verification, device DID matching,
/// and optional seal anchoring. Provider-agnostic — works with any `CryptoProvider`.
///
/// Args:
/// * `events`: Parsed KEL events (inception first).
/// * `attestation`: The attestation linking identity to device.
/// * `device_did`: The expected device DID (checked against attestation subject).
/// * `now`: Reference time for expiration/revocation checks.
/// * `provider`: Cryptographic provider for Ed25519 verification.
///
/// Usage:
/// ```ignore
/// let result = verify_device_link(&events, &att, "did:key:z6Mk...", now, &provider).await;
/// if result.valid { /* ... */ }
/// ```
pub async fn verify_device_link(
events: &[Event],
attestation: &Attestation,
device_did: &str,
now: DateTime<Utc>,
provider: &dyn CryptoProvider,
) -> DeviceLinkVerification {
// rt-002-allow: `events` is the device-link KEL supplied by the caller from the local trusted registry / an authenticated bundle, and the attestation signature is bound to the resulting key-state. Residual: the untrusted WASM verifyDeviceLink boundary — its authenticated counterpart is validateKelJson (which now routes through validate_signed_kel); a signature-carrying verifyDeviceLink input is the tracked RT-002 follow-up.
let key_state = match auths_keri::TrustedKel::from_trusted_source(events).replay() {
Ok(ks) => ks,
Err(e) => return DeviceLinkVerification::failure(format!("KEL verification failed: {e}")),
};
if attestation.subject.as_str() != device_did {
return DeviceLinkVerification::failure(format!(
"Device DID mismatch: attestation subject is '{}', expected '{device_did}'",
attestation.subject
));
}
let current_pk = match key_state.current_keys.first() {
Some(encoded) => match auths_keri::KeriPublicKey::parse(encoded.as_str()) {
Ok(keri_pk) => {
// Curve travels with the key (CESR prefix) — never hardcode it; P-256
// device keys must verify too (the workspace default curve).
let curve = keri_pk.curve();
let bytes = keri_pk.into_bytes().to_vec();
match DevicePublicKey::try_new(curve, &bytes) {
Ok(dpk) => dpk,
Err(e) => {
return DeviceLinkVerification::failure(format!(
"Invalid current key: {e}"
));
}
}
}
Err(e) => {
return DeviceLinkVerification::failure(format!("Invalid current key: {e}"));
}
},
None => return DeviceLinkVerification::failure("KEL has no current keys"),
};
if let Err(e) = verify_with_keys_at(attestation, ¤t_pk, now, true, provider).await {
return DeviceLinkVerification::failure(format!("Attestation verification failed: {e}"));
}
let seal_sequence = compute_attestation_seal_digest(attestation)
.ok()
.and_then(|digest| find_seal_in_kel(events, digest.as_str()));
DeviceLinkVerification::success(key_state, seal_sequence)
}
/// Compute the KERI SAID (Blake3 digest) of an attestation's canonical form.
///
/// This is the digest that should appear in a KEL IXN seal when the attestation
/// is anchored. Returns the SAID string (E-prefixed base64url Blake3).
pub fn compute_attestation_seal_digest(
attestation: &Attestation,
) -> Result<String, AttestationError> {
let canonical = canonicalize_attestation_data(&attestation.canonical_data())?;
let value: serde_json::Value = serde_json::from_slice(&canonical)
.map_err(|e| AttestationError::SerializationError(e.to_string()))?;
Ok(compute_said(&value)
.map_err(|e| AttestationError::SerializationError(e.to_string()))?
.into_inner())
}
// ---------------------------------------------------------------------------
// Internal async functions — used by Verifier and free function wrappers
// ---------------------------------------------------------------------------
pub(crate) async fn verify_with_keys_at(
att: &Attestation,
issuer_pk: &DevicePublicKey,
at: DateTime<Utc>,
check_skew: bool,
provider: &dyn CryptoProvider,
) -> Result<(), AttestationError> {
let reference_time = at;
// --- 1. Check revocation (time-aware) ---
if let Some(revoked_at) = att.revoked_at
&& revoked_at <= reference_time
{
return Err(AttestationError::AttestationRevoked);
}
// --- 2. Check expiration against reference time ---
if let Some(exp) = att.expires_at
&& reference_time > exp
{
return Err(AttestationError::AttestationExpired {
at: exp.to_rfc3339(),
});
}
// --- 3. Check timestamp skew against reference time ---
if check_skew
&& let Some(ts) = att.timestamp
&& ts > reference_time + Duration::seconds(MAX_SKEW_SECS)
{
return Err(AttestationError::TimestampInFuture {
at: ts.to_rfc3339(),
});
}
// --- 4. Reconstruct and canonicalize data ---
let canonical_json_bytes = canonicalize_attestation_data(&att.canonical_data())?;
let data_to_verify = canonical_json_bytes.as_slice();
debug!(
"(Verify) Canonical data: {}",
String::from_utf8_lossy(&canonical_json_bytes)
);
// --- 5. Verify issuer signature (dispatched on curve) ---
if !att.identity_signature.is_empty() {
verify_signature_by_curve(
issuer_pk,
data_to_verify,
att.identity_signature.as_bytes(),
provider,
SignatureRole::Issuer,
)
.await?;
debug!("(Verify) Issuer signature verified successfully.");
} else {
// An attestation with no issuer signature cannot prove that any identity
// authorized it, so the authority path fails closed. A device asserting
// only about its own key is checked through a dedicated self-assertion
// entry point, never here.
return Err(AttestationError::IssuerSignatureFailed(
"missing issuer signature".to_string(),
));
}
// --- 6. Verify device signature (dispatched on curve) ---
verify_signature_by_curve(
&att.device_public_key,
data_to_verify,
att.device_signature.as_bytes(),
provider,
SignatureRole::Device,
)
.await?;
debug!("(Verify) Device signature verified successfully.");
Ok(())
}
/// Which signature slot a curve-dispatch error should be attributed to.
#[derive(Clone, Copy)]
enum SignatureRole {
Issuer,
Device,
}
/// Verify a signature via the canonical `DevicePublicKey::verify`, attributing
/// failures to the appropriate role (issuer vs device) at the boundary.
///
/// Thin wrapper preserved so that existing chain-verification code can keep
/// its role-attributed error enum; the dispatch itself now lives in
/// `DevicePublicKey::verify` (fn-114.14).
async fn verify_signature_by_curve(
pk: &DevicePublicKey,
message: &[u8],
signature: &[u8],
provider: &dyn CryptoProvider,
role: SignatureRole,
) -> Result<(), AttestationError> {
let map_err = |e: String| match role {
SignatureRole::Issuer => AttestationError::IssuerSignatureFailed(e),
SignatureRole::Device => AttestationError::DeviceSignatureFailed(e),
};
pk.verify(message, signature, provider)
.await
.map_err(|e| map_err(e.to_string()))
}
pub(crate) async fn verify_chain_inner(
attestations: &[Attestation],
root_pk: &DevicePublicKey,
provider: &dyn CryptoProvider,
now: DateTime<Utc>,
) -> Result<VerificationReport, AttestationError> {
if attestations.is_empty() {
return Ok(VerificationReport::with_status(
VerificationStatus::BrokenChain {
missing_link: "empty chain".to_string(),
},
vec![],
));
}
let mut chain_links: Vec<ChainLink> = Vec::with_capacity(attestations.len());
let first_att = &attestations[0];
match verify_single_attestation(first_att, root_pk, 0, provider, now).await {
Ok(link) => chain_links.push(link),
Err((status, link)) => {
chain_links.push(link);
return Ok(VerificationReport::with_status(status, chain_links));
}
}
for (idx, att) in attestations.iter().enumerate().skip(1) {
let prev_att = &attestations[idx - 1];
if att.issuer.as_str() != prev_att.subject.as_str() {
let link = ChainLink::invalid(
att.issuer.to_string(),
att.subject.to_string(),
format!(
"Chain broken: expected issuer '{}', got '{}'",
prev_att.subject, att.issuer
),
);
chain_links.push(link);
return Ok(VerificationReport::with_status(
VerificationStatus::BrokenChain {
missing_link: format!(
"Issuer mismatch at step {}: expected '{}', got '{}'",
idx, prev_att.subject, att.issuer
),
},
chain_links,
));
}
let issuer_pk = &prev_att.device_public_key;
match verify_single_attestation(att, issuer_pk, idx, provider, now).await {
Ok(link) => chain_links.push(link),
Err((status, link)) => {
chain_links.push(link);
return Ok(VerificationReport::with_status(status, chain_links));
}
}
}
Ok(VerificationReport::valid(chain_links))
}
pub(crate) async fn verify_device_authorization_inner(
identity_did: &str,
device_did: &CanonicalDid,
attestations: &[Attestation],
identity_pk: &DevicePublicKey,
provider: &dyn CryptoProvider,
now: DateTime<Utc>,
) -> Result<VerificationReport, AttestationError> {
let device_did_str = device_did.to_string();
let matching: Vec<&Attestation> = attestations
.iter()
.filter(|a| a.issuer == identity_did && a.subject.to_string() == device_did_str)
.collect();
if matching.is_empty() {
return Ok(VerificationReport::with_status(
VerificationStatus::BrokenChain {
missing_link: format!(
"No attestation found for device {} under {}",
device_did_str, identity_did
),
},
vec![],
));
}
match verify_single_attestation(matching[0], identity_pk, 0, provider, now).await {
Ok(link) => Ok(VerificationReport::valid(vec![link])),
Err((status, link)) => Ok(VerificationReport::with_status(status, vec![link])),
}
}
async fn verify_single_attestation(
att: &Attestation,
issuer_pk: &DevicePublicKey,
step: usize,
provider: &dyn CryptoProvider,
now: DateTime<Utc>,
) -> Result<ChainLink, (VerificationStatus, ChainLink)> {
let issuer = att.issuer.to_string();
let subject = att.subject.to_string();
if att.is_revoked() {
return Err((
VerificationStatus::Revoked { at: att.revoked_at },
ChainLink::invalid(issuer, subject, "Attestation revoked".to_string()),
));
}
if let Some(exp) = att.expires_at
&& now > exp
{
return Err((
VerificationStatus::Expired { at: exp },
ChainLink::invalid(
issuer,
subject,
format!("Attestation expired on {}", exp.to_rfc3339()),
),
));
}
match verify_with_keys_at(att, issuer_pk, now, true, provider).await {
Ok(()) => Ok(ChainLink::valid(issuer, subject)),
Err(e) => Err((
VerificationStatus::InvalidSignature { step },
ChainLink::invalid(issuer, subject, e.to_string()),
)),
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::disallowed_methods)]
mod tests {
use super::*;
use crate::clock::ClockProvider;
use crate::core::{Ed25519PublicKey, Ed25519Signature, ResourceId};
use crate::types::CanonicalDid;
use crate::verifier::Verifier;
use auths_crypto::RingCryptoProvider;
use auths_crypto::testing::create_test_keypair;
use auths_keri::Said;
use chrono::{DateTime, Duration, TimeZone, Utc};
use ring::signature::{Ed25519KeyPair, KeyPair};
use std::sync::Arc;
/// Wrap a raw 32-byte Ed25519 key into a `DevicePublicKey` for tests.
fn ed(pk: &[u8]) -> DevicePublicKey {
DevicePublicKey::try_new(auths_crypto::CurveType::Ed25519, pk).unwrap()
}
/// Build a `did:key:z...` string from a 32-byte Ed25519 public key (test helper).
fn ed25519_did(pk: &[u8; 32]) -> String {
CanonicalDid::from_public_key_did_key(pk, auths_crypto::CurveType::Ed25519).to_string()
}
struct TestClock(DateTime<Utc>);
impl ClockProvider for TestClock {
fn now(&self) -> DateTime<Utc> {
self.0
}
}
fn fixed_now() -> DateTime<Utc> {
Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap()
}
fn test_verifier() -> Verifier {
Verifier::new(
Arc::new(RingCryptoProvider),
Arc::new(TestClock(fixed_now())),
)
}
/// Helper to create a signed attestation
fn create_signed_attestation(
issuer_kp: &Ed25519KeyPair,
device_kp: &Ed25519KeyPair,
issuer_did: &str,
subject_did: &str,
revoked_at: Option<DateTime<Utc>>,
expires_at: Option<DateTime<Utc>>,
) -> Attestation {
let device_pk: [u8; 32] = device_kp.public_key().as_ref().try_into().unwrap();
let mut att = Attestation {
version: 1,
rid: ResourceId::new("test-rid"),
issuer: CanonicalDid::new_unchecked(issuer_did),
subject: CanonicalDid::new_unchecked(subject_did),
device_public_key: Ed25519PublicKey::from_bytes(device_pk).into(),
identity_signature: Ed25519Signature::empty(),
device_signature: Ed25519Signature::empty(),
revoked_at,
expires_at,
timestamp: Some(fixed_now()),
note: None,
payload: None,
delegated_by: None,
signer_type: None,
environment_claim: None,
commit_sha: None,
commit_message: None,
author: None,
oidc_binding: None,
};
let canonical_bytes = canonicalize_attestation_data(&att.canonical_data()).unwrap();
att.identity_signature =
Ed25519Signature::try_from_slice(issuer_kp.sign(&canonical_bytes).as_ref()).unwrap();
att.device_signature =
Ed25519Signature::try_from_slice(device_kp.sign(&canonical_bytes).as_ref()).unwrap();
att
}
#[tokio::test]
async fn verify_chain_empty_returns_broken_chain() {
let result = test_verifier()
.verify_chain(&[], &ed(&[0u8; 32]))
.await
.unwrap();
assert!(!result.is_valid());
match result.status {
VerificationStatus::BrokenChain { missing_link } => {
assert_eq!(missing_link, "empty chain");
}
_ => panic!("Expected BrokenChain status"),
}
assert!(result.chain.is_empty());
}
#[tokio::test]
async fn verify_chain_single_valid_attestation() {
let (root_kp, root_pk) = create_test_keypair(&[1u8; 32]);
let root_did = ed25519_did(&root_pk);
let (device_kp, device_pk) = create_test_keypair(&[2u8; 32]);
let device_did = ed25519_did(&device_pk);
let att = create_signed_attestation(
&root_kp,
&device_kp,
&root_did,
&device_did,
None,
Some(fixed_now() + Duration::days(365)),
);
let result = test_verifier()
.verify_chain(&[att], &ed(&root_pk))
.await
.unwrap();
assert!(result.is_valid());
assert_eq!(result.chain.len(), 1);
assert!(result.chain[0].valid);
}
#[tokio::test]
async fn verify_chain_valid_report_is_offline_unknown_not_bare() {
// A chain verified offline (no fresher source supplied) is honest about it: the report
// names its freshness as `Unknown`, never a bare `Valid` that reads as real-time fresh.
// This is what the CLI verify callers consume to render "valid (freshness unknown)".
let (root_kp, root_pk) = create_test_keypair(&[1u8; 32]);
let root_did = ed25519_did(&root_pk);
let (device_kp, device_pk) = create_test_keypair(&[2u8; 32]);
let device_did = ed25519_did(&device_pk);
let att = create_signed_attestation(
&root_kp,
&device_kp,
&root_did,
&device_did,
None,
Some(fixed_now() + Duration::days(365)),
);
let report = test_verifier()
.verify_chain(&[att], &ed(&root_pk))
.await
.unwrap();
assert!(report.is_valid());
assert_eq!(
report.freshness(),
crate::freshness::Freshness::Unknown,
"an offline chain verify must surface Unknown freshness, never a bare Valid"
);
}
#[tokio::test]
async fn verify_chain_revoked_attestation_returns_revoked() {
let (root_kp, root_pk) = create_test_keypair(&[1u8; 32]);
let root_did = ed25519_did(&root_pk);
let (device_kp, device_pk) = create_test_keypair(&[2u8; 32]);
let device_did = ed25519_did(&device_pk);
let att = create_signed_attestation(
&root_kp,
&device_kp,
&root_did,
&device_did,
Some(fixed_now()),
Some(fixed_now() + Duration::days(365)),
);
let result = test_verifier()
.verify_chain(&[att], &ed(&root_pk))
.await
.unwrap();
assert!(!result.is_valid());
match result.status {
VerificationStatus::Revoked { .. } => {}
_ => panic!("Expected Revoked status, got {:?}", result.status),
}
}
#[tokio::test]
async fn verify_chain_expired_attestation_returns_expired() {
let (root_kp, root_pk) = create_test_keypair(&[1u8; 32]);
let root_did = ed25519_did(&root_pk);
let (device_kp, device_pk) = create_test_keypair(&[2u8; 32]);
let device_did = ed25519_did(&device_pk);
let att = create_signed_attestation(
&root_kp,
&device_kp,
&root_did,
&device_did,
None,
Some(fixed_now() - Duration::days(1)),
);
let result = test_verifier()
.verify_chain(&[att], &ed(&root_pk))
.await
.unwrap();
assert!(!result.is_valid());
match result.status {
VerificationStatus::Expired { .. } => {}
_ => panic!("Expected Expired status, got {:?}", result.status),
}
}
#[tokio::test]
async fn verify_chain_invalid_signature_returns_invalid_signature() {
let (root_kp, root_pk) = create_test_keypair(&[1u8; 32]);
let root_did = ed25519_did(&root_pk);
let (device_kp, device_pk) = create_test_keypair(&[2u8; 32]);
let device_did = ed25519_did(&device_pk);
let mut att = create_signed_attestation(
&root_kp,
&device_kp,
&root_did,
&device_did,
None,
Some(fixed_now() + Duration::days(365)),
);
let mut tampered = *att.identity_signature.as_bytes();
tampered[0] ^= 0xFF;
att.identity_signature = Ed25519Signature::from_bytes(tampered);
let result = test_verifier()
.verify_chain(&[att], &ed(&root_pk))
.await
.unwrap();
assert!(!result.is_valid());
match result.status {
VerificationStatus::InvalidSignature { step } => {
assert_eq!(step, 0);
}
_ => panic!("Expected InvalidSignature status, got {:?}", result.status),
}
}
#[tokio::test]
async fn verify_chain_broken_link_returns_broken_chain() {
let (root_kp, root_pk) = create_test_keypair(&[1u8; 32]);
let root_did = ed25519_did(&root_pk);
let (device1_kp, device1_pk) = create_test_keypair(&[2u8; 32]);
let device1_did = ed25519_did(&device1_pk);
let (device2_kp, device2_pk) = create_test_keypair(&[3u8; 32]);
let device2_did = ed25519_did(&device2_pk);
let att1 = create_signed_attestation(
&root_kp,
&device1_kp,
&root_did,
&device1_did,
None,
Some(fixed_now() + Duration::days(365)),
);
let att2 = create_signed_attestation(
&device1_kp,
&device2_kp,
&root_did, // WRONG: should be device1_did
&device2_did,
None,
Some(fixed_now() + Duration::days(365)),
);
let result = test_verifier()
.verify_chain(&[att1, att2], &ed(&root_pk))
.await
.unwrap();
assert!(!result.is_valid());
match result.status {
VerificationStatus::BrokenChain { missing_link } => {
assert!(missing_link.contains("Issuer mismatch"));
}
_ => panic!("Expected BrokenChain status, got {:?}", result.status),
}
}
#[tokio::test]
async fn verify_chain_valid_three_level_chain() {
let (root_kp, root_pk) = create_test_keypair(&[1u8; 32]);
let root_did = ed25519_did(&root_pk);
let (identity_kp, identity_pk) = create_test_keypair(&[2u8; 32]);
let identity_did = ed25519_did(&identity_pk);
let (device_kp, device_pk) = create_test_keypair(&[3u8; 32]);
let device_did = ed25519_did(&device_pk);
let att1 = create_signed_attestation(
&root_kp,
&identity_kp,
&root_did,
&identity_did,
None,
Some(fixed_now() + Duration::days(365)),
);
let att2 = create_signed_attestation(
&identity_kp,
&device_kp,
&identity_did,
&device_did,
None,
Some(fixed_now() + Duration::days(365)),
);
let result = test_verifier()
.verify_chain(&[att1, att2], &ed(&root_pk))
.await
.unwrap();
assert!(result.is_valid());
assert_eq!(result.chain.len(), 2);
assert!(result.chain[0].valid);
assert!(result.chain[1].valid);
}
#[tokio::test]
async fn verify_chain_revoked_intermediate_returns_revoked() {
let (root_kp, root_pk) = create_test_keypair(&[1u8; 32]);
let root_did = ed25519_did(&root_pk);
let (identity_kp, identity_pk) = create_test_keypair(&[2u8; 32]);
let identity_did = ed25519_did(&identity_pk);
let (device_kp, device_pk) = create_test_keypair(&[3u8; 32]);
let device_did = ed25519_did(&device_pk);
let att1 = create_signed_attestation(
&root_kp,
&identity_kp,
&root_did,
&identity_did,
None,
Some(fixed_now() + Duration::days(365)),
);
let att2 = create_signed_attestation(
&identity_kp,
&device_kp,
&identity_did,
&device_did,
Some(fixed_now()),
Some(fixed_now() + Duration::days(365)),
);
let result = test_verifier()
.verify_chain(&[att1, att2], &ed(&root_pk))
.await
.unwrap();
assert!(!result.is_valid());
match result.status {
VerificationStatus::Revoked { .. } => {}
_ => panic!("Expected Revoked status, got {:?}", result.status),
}
assert_eq!(result.chain.len(), 2);
assert!(result.chain[0].valid);
assert!(!result.chain[1].valid);
}
#[tokio::test]
async fn verify_at_time_valid_before_expiration() {
let (root_kp, root_pk) = create_test_keypair(&[1u8; 32]);
let root_did = ed25519_did(&root_pk);
let (device_kp, _) = create_test_keypair(&[2u8; 32]);
let device_did = ed25519_did(&root_pk);
let expires = fixed_now() + Duration::days(30);
let att = create_signed_attestation(
&root_kp,
&device_kp,
&root_did,
&device_did,
None,
Some(expires),
);
let verification_time = fixed_now() + Duration::days(10);
let result = test_verifier()
.verify_at_time(&att, &ed(&root_pk), verification_time)
.await;
assert!(result.is_ok());
}
#[tokio::test]
async fn verify_at_time_expired_after_expiration() {
let (root_kp, root_pk) = create_test_keypair(&[1u8; 32]);
let root_did = ed25519_did(&root_pk);
let (device_kp, _) = create_test_keypair(&[2u8; 32]);
let device_did = ed25519_did(&root_pk);
let expires = fixed_now() + Duration::days(30);
let att = create_signed_attestation(
&root_kp,
&device_kp,
&root_did,
&device_did,
None,
Some(expires),
);
let verification_time = fixed_now() + Duration::days(60);
let result = test_verifier()
.verify_at_time(&att, &ed(&root_pk), verification_time)
.await;
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("expired"));
}
#[tokio::test]
async fn verify_at_time_signature_always_checked() {
let (root_kp, root_pk) = create_test_keypair(&[1u8; 32]);
let root_did = ed25519_did(&root_pk);
let (device_kp, _) = create_test_keypair(&[2u8; 32]);
let device_did = ed25519_did(&root_pk);
let mut att = create_signed_attestation(
&root_kp,
&device_kp,
&root_did,
&device_did,
None,
Some(fixed_now() + Duration::days(365)),
);
let mut tampered = *att.identity_signature.as_bytes();
tampered[0] ^= 0xFF;
att.identity_signature = Ed25519Signature::from_bytes(tampered);
let verification_time = fixed_now() - Duration::days(10);
let result = test_verifier()
.verify_at_time(&att, &ed(&root_pk), verification_time)
.await;
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("signature verification failed")
);
}
#[tokio::test]
async fn verify_at_time_with_past_time_skips_skew_check() {
let (root_kp, root_pk) = create_test_keypair(&[1u8; 32]);
let root_did = ed25519_did(&root_pk);
let (device_kp, _) = create_test_keypair(&[2u8; 32]);
let device_did = ed25519_did(&root_pk);
let att = create_signed_attestation(
&root_kp,
&device_kp,
&root_did,
&device_did,
None,
Some(fixed_now() + Duration::days(365)),
);
let verification_time = fixed_now() - Duration::days(30);
let result = test_verifier()
.verify_at_time(&att, &ed(&root_pk), verification_time)
.await;
assert!(result.is_ok());
}
#[tokio::test]
async fn verify_with_keys_still_works() {
let (root_kp, root_pk) = create_test_keypair(&[1u8; 32]);
let root_did = ed25519_did(&root_pk);
let (device_kp, _) = create_test_keypair(&[2u8; 32]);
let device_did = ed25519_did(&root_pk);
let att = create_signed_attestation(
&root_kp,
&device_kp,
&root_did,
&device_did,
None,