Skip to main content

qualia_client_core/wellfair/
consent_store.rs

1//! Persisted owner consent grants evaluated by PolicyDecisionService.
2
3use std::fs::{self, OpenOptions};
4use std::io::{BufRead, BufReader, Write};
5use std::path::{Path, PathBuf};
6use std::time::{SystemTime, UNIX_EPOCH};
7
8use serde::{Deserialize, Serialize};
9
10use super::host_state::ConsentGrantDraft;
11
12pub const CONSENTS_FILE: &str = "wellfair/consents.jsonl";
13pub const MAX_LIST: usize = 64;
14
15#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
16pub struct ConsentGrantRecord {
17    pub id: String,
18    pub recipient: String,
19    pub purpose: String,
20    pub fields: Vec<String>,
21    pub scope: String,
22    pub granted_at_unix: u32,
23    pub expires_at_unix: Option<u64>,
24    pub revoked: bool,
25}
26
27impl ConsentGrantRecord {
28    /// Constructs from draft.
29    pub fn from_draft(draft: &ConsentGrantDraft, scope: &str) -> Self {
30        let granted_at_unix = SystemTime::now()
31            .duration_since(UNIX_EPOCH)
32            .map(|d| d.as_secs() as u32)
33            .unwrap_or(0);
34        Self {
35            id: format!("consent-{granted_at_unix}-{}", &draft.recipient),
36            recipient: draft.recipient.clone(),
37            purpose: draft.purpose.clone(),
38            fields: draft.fields.clone(),
39            scope: scope.to_string(),
40            granted_at_unix,
41            expires_at_unix: draft.expires_at_unix,
42            revoked: false,
43        }
44    }
45
46    /// `true` when active.
47    pub fn is_active(&self, now_unix: u64) -> bool {
48        if self.revoked {
49            return false;
50        }
51        if let Some(exp) = self.expires_at_unix {
52            if now_unix >= exp {
53                return false;
54            }
55        }
56        true
57    }
58}
59
60pub struct ConsentStore {
61    path: PathBuf,
62}
63
64impl ConsentStore {
65    /// Opens.
66    pub fn open(storage_root: impl AsRef<Path>) -> std::io::Result<Self> {
67        let path = storage_root.as_ref().join(CONSENTS_FILE);
68        if let Some(parent) = path.parent() {
69            fs::create_dir_all(parent)?;
70        }
71        if !path.exists() {
72            OpenOptions::new().create(true).write(true).open(&path)?;
73        }
74        Ok(Self { path })
75    }
76
77    /// Appends.
78    pub fn append(&self, grant: &ConsentGrantRecord) -> std::io::Result<()> {
79        let line =
80            serde_json::to_string(grant).map_err(|e| std::io::Error::other(e.to_string()))?;
81        let mut file = OpenOptions::new().append(true).open(&self.path)?;
82        writeln!(file, "{line}")?;
83        file.sync_all()?;
84        Ok(())
85    }
86
87    /// Lists all entries.
88    pub fn list_all(&self) -> std::io::Result<Vec<ConsentGrantRecord>> {
89        let file = fs::File::open(&self.path)?;
90        let reader = BufReader::new(file);
91        let mut records = Vec::new();
92        for line in reader.lines() {
93            let line = line?;
94            if line.trim().is_empty() {
95                continue;
96            }
97            if let Ok(record) = serde_json::from_str::<ConsentGrantRecord>(&line) {
98                records.push(record);
99            }
100        }
101        Ok(records)
102    }
103
104    /// Lists active entries.
105    pub fn list_active(&self, now_unix: u64) -> std::io::Result<Vec<ConsentGrantRecord>> {
106        let all = self.list_all()?;
107        let mut active: Vec<_> = all.into_iter().filter(|g| g.is_active(now_unix)).collect();
108        let keep = MAX_LIST.min(active.len());
109        if active.len() > keep {
110            active.drain(0..active.len() - keep);
111        }
112        active.reverse();
113        Ok(active)
114    }
115
116    /// Revokes.
117    pub fn revoke(&self, grant_id: &str) -> std::io::Result<bool> {
118        let all = self.list_all()?;
119        let mut found = false;
120        let mut rewritten = Vec::with_capacity(all.len());
121        for mut grant in all {
122            if grant.id == grant_id && !grant.revoked {
123                grant.revoked = true;
124                found = true;
125            }
126            rewritten.push(grant);
127        }
128        if !found {
129            return Ok(false);
130        }
131        let tmp = self.path.with_extension("jsonl.tmp");
132        {
133            let mut file = OpenOptions::new()
134                .create(true)
135                .write(true)
136                .truncate(true)
137                .open(&tmp)?;
138            for grant in &rewritten {
139                let line = serde_json::to_string(grant)
140                    .map_err(|e| std::io::Error::other(e.to_string()))?;
141                writeln!(file, "{line}")?;
142            }
143            file.sync_all()?;
144        }
145        fs::rename(&tmp, &self.path)?;
146        Ok(true)
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn consent_grant_round_trip() {
156        let dir = tempfile::tempdir().unwrap();
157        let store = ConsentStore::open(dir.path()).unwrap();
158        let draft = ConsentGrantDraft {
159            recipient: "wellfair-care".into(),
160            purpose: "write_record".into(),
161            fields: vec!["health.observation".into()],
162            expires_at_unix: None,
163        };
164        let grant = ConsentGrantRecord::from_draft(&draft, "write_record");
165        store.append(&grant).unwrap();
166        let active = store.list_active(u64::MAX).unwrap();
167        assert_eq!(active.len(), 1);
168        assert!(store.revoke(&grant.id).unwrap());
169        assert!(store.list_active(u64::MAX).unwrap().is_empty());
170    }
171}