1use serde::{Deserialize, Serialize};
20use uuid::Uuid;
21
22use crate::record::{
23 EpistemicStatus, EvidenceType, InstantBridge, RecordEnvelope, SensitivityClass,
24};
25
26pub mod authority_type {
33 pub const GOVERNMENT: &str = "authority:government";
35 pub const PATHOLOGY: &str = "authority:pathology";
37 pub const EDUCATION: &str = "authority:education";
39 pub const FINANCIAL: &str = "authority:financial";
41 pub const NGO: &str = "authority:ngo";
43}
44
45pub use authority_type::{EDUCATION, FINANCIAL, GOVERNMENT, NGO, PATHOLOGY};
47
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct Authority {
55 pub type_id: String,
57 pub label: String,
59 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub jurisdiction: Option<String>,
61 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub department: Option<String>,
63}
64
65impl Authority {
66 pub fn new(type_id: impl Into<String>, label: impl Into<String>) -> Self {
68 Self {
69 type_id: type_id.into(),
70 label: label.into(),
71 jurisdiction: None,
72 department: None,
73 }
74 }
75
76 pub fn is_government(&self) -> bool {
78 self.type_id == authority_type::GOVERNMENT
79 }
80
81 pub fn is_medical(&self) -> bool {
86 self.type_id == authority_type::PATHOLOGY
87 || self.type_id.starts_with("authority:pathology")
88 || self.type_id.starts_with("authority:medical")
89 }
90}
91
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95pub struct AgentInCapacity {
96 pub name: String,
98 pub capacity: String,
100 #[serde(default, skip_serializing_if = "Option::is_none")]
101 pub did: Option<String>,
102}
103
104impl AgentInCapacity {
105 pub fn new(name: impl Into<String>, capacity: impl Into<String>) -> Self {
107 Self {
108 name: name.into(),
109 capacity: capacity.into(),
110 did: None,
111 }
112 }
113
114 pub fn with_did(mut self, did: impl Into<String>) -> Self {
116 self.did = Some(did.into());
117 self
118 }
119}
120
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
126#[serde(rename_all = "snake_case")]
127pub enum Representation {
128 Pdf,
130 Credential,
132 PdfWithEmbeddedCredential,
134}
135
136impl Default for Representation {
137 fn default() -> Self {
138 Self::Pdf
139 }
140}
141
142#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147pub struct AuthorityAttestation {
148 pub id: String,
149 pub authority: Authority,
150 #[serde(default, skip_serializing_if = "Option::is_none")]
151 pub agent: Option<AgentInCapacity>,
152 #[serde(default)]
153 pub representation: Representation,
154 pub subject: String,
156 pub statement: String,
158 #[serde(default)]
159 pub action_required: bool,
160 pub issued_unix: u32,
161 #[serde(skip_serializing_if = "Option::is_none", default)]
164 pub issued_instant: Option<InstantBridge>,
165 #[serde(default, skip_serializing_if = "Option::is_none")]
166 pub blob_hash: Option<String>,
167}
168
169impl AuthorityAttestation {
170 pub fn new(
173 authority: Authority,
174 subject: impl Into<String>,
175 statement: impl Into<String>,
176 issued_unix: u32,
177 ) -> Self {
178 Self {
179 id: Uuid::new_v4().to_string(),
180 authority,
181 agent: None,
182 representation: Representation::default(),
183 subject: subject.into(),
184 statement: statement.into(),
185 action_required: false,
186 issued_unix,
187 issued_instant: Some(InstantBridge::from_coarse(issued_unix)),
188 blob_hash: None,
189 }
190 }
191
192 pub fn issued_at(&self) -> InstantBridge {
195 self.issued_instant
196 .unwrap_or_else(|| InstantBridge::from_coarse(self.issued_unix))
197 }
198
199 pub fn with_agent(mut self, agent: AgentInCapacity) -> Self {
201 self.agent = Some(agent);
202 self
203 }
204
205 pub fn with_department(mut self, department: impl Into<String>) -> Self {
207 self.authority.department = Some(department.into());
208 self
209 }
210
211 pub fn with_jurisdiction(mut self, jurisdiction: impl Into<String>) -> Self {
213 self.authority.jurisdiction = Some(jurisdiction.into());
214 self
215 }
216
217 pub fn with_blob(mut self, blob_hash: impl Into<String>) -> Self {
219 self.blob_hash = Some(blob_hash.into());
220 self
221 }
222
223 pub fn with_representation(mut self, representation: Representation) -> Self {
225 self.representation = representation;
226 self
227 }
228
229 pub fn with_action_required(mut self, action_required: bool) -> Self {
231 self.action_required = action_required;
232 self
233 }
234}
235
236pub fn government_letter(sender: &str, subject: &str, issued_unix: u32) -> AuthorityAttestation {
243 let authority = Authority::new(authority_type::GOVERNMENT, sender);
244 AuthorityAttestation::new(authority, subject, subject, issued_unix)
245 .with_representation(Representation::Pdf)
246}
247
248pub fn authority_attestation_record_id(uuid: &str) -> String {
250 format!("urn:wellfair:authority_attestation:{uuid}")
251}
252
253pub fn build_authority_attestation_envelope(
263 att: &AuthorityAttestation,
264 owner_did: &str,
265 author_did: &str,
266 asserted_unix: u32,
267) -> RecordEnvelope {
268 let id = authority_attestation_record_id(&att.id);
269 let evidence_type = if att.authority.is_medical() {
270 EvidenceType::ClinicianObserved
271 } else {
272 EvidenceType::SelfReported
273 };
274 RecordEnvelope {
275 id,
276 owner_did: owner_did.to_string(),
277 author_did: author_did.to_string(),
278 proxy_did: None,
279 epistemic_status: EpistemicStatus::Asserted,
280 evidence_type,
281 sensitivity: SensitivityClass::Restricted,
282 asserted_time_unix: asserted_unix,
283 asserted_instant: None,
284 valid_time_start_unix: Some(att.issued_unix),
285 valid_time_start_instant: att.issued_instant,
286 valid_time_end_unix: None,
287 valid_time_end_instant: None,
288 predecessor_id: None,
289 blob_hash: att.blob_hash.clone(),
290 tombstone: false,
291 }
292}
293
294pub fn authority_attestation_summary(att: &AuthorityAttestation) -> String {
296 serde_json::json!({
297 "authority_label": att.authority.label,
298 "authority_type": att.authority.type_id,
299 "jurisdiction": att.authority.jurisdiction,
300 "department": att.authority.department,
301 "capacity": att.agent.as_ref().map(|a| a.capacity.clone()),
302 "agent_name": att.agent.as_ref().map(|a| a.name.clone()),
303 "representation": att.representation,
304 "subject": att.subject,
305 "statement": att.statement,
306 "action_required": att.action_required,
307 "issued_unix": att.issued_unix,
308 })
309 .to_string()
310}
311
312pub fn parse_authority_attestation_summary(
314 summary: &str,
315) -> Result<serde_json::Value, serde_json::Error> {
316 serde_json::from_str(summary)
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322
323 const OWNER: &str = "did:wf:owner";
324
325 #[test]
326 fn builder_round_trips_full_attestation() {
327 let authority = Authority::new(authority_type::PATHOLOGY, "Acme Pathology");
328 let agent = AgentInCapacity::new("Dr. Rao", "pathologist").with_did("did:wf:rao");
329 let att = AuthorityAttestation::new(
330 authority,
331 "Blood panel result",
332 "Full blood count within normal range",
333 1_700_000_000,
334 )
335 .with_agent(agent.clone())
336 .with_jurisdiction("AU-VIC")
337 .with_department("Haematology")
338 .with_representation(Representation::PdfWithEmbeddedCredential)
339 .with_blob("blob-hash-1")
340 .with_action_required(true);
341
342 assert_eq!(att.authority.type_id, authority_type::PATHOLOGY);
343 assert_eq!(att.authority.label, "Acme Pathology");
344 assert_eq!(att.authority.jurisdiction.as_deref(), Some("AU-VIC"));
345 assert_eq!(att.authority.department.as_deref(), Some("Haematology"));
346 assert_eq!(att.agent, Some(agent));
347 assert_eq!(
348 att.representation,
349 Representation::PdfWithEmbeddedCredential
350 );
351 assert_eq!(att.subject, "Blood panel result");
352 assert!(att.action_required);
353 assert_eq!(att.blob_hash.as_deref(), Some("blob-hash-1"));
354
355 let json = serde_json::to_string(&att).unwrap();
357 let back: AuthorityAttestation = serde_json::from_str(&json).unwrap();
358 assert_eq!(att, back);
359 }
360
361 #[test]
362 fn government_letter_is_a_preset_of_the_general_model() {
363 let att = government_letter("Services Australia", "Claim outcome", 1_700_000_100);
364 assert_eq!(att.authority.type_id, authority_type::GOVERNMENT);
365 assert_eq!(att.authority.type_id, GOVERNMENT); assert!(att.authority.is_government());
367 assert_eq!(att.authority.label, "Services Australia");
368 assert_eq!(att.representation, Representation::Pdf);
369 assert_eq!(att.subject, "Claim outcome");
370 assert_eq!(att.statement, "Claim outcome");
371 assert_eq!(att.issued_unix, 1_700_000_100);
372 assert!(att.agent.is_none());
373 }
374
375 #[test]
376 fn record_id_carries_authority_attestation_segment() {
377 let att = government_letter("ATO", "Tax assessment", 1);
378 let rid = authority_attestation_record_id(&att.id);
379 assert!(rid.contains(":authority_attestation:"), "got {rid}");
380 }
381
382 #[test]
383 fn envelope_is_restricted_and_threads_the_blob() {
384 let att = government_letter("Centrelink", "Appointment notice", 1_700_002_000)
385 .with_blob("letter-pdf-hash")
386 .with_action_required(true);
387 let env = build_authority_attestation_envelope(&att, OWNER, OWNER, 1_700_002_010);
388
389 assert!(env.id.contains(":authority_attestation:"));
390 assert_eq!(env.sensitivity, SensitivityClass::Restricted);
391 assert_eq!(env.epistemic_status, EpistemicStatus::Asserted);
392 assert_eq!(env.evidence_type, EvidenceType::SelfReported);
394 assert_eq!(env.valid_time_start_unix, Some(1_700_002_000));
395 assert_eq!(env.asserted_time_unix, 1_700_002_010);
396 assert_eq!(env.proxy_did, None);
397 assert_eq!(env.blob_hash.as_deref(), Some("letter-pdf-hash"));
399 assert!(!env.tombstone);
400 }
401
402 #[test]
403 fn medical_authority_yields_clinician_observed_evidence() {
404 let att = AuthorityAttestation::new(
406 Authority::new(authority_type::PATHOLOGY, "Acme Pathology"),
407 "Blood panel",
408 "Result attached",
409 1_700_003_000,
410 );
411 let env = build_authority_attestation_envelope(&att, OWNER, OWNER, 1_700_003_010);
412 assert_eq!(env.evidence_type, EvidenceType::ClinicianObserved);
413 assert_eq!(env.sensitivity, SensitivityClass::Restricted);
414
415 let att2 = AuthorityAttestation::new(
417 Authority::new("authority:pathology:acme-labs", "Acme Labs"),
418 "Culture result",
419 "No growth",
420 1_700_003_000,
421 );
422 assert!(att2.authority.is_medical());
423 let env2 = build_authority_attestation_envelope(&att2, OWNER, OWNER, 1_700_003_010);
424 assert_eq!(env2.evidence_type, EvidenceType::ClinicianObserved);
425 }
426
427 #[test]
428 fn extensible_custom_authority_builds_with_named_agent_in_capacity() {
429 let authority = Authority::new("authority:pathology:acme-labs", "Acme Labs Pty Ltd");
431 let pathologist = AgentInCapacity::new("Dr. Elena Novak", "pathologist");
432 let att = AuthorityAttestation::new(
433 authority,
434 "Histopathology report",
435 "Specimen benign; no malignancy identified",
436 1_700_004_000,
437 )
438 .with_agent(pathologist)
439 .with_jurisdiction("AU")
440 .with_representation(Representation::Credential)
441 .with_blob("vc-blob-hash");
442
443 assert_eq!(att.authority.type_id, "authority:pathology:acme-labs");
444 assert!(att.authority.is_medical());
445 assert!(!att.authority.is_government());
446 let agent = att.agent.as_ref().unwrap();
447 assert_eq!(agent.name, "Dr. Elena Novak");
448 assert_eq!(agent.capacity, "pathologist");
449 assert_eq!(att.representation, Representation::Credential);
450
451 let env = build_authority_attestation_envelope(&att, OWNER, OWNER, 1_700_004_010);
453 assert_eq!(env.evidence_type, EvidenceType::ClinicianObserved);
454 assert_eq!(env.blob_hash.as_deref(), Some("vc-blob-hash"));
455 }
456
457 #[test]
458 fn summary_round_trips_through_the_parser() {
459 let authority = Authority::new(authority_type::EDUCATION, "State University");
460 let registrar = AgentInCapacity::new("J. Smith", "registrar");
461 let att = AuthorityAttestation::new(
462 authority,
463 "Degree conferral",
464 "Bachelor of Science conferred",
465 1_700_005_000,
466 )
467 .with_agent(registrar)
468 .with_jurisdiction("AU-NSW")
469 .with_department("Registry")
470 .with_representation(Representation::PdfWithEmbeddedCredential)
471 .with_action_required(false);
472
473 let summary = authority_attestation_summary(&att);
474 assert!(
476 summary.contains("pdf_with_embedded_credential"),
477 "representation must be snake_case: {summary}"
478 );
479
480 let v = parse_authority_attestation_summary(&summary).unwrap();
481 assert_eq!(
482 v.get("authority_label").unwrap().as_str().unwrap(),
483 "State University"
484 );
485 assert_eq!(
486 v.get("authority_type").unwrap().as_str().unwrap(),
487 authority_type::EDUCATION
488 );
489 assert_eq!(v.get("jurisdiction").unwrap().as_str().unwrap(), "AU-NSW");
490 assert_eq!(v.get("department").unwrap().as_str().unwrap(), "Registry");
491 assert_eq!(v.get("capacity").unwrap().as_str().unwrap(), "registrar");
492 assert_eq!(v.get("agent_name").unwrap().as_str().unwrap(), "J. Smith");
493 assert_eq!(
494 v.get("representation").unwrap().as_str().unwrap(),
495 "pdf_with_embedded_credential"
496 );
497 assert_eq!(
498 v.get("subject").unwrap().as_str().unwrap(),
499 "Degree conferral"
500 );
501 assert_eq!(v.get("action_required").unwrap().as_bool().unwrap(), false);
502 }
503
504 #[test]
505 fn well_known_authority_type_consts_are_stable() {
506 assert_eq!(authority_type::GOVERNMENT, "authority:government");
507 assert_eq!(authority_type::PATHOLOGY, "authority:pathology");
508 assert_eq!(authority_type::EDUCATION, "authority:education");
509 assert_eq!(authority_type::FINANCIAL, "authority:financial");
510 assert_eq!(authority_type::NGO, "authority:ngo");
511 }
512}