Skip to main content

qualia_client_core/wellfair/
policy.rs

1use super::consent_store::ConsentGrantRecord;
2use super::host_state::{ConsentGrantDraft, PolicyDecisionDto};
3use wellfare_core::record::{EpistemicStatus, SensitivityClass};
4
5/// The outcome of a policy decision (maps to `PolicyDecisionDto` for UI).
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum DecisionResult {
8    Permit {
9        obligations: Vec<String>,
10    },
11    Deny {
12        reasons: Vec<String>,
13    },
14    Prompt {
15        requested_consent: ConsentGrantDraft,
16    },
17    Suspend {
18        required_approvals: u8,
19    },
20}
21
22/// The receipt bound to a policy decision for auditability.
23#[derive(Debug, Clone)]
24pub struct DecisionReceipt {
25    pub id: String,
26    pub timestamp_unix: u32,
27    pub result: DecisionResult,
28}
29
30impl DecisionResult {
31    /// Converts to dto.
32    pub fn to_dto(&self) -> PolicyDecisionDto {
33        match self {
34            Self::Permit { obligations } => PolicyDecisionDto::Permit {
35                obligations: obligations.clone(),
36            },
37            Self::Deny { reasons } => PolicyDecisionDto::Deny {
38                reasons: reasons.clone(),
39            },
40            Self::Prompt { requested_consent } => PolicyDecisionDto::Prompt {
41                requested_consent: requested_consent.clone(),
42            },
43            Self::Suspend { required_approvals } => PolicyDecisionDto::Suspend {
44                required_approvals: *required_approvals,
45            },
46        }
47    }
48}
49
50pub struct PolicyDecisionService {
51    /// qApp IDs permitted to write health observations without extra prompt.
52    health_writers: &'static [&'static str],
53    /// qApps permitted to write Classified sanctuary/wellbeing records (Phase 3).
54    classified_writers: &'static [&'static str],
55}
56
57impl PolicyDecisionService {
58    /// Creates a new instance.
59    pub fn new() -> Self {
60        Self {
61            health_writers: &[
62                "wellfair-health",
63                "wellfair-medication",
64                "wellfair-shell",
65                "wellfair-life",
66                "wellfair-wellbeing",
67                "wellfair-finance",
68                "wellfair-projects",
69                "wellfair-credentials",
70                "wellfair-clinical",
71                "wellfair-welfare",
72                "qualia-cooperative",
73                "wellfair-guardianship",
74                "wellfair",
75            ],
76            classified_writers: &[
77                "wellfair-shell",
78                "wellfair-sanctuary",
79                "wellfair-wellbeing",
80                "wellfair-life",
81            ],
82        }
83    }
84
85    fn has_active_grant(
86        grants: &[ConsentGrantRecord],
87        qapp_id: &str,
88        scope: &str,
89        now_unix: u64,
90    ) -> bool {
91        grants
92            .iter()
93            .any(|g| g.is_active(now_unix) && g.recipient == qapp_id && g.scope == scope)
94    }
95
96    /// Evaluates if a qApp capability is permitted to act on a record with a given sensitivity.
97    ///
98    /// `is_proxy_action` marks a write made by an agent acting *on behalf of* the principal
99    /// (the envelope carries a `proxy_did` distinct from the owner). Supported-agency
100    /// accountability holds such a write in escrow for M-of-N guardian co-signature rather than
101    /// committing it silently — see `super::guardianship()`. Non-proxy writes (the principal
102    /// acting for themselves) are unaffected.
103    pub fn evaluate_access(
104        &self,
105        qapp_id: &str,
106        requested_scope: &str,
107        sensitivity: SensitivityClass,
108        epistemic: EpistemicStatus,
109        active_grants: &[ConsentGrantRecord],
110        now_unix: u64,
111        is_proxy_action: bool,
112    ) -> DecisionResult {
113        if sensitivity == SensitivityClass::Classified {
114            if requested_scope == "write_record"
115                && self.classified_writers.iter().any(|id| *id == qapp_id)
116            {
117                return DecisionResult::Permit {
118                    obligations: vec![
119                        "emit_wal_receipt".into(),
120                        "sanctuary_projection_required".into(),
121                    ],
122                };
123            }
124            return DecisionResult::Deny {
125                reasons: vec!["Classified records require explicit guardian approval".into()],
126            };
127        }
128
129        if epistemic == EpistemicStatus::Refuted {
130            return DecisionResult::Deny {
131                reasons: vec!["Refuted claims cannot be written as active records".into()],
132            };
133        }
134
135        // Supported-agency escrow: a proxy writing a protected record on the principal's behalf
136        // does not auto-commit — it suspends pending M-of-N guardian co-signature. (Classified is
137        // handled above by the fail-closed writer allowlist; Public needs no escrow.)
138        if is_proxy_action
139            && requested_scope == "write_record"
140            && sensitivity == SensitivityClass::Restricted
141        {
142            return DecisionResult::Suspend {
143                required_approvals: 2,
144            };
145        }
146
147        match requested_scope {
148            "write_record" | "read_record" => {
149                if self.health_writers.iter().any(|id| *id == qapp_id) {
150                    return DecisionResult::Permit {
151                        obligations: vec!["emit_wal_receipt".into()],
152                    };
153                }
154                if Self::has_active_grant(active_grants, qapp_id, requested_scope, now_unix) {
155                    return DecisionResult::Permit {
156                        obligations: vec![
157                            "emit_wal_receipt".into(),
158                            "honour_consent_expiry".into(),
159                        ],
160                    };
161                }
162                let fields = if requested_scope == "write_record" {
163                    vec!["health.observation".into()]
164                } else {
165                    vec!["health.observation".into(), "profile.display_name".into()]
166                };
167                DecisionResult::Prompt {
168                    requested_consent: ConsentGrantDraft {
169                        recipient: qapp_id.to_string(),
170                        purpose: format!("{requested_scope} via WellFair host"),
171                        fields,
172                        expires_at_unix: None,
173                    },
174                }
175            }
176            _ => DecisionResult::Deny {
177                reasons: vec![format!("Unknown scope: {requested_scope}")],
178            },
179        }
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn classified_fails_closed() {
189        let svc = PolicyDecisionService::new();
190        let d = svc.evaluate_access(
191            "wellfair-health",
192            "write_record",
193            SensitivityClass::Classified,
194            EpistemicStatus::Asserted,
195            &[],
196            0,
197            false,
198        );
199        assert!(matches!(d, DecisionResult::Deny { .. }));
200    }
201
202    #[test]
203    fn health_writer_permitted() {
204        let svc = PolicyDecisionService::new();
205        let d = svc.evaluate_access(
206            "wellfair-health",
207            "write_record",
208            SensitivityClass::Restricted,
209            EpistemicStatus::Asserted,
210            &[],
211            0,
212            false,
213        );
214        assert!(matches!(d, DecisionResult::Permit { .. }));
215    }
216
217    #[test]
218    fn medication_writer_permitted() {
219        let svc = PolicyDecisionService::new();
220        let d = svc.evaluate_access(
221            "wellfair-medication",
222            "write_record",
223            SensitivityClass::Restricted,
224            EpistemicStatus::Asserted,
225            &[],
226            0,
227            false,
228        );
229        assert!(matches!(d, DecisionResult::Permit { .. }));
230    }
231
232    #[test]
233    fn active_grant_permits_third_party_qapp() {
234        use super::super::consent_store::ConsentGrantRecord;
235        let svc = PolicyDecisionService::new();
236        let grant = ConsentGrantRecord {
237            id: "g1".into(),
238            recipient: "wellfair-care".into(),
239            purpose: "care team write".into(),
240            fields: vec!["health.observation".into()],
241            scope: "write_record".into(),
242            granted_at_unix: 1,
243            expires_at_unix: None,
244            revoked: false,
245        };
246        let d = svc.evaluate_access(
247            "wellfair-care",
248            "write_record",
249            SensitivityClass::Restricted,
250            EpistemicStatus::Asserted,
251            &[grant],
252            100,
253            false,
254        );
255        assert!(matches!(d, DecisionResult::Permit { .. }));
256    }
257
258    #[test]
259    fn proxy_restricted_write_suspends_for_guardian_cosignature() {
260        let svc = PolicyDecisionService::new();
261        // Even a trusted health-writer qapp: a *proxy* write on protected data escrows.
262        let d = svc.evaluate_access(
263            "wellfair-health",
264            "write_record",
265            SensitivityClass::Restricted,
266            EpistemicStatus::Asserted,
267            &[],
268            0,
269            true,
270        );
271        assert!(matches!(
272            d,
273            DecisionResult::Suspend {
274                required_approvals: 2
275            }
276        ));
277    }
278
279    #[test]
280    fn proxy_public_write_is_not_escrowed() {
281        let svc = PolicyDecisionService::new();
282        let d = svc.evaluate_access(
283            "wellfair-health",
284            "write_record",
285            SensitivityClass::Public,
286            EpistemicStatus::Asserted,
287            &[],
288            0,
289            true,
290        );
291        assert!(matches!(d, DecisionResult::Permit { .. }));
292    }
293
294    #[test]
295    fn non_proxy_restricted_write_still_permits() {
296        let svc = PolicyDecisionService::new();
297        let d = svc.evaluate_access(
298            "wellfair-health",
299            "write_record",
300            SensitivityClass::Restricted,
301            EpistemicStatus::Asserted,
302            &[],
303            0,
304            false,
305        );
306        assert!(matches!(d, DecisionResult::Permit { .. }));
307    }
308}