use std::collections::HashMap;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::error::{VcpError, VcpResult};
pub const MAX_TRUST_CONFIG_BYTES: usize = 16 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AnchorType {
Issuer,
Auditor,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AnchorState {
Active,
Rotating,
Retired,
Compromised,
}
impl AnchorState {
pub fn allows_verification(self) -> bool {
matches!(self, AnchorState::Active | AnchorState::Rotating)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TrustAnchor {
pub id: String,
pub key_id: String,
pub algorithm: String,
pub public_key: String,
pub anchor_type: AnchorType,
pub valid_from: DateTime<Utc>,
pub valid_until: DateTime<Utc>,
#[serde(default = "default_anchor_state")]
pub state: AnchorState,
}
fn default_anchor_state() -> AnchorState {
AnchorState::Active
}
impl TrustAnchor {
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
}
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,
})
}
}
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}")))
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TrustConfig {
pub issuers: HashMap<String, Vec<TrustAnchor>>,
pub auditors: HashMap<String, Vec<TrustAnchor>>,
}
impl TrustConfig {
pub fn new() -> Self {
Self::default()
}
pub fn add_issuer(&mut self, issuer_id: &str, anchor: TrustAnchor) {
self.issuers
.entry(issuer_id.to_string())
.or_default()
.push(anchor);
}
pub fn add_auditor(&mut self, auditor_id: &str, anchor: TrustAnchor) {
self.auditors
.entry(auditor_id.to_string())
.or_default()
.push(anchor);
}
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))
})
}
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))
})
}
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 {
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)
}
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)
}
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 })
}
pub fn to_json(&self) -> VcpResult<String> {
serde_json::to_string_pretty(&self.to_dict())
.map_err(|e| VcpError::JsonError(e.to_string()))
}
}
#[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();
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());
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"
}
}
});
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"
});
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);
assert!(config.get_issuer_key("creed", None).is_some());
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());
}
}