Skip to main content

adk_core/subject/
consent.rs

1//! Consent records and the store that keeps them.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::sync::Arc;
6
7use async_trait::async_trait;
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12use crate::principal::SubjectRef;
13use crate::{AdkError, ErrorCategory, ErrorComponent, Result};
14
15/// The error code of a grant whose id another consent record already has.
16pub const CONSENT_CONFLICT_CODE: &str = "consent.conflict";
17
18/// What a subject consents to: the purpose a lasting write serves.
19///
20/// The names match AWP's consent scopes one to one, so an AWP receipt records consent
21/// for the purpose of the same name. Any other name is [`Custom`](Self::Custom).
22///
23/// | Purpose | Lasting writes it allows |
24/// |---------|--------------------------|
25/// | [`SessionContinuity`](Self::SessionContinuity) | A conversation kept beyond the visit |
26/// | [`PersistentProfile`](Self::PersistentProfile) | The `user:` state tier and long-term memory |
27/// | [`Analytics`](Self::Analytics) | User attributes on telemetry; visit counting |
28/// | [`ProactiveOutreach`](Self::ProactiveOutreach) | Messages the site starts |
29/// | [`PaymentData`](Self::PaymentData) | Stored payment preferences |
30/// | [`Newsletter`](Self::Newsletter) | The site's newsletter |
31///
32/// # Example
33///
34/// ```rust
35/// use adk_core::subject::ConsentPurpose;
36///
37/// assert_eq!(ConsentPurpose::PersistentProfile.as_str(), "persistent_profile");
38/// assert_eq!(ConsentPurpose::from("analytics"), ConsentPurpose::Analytics);
39/// assert_eq!(ConsentPurpose::from("contact"), ConsentPurpose::Custom("contact".into()));
40/// assert_eq!(serde_json::to_value(ConsentPurpose::Newsletter).unwrap(), "newsletter");
41/// ```
42#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
43#[serde(from = "String", into = "String")]
44#[non_exhaustive]
45pub enum ConsentPurpose {
46    /// Keep a conversation beyond the visit and link it across channels.
47    SessionContinuity,
48    /// Keep data about the subject beyond the session: the `user:` tier and memory.
49    PersistentProfile,
50    /// Measure use: user attributes on telemetry and visit counts.
51    Analytics,
52    /// Send messages the subject did not ask for in the moment.
53    ProactiveOutreach,
54    /// Store payment preferences.
55    PaymentData,
56    /// Send the site's newsletter.
57    Newsletter,
58    /// A purpose the deployment defines.
59    Custom(String),
60}
61
62impl ConsentPurpose {
63    /// Returns the wire name.
64    pub fn as_str(&self) -> &str {
65        match self {
66            Self::SessionContinuity => "session_continuity",
67            Self::PersistentProfile => "persistent_profile",
68            Self::Analytics => "analytics",
69            Self::ProactiveOutreach => "proactive_outreach",
70            Self::PaymentData => "payment_data",
71            Self::Newsletter => "newsletter",
72            Self::Custom(name) => name,
73        }
74    }
75}
76
77impl fmt::Display for ConsentPurpose {
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        f.write_str(self.as_str())
80    }
81}
82
83impl From<&str> for ConsentPurpose {
84    fn from(value: &str) -> Self {
85        match value {
86            "session_continuity" => Self::SessionContinuity,
87            "persistent_profile" => Self::PersistentProfile,
88            "analytics" => Self::Analytics,
89            "proactive_outreach" => Self::ProactiveOutreach,
90            "payment_data" => Self::PaymentData,
91            "newsletter" => Self::Newsletter,
92            other => Self::Custom(other.to_owned()),
93        }
94    }
95}
96
97impl From<String> for ConsentPurpose {
98    fn from(value: String) -> Self {
99        match Self::from(value.as_str()) {
100            Self::Custom(_) => Self::Custom(value),
101            known => known,
102        }
103    }
104}
105
106impl From<ConsentPurpose> for String {
107    fn from(value: ConsentPurpose) -> Self {
108        match value {
109            ConsentPurpose::Custom(name) => name,
110            known => known.as_str().to_owned(),
111        }
112    }
113}
114
115/// What shows that consent was given, held in the system that issued it.
116///
117/// # Example
118///
119/// ```rust
120/// use adk_core::subject::ConsentEvidence;
121///
122/// let evidence = ConsentEvidence::new("awp.receipt", "0b6f…");
123/// assert!(evidence.document.is_none());
124/// ```
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126#[serde(rename_all = "camelCase")]
127pub struct ConsentEvidence {
128    /// What the evidence is, such as `awp.receipt` for a signed AWP consent receipt.
129    pub kind: String,
130    /// Its identifier where it is held, such as the receipt id.
131    pub reference: String,
132    /// A copy of the evidence, such as the signed receipt, when the record carries one.
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub document: Option<Value>,
135}
136
137impl ConsentEvidence {
138    /// Evidence of `kind` held under `reference`, with no copy.
139    pub fn new(kind: impl Into<String>, reference: impl Into<String>) -> Self {
140        Self { kind: kind.into(), reference: reference.into(), document: None }
141    }
142
143    /// Attaches a copy of the evidence.
144    #[must_use]
145    pub fn with_document(mut self, document: Value) -> Self {
146        self.document = Some(document);
147        self
148    }
149}
150
151/// One grant of consent by a subject for a purpose, under a policy version.
152///
153/// A record is live from `granted_at` until it expires or is revoked. Revocation is kept
154/// on the record, so the history of a subject's consent reads back until the subject is
155/// erased.
156///
157/// # Example
158///
159/// ```rust
160/// use adk_core::principal::SubjectRef;
161/// use adk_core::subject::{ConsentPurpose, ConsentRecord};
162/// use chrono::{Duration, Utc};
163///
164/// let now = Utc::now();
165/// let record = ConsentRecord::new(SubjectRef::visitor("v:1"), ConsentPurpose::Analytics, "2026-10")
166///     .granted_at(now)
167///     .with_expires_at(now + Duration::days(30));
168/// assert!(record.is_live(now));
169/// assert!(!record.is_live(now + Duration::days(31)));
170/// ```
171#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
172#[serde(rename_all = "camelCase")]
173pub struct ConsentRecord {
174    /// The record's id.
175    pub id: String,
176    /// Who consented.
177    pub subject: SubjectRef,
178    /// What for.
179    pub purpose: ConsentPurpose,
180    /// The version of the policy the subject agreed to.
181    pub policy_version: String,
182    /// When consent was given.
183    pub granted_at: DateTime<Utc>,
184    /// When consent lapses; `None` until revoked.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub expires_at: Option<DateTime<Utc>>,
187    /// When the subject revoked it.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub revoked_at: Option<DateTime<Utc>>,
190    /// What shows the grant, such as a signed receipt.
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub evidence: Option<ConsentEvidence>,
193}
194
195impl ConsentRecord {
196    /// A grant by `subject` for `purpose` under `policy_version`, made now, with a random id.
197    pub fn new(
198        subject: SubjectRef,
199        purpose: ConsentPurpose,
200        policy_version: impl Into<String>,
201    ) -> Self {
202        Self {
203            id: uuid::Uuid::new_v4().to_string(),
204            subject,
205            purpose,
206            policy_version: policy_version.into(),
207            granted_at: Utc::now(),
208            expires_at: None,
209            revoked_at: None,
210            evidence: None,
211        }
212    }
213
214    /// Sets the id, such as the id of the receipt that is the grant's evidence.
215    #[must_use]
216    pub fn with_id(mut self, id: impl Into<String>) -> Self {
217        self.id = id.into();
218        self
219    }
220
221    /// Sets when consent was given.
222    #[must_use]
223    pub fn granted_at(mut self, at: DateTime<Utc>) -> Self {
224        self.granted_at = at;
225        self
226    }
227
228    /// Sets when consent lapses.
229    #[must_use]
230    pub fn with_expires_at(mut self, at: DateTime<Utc>) -> Self {
231        self.expires_at = Some(at);
232        self
233    }
234
235    /// Sets the evidence.
236    #[must_use]
237    pub fn with_evidence(mut self, evidence: ConsentEvidence) -> Self {
238        self.evidence = Some(evidence);
239        self
240    }
241
242    /// Whether the record is granted, unexpired, and unrevoked at `at`.
243    pub fn is_live(&self, at: DateTime<Utc>) -> bool {
244        self.granted_at <= at
245            && self.expires_at.is_none_or(|expires| at < expires)
246            && self.revoked_at.is_none_or(|revoked| at < revoked)
247    }
248}
249
250/// The error a [`ConsentStore`] returns when a grant's id is taken.
251pub fn consent_conflict_error(id: &str) -> AdkError {
252    AdkError::new(
253        ErrorComponent::Auth,
254        ErrorCategory::Conflict,
255        CONSENT_CONFLICT_CODE,
256        format!("a consent record with id '{id}' already exists; give each grant its own id"),
257    )
258}
259
260/// Consent records, by subject and purpose.
261///
262/// Consent gates read [`live`](Self::live) before a lasting write; revocation stops later
263/// writes and erases nothing. Records are deployment-wide: one subject's consent covers
264/// every application of the deployment.
265///
266/// [`InMemoryConsentStore`] is the reference implementation; `adk-session` ships the
267/// durable ones. Every backend passes `adk_core::consent_store_conformance_tests!`
268/// (feature `conformance`).
269///
270/// # Example
271///
272/// ```rust
273/// use adk_core::principal::SubjectRef;
274/// use adk_core::subject::{ConsentPurpose, ConsentRecord, ConsentStore, InMemoryConsentStore};
275/// use chrono::Utc;
276///
277/// # async fn demo() -> adk_core::Result<()> {
278/// let store = InMemoryConsentStore::new();
279/// let visitor = SubjectRef::visitor("v:1");
280/// store.grant(ConsentRecord::new(visitor.clone(), ConsentPurpose::Analytics, "2026-10")).await?;
281///
282/// let revoked = store.revoke_purpose(&visitor, Some(&ConsentPurpose::Analytics), Utc::now()).await?;
283/// assert_eq!(revoked.len(), 1);
284/// assert!(store.live(&visitor, &ConsentPurpose::Analytics, Utc::now()).await?.is_none());
285/// # Ok(())
286/// # }
287/// ```
288#[async_trait]
289pub trait ConsentStore: Send + Sync {
290    /// Stores a grant.
291    ///
292    /// # Errors
293    ///
294    /// [`CONSENT_CONFLICT_CODE`] when a record with the same id exists.
295    async fn grant(&self, record: ConsentRecord) -> Result<()>;
296
297    /// Returns record `id`.
298    async fn get(&self, id: &str) -> Result<Option<ConsentRecord>>;
299
300    /// Returns every record of `subject`, oldest grant first.
301    async fn for_subject(&self, subject: &SubjectRef) -> Result<Vec<ConsentRecord>>;
302
303    /// Revokes record `id` at `at` and returns it; a revoked record keeps its first
304    /// revocation time. `None` when no record has that id.
305    async fn revoke(&self, id: &str, at: DateTime<Utc>) -> Result<Option<ConsentRecord>>;
306
307    /// Erases every record of `subject` and returns how many.
308    async fn erase(&self, subject: &SubjectRef) -> Result<u64>;
309
310    /// Revokes every record of `subject` that is live at `at` for `purpose`, or for every
311    /// purpose when `purpose` is `None`, and returns them as revoked.
312    async fn revoke_purpose(
313        &self,
314        subject: &SubjectRef,
315        purpose: Option<&ConsentPurpose>,
316        at: DateTime<Utc>,
317    ) -> Result<Vec<ConsentRecord>> {
318        let mut revoked = Vec::new();
319        for record in self.for_subject(subject).await? {
320            if record.is_live(at) && purpose.is_none_or(|purpose| *purpose == record.purpose) {
321                revoked.extend(self.revoke(&record.id, at).await?);
322            }
323        }
324        Ok(revoked)
325    }
326
327    /// Returns the most recent record of `subject` live at `at` for `purpose`.
328    async fn live(
329        &self,
330        subject: &SubjectRef,
331        purpose: &ConsentPurpose,
332        at: DateTime<Utc>,
333    ) -> Result<Option<ConsentRecord>> {
334        Ok(self
335            .for_subject(subject)
336            .await?
337            .into_iter()
338            .rev()
339            .find(|record| record.purpose == *purpose && record.is_live(at)))
340    }
341}
342
343/// In-memory [`ConsentStore`] for tests and single-process development.
344///
345/// Clones share the same records.
346#[derive(Debug, Clone, Default)]
347pub struct InMemoryConsentStore {
348    records: Arc<tokio::sync::RwLock<HashMap<String, ConsentRecord>>>,
349}
350
351impl InMemoryConsentStore {
352    /// Creates an empty store.
353    pub fn new() -> Self {
354        Self::default()
355    }
356}
357
358#[async_trait]
359impl ConsentStore for InMemoryConsentStore {
360    async fn grant(&self, record: ConsentRecord) -> Result<()> {
361        let mut records = self.records.write().await;
362        if records.contains_key(&record.id) {
363            return Err(consent_conflict_error(&record.id));
364        }
365        records.insert(record.id.clone(), record);
366        Ok(())
367    }
368
369    async fn get(&self, id: &str) -> Result<Option<ConsentRecord>> {
370        Ok(self.records.read().await.get(id).cloned())
371    }
372
373    async fn for_subject(&self, subject: &SubjectRef) -> Result<Vec<ConsentRecord>> {
374        let mut found: Vec<ConsentRecord> = self
375            .records
376            .read()
377            .await
378            .values()
379            .filter(|record| record.subject == *subject)
380            .cloned()
381            .collect();
382        found.sort_by(|a, b| a.granted_at.cmp(&b.granted_at).then_with(|| a.id.cmp(&b.id)));
383        Ok(found)
384    }
385
386    async fn revoke(&self, id: &str, at: DateTime<Utc>) -> Result<Option<ConsentRecord>> {
387        let mut records = self.records.write().await;
388        Ok(records.get_mut(id).map(|record| {
389            record.revoked_at.get_or_insert(at);
390            record.clone()
391        }))
392    }
393
394    async fn erase(&self, subject: &SubjectRef) -> Result<u64> {
395        let mut records = self.records.write().await;
396        let before = records.len();
397        records.retain(|_, record| record.subject != *subject);
398        Ok((before - records.len()) as u64)
399    }
400}