mod audit;
mod consent;
mod gate;
mod registry;
mod rights;
use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::principal::SubjectRef;
pub use audit::{AuditLogSubjectData, PseudonymousRecorder};
pub use consent::{
CONSENT_CONFLICT_CODE, ConsentEvidence, ConsentPurpose, ConsentRecord, ConsentStore,
InMemoryConsentStore, consent_conflict_error,
};
pub use gate::{CONSENT_REQUIRED_CODE, ConsentGate, consent_required_error};
pub use registry::{
InMemorySubjectRegistry, PSEUDONYM_PREFIX, SUBJECT_ERASING_CODE, SUBJECT_LINK_CONSUMED_CODE,
SUBJECT_LINK_INVALID_CODE, SubjectRecord, SubjectRegistry, SubjectState, erasing_error,
link_consumed_error, link_invalid_error, new_pseudonym, validate_link,
};
pub use rights::{
ErasureReport, ErasureStatus, ExportOutcome, Revocation, SUBJECT_UNSUPPORTED_CODE,
StoreErasure, StoreExport, StoreOutcome, StoreReport, StoreSupport, SubjectDataStore,
SubjectExport, SubjectRights, unsupported_error,
};
pub const VISITOR_ID_PREFIX: &str = "v:";
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[error(
"'{0}' is not a visitor id; visitor ids are `v:` followed by 64 lowercase hex characters \
and come from VisitorId::generate"
)]
pub struct InvalidVisitorId(pub String);
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct VisitorId(String);
impl VisitorId {
pub fn generate() -> Self {
Self(format!(
"{VISITOR_ID_PREFIX}{}{}",
uuid::Uuid::new_v4().simple(),
uuid::Uuid::new_v4().simple()
))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn subject(&self) -> SubjectRef {
SubjectRef::visitor(self.0.clone())
}
}
impl fmt::Display for VisitorId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl FromStr for VisitorId {
type Err = InvalidVisitorId;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let valid = s.strip_prefix(VISITOR_ID_PREFIX).is_some_and(|hex| {
hex.len() == 64 && hex.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
});
if valid { Ok(Self(s.to_owned())) } else { Err(InvalidVisitorId(s.to_owned())) }
}
}
impl TryFrom<String> for VisitorId {
type Error = InvalidVisitorId;
fn try_from(value: String) -> Result<Self, Self::Error> {
value.parse()
}
}
impl From<VisitorId> for String {
fn from(id: VisitorId) -> Self {
id.0
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubjectScope {
pub app_names: Vec<String>,
pub subject: SubjectRef,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub linked: Vec<SubjectRef>,
}
impl SubjectScope {
pub fn new<I, S>(app_names: I, subject: SubjectRef) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self {
app_names: app_names.into_iter().map(Into::into).collect(),
subject,
linked: Vec::new(),
}
}
#[must_use]
pub fn with_linked(mut self, linked: Vec<SubjectRef>) -> Self {
self.linked = linked;
self
}
pub fn subjects(&self) -> impl Iterator<Item = &SubjectRef> {
std::iter::once(&self.subject).chain(self.linked.iter())
}
pub fn user_ids(&self) -> Vec<&str> {
let mut ids: Vec<&str> = Vec::with_capacity(1 + self.linked.len());
for subject in self.subjects() {
if !ids.contains(&subject.id.as_str()) {
ids.push(&subject.id);
}
}
ids
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn visitor_ids_are_random_and_parse_only_their_own_form() {
let id = VisitorId::generate();
assert_eq!(id.as_str().len(), 66);
assert!(id.as_str().starts_with("v:"));
assert_eq!(VisitorId::from_str(id.as_str()), Ok(id.clone()));
assert_ne!(VisitorId::generate(), id);
for bad in
["", "v:", "v:abc", &format!("x:{}", &id.as_str()[2..]), &id.as_str().to_uppercase()]
{
assert!(VisitorId::from_str(bad).is_err(), "{bad} is not a visitor id");
}
let json = serde_json::to_value(&id).unwrap();
assert_eq!(serde_json::from_value::<VisitorId>(json).unwrap(), id);
assert!(serde_json::from_value::<VisitorId>(serde_json::json!("v:1")).is_err());
}
#[test]
fn scope_lists_each_user_id_once() {
let scope = SubjectScope::new(["a", "b"], SubjectRef::human("alice")).with_linked(vec![
SubjectRef::visitor("v:1"),
SubjectRef::visitor("v:2"),
SubjectRef::visitor("v:1"),
]);
assert_eq!(scope.user_ids(), ["alice", "v:1", "v:2"]);
assert_eq!(scope.subjects().count(), 4);
}
}