use std::collections::BTreeMap;
use std::sync::Arc;
use super::VisitorId;
use super::consent::{ConsentPurpose, ConsentStore};
use super::registry::{SubjectRegistry, SubjectState, erasing_error};
use crate::principal::{SubjectKind, SubjectRef};
use crate::{AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock};
pub const CONSENT_REQUIRED_CODE: &str = "consent.required";
pub fn consent_required_error(purpose: &ConsentPurpose) -> AdkError {
AdkError::new(
ErrorComponent::Auth,
ErrorCategory::Forbidden,
CONSENT_REQUIRED_CODE,
format!(
"this needs the subject's consent for '{purpose}', which it has not given or has \
revoked; ask for consent before writing anything lasting for this purpose"
),
)
}
#[derive(Clone)]
pub struct ConsentGate {
consent: Arc<dyn ConsentStore>,
registry: Option<Arc<dyn SubjectRegistry>>,
every_subject: bool,
tools: BTreeMap<String, ConsentPurpose>,
clock: Arc<dyn Clock>,
}
impl std::fmt::Debug for ConsentGate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ConsentGate")
.field("every_subject", &self.every_subject)
.field("tools", &self.tools)
.finish_non_exhaustive()
}
}
impl ConsentGate {
pub fn new(consent: Arc<dyn ConsentStore>) -> Self {
Self {
consent,
registry: None,
every_subject: false,
tools: BTreeMap::new(),
clock: Arc::new(SystemClock),
}
}
#[must_use]
pub fn with_registry(mut self, registry: Arc<dyn SubjectRegistry>) -> Self {
self.registry = Some(registry);
self
}
#[must_use]
pub fn for_every_subject(mut self) -> Self {
self.every_subject = true;
self
}
#[must_use]
pub fn with_tool(mut self, tool_name: impl Into<String>, purpose: ConsentPurpose) -> Self {
self.tools.insert(tool_name.into(), purpose);
self
}
#[must_use]
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
pub fn tool_purpose(&self, tool_name: &str) -> Option<&ConsentPurpose> {
self.tools.get(tool_name)
}
pub fn subject_of(&self, user_id: &str) -> Option<SubjectRef> {
if user_id.parse::<VisitorId>().is_ok() {
Some(SubjectRef::visitor(user_id))
} else if self.every_subject {
Some(SubjectRef::human(user_id))
} else {
None
}
}
pub fn is_gated(&self, subject: &SubjectRef) -> bool {
match subject.kind {
SubjectKind::Visitor => true,
SubjectKind::Human | SubjectKind::Service => self.every_subject,
SubjectKind::Agent => false,
}
}
pub async fn ensure_writable(&self, subject: &SubjectRef) -> Result<()> {
let Some(registry) = &self.registry else { return Ok(()) };
match registry.get(subject).await? {
Some(record) if record.state == SubjectState::Erasing => Err(erasing_error(subject)),
Some(_) | None => Ok(()),
}
}
pub async fn permits(&self, subject: &SubjectRef, purpose: &ConsentPurpose) -> Result<bool> {
if !self.is_gated(subject) {
return Ok(true);
}
Ok(self.consent.live(subject, purpose, self.clock.now()).await?.is_some())
}
pub async fn require(&self, subject: &SubjectRef, purpose: &ConsentPurpose) -> Result<()> {
self.ensure_writable(subject).await?;
if self.permits(subject, purpose).await? {
Ok(())
} else {
Err(consent_required_error(purpose))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::subject::{
ConsentRecord, InMemoryConsentStore, InMemorySubjectRegistry, SUBJECT_ERASING_CODE,
};
#[tokio::test]
async fn gates_visitors_by_default_and_everyone_on_request() {
let consent = Arc::new(InMemoryConsentStore::new());
let registry = Arc::new(InMemorySubjectRegistry::new());
let gate = ConsentGate::new(consent.clone()).with_registry(registry.clone());
let visitor = VisitorId::generate();
let subject = gate.subject_of(visitor.as_str()).unwrap();
assert_eq!(subject, visitor.subject());
assert_eq!(gate.subject_of("alice"), None);
assert!(
gate.permits(&SubjectRef::human("alice"), &ConsentPurpose::Analytics).await.unwrap()
);
let purpose = ConsentPurpose::PersistentProfile;
assert_eq!(gate.require(&subject, &purpose).await.unwrap_err().code, CONSENT_REQUIRED_CODE);
consent.grant(ConsentRecord::new(subject.clone(), purpose.clone(), "v1")).await.unwrap();
gate.require(&subject, &purpose).await.unwrap();
registry.set_state(&subject, SubjectState::Erasing).await.unwrap();
assert_eq!(gate.require(&subject, &purpose).await.unwrap_err().code, SUBJECT_ERASING_CODE);
let everyone = ConsentGate::new(consent).for_every_subject();
assert_eq!(everyone.subject_of("alice"), Some(SubjectRef::human("alice")));
assert!(!everyone.permits(&SubjectRef::service("crm"), &purpose).await.unwrap());
assert!(!everyone.is_gated(&SubjectRef::new(SubjectKind::Agent, "urn:adk:agent:a")));
}
}