adk_core/subject/mod.rs
1//! Data subjects: visitor ids, consent, and the operations that export, erase, and link
2//! one person's data across every store an agent writes.
3//!
4//! | Type | Role |
5//! |------|------|
6//! | [`VisitorId`] | A random id a deployment issues to a person it cannot otherwise identify |
7//! | [`ConsentStore`] | Consent records per subject and purpose, read before a lasting write |
8//! | [`SubjectRegistry`] | Each subject's pseudonym, links, and erasure state — never its data |
9//! | [`SubjectDataStore`] | One store family's adapter: export and erase a subject's data |
10//! | [`SubjectRights`] | Fans `export`, `erase`, and `link` out over the registry, the consent store, and every adapter |
11//! | [`ConsentGate`] | Whether a subject may have something lasting written for a purpose; read by the session and memory wrappers, the tool path, and the runner |
12//! | [`PseudonymousRecorder`] | Names subjects in audit records by registry pseudonym |
13//! | [`AuditLogSubjectData`] | The audit log as an adapter: redacts the bodies of records that name a subject by id |
14//!
15//! Stores keyed by `(app, user)` — sessions, memory, artifacts — find a subject by its
16//! id. The registry holds no index of records, so no second copy of a person's data can
17//! drift from the stores that hold it.
18//!
19//! # Erasure
20//!
21//! [`SubjectRights::erase`] works in this order, and can be repeated until it completes:
22//!
23//! 1. The subject and every visitor id linked to it move to [`SubjectState::Erasing`];
24//! consent gates refuse writes for a subject in that state.
25//! 2. Every live consent record is revoked.
26//! 3. Each [`SubjectDataStore`] erases the subject's data, by its
27//! [`StoreSupport`]: a store that cannot erase is reported, never skipped.
28//! 4. The consent records are erased.
29//! 5. An [`AuditRecordKind::Erasure`](crate::audit_log::AuditRecordKind::Erasure) record
30//! names the subject's pseudonym, never its id.
31//! 6. When no store failed, the registry forgets the subject, its pseudonym, and its
32//! links. A store that failed leaves the subject `Erasing`, so a repeat finishes the job.
33//!
34//! The module provides mechanisms. Whether a deployment's use of them meets an obligation
35//! it has is for the deployment to assess.
36//!
37//! # Example
38//!
39//! ```rust
40//! use std::sync::Arc;
41//! use adk_core::subject::{
42//! ConsentPurpose, ConsentRecord, ConsentStore, ErasureStatus, InMemoryConsentStore,
43//! InMemorySubjectRegistry, SubjectRights, VisitorId,
44//! };
45//!
46//! # async fn demo() -> adk_core::Result<()> {
47//! let rights = SubjectRights::new(
48//! Arc::new(InMemorySubjectRegistry::new()),
49//! Arc::new(InMemoryConsentStore::new()),
50//! )
51//! .with_app("shop");
52//!
53//! let visitor = VisitorId::generate().subject();
54//! rights
55//! .grant(ConsentRecord::new(visitor.clone(), ConsentPurpose::PersistentProfile, "2026-10"))
56//! .await?;
57//! assert!(rights.consent().live(&visitor, &ConsentPurpose::PersistentProfile, chrono::Utc::now()).await?.is_some());
58//!
59//! let report = rights.erase(&visitor).await?;
60//! assert_eq!(report.status, ErasureStatus::Completed);
61//! assert!(rights.consent().for_subject(&visitor).await?.is_empty());
62//! # Ok(())
63//! # }
64//! ```
65
66mod audit;
67mod consent;
68mod gate;
69mod registry;
70mod rights;
71
72use std::fmt;
73use std::str::FromStr;
74
75use serde::{Deserialize, Serialize};
76use thiserror::Error;
77
78use crate::principal::SubjectRef;
79
80pub use audit::{AuditLogSubjectData, PseudonymousRecorder};
81pub use consent::{
82 CONSENT_CONFLICT_CODE, ConsentEvidence, ConsentPurpose, ConsentRecord, ConsentStore,
83 InMemoryConsentStore, consent_conflict_error,
84};
85pub use gate::{CONSENT_REQUIRED_CODE, ConsentGate, consent_required_error};
86pub use registry::{
87 InMemorySubjectRegistry, PSEUDONYM_PREFIX, SUBJECT_ERASING_CODE, SUBJECT_LINK_CONSUMED_CODE,
88 SUBJECT_LINK_INVALID_CODE, SubjectRecord, SubjectRegistry, SubjectState, erasing_error,
89 link_consumed_error, link_invalid_error, new_pseudonym, validate_link,
90};
91pub use rights::{
92 ErasureReport, ErasureStatus, ExportOutcome, Revocation, SUBJECT_UNSUPPORTED_CODE,
93 StoreErasure, StoreExport, StoreOutcome, StoreReport, StoreSupport, SubjectDataStore,
94 SubjectExport, SubjectRights, unsupported_error,
95};
96
97/// The prefix of every [`VisitorId`].
98pub const VISITOR_ID_PREFIX: &str = "v:";
99
100/// Error returned when a string is not a [`VisitorId`].
101///
102/// # Example
103///
104/// ```rust
105/// use adk_core::subject::VisitorId;
106///
107/// assert!("v:not-random".parse::<VisitorId>().is_err());
108/// ```
109#[derive(Debug, Error, Clone, PartialEq, Eq)]
110#[error(
111 "'{0}' is not a visitor id; visitor ids are `v:` followed by 64 lowercase hex characters \
112 and come from VisitorId::generate"
113)]
114pub struct InvalidVisitorId(pub String);
115
116/// A random identifier a deployment issues to a person it knows nothing else about, such
117/// as a website visitor who has not signed in.
118///
119/// `v:` followed by 64 lowercase hex characters drawn from two random UUIDs (244 random
120/// bits). An id is never derived from an address, a user agent, or a device fingerprint:
121/// [`VisitorId::generate`] is the only way to make one, and parsing accepts only that form.
122///
123/// # Example
124///
125/// ```rust
126/// use adk_core::principal::SubjectKind;
127/// use adk_core::subject::VisitorId;
128///
129/// let id = VisitorId::generate();
130/// assert_eq!(id.as_str().parse::<VisitorId>(), Ok(id.clone()));
131/// assert_eq!(id.subject().kind, SubjectKind::Visitor);
132/// assert_ne!(VisitorId::generate(), id);
133/// ```
134#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
135#[serde(try_from = "String", into = "String")]
136pub struct VisitorId(String);
137
138impl VisitorId {
139 /// Generates a new random visitor id.
140 pub fn generate() -> Self {
141 Self(format!(
142 "{VISITOR_ID_PREFIX}{}{}",
143 uuid::Uuid::new_v4().simple(),
144 uuid::Uuid::new_v4().simple()
145 ))
146 }
147
148 /// Returns the id as a string slice.
149 pub fn as_str(&self) -> &str {
150 &self.0
151 }
152
153 /// The subject this id names, of kind [`SubjectKind::Visitor`](crate::principal::SubjectKind::Visitor).
154 pub fn subject(&self) -> SubjectRef {
155 SubjectRef::visitor(self.0.clone())
156 }
157}
158
159impl fmt::Display for VisitorId {
160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161 f.write_str(&self.0)
162 }
163}
164
165impl FromStr for VisitorId {
166 type Err = InvalidVisitorId;
167
168 fn from_str(s: &str) -> Result<Self, Self::Err> {
169 let valid = s.strip_prefix(VISITOR_ID_PREFIX).is_some_and(|hex| {
170 hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
171 });
172 if valid { Ok(Self(s.to_owned())) } else { Err(InvalidVisitorId(s.to_owned())) }
173 }
174}
175
176impl TryFrom<String> for VisitorId {
177 type Error = InvalidVisitorId;
178
179 fn try_from(value: String) -> Result<Self, Self::Error> {
180 value.parse()
181 }
182}
183
184impl From<VisitorId> for String {
185 fn from(id: VisitorId) -> Self {
186 id.0
187 }
188}
189
190/// Whose data an export or an erasure covers: a subject, the visitor ids linked to it,
191/// and the applications whose `(app, user)`-keyed stores hold it.
192///
193/// # Example
194///
195/// ```rust
196/// use adk_core::principal::SubjectRef;
197/// use adk_core::subject::SubjectScope;
198///
199/// let scope = SubjectScope::new(["shop"], SubjectRef::human("alice"))
200/// .with_linked(vec![SubjectRef::visitor("v:1"), SubjectRef::human("alice")]);
201/// assert_eq!(scope.user_ids(), ["alice", "v:1"]);
202/// ```
203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
204#[serde(rename_all = "camelCase")]
205pub struct SubjectScope {
206 /// The applications whose stores are searched.
207 pub app_names: Vec<String>,
208 /// The subject.
209 pub subject: SubjectRef,
210 /// The visitor ids linked to the subject; data held under them is the subject's.
211 #[serde(default, skip_serializing_if = "Vec::is_empty")]
212 pub linked: Vec<SubjectRef>,
213}
214
215impl SubjectScope {
216 /// The scope of `subject` alone in `app_names`.
217 pub fn new<I, S>(app_names: I, subject: SubjectRef) -> Self
218 where
219 I: IntoIterator<Item = S>,
220 S: Into<String>,
221 {
222 Self {
223 app_names: app_names.into_iter().map(Into::into).collect(),
224 subject,
225 linked: Vec::new(),
226 }
227 }
228
229 /// Sets the linked visitor ids.
230 #[must_use]
231 pub fn with_linked(mut self, linked: Vec<SubjectRef>) -> Self {
232 self.linked = linked;
233 self
234 }
235
236 /// The subject followed by its linked ids.
237 pub fn subjects(&self) -> impl Iterator<Item = &SubjectRef> {
238 std::iter::once(&self.subject).chain(self.linked.iter())
239 }
240
241 /// The user ids that `(app, user)`-keyed stores hold the subject's data under: the
242 /// subject's id, then each linked id, without repeats.
243 pub fn user_ids(&self) -> Vec<&str> {
244 let mut ids: Vec<&str> = Vec::with_capacity(1 + self.linked.len());
245 for subject in self.subjects() {
246 if !ids.contains(&subject.id.as_str()) {
247 ids.push(&subject.id);
248 }
249 }
250 ids
251 }
252}
253
254#[cfg(test)]
255mod tests {
256 use super::*;
257
258 #[test]
259 fn visitor_ids_are_random_and_parse_only_their_own_form() {
260 let id = VisitorId::generate();
261 assert_eq!(id.as_str().len(), 66);
262 assert!(id.as_str().starts_with("v:"));
263 assert_eq!(VisitorId::from_str(id.as_str()), Ok(id.clone()));
264 assert_ne!(VisitorId::generate(), id);
265 for bad in
266 ["", "v:", "v:abc", &format!("x:{}", &id.as_str()[2..]), &id.as_str().to_uppercase()]
267 {
268 assert!(VisitorId::from_str(bad).is_err(), "{bad} is not a visitor id");
269 }
270 let json = serde_json::to_value(&id).unwrap();
271 assert_eq!(serde_json::from_value::<VisitorId>(json).unwrap(), id);
272 assert!(serde_json::from_value::<VisitorId>(serde_json::json!("v:1")).is_err());
273 }
274
275 #[test]
276 fn scope_lists_each_user_id_once() {
277 let scope = SubjectScope::new(["a", "b"], SubjectRef::human("alice")).with_linked(vec![
278 SubjectRef::visitor("v:1"),
279 SubjectRef::visitor("v:2"),
280 SubjectRef::visitor("v:1"),
281 ]);
282 assert_eq!(scope.user_ids(), ["alice", "v:1", "v:2"]);
283 assert_eq!(scope.subjects().count(), 4);
284 }
285}