Skip to main content

adk_awp/
consent.rs

1//! Consent capture, check, and revocation framework.
2//!
3//! Provides two implementations:
4//! - [`InMemoryConsentService`] — ephemeral, for development and testing
5//! - [`FileConsentService`] — durable local JSON storage
6
7use std::io::Write;
8use std::path::{Path, PathBuf};
9
10use async_trait::async_trait;
11use awp_types::AwpError;
12use chrono::{DateTime, Utc};
13use dashmap::DashMap;
14use serde::{Deserialize, Serialize};
15
16/// Trait for managing user consent records.
17#[async_trait]
18pub trait ConsentService: Send + Sync {
19    /// Record consent for a subject and purpose.
20    async fn capture_consent(&self, subject: &str, purpose: &str) -> Result<(), AwpError>;
21
22    /// Check whether consent is currently active for a subject and purpose.
23    async fn check_consent(&self, subject: &str, purpose: &str) -> Result<bool, AwpError>;
24
25    /// Revoke previously captured consent.
26    async fn revoke_consent(&self, subject: &str, purpose: &str) -> Result<(), AwpError>;
27}
28
29// ---------------------------------------------------------------------------
30// In-memory implementation
31// ---------------------------------------------------------------------------
32
33/// A consent record with timestamp and revocation state.
34#[derive(Debug, Clone)]
35struct ConsentRecord {
36    _captured_at: DateTime<Utc>,
37    revoked: bool,
38}
39
40/// In-memory consent service backed by [`DashMap`].
41///
42/// Keys are `(subject, purpose)` tuples. Capturing consent on an already-
43/// captured pair re-activates it (clears the revoked flag).
44///
45/// Records are lost on process restart. Use [`FileConsentService`] for
46/// durable storage.
47pub struct InMemoryConsentService {
48    records: DashMap<(String, String), ConsentRecord>,
49}
50
51impl InMemoryConsentService {
52    /// Create a new empty consent service.
53    pub fn new() -> Self {
54        Self { records: DashMap::new() }
55    }
56}
57
58impl Default for InMemoryConsentService {
59    fn default() -> Self {
60        Self::new()
61    }
62}
63
64#[async_trait]
65impl ConsentService for InMemoryConsentService {
66    async fn capture_consent(&self, subject: &str, purpose: &str) -> Result<(), AwpError> {
67        let key = (subject.to_string(), purpose.to_string());
68        self.records.insert(key, ConsentRecord { _captured_at: Utc::now(), revoked: false });
69        Ok(())
70    }
71
72    async fn check_consent(&self, subject: &str, purpose: &str) -> Result<bool, AwpError> {
73        let key = (subject.to_string(), purpose.to_string());
74        Ok(self.records.get(&key).is_some_and(|r| !r.revoked))
75    }
76
77    async fn revoke_consent(&self, subject: &str, purpose: &str) -> Result<(), AwpError> {
78        let key = (subject.to_string(), purpose.to_string());
79        if let Some(mut entry) = self.records.get_mut(&key) {
80            entry.revoked = true;
81        }
82        Ok(())
83    }
84}
85
86// ---------------------------------------------------------------------------
87// File-backed implementation
88// ---------------------------------------------------------------------------
89
90/// Serializable consent record for file persistence.
91#[derive(Debug, Clone, Serialize, Deserialize)]
92struct FileConsentRecord {
93    subject: String,
94    purpose: String,
95    captured_at: DateTime<Utc>,
96    revoked: bool,
97    #[serde(skip_serializing_if = "Option::is_none")]
98    revoked_at: Option<DateTime<Utc>>,
99}
100
101/// Serializable consent store for JSON file persistence.
102#[derive(Debug, Clone, Serialize, Deserialize, Default)]
103struct FileConsentStore {
104    records: Vec<FileConsentRecord>,
105}
106
107/// JSON file-backed consent service for durable storage.
108///
109/// Persists consent records to a JSON file on every mutation (capture/revoke).
110/// Loads existing records from the file on construction. Safe for single-process
111/// deployments; for multi-process, use a database-backed implementation.
112///
113/// Each write goes to a temporary file in the same directory, is synced, and is renamed
114/// over the target on a blocking thread, so a reader or a crash never sees a partial file
115/// and the async executor never blocks on disk (spec 3.5 §10 X3). Writes are serialised, so
116/// the file always ends with the latest state.
117///
118/// # Example
119///
120/// ```rust,ignore
121/// use adk_awp::FileConsentService;
122///
123/// let consent = FileConsentService::new("data/consent.json")?;
124/// consent.capture_consent("visitor-123", "analytics").await?;
125/// assert!(consent.check_consent("visitor-123", "analytics").await?);
126/// ```
127pub struct FileConsentService {
128    path: PathBuf,
129    records: DashMap<(String, String), FileConsentRecord>,
130    write_lock: tokio::sync::Mutex<()>,
131}
132
133impl FileConsentService {
134    /// Create a new file-backed consent service.
135    ///
136    /// If the file exists, records are loaded from it. If it doesn't exist,
137    /// an empty store is created and the file is written on first mutation.
138    ///
139    /// # Errors
140    ///
141    /// Returns [`AwpError::InternalError`] if the file exists but cannot be
142    /// read or parsed.
143    pub fn new(path: impl AsRef<Path>) -> Result<Self, AwpError> {
144        let path = path.as_ref().to_path_buf();
145        let records = DashMap::new();
146
147        if path.exists() {
148            let content = std::fs::read_to_string(&path).map_err(|e| {
149                AwpError::InternalError(format!(
150                    "failed to read consent file {}: {e}",
151                    path.display()
152                ))
153            })?;
154            let store: FileConsentStore = serde_json::from_str(&content).map_err(|e| {
155                AwpError::InternalError(format!(
156                    "failed to parse consent file {}: {e}",
157                    path.display()
158                ))
159            })?;
160            for record in store.records {
161                let key = (record.subject.clone(), record.purpose.clone());
162                records.insert(key, record);
163            }
164        }
165
166        Ok(Self { path, records, write_lock: tokio::sync::Mutex::new(()) })
167    }
168
169    /// Persist all records to the JSON file.
170    async fn flush(&self) -> Result<(), AwpError> {
171        // The snapshot is taken under the lock, so writes land in order and the last one
172        // holds every mutation made before it.
173        let _guard = self.write_lock.lock().await;
174        let mut records: Vec<FileConsentRecord> =
175            self.records.iter().map(|entry| entry.value().clone()).collect();
176        records.sort_by(|a, b| (&a.subject, &a.purpose).cmp(&(&b.subject, &b.purpose)));
177        let json = serde_json::to_vec_pretty(&FileConsentStore { records }).map_err(|e| {
178            AwpError::InternalError(format!("failed to serialize consent records: {e}"))
179        })?;
180        let path = self.path.clone();
181        tokio::task::spawn_blocking(move || write_atomically(&path, &json))
182            .await
183            .map_err(|e| AwpError::InternalError(format!("consent file write task failed: {e}")))?
184    }
185}
186
187/// Writes `bytes` to a synced temporary file beside `path` and renames it over `path`.
188fn write_atomically(path: &Path, bytes: &[u8]) -> Result<(), AwpError> {
189    let io_error = |action: &str, target: &Path, e: std::io::Error| {
190        AwpError::InternalError(format!("failed to {action} {}: {e}", target.display()))
191    };
192    let Some(file_name) = path.file_name() else {
193        return Err(AwpError::InternalError(format!(
194            "consent file path {} has no file name",
195            path.display()
196        )));
197    };
198    if let Some(parent) = path.parent()
199        && !parent.as_os_str().is_empty()
200        && !parent.exists()
201    {
202        std::fs::create_dir_all(parent)
203            .map_err(|e| io_error("create consent directory", parent, e))?;
204    }
205    let temp = path.with_file_name(format!(
206        ".{}.{}.tmp",
207        file_name.to_string_lossy(),
208        uuid::Uuid::now_v7().simple()
209    ));
210    let written = std::fs::File::create(&temp)
211        .and_then(|mut file| {
212            file.write_all(bytes)?;
213            file.sync_all()
214        })
215        .map_err(|e| io_error("write consent file", &temp, e))
216        .and_then(|()| {
217            std::fs::rename(&temp, path).map_err(|e| io_error("replace consent file", path, e))
218        });
219    if written.is_err() {
220        // Best effort: the temporary file is never read, only left behind.
221        let _ = std::fs::remove_file(&temp);
222    }
223    written
224}
225
226#[async_trait]
227impl ConsentService for FileConsentService {
228    async fn capture_consent(&self, subject: &str, purpose: &str) -> Result<(), AwpError> {
229        let key = (subject.to_string(), purpose.to_string());
230        self.records.insert(
231            key,
232            FileConsentRecord {
233                subject: subject.to_string(),
234                purpose: purpose.to_string(),
235                captured_at: Utc::now(),
236                revoked: false,
237                revoked_at: None,
238            },
239        );
240        self.flush().await
241    }
242
243    async fn check_consent(&self, subject: &str, purpose: &str) -> Result<bool, AwpError> {
244        let key = (subject.to_string(), purpose.to_string());
245        Ok(self.records.get(&key).is_some_and(|r| !r.revoked))
246    }
247
248    async fn revoke_consent(&self, subject: &str, purpose: &str) -> Result<(), AwpError> {
249        let key = (subject.to_string(), purpose.to_string());
250        if let Some(mut entry) = self.records.get_mut(&key) {
251            entry.revoked = true;
252            entry.revoked_at = Some(Utc::now());
253        }
254        self.flush().await
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    // --- InMemoryConsentService tests ---
263
264    #[tokio::test]
265    async fn test_capture_and_check() {
266        let svc = InMemoryConsentService::new();
267        svc.capture_consent("user1", "analytics").await.unwrap();
268        assert!(svc.check_consent("user1", "analytics").await.unwrap());
269    }
270
271    #[tokio::test]
272    async fn test_check_without_capture_returns_false() {
273        let svc = InMemoryConsentService::new();
274        assert!(!svc.check_consent("user1", "analytics").await.unwrap());
275    }
276
277    #[tokio::test]
278    async fn test_revoke_consent() {
279        let svc = InMemoryConsentService::new();
280        svc.capture_consent("user1", "analytics").await.unwrap();
281        assert!(svc.check_consent("user1", "analytics").await.unwrap());
282
283        svc.revoke_consent("user1", "analytics").await.unwrap();
284        assert!(!svc.check_consent("user1", "analytics").await.unwrap());
285    }
286
287    #[tokio::test]
288    async fn test_recapture_after_revoke() {
289        let svc = InMemoryConsentService::new();
290        svc.capture_consent("user1", "analytics").await.unwrap();
291        svc.revoke_consent("user1", "analytics").await.unwrap();
292        assert!(!svc.check_consent("user1", "analytics").await.unwrap());
293
294        svc.capture_consent("user1", "analytics").await.unwrap();
295        assert!(svc.check_consent("user1", "analytics").await.unwrap());
296    }
297
298    #[tokio::test]
299    async fn test_different_subjects_independent() {
300        let svc = InMemoryConsentService::new();
301        svc.capture_consent("user1", "analytics").await.unwrap();
302        assert!(!svc.check_consent("user2", "analytics").await.unwrap());
303    }
304
305    #[tokio::test]
306    async fn test_different_purposes_independent() {
307        let svc = InMemoryConsentService::new();
308        svc.capture_consent("user1", "analytics").await.unwrap();
309        assert!(!svc.check_consent("user1", "marketing").await.unwrap());
310    }
311
312    #[tokio::test]
313    async fn test_revoke_nonexistent_is_noop() {
314        let svc = InMemoryConsentService::new();
315        svc.revoke_consent("user1", "analytics").await.unwrap();
316        assert!(!svc.check_consent("user1", "analytics").await.unwrap());
317    }
318
319    // --- FileConsentService tests ---
320
321    #[tokio::test]
322    async fn test_file_capture_and_check() {
323        let dir = tempfile::tempdir().unwrap();
324        let path = dir.path().join("consent.json");
325        let svc = FileConsentService::new(&path).unwrap();
326
327        svc.capture_consent("user1", "analytics").await.unwrap();
328        assert!(svc.check_consent("user1", "analytics").await.unwrap());
329
330        // File should exist
331        assert!(path.exists());
332    }
333
334    #[tokio::test]
335    async fn test_file_persistence_across_instances() {
336        let dir = tempfile::tempdir().unwrap();
337        let path = dir.path().join("consent.json");
338
339        // First instance: capture consent
340        {
341            let svc = FileConsentService::new(&path).unwrap();
342            svc.capture_consent("user1", "analytics").await.unwrap();
343            svc.capture_consent("user2", "marketing").await.unwrap();
344        }
345
346        // Second instance: records should be loaded from file
347        {
348            let svc = FileConsentService::new(&path).unwrap();
349            assert!(svc.check_consent("user1", "analytics").await.unwrap());
350            assert!(svc.check_consent("user2", "marketing").await.unwrap());
351            assert!(!svc.check_consent("user3", "analytics").await.unwrap());
352        }
353    }
354
355    #[tokio::test]
356    async fn test_file_revoke_persists() {
357        let dir = tempfile::tempdir().unwrap();
358        let path = dir.path().join("consent.json");
359
360        {
361            let svc = FileConsentService::new(&path).unwrap();
362            svc.capture_consent("user1", "analytics").await.unwrap();
363            svc.revoke_consent("user1", "analytics").await.unwrap();
364        }
365
366        {
367            let svc = FileConsentService::new(&path).unwrap();
368            assert!(!svc.check_consent("user1", "analytics").await.unwrap());
369        }
370    }
371
372    #[tokio::test]
373    async fn test_file_recapture_after_revoke_persists() {
374        let dir = tempfile::tempdir().unwrap();
375        let path = dir.path().join("consent.json");
376
377        {
378            let svc = FileConsentService::new(&path).unwrap();
379            svc.capture_consent("user1", "analytics").await.unwrap();
380            svc.revoke_consent("user1", "analytics").await.unwrap();
381            svc.capture_consent("user1", "analytics").await.unwrap();
382        }
383
384        {
385            let svc = FileConsentService::new(&path).unwrap();
386            assert!(svc.check_consent("user1", "analytics").await.unwrap());
387        }
388    }
389
390    #[tokio::test]
391    async fn test_file_nonexistent_path_creates_on_write() {
392        let dir = tempfile::tempdir().unwrap();
393        let path = dir.path().join("subdir").join("consent.json");
394        assert!(!path.exists());
395
396        let svc = FileConsentService::new(&path).unwrap();
397        svc.capture_consent("user1", "analytics").await.unwrap();
398        assert!(path.exists());
399    }
400
401    /// Writes go through a temporary file that is renamed away (spec 3.5 §10 X3).
402    #[tokio::test]
403    async fn test_file_writes_leave_no_temporary_files() {
404        let dir = tempfile::tempdir().unwrap();
405        let path = dir.path().join("consent.json");
406        let svc = FileConsentService::new(&path).unwrap();
407        for i in 0..10 {
408            svc.capture_consent(&format!("user{i}"), "analytics").await.unwrap();
409        }
410        svc.revoke_consent("user3", "analytics").await.unwrap();
411        let names: Vec<String> = std::fs::read_dir(dir.path())
412            .unwrap()
413            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
414            .collect();
415        assert_eq!(names, vec!["consent.json"]);
416    }
417
418    /// Concurrent mutations all reach the file, and the last write holds every one of them.
419    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
420    async fn test_file_concurrent_captures_all_persist() {
421        let dir = tempfile::tempdir().unwrap();
422        let path = dir.path().join("consent.json");
423        let svc = std::sync::Arc::new(FileConsentService::new(&path).unwrap());
424        let tasks: Vec<_> = (0..64)
425            .map(|i| {
426                let svc = std::sync::Arc::clone(&svc);
427                tokio::spawn(
428                    async move { svc.capture_consent(&format!("user{i}"), "outreach").await },
429                )
430            })
431            .collect();
432        for task in tasks {
433            task.await.unwrap().unwrap();
434        }
435        let reloaded = FileConsentService::new(&path).unwrap();
436        for i in 0..64 {
437            assert!(
438                reloaded.check_consent(&format!("user{i}"), "outreach").await.unwrap(),
439                "user{i}"
440            );
441        }
442    }
443
444    /// A reader never sees a partially written file (spec 3.5 §10 X3).
445    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
446    async fn test_file_readers_never_see_a_partial_file() {
447        use std::sync::Arc;
448        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
449
450        let dir = tempfile::tempdir().unwrap();
451        let path = dir.path().join("consent.json");
452        let svc = FileConsentService::new(&path).unwrap();
453        svc.capture_consent("seed", "analytics").await.unwrap();
454
455        let done = Arc::new(AtomicBool::new(false));
456        let reads = Arc::new(AtomicUsize::new(0));
457        let reader = {
458            let (done, reads, path) = (Arc::clone(&done), Arc::clone(&reads), path.clone());
459            std::thread::spawn(move || {
460                while !done.load(Ordering::Relaxed) {
461                    let content = std::fs::read_to_string(&path).unwrap();
462                    serde_json::from_str::<FileConsentStore>(&content)
463                        .unwrap_or_else(|e| panic!("partial consent file ({e}): {content:?}"));
464                    reads.fetch_add(1, Ordering::Relaxed);
465                }
466            })
467        };
468        for i in 0..200 {
469            svc.capture_consent(&format!("visitor-{i:04}"), "persistent_profile").await.unwrap();
470        }
471        done.store(true, Ordering::Relaxed);
472        reader.join().expect("every read parsed");
473        assert!(reads.load(Ordering::Relaxed) > 0);
474    }
475
476    #[test]
477    fn test_file_invalid_json_returns_error() {
478        let dir = tempfile::tempdir().unwrap();
479        let path = dir.path().join("consent.json");
480        std::fs::write(&path, "not valid json").unwrap();
481
482        let result = FileConsentService::new(&path);
483        assert!(result.is_err());
484    }
485
486    #[tokio::test]
487    async fn test_file_check_without_capture_returns_false() {
488        let dir = tempfile::tempdir().unwrap();
489        let path = dir.path().join("consent.json");
490        let svc = FileConsentService::new(&path).unwrap();
491        assert!(!svc.check_consent("user1", "analytics").await.unwrap());
492    }
493
494    #[tokio::test]
495    async fn test_file_revoke_nonexistent_is_noop() {
496        let dir = tempfile::tempdir().unwrap();
497        let path = dir.path().join("consent.json");
498        let svc = FileConsentService::new(&path).unwrap();
499        svc.revoke_consent("user1", "analytics").await.unwrap();
500        assert!(!svc.check_consent("user1", "analytics").await.unwrap());
501    }
502
503    #[tokio::test]
504    async fn test_file_consent_json_structure() {
505        let dir = tempfile::tempdir().unwrap();
506        let path = dir.path().join("consent.json");
507        let svc = FileConsentService::new(&path).unwrap();
508        svc.capture_consent("user1", "analytics").await.unwrap();
509
510        let content = std::fs::read_to_string(&path).unwrap();
511        let json: serde_json::Value = serde_json::from_str(&content).unwrap();
512        assert!(json["records"].is_array());
513        let record = &json["records"][0];
514        assert_eq!(record["subject"], "user1");
515        assert_eq!(record["purpose"], "analytics");
516        assert_eq!(record["revoked"], false);
517    }
518}