vcp-core 4.2.0

Value Context Protocol (VCP) core types and parsing
Documentation
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
//! Trust anchor management for VCP issuers and auditors.
//!
//! Mirrors the Python SDK's `vcp.trust` module. A [`TrustConfig`] holds
//! collections of [`TrustAnchor`] entries keyed by entity ID. Each anchor
//! represents a public key for an issuer or auditor, with validity windows
//! and lifecycle state tracking.
//!
//! # Examples
//!
//! ```
//! use vcp_core::trust::{AnchorState, AnchorType, TrustAnchor, TrustConfig};
//! use chrono::{Utc, Duration};
//!
//! let mut config = TrustConfig::default();
//!
//! let anchor = TrustAnchor {
//!     id: "creed-space".into(),
//!     key_id: "key-2025-01".into(),
//!     algorithm: "ed25519".into(),
//!     public_key: "base64:AAAA".into(),
//!     anchor_type: AnchorType::Issuer,
//!     valid_from: Utc::now() - Duration::days(1),
//!     valid_until: Utc::now() + Duration::days(365),
//!     state: AnchorState::Active,
//! };
//!
//! config.add_issuer("creed-space", anchor);
//! assert!(config.get_issuer_key("creed-space", None).is_some());
//! ```

use std::collections::HashMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::error::{VcpError, VcpResult};

/// Maximum encoded trust configuration size accepted by [`TrustConfig::from_json`].
pub const MAX_TRUST_CONFIG_BYTES: usize = 16 * 1024 * 1024;

// ── Anchor types ────────────────────────────────────────────

/// The role an anchor fulfills in the trust chain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AnchorType {
    Issuer,
    Auditor,
}

/// Lifecycle state of a trust anchor.
///
/// Only `Active` and `Rotating` anchors are considered valid for
/// signature verification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AnchorState {
    Active,
    Rotating,
    Retired,
    Compromised,
}

impl AnchorState {
    /// Returns `true` if the anchor is in a state that allows verification.
    pub fn allows_verification(self) -> bool {
        matches!(self, AnchorState::Active | AnchorState::Rotating)
    }
}

// ── TrustAnchor ─────────────────────────────────────────────

/// A trusted public key for an issuer or auditor.
///
/// Corresponds to the Python SDK's `TrustAnchor` dataclass.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TrustAnchor {
    /// Entity identifier (e.g., `"creed-space"`).
    pub id: String,
    /// Key identifier within the entity (e.g., `"key-2025-01"`).
    pub key_id: String,
    /// Signing algorithm (e.g., `"ed25519"`).
    pub algorithm: String,
    /// Public key material, typically `"base64:<encoded>"`.
    pub public_key: String,
    /// Whether this anchor is for an issuer or auditor.
    pub anchor_type: AnchorType,
    /// Start of the validity window.
    pub valid_from: DateTime<Utc>,
    /// End of the validity window.
    pub valid_until: DateTime<Utc>,
    /// Lifecycle state of this anchor.
    #[serde(default = "default_anchor_state")]
    pub state: AnchorState,
}

fn default_anchor_state() -> AnchorState {
    AnchorState::Active
}

impl TrustAnchor {
    /// Check whether this anchor is valid at the given time.
    ///
    /// An anchor is valid when its state allows verification and the
    /// provided timestamp falls within `[valid_from, valid_until]`.
    ///
    /// If `at_time` is `None`, the current UTC time is used.
    pub fn is_valid(&self, at_time: Option<DateTime<Utc>>) -> bool {
        let at = at_time.unwrap_or_else(Utc::now);
        self.state.allows_verification() && at >= self.valid_from && at <= self.valid_until
    }

    /// Parse a `TrustAnchor` from a dictionary-style JSON value.
    ///
    /// Expects the same shape as the Python `TrustAnchor.from_dict()`:
    ///
    /// ```json
    /// {
    ///   "id": "key-2025-01",
    ///   "algorithm": "ed25519",
    ///   "public_key": "base64:...",
    ///   "type": "issuer",
    ///   "valid_from": "2025-01-01T00:00:00Z",
    ///   "valid_until": "2026-01-01T00:00:00Z",
    ///   "state": "active"
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`VcpError::ParseError`] if required fields are missing or
    /// dates cannot be parsed.
    pub fn from_dict(entity_id: &str, data: &serde_json::Value) -> VcpResult<Self> {
        let obj = data
            .as_object()
            .ok_or_else(|| VcpError::ParseError("trust anchor data must be an object".into()))?;

        let key_id = obj
            .get("id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| VcpError::ParseError("missing 'id' in trust anchor".into()))?;

        let algorithm = obj
            .get("algorithm")
            .and_then(|v| v.as_str())
            .ok_or_else(|| VcpError::ParseError("missing 'algorithm' in trust anchor".into()))?;

        let public_key = obj
            .get("public_key")
            .and_then(|v| v.as_str())
            .ok_or_else(|| VcpError::ParseError("missing 'public_key' in trust anchor".into()))?;

        if entity_id.trim().is_empty() || key_id.trim().is_empty() {
            return Err(VcpError::ParseError(
                "trust anchor entity and key identifiers must be non-empty".into(),
            ));
        }
        if algorithm.trim().is_empty() || public_key.trim().is_empty() {
            return Err(VcpError::ParseError(
                "trust anchor algorithm and public_key must be non-empty".into(),
            ));
        }

        let anchor_type_str = match obj.get("type") {
            None => "issuer",
            Some(value) => value
                .as_str()
                .ok_or_else(|| VcpError::ParseError("trust anchor type must be a string".into()))?,
        };
        let anchor_type = match anchor_type_str {
            "issuer" => AnchorType::Issuer,
            "auditor" => AnchorType::Auditor,
            other => {
                return Err(VcpError::ParseError(format!(
                    "unknown trust anchor type: {other}"
                )))
            }
        };

        let valid_from = parse_datetime(
            obj.get("valid_from")
                .and_then(|v| v.as_str())
                .ok_or_else(|| VcpError::ParseError("missing 'valid_from'".into()))?,
        )?;

        let valid_until = parse_datetime(
            obj.get("valid_until")
                .and_then(|v| v.as_str())
                .ok_or_else(|| VcpError::ParseError("missing 'valid_until'".into()))?,
        )?;

        let state_str = match obj.get("state") {
            None => "active",
            Some(value) => value.as_str().ok_or_else(|| {
                VcpError::ParseError("trust anchor state must be a string".into())
            })?,
        };
        let state = match state_str {
            "active" => AnchorState::Active,
            "rotating" => AnchorState::Rotating,
            "retired" => AnchorState::Retired,
            "compromised" => AnchorState::Compromised,
            other => {
                return Err(VcpError::ParseError(format!(
                    "unknown trust anchor state: {other}"
                )))
            }
        };

        if valid_from > valid_until {
            return Err(VcpError::ParseError(
                "trust anchor valid_from must not be after valid_until".into(),
            ));
        }

        Ok(Self {
            id: entity_id.to_string(),
            key_id: key_id.to_string(),
            algorithm: algorithm.to_string(),
            public_key: public_key.to_string(),
            anchor_type,
            valid_from,
            valid_until,
            state,
        })
    }
}

/// Parse a timezone-qualified RFC 3339 datetime string.
fn parse_datetime(s: &str) -> VcpResult<DateTime<Utc>> {
    DateTime::parse_from_rfc3339(s)
        .map(|dt| dt.with_timezone(&Utc))
        .map_err(|e| VcpError::ParseError(format!("invalid datetime '{s}': {e}")))
}

// ── TrustConfig ─────────────────────────────────────────────

/// Configuration holding trusted issuers and auditors.
///
/// Corresponds to the Python SDK's `TrustConfig` dataclass.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TrustConfig {
    /// Trusted issuer anchors, keyed by entity ID.
    pub issuers: HashMap<String, Vec<TrustAnchor>>,
    /// Trusted auditor anchors, keyed by entity ID.
    pub auditors: HashMap<String, Vec<TrustAnchor>>,
}

impl TrustConfig {
    /// Create an empty trust configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a trusted issuer key.
    pub fn add_issuer(&mut self, issuer_id: &str, anchor: TrustAnchor) {
        self.issuers
            .entry(issuer_id.to_string())
            .or_default()
            .push(anchor);
    }

    /// Add a trusted auditor key.
    pub fn add_auditor(&mut self, auditor_id: &str, anchor: TrustAnchor) {
        self.auditors
            .entry(auditor_id.to_string())
            .or_default()
            .push(anchor);
    }

    /// Get the first valid trust anchor for an issuer.
    ///
    /// If `key_id` is `Some`, only anchors with that key ID are considered.
    /// Returns the first anchor that is currently valid (active/rotating and
    /// within its validity window).
    pub fn get_issuer_key(&self, issuer_id: &str, key_id: Option<&str>) -> Option<&TrustAnchor> {
        let anchors = self.issuers.get(issuer_id)?;
        let now = Utc::now();
        anchors.iter().find(|a| {
            if a.id != issuer_id || a.anchor_type != AnchorType::Issuer {
                return false;
            }
            if let Some(kid) = key_id {
                if a.key_id != kid {
                    return false;
                }
            }
            a.is_valid(Some(now))
        })
    }

    /// Get the first valid trust anchor for an auditor.
    ///
    /// If `key_id` is `Some`, only anchors with that key ID are considered.
    /// Returns the first anchor that is currently valid (active/rotating and
    /// within its validity window).
    pub fn get_auditor_key(&self, auditor_id: &str, key_id: Option<&str>) -> Option<&TrustAnchor> {
        let anchors = self.auditors.get(auditor_id)?;
        let now = Utc::now();
        anchors.iter().find(|a| {
            if a.id != auditor_id || a.anchor_type != AnchorType::Auditor {
                return false;
            }
            if let Some(kid) = key_id {
                if a.key_id != kid {
                    return false;
                }
            }
            a.is_valid(Some(now))
        })
    }

    /// Parse a `TrustConfig` from a dictionary-style JSON value.
    ///
    /// Expects the same shape as the Python `TrustConfig.from_dict()`:
    ///
    /// ```json
    /// {
    ///   "trust_anchors": {
    ///     "creed-space": {
    ///       "type": "issuer",
    ///       "keys": [
    ///         { "id": "key-2025-01", "algorithm": "ed25519", ... }
    ///       ]
    ///     }
    ///   }
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`VcpError::ParseError`] if the structure is malformed.
    pub fn from_dict(data: &serde_json::Value) -> VcpResult<Self> {
        let mut config = Self::new();

        let root = data
            .as_object()
            .ok_or_else(|| VcpError::ParseError("trust config must be an object".into()))?;
        let Some(anchors_value) = root.get("trust_anchors") else {
            return Ok(config);
        };
        let anchors_obj = anchors_value
            .as_object()
            .ok_or_else(|| VcpError::ParseError("'trust_anchors' must be an object".into()))?;

        for (entity_id, entity_data) in anchors_obj {
            let entity_type = match entity_data.get("type") {
                None => "issuer",
                Some(value) => value.as_str().ok_or_else(|| {
                    VcpError::ParseError(format!(
                        "trust anchor type for '{entity_id}' must be a string"
                    ))
                })?,
            };
            if !matches!(entity_type, "issuer" | "auditor") {
                return Err(VcpError::ParseError(format!(
                    "unknown trust anchor type for '{entity_id}': {entity_type}"
                )));
            }

            let keys = entity_data
                .get("keys")
                .and_then(|v| v.as_array())
                .ok_or_else(|| {
                    VcpError::ParseError(format!(
                        "missing 'keys' array for trust anchor '{entity_id}'"
                    ))
                })?;

            for key_data in keys {
                // Inject the entity type into the key data for parsing.
                let mut key_obj = key_data.clone();
                if let Some(obj) = key_obj.as_object_mut() {
                    obj.insert("type".to_string(), serde_json::json!(entity_type));
                }

                let anchor = TrustAnchor::from_dict(entity_id, &key_obj)?;

                if entity_type == "auditor" {
                    config.add_auditor(entity_id, anchor);
                } else {
                    config.add_issuer(entity_id, anchor);
                }
            }
        }

        Ok(config)
    }

    /// Parse a `TrustConfig` from a JSON string.
    ///
    /// # Errors
    ///
    /// Returns [`VcpError::JsonError`] if the JSON is invalid, or
    /// [`VcpError::ParseError`] if the structure is malformed.
    pub fn from_json(json_str: &str) -> VcpResult<Self> {
        if json_str.len() > MAX_TRUST_CONFIG_BYTES {
            return Err(VcpError::ParseError(format!(
                "trust config exceeds {MAX_TRUST_CONFIG_BYTES} bytes"
            )));
        }
        let data = crate::transport::parse_json_strict(json_str)?;
        Self::from_dict(&data)
    }

    /// Serialize the trust config to a dictionary-style JSON value.
    ///
    /// Produces the same shape as the Python `TrustConfig.to_dict()`.
    pub fn to_dict(&self) -> serde_json::Value {
        let mut trust_anchors = serde_json::Map::new();

        for (issuer_id, anchors) in &self.issuers {
            let keys: Vec<serde_json::Value> = anchors
                .iter()
                .map(|a| {
                    serde_json::json!({
                        "id": a.key_id,
                        "algorithm": a.algorithm,
                        "public_key": a.public_key,
                        "state": format!("{}", serde_json::to_value(a.state).unwrap_or_default()).trim_matches('"'),
                        "valid_from": a.valid_from.to_rfc3339(),
                        "valid_until": a.valid_until.to_rfc3339(),
                    })
                })
                .collect();

            trust_anchors.insert(
                issuer_id.clone(),
                serde_json::json!({
                    "type": "issuer",
                    "keys": keys,
                }),
            );
        }

        for (auditor_id, anchors) in &self.auditors {
            let keys: Vec<serde_json::Value> = anchors
                .iter()
                .map(|a| {
                    serde_json::json!({
                        "id": a.key_id,
                        "algorithm": a.algorithm,
                        "public_key": a.public_key,
                        "state": format!("{}", serde_json::to_value(a.state).unwrap_or_default()).trim_matches('"'),
                        "valid_from": a.valid_from.to_rfc3339(),
                        "valid_until": a.valid_until.to_rfc3339(),
                    })
                })
                .collect();

            trust_anchors.insert(
                auditor_id.clone(),
                serde_json::json!({
                    "type": "auditor",
                    "keys": keys,
                }),
            );
        }

        serde_json::json!({ "trust_anchors": trust_anchors })
    }

    /// Serialize the trust config to a JSON string.
    ///
    /// # Errors
    ///
    /// Returns [`VcpError::JsonError`] if serialization fails.
    pub fn to_json(&self) -> VcpResult<String> {
        serde_json::to_string_pretty(&self.to_dict())
            .map_err(|e| VcpError::JsonError(e.to_string()))
    }
}

// ── Tests ───────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Duration;
    use pretty_assertions::assert_eq;

    fn make_anchor(
        entity_id: &str,
        key_id: &str,
        anchor_type: AnchorType,
        state: AnchorState,
        days_before: i64,
        days_after: i64,
    ) -> TrustAnchor {
        TrustAnchor {
            id: entity_id.to_string(),
            key_id: key_id.to_string(),
            algorithm: "ed25519".to_string(),
            public_key: "base64:AAAA".to_string(),
            anchor_type,
            valid_from: Utc::now() - Duration::days(days_before),
            valid_until: Utc::now() + Duration::days(days_after),
            state,
        }
    }

    #[test]
    fn anchor_valid_active_within_window() {
        let anchor = make_anchor(
            "test",
            "k1",
            AnchorType::Issuer,
            AnchorState::Active,
            1,
            365,
        );
        assert!(anchor.is_valid(None));
    }

    #[test]
    fn anchor_valid_rotating_within_window() {
        let anchor = make_anchor(
            "test",
            "k1",
            AnchorType::Issuer,
            AnchorState::Rotating,
            1,
            365,
        );
        assert!(anchor.is_valid(None));
    }

    #[test]
    fn anchor_invalid_retired() {
        let anchor = make_anchor(
            "test",
            "k1",
            AnchorType::Issuer,
            AnchorState::Retired,
            1,
            365,
        );
        assert!(!anchor.is_valid(None));
    }

    #[test]
    fn anchor_invalid_compromised() {
        let anchor = make_anchor(
            "test",
            "k1",
            AnchorType::Issuer,
            AnchorState::Compromised,
            1,
            365,
        );
        assert!(!anchor.is_valid(None));
    }

    #[test]
    fn anchor_invalid_expired() {
        let anchor = make_anchor(
            "test",
            "k1",
            AnchorType::Issuer,
            AnchorState::Active,
            365,
            -1,
        );
        assert!(!anchor.is_valid(None));
    }

    #[test]
    fn anchor_invalid_not_yet_valid() {
        let anchor = make_anchor(
            "test",
            "k1",
            AnchorType::Issuer,
            AnchorState::Active,
            -1,
            365,
        );
        assert!(!anchor.is_valid(None));
    }

    #[test]
    fn anchor_valid_at_specific_time() {
        let anchor = make_anchor(
            "test",
            "k1",
            AnchorType::Issuer,
            AnchorState::Active,
            30,
            30,
        );
        let past = Utc::now() - Duration::days(10);
        assert!(anchor.is_valid(Some(past)));

        let too_early = Utc::now() - Duration::days(60);
        assert!(!anchor.is_valid(Some(too_early)));
    }

    #[test]
    fn config_add_and_get_issuer() {
        let mut config = TrustConfig::new();
        let anchor = make_anchor(
            "creed",
            "k1",
            AnchorType::Issuer,
            AnchorState::Active,
            1,
            365,
        );
        config.add_issuer("creed", anchor);

        assert!(config.get_issuer_key("creed", None).is_some());
        assert!(config.get_issuer_key("creed", Some("k1")).is_some());
        assert!(config.get_issuer_key("creed", Some("wrong-key")).is_none());
        assert!(config.get_issuer_key("unknown", None).is_none());
    }

    #[test]
    fn config_add_and_get_auditor() {
        let mut config = TrustConfig::new();
        let anchor = make_anchor(
            "auditor-1",
            "k1",
            AnchorType::Auditor,
            AnchorState::Active,
            1,
            365,
        );
        config.add_auditor("auditor-1", anchor);

        assert!(config.get_auditor_key("auditor-1", None).is_some());
        assert!(config.get_auditor_key("auditor-1", Some("k1")).is_some());
        assert!(config.get_auditor_key("auditor-1", Some("wrong")).is_none());
        assert!(config.get_auditor_key("unknown", None).is_none());
    }

    #[test]
    fn config_skips_invalid_anchors() {
        let mut config = TrustConfig::new();

        // Add an expired anchor and a valid one.
        let expired = make_anchor(
            "creed",
            "old",
            AnchorType::Issuer,
            AnchorState::Active,
            365,
            -1,
        );
        let valid = make_anchor(
            "creed",
            "new",
            AnchorType::Issuer,
            AnchorState::Active,
            1,
            365,
        );

        config.add_issuer("creed", expired);
        config.add_issuer("creed", valid);

        let found = config.get_issuer_key("creed", None).unwrap();
        assert_eq!(found.key_id, "new");
    }

    #[test]
    fn config_from_dict_issuers() {
        let data = serde_json::json!({
            "trust_anchors": {
                "creed-space": {
                    "type": "issuer",
                    "keys": [{
                        "id": "key-2025-01",
                        "algorithm": "ed25519",
                        "public_key": "base64:test-key",
                        "valid_from": "2020-01-01T00:00:00Z",
                        "valid_until": "2030-01-01T00:00:00Z",
                        "state": "active"
                    }]
                }
            }
        });

        let config = TrustConfig::from_dict(&data).unwrap();
        let anchor = config.get_issuer_key("creed-space", Some("key-2025-01"));
        assert!(anchor.is_some());

        let a = anchor.unwrap();
        assert_eq!(a.algorithm, "ed25519");
        assert_eq!(a.public_key, "base64:test-key");
    }

    #[test]
    fn config_from_dict_auditors() {
        let data = serde_json::json!({
            "trust_anchors": {
                "safety-auditor": {
                    "type": "auditor",
                    "keys": [{
                        "id": "aud-key-01",
                        "algorithm": "ed25519",
                        "public_key": "base64:auditor-key",
                        "valid_from": "2020-01-01T00:00:00Z",
                        "valid_until": "2030-01-01T00:00:00Z"
                    }]
                }
            }
        });

        let config = TrustConfig::from_dict(&data).unwrap();
        assert!(config.get_auditor_key("safety-auditor", None).is_some());
        assert!(config.get_issuer_key("safety-auditor", None).is_none());
    }

    #[test]
    fn config_from_dict_mixed() {
        let data = serde_json::json!({
            "trust_anchors": {
                "creed-space": {
                    "type": "issuer",
                    "keys": [{
                        "id": "k1",
                        "algorithm": "ed25519",
                        "public_key": "base64:issuer-key",
                        "valid_from": "2020-01-01T00:00:00Z",
                        "valid_until": "2030-01-01T00:00:00Z"
                    }]
                },
                "safety-co": {
                    "type": "auditor",
                    "keys": [{
                        "id": "k2",
                        "algorithm": "ed25519",
                        "public_key": "base64:auditor-key",
                        "valid_from": "2020-01-01T00:00:00Z",
                        "valid_until": "2030-01-01T00:00:00Z"
                    }]
                }
            }
        });

        let config = TrustConfig::from_dict(&data).unwrap();
        assert!(config.get_issuer_key("creed-space", None).is_some());
        assert!(config.get_auditor_key("safety-co", None).is_some());
    }

    #[test]
    fn config_from_json_roundtrip() {
        let json_str = r#"{
            "trust_anchors": {
                "test-issuer": {
                    "type": "issuer",
                    "keys": [{
                        "id": "k1",
                        "algorithm": "ed25519",
                        "public_key": "base64:roundtrip-key",
                        "valid_from": "2020-01-01T00:00:00Z",
                        "valid_until": "2030-01-01T00:00:00Z",
                        "state": "active"
                    }]
                }
            }
        }"#;

        let config = TrustConfig::from_json(json_str).unwrap();
        assert!(config.get_issuer_key("test-issuer", Some("k1")).is_some());

        // Verify to_dict produces valid structure.
        let dict = config.to_dict();
        let reparsed = TrustConfig::from_dict(&dict).unwrap();
        assert!(reparsed.get_issuer_key("test-issuer", Some("k1")).is_some());
    }

    #[test]
    fn config_from_json_rejects_duplicate_keys() {
        assert!(TrustConfig::from_json(r#"{"trust_anchors": {}, "trust_anchors": {}}"#).is_err());
    }

    #[test]
    fn config_empty_trust_anchors() {
        let data = serde_json::json!({});
        let config = TrustConfig::from_dict(&data).unwrap();
        assert!(config.issuers.is_empty());
        assert!(config.auditors.is_empty());
    }

    #[test]
    fn config_from_dict_missing_keys_error() {
        let data = serde_json::json!({
            "trust_anchors": {
                "bad-entity": {
                    "type": "issuer"
                    // missing "keys" array
                }
            }
        });

        let result = TrustConfig::from_dict(&data);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("keys"));
    }

    #[test]
    fn anchor_from_dict_defaults() {
        let data = serde_json::json!({
            "id": "k1",
            "algorithm": "ed25519",
            "public_key": "base64:test",
            "valid_from": "2020-01-01T00:00:00Z",
            "valid_until": "2030-01-01T00:00:00Z"
            // no "type" or "state" — should default to issuer/active
        });

        let anchor = TrustAnchor::from_dict("test-entity", &data).unwrap();
        assert_eq!(anchor.anchor_type, AnchorType::Issuer);
        assert_eq!(anchor.state, AnchorState::Active);
    }

    #[test]
    fn anchor_from_dict_auditor_rotating() {
        let data = serde_json::json!({
            "id": "k2",
            "algorithm": "ed25519",
            "public_key": "base64:test",
            "type": "auditor",
            "state": "rotating",
            "valid_from": "2020-01-01T00:00:00Z",
            "valid_until": "2030-01-01T00:00:00Z"
        });

        let anchor = TrustAnchor::from_dict("aud", &data).unwrap();
        assert_eq!(anchor.anchor_type, AnchorType::Auditor);
        assert_eq!(anchor.state, AnchorState::Rotating);
        assert!(anchor.is_valid(None));
    }

    #[test]
    fn parse_datetime_requires_an_explicit_timezone() {
        assert!(parse_datetime("2025-01-01T00:00:00Z").is_ok());
        assert!(parse_datetime("2025-01-01T01:00:00+01:00").is_ok());
        assert!(parse_datetime("2025-01-01T00:00:00").is_err());
        assert!(parse_datetime("not-a-date").is_err());
    }

    #[test]
    fn anchor_from_dict_rejects_unknown_security_enums() {
        let base = serde_json::json!({
            "id": "k1",
            "algorithm": "ed25519",
            "public_key": "base64:test",
            "valid_from": "2020-01-01T00:00:00Z",
            "valid_until": "2030-01-01T00:00:00Z"
        });

        for (field, value) in [("type", "superuser"), ("state", "trusted")] {
            let mut malformed = base.clone();
            malformed[field] = serde_json::json!(value);
            assert!(TrustAnchor::from_dict("entity", &malformed).is_err());
        }
        for field in ["type", "state"] {
            let mut malformed = base.clone();
            malformed[field] = serde_json::json!(false);
            assert!(TrustAnchor::from_dict("entity", &malformed).is_err());
        }
    }

    #[test]
    fn anchor_from_dict_rejects_empty_identifiers_and_reversed_window() {
        let mut data = serde_json::json!({
            "id": "",
            "algorithm": "ed25519",
            "public_key": "base64:test",
            "valid_from": "2030-01-01T00:00:00Z",
            "valid_until": "2020-01-01T00:00:00Z"
        });

        assert!(TrustAnchor::from_dict("entity", &data).is_err());
        data["id"] = serde_json::json!("k1");
        assert!(TrustAnchor::from_dict("entity", &data).is_err());
        data["valid_from"] = serde_json::json!("2020-01-01T00:00:00Z");
        assert!(TrustAnchor::from_dict("", &data).is_err());
    }

    #[test]
    fn config_from_dict_rejects_malformed_anchor_container_and_type() {
        assert!(TrustConfig::from_dict(&serde_json::json!([])).is_err());
        assert!(TrustConfig::from_dict(&serde_json::json!({
            "trust_anchors": []
        }))
        .is_err());
        assert!(TrustConfig::from_dict(&serde_json::json!({
            "trust_anchors": {
                "entity": {"type": "root", "keys": []}
            }
        }))
        .is_err());
        assert!(TrustConfig::from_dict(&serde_json::json!({
            "trust_anchors": {
                "entity": {"type": false, "keys": []}
            }
        }))
        .is_err());
    }

    #[test]
    fn config_from_json_enforces_inclusive_size_limit() {
        let at_limit = format!("{}{{}}", " ".repeat(MAX_TRUST_CONFIG_BYTES - 2));
        assert_eq!(at_limit.len(), MAX_TRUST_CONFIG_BYTES);
        assert!(TrustConfig::from_json(&at_limit).is_ok());

        assert!(TrustConfig::from_json(&format!(" {at_limit}")).is_err());
    }

    #[test]
    fn lookup_rejects_misfiled_anchor_role_or_identity() {
        let mut config = TrustConfig::new();
        config.add_issuer(
            "issuer-map-key",
            make_anchor(
                "different-id",
                "k1",
                AnchorType::Issuer,
                AnchorState::Active,
                1,
                365,
            ),
        );
        config.add_issuer(
            "auditor-in-issuer-map",
            make_anchor(
                "auditor-in-issuer-map",
                "k2",
                AnchorType::Auditor,
                AnchorState::Active,
                1,
                365,
            ),
        );

        assert!(config.get_issuer_key("issuer-map-key", None).is_none());
        assert!(config
            .get_issuer_key("auditor-in-issuer-map", None)
            .is_none());
    }

    #[test]
    fn config_multiple_keys_per_entity() {
        let mut config = TrustConfig::new();
        let k1 = make_anchor(
            "creed",
            "k1",
            AnchorType::Issuer,
            AnchorState::Active,
            1,
            365,
        );
        let k2 = make_anchor(
            "creed",
            "k2",
            AnchorType::Issuer,
            AnchorState::Active,
            1,
            365,
        );

        config.add_issuer("creed", k1);
        config.add_issuer("creed", k2);

        assert_eq!(config.issuers["creed"].len(), 2);

        // Without key_id filter, returns first valid.
        assert!(config.get_issuer_key("creed", None).is_some());

        // With specific key_id.
        let found = config.get_issuer_key("creed", Some("k2")).unwrap();
        assert_eq!(found.key_id, "k2");
    }

    #[test]
    fn anchor_state_allows_verification() {
        assert!(AnchorState::Active.allows_verification());
        assert!(AnchorState::Rotating.allows_verification());
        assert!(!AnchorState::Retired.allows_verification());
        assert!(!AnchorState::Compromised.allows_verification());
    }
}