1use serde_json::{json, Map, Value};
18
19use crate::credentials::{verify_temporal, VerifyResult, VC_CONTEXT_V2, VC_TYPE, VOUCH_CONTEXT_V1};
20use crate::data_integrity::{self, BuildProofOptions};
21use crate::error::{CoreError, Result};
22
23pub const AUTHORITY_STATE_TYPE: &str = "AuthorityState";
24
25pub const STATUS_ACTIVE: &str = "active";
26pub const STATUS_SUSPENDED: &str = "suspended";
27pub const STATUS_INCIDENT: &str = "incident";
28pub const STATUS_EXPOSURE_BREACHED: &str = "exposure_breached";
29pub const STATUS_REVOKED: &str = "revoked";
30
31pub const VALID_AUTHORITY_STATUSES: [&str; 5] = [
32 STATUS_ACTIVE,
33 STATUS_SUSPENDED,
34 STATUS_INCIDENT,
35 STATUS_EXPOSURE_BREACHED,
36 STATUS_REVOKED,
37];
38
39pub const CONSEQUENCE_ROUTINE: &str = "routine";
42pub const CONSEQUENCE_SENSITIVE: &str = "sensitive";
43pub const CONSEQUENCE_CRITICAL: &str = "critical";
44
45fn is_valid_status(status: &str) -> bool {
46 VALID_AUTHORITY_STATUSES.contains(&status)
47}
48
49fn epoch_str(epoch: Option<i64>) -> String {
52 match epoch {
53 Some(e) => e.to_string(),
54 None => "?".to_string(),
55 }
56}
57
58#[derive(Debug, Clone)]
61pub struct BuildAuthorityStateOptions {
62 pub issuer_did: String,
63 pub credential_id: String,
64 pub authority_epoch: i64,
65 pub status: String,
66 pub valid_from: String,
67 pub valid_until: String,
68 pub subject_did: Option<String>,
70}
71
72pub fn build_authority_state(opts: &BuildAuthorityStateOptions) -> Result<Value> {
74 if opts.authority_epoch < 0 {
75 return Err(CoreError::Json(
76 "authorityEpoch must be non-negative".into(),
77 ));
78 }
79 if !is_valid_status(&opts.status) {
80 return Err(CoreError::Json(format!(
81 "status must be one of {VALID_AUTHORITY_STATUSES:?}"
82 )));
83 }
84 if opts.issuer_did.is_empty() {
85 return Err(CoreError::Json("issuer_did is required".into()));
86 }
87
88 let subject_did = opts
89 .subject_did
90 .clone()
91 .unwrap_or_else(|| opts.issuer_did.clone());
92
93 let mut subject = Map::new();
94 subject.insert("id".into(), json!(subject_did));
95 subject.insert("authorityEpoch".into(), json!(opts.authority_epoch));
96 subject.insert("status".into(), json!(opts.status));
97
98 let mut vc = Map::new();
99 vc.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
100 vc.insert("id".into(), json!(opts.credential_id));
101 vc.insert("type".into(), json!([VC_TYPE, AUTHORITY_STATE_TYPE]));
102 vc.insert("issuer".into(), json!(opts.issuer_did));
103 vc.insert("validFrom".into(), json!(opts.valid_from));
104 vc.insert("validUntil".into(), json!(opts.valid_until));
105 vc.insert("credentialSubject".into(), Value::Object(subject));
106 Ok(Value::Object(vc))
107}
108
109pub fn sign_authority_state(
111 opts: &BuildAuthorityStateOptions,
112 raw_private_seed: &[u8],
113 proof_opts: &BuildProofOptions,
114) -> Result<Value> {
115 let cred = build_authority_state(opts)?;
116 data_integrity::sign(&cred, raw_private_seed, proof_opts)
117}
118
119pub fn verify(
123 credential: &Value,
124 raw_public_key: &[u8],
125 now_iso: &str,
126 clock_skew_seconds: i64,
127) -> Result<VerifyResult> {
128 let ty = credential.get("type").and_then(|v| v.as_array());
129 let is_authority_state = ty
130 .map(|arr| arr.iter().any(|t| t.as_str() == Some(AUTHORITY_STATE_TYPE)))
131 .unwrap_or(false);
132 if !is_authority_state {
133 return Err(CoreError::Json(
134 "credential is not an AuthorityState".into(),
135 ));
136 }
137 let proof_valid = data_integrity::verify_proof(credential, raw_public_key)?;
138 let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds)?;
139 Ok(VerifyResult {
140 proof_valid,
141 time_valid,
142 chain_valid: true,
144 })
145}
146
147pub fn read_authority_epoch(credential: &Value) -> Result<i64> {
150 credential
151 .get("credentialSubject")
152 .and_then(|s| s.get("authorityEpoch"))
153 .and_then(|v| v.as_i64())
154 .filter(|e| *e >= 0)
155 .ok_or_else(|| CoreError::Json("missing or invalid authorityEpoch".into()))
156}
157
158pub fn read_authority_status(credential: &Value) -> Result<String> {
160 credential
161 .get("credentialSubject")
162 .and_then(|s| s.get("status"))
163 .and_then(|v| v.as_str())
164 .filter(|s| is_valid_status(s))
165 .map(|s| s.to_string())
166 .ok_or_else(|| CoreError::Json("missing or invalid status".into()))
167}
168
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
171pub struct FreshnessRule {
172 pub enforce_epoch: bool,
173 pub require_live_cosign: bool,
174}
175
176pub fn freshness_rule(tier: &str) -> FreshnessRule {
178 match tier {
179 CONSEQUENCE_ROUTINE => FreshnessRule {
180 enforce_epoch: false,
181 require_live_cosign: false,
182 },
183 CONSEQUENCE_SENSITIVE => FreshnessRule {
184 enforce_epoch: true,
185 require_live_cosign: false,
186 },
187 _ => FreshnessRule {
189 enforce_epoch: true,
190 require_live_cosign: true,
191 },
192 }
193}
194
195#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct AuthorityFreshnessVerdict {
198 pub allow: bool,
199 pub tier: String,
200 pub reason: String,
201}
202
203pub fn evaluate_authority_freshness(
210 tier: &str,
211 voucher_epoch: Option<i64>,
212 last_seen_epoch: Option<i64>,
213 current_status: Option<&str>,
214 live_cosign_ok: Option<bool>,
215) -> AuthorityFreshnessVerdict {
216 let canonical_tier = match tier {
217 CONSEQUENCE_ROUTINE | CONSEQUENCE_SENSITIVE | CONSEQUENCE_CRITICAL => tier,
218 _ => CONSEQUENCE_CRITICAL,
219 };
220 let rule = freshness_rule(canonical_tier);
221 let mk = |allow: bool, reason: String| AuthorityFreshnessVerdict {
222 allow,
223 tier: canonical_tier.to_string(),
224 reason,
225 };
226
227 if !rule.enforce_epoch && !rule.require_live_cosign {
228 return mk(true, "routine tier: time-decay only".into());
229 }
230
231 if let Some(status) = current_status {
232 if status != STATUS_ACTIVE {
233 return mk(
234 false,
235 format!("authority_status_not_active:status={status}"),
236 );
237 }
238 }
239
240 if rule.require_live_cosign && live_cosign_ok != Some(true) {
241 return mk(false, format!("live_cosign_required:tier={canonical_tier}"));
242 }
243
244 if rule.enforce_epoch {
245 match (voucher_epoch, last_seen_epoch) {
254 (Some(v), Some(seen)) => {
255 if v < seen {
256 return mk(
257 false,
258 format!("authority_epoch_stale:seen={seen},voucher={v}"),
259 );
260 }
261 }
262 _ => {
263 return mk(
266 false,
267 format!(
268 "authority_epoch_unknown:voucher={},seen={}",
269 epoch_str(voucher_epoch),
270 epoch_str(last_seen_epoch)
271 ),
272 );
273 }
274 }
275 }
276
277 mk(
278 true,
279 format!("{canonical_tier} tier: authority state fresh"),
280 )
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 fn opts() -> BuildAuthorityStateOptions {
288 BuildAuthorityStateOptions {
289 issuer_did: "did:web:treasury.example.com".into(),
290 credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
291 authority_epoch: 7,
292 status: STATUS_ACTIVE.into(),
293 valid_from: "2026-07-26T10:00:00Z".into(),
294 valid_until: "2026-07-26T10:05:00Z".into(),
295 subject_did: None,
296 }
297 }
298
299 #[test]
300 fn builds_expected_shape() {
301 let vc = build_authority_state(&opts()).unwrap();
302 assert_eq!(
303 vc["type"],
304 json!(["VerifiableCredential", "AuthorityState"])
305 );
306 assert_eq!(vc["credentialSubject"]["authorityEpoch"], json!(7));
307 assert_eq!(vc["credentialSubject"]["status"], json!("active"));
308 }
309
310 #[test]
311 fn rejects_bad_status() {
312 let mut o = opts();
313 o.status = "bogus".into();
314 assert!(build_authority_state(&o).is_err());
315 }
316
317 #[test]
318 fn sign_and_verify_within_window() {
319 let seed = [7u8; 32];
320 let proof_opts =
321 BuildProofOptions::new("did:web:treasury.example.com#key-1", "2026-07-26T10:00:00Z");
322 let signed = sign_authority_state(&opts(), &seed, &proof_opts).unwrap();
323 let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
324 let r = verify(&signed, &pk, "2026-07-26T10:02:00Z", 30).unwrap();
325 assert!(r.is_valid());
326 assert_eq!(read_authority_epoch(&signed).unwrap(), 7);
327 assert_eq!(read_authority_status(&signed).unwrap(), "active");
328 }
329
330 #[test]
331 fn routine_ignores_stale_epoch() {
332 let v = evaluate_authority_freshness(CONSEQUENCE_ROUTINE, Some(1), Some(9), None, None);
333 assert!(v.allow);
334 }
335
336 #[test]
337 fn sensitive_rejects_stale_epoch() {
338 let v = evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(5), Some(7), None, None);
339 assert!(!v.allow);
340 assert_eq!(v.reason, "authority_epoch_stale:seen=7,voucher=5");
341 }
342
343 #[test]
344 fn sensitive_rejects_unknown_epoch() {
345 let v = evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, None, Some(3), None, None);
348 assert!(!v.allow);
349 assert_eq!(v.reason, "authority_epoch_unknown:voucher=?,seen=3");
350 let v2 = evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(5), None, None, None);
351 assert_eq!(v2.reason, "authority_epoch_unknown:voucher=5,seen=?");
352 }
353
354 #[test]
355 fn sensitive_allows_current_epoch() {
356 let v = evaluate_authority_freshness(CONSEQUENCE_SENSITIVE, Some(9), Some(9), None, None);
357 assert!(v.allow);
358 }
359
360 #[test]
361 fn non_active_status_fails_closed() {
362 let v = evaluate_authority_freshness(
363 CONSEQUENCE_SENSITIVE,
364 Some(9),
365 Some(9),
366 Some(STATUS_SUSPENDED),
367 None,
368 );
369 assert!(!v.allow);
370 assert_eq!(v.reason, "authority_status_not_active:status=suspended");
371 }
372
373 #[test]
374 fn critical_requires_live_cosign() {
375 let denied =
376 evaluate_authority_freshness(CONSEQUENCE_CRITICAL, Some(9), Some(9), None, None);
377 assert!(!denied.allow);
378 assert!(denied.reason.starts_with("live_cosign_required"));
379 let allowed =
380 evaluate_authority_freshness(CONSEQUENCE_CRITICAL, Some(9), Some(9), None, Some(true));
381 assert!(allowed.allow);
382 }
383
384 #[test]
385 fn unknown_tier_coerces_to_critical() {
386 let v = evaluate_authority_freshness("made-up", Some(9), Some(9), None, None);
387 assert_eq!(v.tier, "critical");
388 assert!(!v.allow);
389 }
390}