1use serde::{Deserialize, Serialize};
16use uuid::Uuid;
17
18use crate::record::{EpistemicStatus, EvidenceType, RecordEnvelope, SensitivityClass};
19
20use crate::agency_domain::is_consequential;
21use crate::authority_type::AuthorityProfile;
22use crate::provenance::JudgementProvenance;
23use crate::taxonomy::{Sphere, Taxonomy, TermId};
24use crate::trigger::{evaluate as evaluate_trigger, Trigger, TriggerContext};
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
29#[serde(rename_all = "snake_case")]
30pub enum Precedence {
31 #[default]
32 Primary,
33 Secondary,
34 LocalTemporary,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
39#[serde(rename_all = "snake_case")]
40pub enum ConsentState {
41 #[default]
42 Pending,
43 Granted,
44 Withdrawn,
45 NotRequired,
47}
48
49impl ConsentState {
50 fn is_effective(self) -> bool {
51 matches!(self, ConsentState::Granted | ConsentState::NotRequired)
52 }
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
58#[serde(rename_all = "snake_case")]
59pub enum ControlStage {
60 GuardianSole,
61 CoSigned,
62 PrincipalSole,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub struct TransferStage {
69 pub domain: TermId,
70 pub to_stage: ControlStage,
71 pub trigger: Trigger,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76pub struct AgencyDelegation {
77 pub id: String,
78 pub principal_did: String,
79 pub agent_dids: Vec<String>,
80 pub domain: TermId,
82 #[serde(default)]
83 pub authority: AuthorityProfile,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
86 pub trigger: Option<Trigger>,
87 pub values_anchor: String,
90 #[serde(default)]
93 pub scope: Vec<(String, String)>,
94 #[serde(default, skip_serializing_if = "Option::is_none")]
95 pub jurisdiction: Option<TermId>,
96 #[serde(default)]
97 pub precedence: Precedence,
98 pub valid_from_unix: u32,
99 #[serde(default, skip_serializing_if = "Option::is_none")]
100 pub valid_to_unix: Option<u32>,
101 #[serde(default)]
102 pub consent: ConsentState,
103 #[serde(default)]
104 pub revoked: bool,
105 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub evidence_ref: Option<String>,
108 #[serde(default, skip_serializing_if = "Vec::is_empty")]
110 pub transfer_schedule: Vec<TransferStage>,
111}
112
113impl AgencyDelegation {
114 pub fn new(
116 principal_did: impl Into<String>,
117 domain: impl Into<TermId>,
118 values_anchor: impl Into<String>,
119 valid_from_unix: u32,
120 ) -> Self {
121 Self {
122 id: Uuid::new_v4().to_string(),
123 principal_did: principal_did.into(),
124 agent_dids: Vec::new(),
125 domain: domain.into(),
126 authority: AuthorityProfile::default(),
127 trigger: None,
128 values_anchor: values_anchor.into(),
129 scope: Vec::new(),
130 jurisdiction: None,
131 precedence: Precedence::Primary,
132 valid_from_unix,
133 valid_to_unix: None,
134 consent: ConsentState::Pending,
135 revoked: false,
136 evidence_ref: None,
137 transfer_schedule: Vec::new(),
138 }
139 }
140
141 fn scope_has(&self, key: &str, value: &str) -> bool {
142 self.scope.iter().any(|(k, v)| k == key && v == value)
143 }
144}
145
146pub fn agency_delegation_record_id(uuid: &str) -> String {
148 format!("urn:qualia:agency-delegation:{uuid}")
149}
150
151pub fn build_agency_delegation_envelope(
153 delegation: &AgencyDelegation,
154 owner_did: &str,
155 author_did: &str,
156 asserted_unix: u32,
157) -> RecordEnvelope {
158 RecordEnvelope {
159 id: agency_delegation_record_id(&delegation.id),
160 owner_did: owner_did.to_string(),
161 author_did: author_did.to_string(),
162 proxy_did: None,
163 epistemic_status: EpistemicStatus::Asserted,
164 evidence_type: EvidenceType::SelfReported,
165 sensitivity: SensitivityClass::Restricted,
166 asserted_time_unix: asserted_unix,
167 asserted_instant: None,
168 valid_time_start_unix: Some(delegation.valid_from_unix),
169 valid_time_start_instant: None,
170 valid_time_end_unix: delegation.valid_to_unix,
171 valid_time_end_instant: None,
172 predecessor_id: None,
173 blob_hash: None,
174 tombstone: false,
175 }
176}
177
178pub fn agency_delegation_summary(delegation: &AgencyDelegation) -> String {
180 serde_json::json!({
181 "id": delegation.id,
182 "principal_did": delegation.principal_did,
183 "agent_dids": delegation.agent_dids,
184 "domain": delegation.domain,
185 "precedence": delegation.precedence,
186 "consent": delegation.consent,
187 "revoked": delegation.revoked,
188 "jurisdiction": delegation.jurisdiction,
189 })
190 .to_string()
191}
192
193pub fn agency_delegation_full_json(delegation: &AgencyDelegation) -> String {
197 serde_json::to_string(delegation).unwrap_or_default()
198}
199
200pub fn parse_agency_delegation(json: &str) -> Option<AgencyDelegation> {
202 serde_json::from_str(json).ok()
203}
204
205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
212pub struct AccessRequest {
213 pub domain: TermId,
214 #[serde(default)]
215 pub data_class: String,
216 pub action: String,
218 #[serde(default)]
219 pub sphere: Sphere,
220 #[serde(default, skip_serializing_if = "Option::is_none")]
221 pub jurisdiction: Option<TermId>,
222 #[serde(default, skip_serializing_if = "Option::is_none")]
223 pub provenance: Option<JudgementProvenance>,
224}
225
226impl AccessRequest {
227 fn is_judgement(&self) -> bool {
228 matches!(self.action.as_str(), "write" | "decide")
229 }
230}
231
232#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
233#[serde(rename_all = "snake_case")]
234pub enum AccessDecision {
235 Permit,
236 Deny(String),
237}
238
239impl AccessDecision {
240 pub fn is_permit(&self) -> bool {
242 matches!(self, AccessDecision::Permit)
243 }
244}
245
246pub fn delegation_permits(
249 delegation: &AgencyDelegation,
250 domains: &Taxonomy,
251 request: &AccessRequest,
252 ctx: &TriggerContext,
253) -> AccessDecision {
254 if delegation.revoked {
255 return AccessDecision::Deny("delegation revoked".into());
256 }
257 if !delegation.consent.is_effective() {
258 return AccessDecision::Deny(format!("consent not effective ({:?})", delegation.consent));
259 }
260 if ctx.now_unix < delegation.valid_from_unix {
261 return AccessDecision::Deny("delegation not yet valid".into());
262 }
263 if let Some(end) = delegation.valid_to_unix {
264 if ctx.now_unix > end {
265 return AccessDecision::Deny("delegation expired".into());
266 }
267 }
268 if let Some(trigger) = &delegation.trigger {
269 if !evaluate_trigger(trigger, ctx) {
270 return AccessDecision::Deny("delegation trigger is not active".into());
271 }
272 }
273 if request.domain != delegation.domain {
274 return AccessDecision::Deny(format!(
275 "delegation does not cover domain '{}'",
276 request.domain
277 ));
278 }
279 if request.sphere == Sphere::Selfhood && !delegation.scope_has("selfhood_grant", "explicit") {
282 return AccessDecision::Deny(
283 "selfhood is not delegable without an explicit selfhood grant".into(),
284 );
285 }
286 if request.is_judgement() && is_consequential(domains, &request.domain) {
288 match &request.provenance {
289 Some(p) if p.epistemic_horizon.is_some() => {}
290 _ => return AccessDecision::Deny(
291 "consequential judgement requires declared provenance with an epistemic horizon"
292 .into(),
293 ),
294 }
295 }
296 if let (Some(dj), Some(rj)) = (&delegation.jurisdiction, &request.jurisdiction) {
299 if dj != rj {
300 return AccessDecision::Deny("jurisdiction mismatch".into());
301 }
302 }
303 AccessDecision::Permit
304}
305
306#[cfg(test)]
307mod tests {
308 use super::*;
309 use crate::agency_domain::{agency_domain_taxonomy, ids as dom};
310 use crate::provenance::{AgentRef, JudgementProvenance};
311 use crate::trigger::{Attestation, Trigger, TriggerContext};
312
313 fn ctx(now: u32) -> TriggerContext {
314 TriggerContext::at(now)
315 }
316
317 fn granted(domain: &str) -> AgencyDelegation {
318 let mut d = AgencyDelegation::new("did:wf:alice", domain, "urn:un:hr:udhr", 100);
319 d.consent = ConsentState::Granted;
320 d
321 }
322
323 fn read_req(domain: &str) -> AccessRequest {
324 AccessRequest {
325 domain: domain.into(),
326 data_class: "x".into(),
327 action: "read".into(),
328 sphere: Sphere::Personhood,
329 jurisdiction: None,
330 provenance: None,
331 }
332 }
333
334 #[test]
335 fn permits_within_scope_when_valid_and_consented() {
336 let tax = agency_domain_taxonomy();
337 let d = granted(dom::PERSONAL_WELFARE);
338 assert!(
339 delegation_permits(&d, &tax, &read_req(dom::PERSONAL_WELFARE), &ctx(200)).is_permit()
340 );
341 }
342
343 #[test]
344 fn denies_revoked_pending_withdrawn_expired_and_not_yet_valid() {
345 let tax = agency_domain_taxonomy();
346 let base = granted(dom::PERSONAL_WELFARE);
347 let req = read_req(dom::PERSONAL_WELFARE);
348
349 let mut revoked = base.clone();
350 revoked.revoked = true;
351 assert!(!delegation_permits(&revoked, &tax, &req, &ctx(200)).is_permit());
352
353 let mut pending = base.clone();
354 pending.consent = ConsentState::Pending;
355 assert!(!delegation_permits(&pending, &tax, &req, &ctx(200)).is_permit());
356
357 let mut withdrawn = base.clone();
358 withdrawn.consent = ConsentState::Withdrawn;
359 assert!(!delegation_permits(&withdrawn, &tax, &req, &ctx(200)).is_permit());
360
361 let mut expiring = base.clone();
362 expiring.valid_to_unix = Some(150);
363 assert!(!delegation_permits(&expiring, &tax, &req, &ctx(200)).is_permit());
364
365 assert!(!delegation_permits(&base, &tax, &req, &ctx(50)).is_permit());
367 }
368
369 #[test]
370 fn wrong_domain_is_denied() {
371 let tax = agency_domain_taxonomy();
372 let d = granted(dom::FINANCIAL);
373 assert!(!delegation_permits(&d, &tax, &read_req(dom::MEDICAL), &ctx(200)).is_permit());
374 }
375
376 #[test]
377 fn trigger_gates_activation() {
378 let tax = agency_domain_taxonomy();
379 let mut d = granted(dom::MEDICAL);
380 d.trigger = Some(Trigger::All(vec![
382 Trigger::VerifiableEvent {
383 event_id: "er".into(),
384 },
385 Trigger::HumanConsensus {
386 required_capacity: Some("physician".into()),
387 m: 2,
388 n: 5,
389 },
390 ]));
391 let req = read_req(dom::MEDICAL);
393
394 assert!(!delegation_permits(&d, &tax, &req, &ctx(200)).is_permit());
396
397 let active = ctx(200)
399 .with_event("er")
400 .with_attestation(Attestation::signed("physician"))
401 .with_attestation(Attestation::signed("physician"));
402 assert!(delegation_permits(&d, &tax, &req, &active).is_permit());
403 }
404
405 #[test]
406 fn selfhood_is_denied_without_explicit_grant() {
407 let tax = agency_domain_taxonomy();
408 let d = granted(dom::REPRODUCTIVE_BIOMETRIC_GENETIC);
409 let mut req = read_req(dom::REPRODUCTIVE_BIOMETRIC_GENETIC);
410 req.sphere = Sphere::Selfhood;
411 assert!(!delegation_permits(&d, &tax, &req, &ctx(200)).is_permit());
413
414 let mut explicit = d.clone();
416 explicit
417 .scope
418 .push(("selfhood_grant".into(), "explicit".into()));
419 assert!(delegation_permits(&explicit, &tax, &req, &ctx(200)).is_permit());
420 }
421
422 #[test]
423 fn consequential_judgement_requires_provenance_with_horizon() {
424 let tax = agency_domain_taxonomy();
425 let d = granted(dom::MEDICAL);
426 let mut decide = read_req(dom::MEDICAL);
427 decide.action = "decide".into();
428
429 assert!(!delegation_permits(&d, &tax, &decide, &ctx(200)).is_permit());
431
432 let mut no_horizon = decide.clone();
434 no_horizon.provenance = Some(JudgementProvenance::new(AgentRef::natural_person("did:dr")));
435 assert!(!delegation_permits(&d, &tax, &no_horizon, &ctx(200)).is_permit());
436
437 let mut with_horizon = decide.clone();
439 with_horizon.provenance = Some(
440 JudgementProvenance::new(AgentRef::natural_person("did:dr")).with_horizon("merkle:abc"),
441 );
442 assert!(delegation_permits(&d, &tax, &with_horizon, &ctx(200)).is_permit());
443 }
444
445 #[test]
446 fn jurisdiction_mismatch_denied_but_local_temporary_matches_its_own() {
447 let tax = agency_domain_taxonomy();
448 let mut d = granted(dom::MEDICAL);
449 d.jurisdiction = Some("urn:jur:au-vic".into());
450 let mut req = read_req(dom::MEDICAL);
451 req.jurisdiction = Some("urn:jur:th".into());
452 assert!(!delegation_permits(&d, &tax, &req, &ctx(200)).is_permit());
453
454 let mut local = granted(dom::MEDICAL);
456 local.precedence = Precedence::LocalTemporary;
457 local.jurisdiction = Some("urn:jur:th".into());
458 assert!(delegation_permits(&local, &tax, &req, &ctx(200)).is_permit());
459 }
460
461 #[test]
462 fn envelope_kind_and_summary_round_trip() {
463 let d = granted(dom::FINANCIAL);
464 let env = build_agency_delegation_envelope(&d, "did:wf:alice", "did:wf:alice", 100);
465 assert!(env.id.contains(":agency-delegation:"));
466 assert_eq!(env.sensitivity, SensitivityClass::Restricted);
467 let summary = agency_delegation_summary(&d);
468 assert!(summary.contains(dom::FINANCIAL));
469 }
470
471 #[test]
472 fn full_json_round_trips_losslessly() {
473 let mut d = granted(dom::MEDICAL);
476 d.agent_dids = vec!["did:wf:carer".into()];
477 d.scope = vec![("data_class".into(), "medication".into())];
478 d.trigger = Some(Trigger::TemporalWindow {
479 from_unix: 10,
480 to_unix: Some(20),
481 });
482 d.transfer_schedule = vec![TransferStage {
483 domain: dom::MEDICAL.into(),
484 to_stage: ControlStage::CoSigned,
485 trigger: Trigger::TemporalWindow {
486 from_unix: 1_000,
487 to_unix: None,
488 },
489 }];
490 let json = agency_delegation_full_json(&d);
491 let back = parse_agency_delegation(&json).expect("reconstructs");
492 assert_eq!(d, back);
493 assert!(!agency_delegation_summary(&d).contains("temporal_window"));
495 }
496
497 #[test]
498 fn developmental_transfer_stages_are_ordered_and_serde_round_trip() {
499 let mut d = granted(dom::COMMUNICATION);
500 d.transfer_schedule = vec![
501 TransferStage {
502 domain: dom::COMMUNICATION.into(),
503 to_stage: ControlStage::CoSigned,
504 trigger: Trigger::TemporalWindow {
505 from_unix: 1_000,
506 to_unix: None,
507 },
508 },
509 TransferStage {
510 domain: dom::COMMUNICATION.into(),
511 to_stage: ControlStage::PrincipalSole,
512 trigger: Trigger::TemporalWindow {
513 from_unix: 2_000,
514 to_unix: None,
515 },
516 },
517 ];
518 assert!(d.transfer_schedule[0].to_stage < d.transfer_schedule[1].to_stage);
520 let json = serde_json::to_string(&d).unwrap();
521 let back: AgencyDelegation = serde_json::from_str(&json).unwrap();
522 assert_eq!(d, back);
523 }
524}