use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::principal::SubjectRef;
use crate::{AdkError, ErrorCategory, ErrorComponent, Result};
pub const CONSENT_CONFLICT_CODE: &str = "consent.conflict";
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
#[non_exhaustive]
pub enum ConsentPurpose {
SessionContinuity,
PersistentProfile,
Analytics,
ProactiveOutreach,
PaymentData,
Newsletter,
Custom(String),
}
impl ConsentPurpose {
pub fn as_str(&self) -> &str {
match self {
Self::SessionContinuity => "session_continuity",
Self::PersistentProfile => "persistent_profile",
Self::Analytics => "analytics",
Self::ProactiveOutreach => "proactive_outreach",
Self::PaymentData => "payment_data",
Self::Newsletter => "newsletter",
Self::Custom(name) => name,
}
}
}
impl fmt::Display for ConsentPurpose {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl From<&str> for ConsentPurpose {
fn from(value: &str) -> Self {
match value {
"session_continuity" => Self::SessionContinuity,
"persistent_profile" => Self::PersistentProfile,
"analytics" => Self::Analytics,
"proactive_outreach" => Self::ProactiveOutreach,
"payment_data" => Self::PaymentData,
"newsletter" => Self::Newsletter,
other => Self::Custom(other.to_owned()),
}
}
}
impl From<String> for ConsentPurpose {
fn from(value: String) -> Self {
match Self::from(value.as_str()) {
Self::Custom(_) => Self::Custom(value),
known => known,
}
}
}
impl From<ConsentPurpose> for String {
fn from(value: ConsentPurpose) -> Self {
match value {
ConsentPurpose::Custom(name) => name,
known => known.as_str().to_owned(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConsentEvidence {
pub kind: String,
pub reference: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub document: Option<Value>,
}
impl ConsentEvidence {
pub fn new(kind: impl Into<String>, reference: impl Into<String>) -> Self {
Self { kind: kind.into(), reference: reference.into(), document: None }
}
#[must_use]
pub fn with_document(mut self, document: Value) -> Self {
self.document = Some(document);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConsentRecord {
pub id: String,
pub subject: SubjectRef,
pub purpose: ConsentPurpose,
pub policy_version: String,
pub granted_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revoked_at: Option<DateTime<Utc>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub evidence: Option<ConsentEvidence>,
}
impl ConsentRecord {
pub fn new(
subject: SubjectRef,
purpose: ConsentPurpose,
policy_version: impl Into<String>,
) -> Self {
Self {
id: uuid::Uuid::new_v4().to_string(),
subject,
purpose,
policy_version: policy_version.into(),
granted_at: Utc::now(),
expires_at: None,
revoked_at: None,
evidence: None,
}
}
#[must_use]
pub fn with_id(mut self, id: impl Into<String>) -> Self {
self.id = id.into();
self
}
#[must_use]
pub fn granted_at(mut self, at: DateTime<Utc>) -> Self {
self.granted_at = at;
self
}
#[must_use]
pub fn with_expires_at(mut self, at: DateTime<Utc>) -> Self {
self.expires_at = Some(at);
self
}
#[must_use]
pub fn with_evidence(mut self, evidence: ConsentEvidence) -> Self {
self.evidence = Some(evidence);
self
}
pub fn is_live(&self, at: DateTime<Utc>) -> bool {
self.granted_at <= at
&& self.expires_at.is_none_or(|expires| at < expires)
&& self.revoked_at.is_none_or(|revoked| at < revoked)
}
}
pub fn consent_conflict_error(id: &str) -> AdkError {
AdkError::new(
ErrorComponent::Auth,
ErrorCategory::Conflict,
CONSENT_CONFLICT_CODE,
format!("a consent record with id '{id}' already exists; give each grant its own id"),
)
}
#[async_trait]
pub trait ConsentStore: Send + Sync {
async fn grant(&self, record: ConsentRecord) -> Result<()>;
async fn get(&self, id: &str) -> Result<Option<ConsentRecord>>;
async fn for_subject(&self, subject: &SubjectRef) -> Result<Vec<ConsentRecord>>;
async fn revoke(&self, id: &str, at: DateTime<Utc>) -> Result<Option<ConsentRecord>>;
async fn erase(&self, subject: &SubjectRef) -> Result<u64>;
async fn revoke_purpose(
&self,
subject: &SubjectRef,
purpose: Option<&ConsentPurpose>,
at: DateTime<Utc>,
) -> Result<Vec<ConsentRecord>> {
let mut revoked = Vec::new();
for record in self.for_subject(subject).await? {
if record.is_live(at) && purpose.is_none_or(|purpose| *purpose == record.purpose) {
revoked.extend(self.revoke(&record.id, at).await?);
}
}
Ok(revoked)
}
async fn live(
&self,
subject: &SubjectRef,
purpose: &ConsentPurpose,
at: DateTime<Utc>,
) -> Result<Option<ConsentRecord>> {
Ok(self
.for_subject(subject)
.await?
.into_iter()
.rev()
.find(|record| record.purpose == *purpose && record.is_live(at)))
}
}
#[derive(Debug, Clone, Default)]
pub struct InMemoryConsentStore {
records: Arc<tokio::sync::RwLock<HashMap<String, ConsentRecord>>>,
}
impl InMemoryConsentStore {
pub fn new() -> Self {
Self::default()
}
}
#[async_trait]
impl ConsentStore for InMemoryConsentStore {
async fn grant(&self, record: ConsentRecord) -> Result<()> {
let mut records = self.records.write().await;
if records.contains_key(&record.id) {
return Err(consent_conflict_error(&record.id));
}
records.insert(record.id.clone(), record);
Ok(())
}
async fn get(&self, id: &str) -> Result<Option<ConsentRecord>> {
Ok(self.records.read().await.get(id).cloned())
}
async fn for_subject(&self, subject: &SubjectRef) -> Result<Vec<ConsentRecord>> {
let mut found: Vec<ConsentRecord> = self
.records
.read()
.await
.values()
.filter(|record| record.subject == *subject)
.cloned()
.collect();
found.sort_by(|a, b| a.granted_at.cmp(&b.granted_at).then_with(|| a.id.cmp(&b.id)));
Ok(found)
}
async fn revoke(&self, id: &str, at: DateTime<Utc>) -> Result<Option<ConsentRecord>> {
let mut records = self.records.write().await;
Ok(records.get_mut(id).map(|record| {
record.revoked_at.get_or_insert(at);
record.clone()
}))
}
async fn erase(&self, subject: &SubjectRef) -> Result<u64> {
let mut records = self.records.write().await;
let before = records.len();
records.retain(|_, record| record.subject != *subject);
Ok((before - records.len()) as u64)
}
}