Skip to main content

wellfare_core/
authority_attestation.rs

1//! Authority attestation — the general domain model of which a "government letter" is one preset.
2//!
3//! A `GovernmentLetter` (see `welfare_support.rs`) is only the narrow special case where the
4//! authorizing body happens to be a government. The general concept is an **authority
5//! attestation**: some **authority** (a government, but equally a pathology company, a university,
6//! a bank, an NGO) attests something about a **subject**, optionally through an **agent-in-capacity**
7//! (the natural person or software agent acting *for* that authority in a stated role), and delivers
8//! it in one of several orthogonal **representations** (a PDF, a verifiable credential, or a PDF with
9//! an embedded credential).
10//!
11//! The authority *type* is a URI-ish string id, NOT a closed enum — `"authority:government"` is just
12//! a well-known upper-level constant. Downstream owners coin their own type ids freely
13//! (`"authority:pathology:acme-labs"`, etc.) without touching this file.
14//!
15//! Like the other WellFair Restricted records, the attestation body lives out-of-band as a blob
16//! (`blob_hash`) — the PDF / credential bytes live in the content-addressed blob store, and this
17//! struct is the indexable envelope over them, flagging whether the owner must act.
18
19use serde::{Deserialize, Serialize};
20use uuid::Uuid;
21
22use crate::record::{
23    EpistemicStatus, EvidenceType, InstantBridge, RecordEnvelope, SensitivityClass,
24};
25
26/// Well-known upper-level authority type ids.
27///
28/// These are an *open* vocabulary: the field on [`Authority`] is a plain `String`, so callers may
29/// use one of these consts or coin their own URI-ish id (e.g. `"authority:pathology:acme-labs"`).
30/// "Government" is deliberately just one of many — a pathology company, a university, a bank and an
31/// NGO are equally authorities.
32pub mod authority_type {
33    /// A government body — the classic "government letter" case.
34    pub const GOVERNMENT: &str = "authority:government";
35    /// A pathology / medical laboratory or provider.
36    pub const PATHOLOGY: &str = "authority:pathology";
37    /// A university, school, or other educational institution.
38    pub const EDUCATION: &str = "authority:education";
39    /// A bank or other financial institution.
40    pub const FINANCIAL: &str = "authority:financial";
41    /// A non-governmental / charitable organisation.
42    pub const NGO: &str = "authority:ngo";
43}
44
45// Re-export the well-known consts at module top level for ergonomic `authority_attestation::GOVERNMENT`.
46pub use authority_type::{EDUCATION, FINANCIAL, GOVERNMENT, NGO, PATHOLOGY};
47
48/// The authorizing body behind an attestation.
49///
50/// `type_id` is an extensible URI-ish string (see [`authority_type`]); `label` is the human-readable
51/// name. `jurisdiction` locates the authority's remit (e.g. `"AU"`, `"AU-VIC"`), and `department` is
52/// an optional branch / sub-unit within the authority.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct Authority {
55    /// Extensible type id, e.g. `authority_type::GOVERNMENT` or a caller-coined `"authority:…"`.
56    pub type_id: String,
57    /// Human-readable name of the authority, e.g. "Services Australia", "Acme Pathology".
58    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    /// A new authority of the given extensible `type_id` with a human `label`.
67    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    /// True if this authority is a government (`authority_type::GOVERNMENT`).
77    pub fn is_government(&self) -> bool {
78        self.type_id == authority_type::GOVERNMENT
79    }
80
81    /// True if this authority is a pathology / medical body — its attestations carry more weight as
82    /// evidence (see [`build_authority_attestation_envelope`]). Matches the exact `PATHOLOGY` const
83    /// or any type id under the `authority:pathology`/`authority:medical` prefix so caller-coined
84    /// ids like `"authority:pathology:acme-labs"` are still recognised as clinician-grade.
85    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/// A natural person (or software agent) acting FOR the authority in a stated capacity/role —
93/// e.g. a pathologist signing off a result, a case officer issuing a determination.
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95pub struct AgentInCapacity {
96    /// Name of the person or software agent.
97    pub name: String,
98    /// The role/capacity they act in, e.g. "pathologist", "case officer", "registrar".
99    pub capacity: String,
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub did: Option<String>,
102}
103
104impl AgentInCapacity {
105    /// Creates a new instance.
106    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    /// Attach a DID to the agent.
115    pub fn with_did(mut self, did: impl Into<String>) -> Self {
116        self.did = Some(did.into());
117        self
118    }
119}
120
121/// How an attestation is delivered — ORTHOGONAL to its content.
122///
123/// The same attestation (same authority, subject, statement) can arrive as a plain document blob,
124/// as a verifiable credential, or as a PDF with a credential baked in.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
126#[serde(rename_all = "snake_case")]
127pub enum Representation {
128    /// A document blob (e.g. a PDF letter).
129    Pdf,
130    /// A verifiable credential.
131    Credential,
132    /// A PDF document with an embedded verifiable credential.
133    PdfWithEmbeddedCredential,
134}
135
136impl Default for Representation {
137    fn default() -> Self {
138        Self::Pdf
139    }
140}
141
142/// An attestation issued by an authority (through an optional agent-in-capacity) about a subject.
143///
144/// This is the general model; [`government_letter`] is a preset over it. The attestation body
145/// itself lives out-of-band as a blob (`blob_hash`); this struct is the indexable envelope.
146#[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    /// What / who is attested (the subject of the attestation).
155    pub subject: String,
156    /// Free-text statement / subject line describing the attestation.
157    pub statement: String,
158    #[serde(default)]
159    pub action_required: bool,
160    pub issued_unix: u32,
161    /// High-resolution instant (T71 bridge). Preferred over `issued_unix`
162    /// when present; the u32 field is kept for backward-compatible deserialization.
163    #[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    /// A new attestation from `authority` about `subject`, with the given free-text `statement`,
171    /// issued at `issued_unix`. Defaults: no agent, `Pdf` representation, no action required, no blob.
172    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    /// Resolve the issued instant, preferring the high-resolution
193    /// `InstantBridge` field when present (T71 bridge).
194    pub fn issued_at(&self) -> InstantBridge {
195        self.issued_instant
196            .unwrap_or_else(|| InstantBridge::from_coarse(self.issued_unix))
197    }
198
199    /// Attach the agent-in-capacity who issued the attestation.
200    pub fn with_agent(mut self, agent: AgentInCapacity) -> Self {
201        self.agent = Some(agent);
202        self
203    }
204
205    /// Set the authority's department / branch.
206    pub fn with_department(mut self, department: impl Into<String>) -> Self {
207        self.authority.department = Some(department.into());
208        self
209    }
210
211    /// Set the authority's jurisdiction (e.g. "AU", "AU-VIC").
212    pub fn with_jurisdiction(mut self, jurisdiction: impl Into<String>) -> Self {
213        self.authority.jurisdiction = Some(jurisdiction.into());
214        self
215    }
216
217    /// Reference the content-addressed blob (PDF / credential bytes) for this attestation.
218    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    /// Set the delivery representation (Pdf / Credential / PdfWithEmbeddedCredential).
224    pub fn with_representation(mut self, representation: Representation) -> Self {
225        self.representation = representation;
226        self
227    }
228
229    /// Mark whether the owner must act on this attestation.
230    pub fn with_action_required(mut self, action_required: bool) -> Self {
231        self.action_required = action_required;
232        self
233    }
234}
235
236/// The "government letter" specialization: an [`AuthorityAttestation`] whose authority is a
237/// government (`authority_type::GOVERNMENT`), labelled from `sender`, delivered as a `Pdf`.
238///
239/// This makes the old `GovernmentLetter` just a preset of the general model. `subject` is used both
240/// as the attestation subject and its statement/subject line (a government letter's "what it's
241/// about" is its subject line).
242pub 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
248///  record ID.
249pub fn authority_attestation_record_id(uuid: &str) -> String {
250    format!("urn:wellfair:authority_attestation:{uuid}")
251}
252
253/// Build the Restricted envelope for an authority attestation.
254///
255/// Sensitivity is always `Restricted` (this is authority paperwork about the owner, not a public
256/// disclosure). The epistemic status is `Asserted`. Evidence type is chosen by the authority: a
257/// pathology / medical authority's attestation is `ClinicianObserved` (it is a clinician acting in
258/// capacity), whereas any other authority is treated as `SelfReported` — the owner is asserting
259/// "here is a letter I received", not making an independently-verified clinical claim. The
260/// attestation's own `blob_hash` (the PDF / credential bytes) flows through to the envelope, and
261/// validity anchors to when the attestation was issued. `proxy_did` is `None`.
262pub 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
294/// A compact JSON projection of an attestation for journal display.
295pub 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
312/// Parse a compact projection produced by [`authority_attestation_summary`] back into a value.
313pub 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        // Serde round-trip preserves every field.
356        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); // re-exported const
366        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        // A government (non-medical) authority yields SelfReported evidence.
393        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        // The attestation's blob flows through to the envelope.
398        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        // Exact PATHOLOGY const.
405        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        // Caller-coined pathology sub-type is still recognised as clinician-grade.
416        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        // A pathology company (custom type id) with a named pathologist acting in capacity.
430        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        // Envelope reflects clinician evidence + the credential blob.
452        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        // Representation serializes snake_case.
475        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}