use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::Arc;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::audit::RoleName;
use crate::auth::AuthContext;
use crate::identity::Principal;
pub const ADMIN: &str = "admin";
pub const CEILING_KEY: &str = "ceiling";
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Grant(String);
impl Grant {
pub fn new(path: impl Into<String>) -> Self {
Self(path.into())
}
pub fn of(activation: &str, method: &str) -> Self {
Self(format!("{activation}.{method}"))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for Grant {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum ScopeRef {
Everywhere,
Named(String),
}
impl ScopeRef {
pub fn parse(text: &str) -> Self {
match text.trim() {
"*" => Self::Everywhere,
other => Self::Named(other.to_string()),
}
}
pub fn named(name: impl Into<String>) -> Self {
Self::Named(name.into())
}
pub fn as_str(&self) -> &str {
match self {
Self::Everywhere => "*",
Self::Named(n) => n,
}
}
pub fn is_everywhere(&self) -> bool {
matches!(self, Self::Everywhere)
}
pub fn parse_checked(text: &str) -> Result<Self, AddressError> {
match text {
"*" | "self" => Ok(Self::Everywhere),
t if t.starts_with('/') => match address_form(t) {
Some(_) => Ok(Self::Named(t.to_string())),
None => Err(AddressError(format!(
"`{t}` is not an address scope: `/` then dotted segments of A-Z a-z 0-9 _ -, \
optionally ending `.*`"
))),
},
t if t.is_empty() || t.trim() != t => Err(AddressError(format!("`{t}` is not a scope"))),
t => Ok(Self::Named(t.to_string())),
}
}
pub fn is_address(&self) -> bool {
matches!(self, Self::Named(n) if n.starts_with('/'))
}
fn is_data(&self) -> bool {
matches!(self, Self::Named(n) if !n.starts_with('/') && n != "self")
}
pub fn covers_address(&self, at: &CallAddress) -> bool {
match self {
Self::Everywhere => true,
Self::Named(n) => match address_form(n) {
Some((p, true)) => at.path() == p || at.path().strip_prefix(p).is_some_and(|rest| rest.starts_with('.')),
Some((p, false)) => p == at.activation() || p == at.path(),
None => false,
},
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddressError(pub String);
impl fmt::Display for AddressError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for AddressError {}
fn segment_ok(segment: &str) -> bool {
!segment.is_empty() && segment.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
fn path_ok(path: &str) -> bool {
path.split('.').all(segment_ok)
}
fn address_form(scope: &str) -> Option<(&str, bool)> {
let body = scope.strip_prefix('/')?;
let (path, subtree) = match body.strip_suffix(".*") {
Some(p) => (p, true),
None => (body, false),
};
path_ok(path).then_some((path, subtree))
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CallAddress {
path: String,
dot: usize,
}
impl CallAddress {
pub fn new(activation: &str, method: &str) -> Result<Self, AddressError> {
if !path_ok(activation) {
return Err(AddressError(format!("`{activation}` is not an activation's address")));
}
if !segment_ok(method) {
return Err(AddressError(format!("`{method}` is not a method's name (one segment, no dot)")));
}
Ok(Self { path: format!("{activation}.{method}"), dot: activation.len() })
}
pub fn of_segments(activation: &[&str], method: &str) -> Result<Self, AddressError> {
match activation.iter().find(|s| !segment_ok(s)) {
Some(bad) => Err(AddressError(format!("`{bad}` is not one segment of an address"))),
None if activation.is_empty() => Err(AddressError("an activation's address has a segment".into())),
None => Self::new(&activation.join("."), method),
}
}
pub fn activation(&self) -> &str {
&self.path[..self.dot]
}
pub fn method(&self) -> &str {
&self.path[self.dot + 1..]
}
pub fn path(&self) -> &str {
&self.path
}
}
impl fmt::Display for CallAddress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.path)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DispatchedCall {
at: CallAddress,
grant: Grant,
}
impl DispatchedCall {
pub fn new(at: CallAddress, grant: Grant) -> Self {
Self { at, grant }
}
pub fn at(&self) -> &CallAddress {
&self.at
}
pub fn grant(&self) -> &Grant {
&self.grant
}
}
impl fmt::Display for ScopeRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl Serialize for ScopeRef {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for ScopeRef {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
Ok(Self::parse(&s))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GrantSet {
All,
Listed(BTreeSet<Grant>),
}
impl GrantSet {
pub fn contains(&self, grant: &Grant) -> bool {
match self {
Self::All => true,
Self::Listed(set) => set.contains(grant),
}
}
pub fn listed<I, G>(grants: I) -> Self
where
I: IntoIterator<Item = G>,
G: Into<String>,
{
Self::Listed(grants.into_iter().map(|g| Grant::new(g)).collect())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum RoleOrGrant {
Role(RoleName),
Grant(Grant),
}
impl RoleOrGrant {
pub fn parse(text: &str) -> Self {
let t = text.trim();
if t.contains('.') {
Self::Grant(Grant::new(t))
} else {
Self::Role(RoleName::new(t))
}
}
}
impl fmt::Display for RoleOrGrant {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Role(r) => write!(f, "{r}"),
Self::Grant(g) => write!(f, "{g}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Membership {
pub principal: Principal,
pub role: RoleName,
pub scope: ScopeRef,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct Ceiling(pub Vec<(RoleOrGrant, ScopeRef)>);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CeilingError(pub String);
impl fmt::Display for CeilingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for CeilingError {}
impl Ceiling {
pub fn entry(text: &str) -> Result<(RoleOrGrant, ScopeRef), CeilingError> {
let (left, scope) = text
.trim()
.split_once('@')
.ok_or_else(|| CeilingError(format!("`{}` is not role@SCOPE or grant@SCOPE", text.trim())))?;
if left.trim().is_empty() || scope.trim().is_empty() {
return Err(CeilingError(format!("`{}` is not role@SCOPE or grant@SCOPE", text.trim())));
}
Ok((RoleOrGrant::parse(left), ScopeRef::parse(scope)))
}
pub fn parse<I, S>(entries: I) -> Result<Self, CeilingError>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
entries
.into_iter()
.map(|e| Self::entry(e.as_ref()))
.collect::<Result<Vec<_>, _>>()
.map(Ceiling)
}
pub fn text(&self) -> Vec<String> {
self.0.iter().map(|(rg, s)| format!("{rg}@{s}")).collect()
}
pub fn layers_of(ctx: &AuthContext) -> Result<Vec<Ceiling>, CeilingError> {
let Some(v) = ctx.metadata.get(CEILING_KEY) else {
return Ok(Vec::new());
};
let unreadable = || CeilingError("this session's ceiling cannot be read: sign in again".into());
let items = v.as_array().ok_or_else(unreadable)?;
if items.iter().all(|i| i.is_string()) {
let texts: Vec<&str> = items.iter().filter_map(|i| i.as_str()).collect();
return Ok(vec![Self::parse(texts).map_err(|_| unreadable())?]);
}
items
.iter()
.map(|layer| {
let entries = layer.as_array().ok_or_else(unreadable)?;
let texts = entries
.iter()
.map(|e| e.as_str().ok_or_else(unreadable))
.collect::<Result<Vec<_>, _>>()?;
Self::parse(texts).map_err(|_| unreadable())
})
.collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Fingerprint {
held: Vec<(RoleName, ScopeRef)>,
layers: Vec<Ceiling>,
}
pub trait Memberships: Send + Sync {
fn held(&self, who: &Principal) -> Vec<Membership>;
fn own_held(&self, who: &Principal) -> Vec<Membership> {
self.held(who)
}
}
pub trait Roles: Send + Sync {
fn grants(&self, role: &RoleName) -> Option<GrantSet>;
fn names(&self) -> Vec<RoleName> {
Vec::new()
}
}
pub trait Resolve: Send + Sync {
fn chain(&self, target: &str) -> Option<Vec<ScopeRef>>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RoleTableError {
UnknownRole { role: String, includes: String },
}
impl fmt::Display for RoleTableError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownRole { role, includes } => write!(
f,
"role {role} includes {includes}, which is not defined before it"
),
}
}
}
impl std::error::Error for RoleTableError {}
#[derive(Debug, Clone, Default)]
pub struct RoleTable {
roles: BTreeMap<RoleName, GrantSet>,
}
impl RoleTable {
pub fn new() -> Self {
Self::default()
}
pub fn define<I, S>(mut self, role: &str, entries: I) -> Result<Self, RoleTableError>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let name = RoleName::new(role);
let mut set = match self.roles.remove(&name) {
Some(GrantSet::Listed(s)) => s,
Some(GrantSet::All) => {
self.roles.insert(name, GrantSet::All);
return Ok(self);
}
None => BTreeSet::new(),
};
let mut all = name.as_str() == ADMIN;
for entry in entries {
let e = entry.as_ref().trim();
if e.contains('.') {
set.insert(Grant::new(e));
continue;
}
if e == ADMIN {
all = true;
continue;
}
match self.roles.get(&RoleName::new(e)) {
Some(GrantSet::All) => all = true,
Some(GrantSet::Listed(inc)) => set.extend(inc.iter().cloned()),
None => {
return Err(RoleTableError::UnknownRole { role: role.to_string(), includes: e.to_string() })
}
}
}
self.roles.insert(name, if all { GrantSet::All } else { GrantSet::Listed(set) });
Ok(self)
}
pub fn set(&mut self, role: &str, grants: GrantSet) {
self.roles.insert(RoleName::new(role), grants);
}
pub fn from_lists<'a, I, G>(lists: I) -> Self
where
I: IntoIterator<Item = (&'a str, G)>,
G: IntoIterator,
G::Item: AsRef<str>,
{
let mut table = Self::new();
for (role, grants) in lists {
let name = RoleName::new(role);
let grants: Vec<Grant> = grants.into_iter().map(|g| Grant::new(g.as_ref().trim())).collect();
match table.roles.entry(name) {
std::collections::btree_map::Entry::Occupied(mut o) => {
if let GrantSet::Listed(s) = o.get_mut() {
s.extend(grants);
}
}
std::collections::btree_map::Entry::Vacant(v) => {
v.insert(if role == ADMIN { GrantSet::All } else { GrantSet::Listed(grants.into_iter().collect()) });
}
}
}
table
}
}
impl Roles for RoleTable {
fn grants(&self, role: &RoleName) -> Option<GrantSet> {
if role.as_str() == ADMIN {
return Some(GrantSet::All);
}
self.roles.get(role).cloned()
}
fn names(&self) -> Vec<RoleName> {
self.roles.keys().cloned().collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Refusal {
Unauthenticated,
MissingGrant {
grant: Grant,
scope: ScopeRef,
roles: Vec<RoleName>,
held_on: Vec<ScopeRef>,
},
Ended {
reason: String,
},
}
impl fmt::Display for Refusal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unauthenticated => f.write_str("sign in first"),
Self::Ended { reason } => f.write_str(reason),
Self::MissingGrant { grant, scope, .. } => write!(f, "needs {grant} on {scope}"),
}
}
}
impl std::error::Error for Refusal {}
#[derive(Clone)]
pub struct Reach {
held_on: std::borrow::Cow<'static, [ScopeRef]>,
live: Option<Live>,
}
#[derive(Clone)]
struct Live {
gate: Gate,
caller: Option<AuthContext>,
grant: Grant,
everywhere: bool,
call: Option<DispatchedCall>,
}
impl Live {
fn now(&self) -> Result<Reach, Refusal> {
self.now_on(None)
}
fn now_on(&self, target: Option<&str>) -> Result<Reach, Refusal> {
match self.everywhere {
true => self.gate.everywhere_in(self.caller.as_ref(), &self.grant, self.call.as_ref()),
false => self.gate.check_in(self.caller.as_ref(), &self.grant, target),
}
}
}
impl fmt::Debug for Reach {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Reach")
.field("held_on", &self.held_on)
.field("grant", &self.live.as_ref().map(|l| l.grant.as_str()))
.finish()
}
}
impl PartialEq for Reach {
fn eq(&self, other: &Self) -> bool {
self.held_on == other.held_on && self.grant() == other.grant()
}
}
impl Reach {
pub fn everywhere() -> Self {
static EVERYWHERE: [ScopeRef; 1] = [ScopeRef::Everywhere];
Self { held_on: std::borrow::Cow::Borrowed(&EVERYWHERE), live: None }
}
pub fn nowhere() -> Self {
Self { held_on: std::borrow::Cow::Borrowed(&[]), live: None }
}
pub fn is_everywhere(&self) -> bool {
self.held_on.iter().any(ScopeRef::is_everywhere)
}
pub fn holds_activation(&self) -> bool {
self.is_everywhere() || self.live.as_ref().is_some_and(|l| l.everywhere && l.call.is_some())
}
pub fn is_empty(&self) -> bool {
self.held_on.is_empty()
}
pub fn held_on(&self) -> &[ScopeRef] {
&self.held_on
}
pub fn caller(&self) -> Option<&AuthContext> {
self.live.as_ref().and_then(|l| l.caller.as_ref())
}
pub fn grant(&self) -> Option<&Grant> {
self.live.as_ref().map(|l| &l.grant)
}
pub fn generation(&self) -> Option<&GrantsGeneration> {
self.live.as_ref().map(|l| l.gate.generation())
}
pub fn allows(&self, target: &str) -> bool {
match &self.live {
None => self.is_everywhere(),
Some(l) if l.everywhere && l.call.is_none() => l.now().is_ok(),
Some(l) if l.everywhere => match l.now() {
Ok(now) => now.is_everywhere() || l.gate.check_in(l.caller.as_ref(), &l.grant, Some(target)).is_ok(),
Err(_) => false,
},
Some(l) => l.now_on(Some(target)).is_ok(),
}
}
pub fn current(&self) -> Option<Reach> {
match &self.live {
None => Some(self.clone()),
Some(l) => l.now().ok(),
}
}
pub fn recheck(&self) -> Result<Reach, Refusal> {
match &self.live {
None => Ok(self.clone()),
Some(l) => l.now(),
}
}
pub fn covers(&self, chain: &[ScopeRef]) -> bool {
self.is_everywhere() || self.held_on.iter().any(|s| chain.contains(s))
}
}
pub trait Liveness: Send + Sync {
fn alive(&self, caller: &AuthContext) -> Result<(), String>;
}
struct GateInner {
memberships: Arc<dyn Memberships>,
roles: Arc<dyn Roles>,
resolve: Arc<dyn Resolve>,
liveness: Option<Arc<dyn Liveness>>,
generation: GrantsGeneration,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GrantsMove {
Grant,
Revoke,
RoleEdit,
TeamAdd,
TeamRemove,
SignOut,
}
#[derive(Clone)]
pub struct GrantsGeneration {
now: Arc<std::sync::atomic::AtomicU64>,
tx: Arc<tokio::sync::watch::Sender<u64>>,
}
impl fmt::Debug for GrantsGeneration {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("GrantsGeneration").field(&self.current()).finish()
}
}
impl Default for GrantsGeneration {
fn default() -> Self {
Self::new()
}
}
static ON_MOVE: std::sync::OnceLock<fn(u64)> = std::sync::OnceLock::new();
impl GrantsGeneration {
pub fn new() -> Self {
Self { now: Arc::new(std::sync::atomic::AtomicU64::new(0)), tx: Arc::new(tokio::sync::watch::channel(0).0) }
}
pub fn bump(&self) -> u64 {
let n = self.now.fetch_add(1, std::sync::atomic::Ordering::AcqRel) + 1;
if let Some(told) = ON_MOVE.get() {
told(n);
}
self.tx.send_replace(n);
n
}
pub fn on_move(told: fn(u64)) {
let _ = ON_MOVE.set(told);
}
pub fn moved(&self, why: GrantsMove) -> u64 {
let _ = why;
self.bump()
}
pub fn current(&self) -> u64 {
self.now.load(std::sync::atomic::Ordering::Acquire)
}
pub fn raise_to(&self, n: u64) {
let was = self.now.fetch_max(n, std::sync::atomic::Ordering::AcqRel);
if n > was {
self.tx.send_replace(self.current());
}
}
pub fn subscribe(&self) -> tokio::sync::watch::Receiver<u64> {
self.tx.subscribe()
}
}
#[derive(Clone)]
pub struct Gate {
inner: Arc<GateInner>,
}
impl fmt::Debug for Gate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Gate")
}
}
impl Gate {
pub fn new(memberships: Arc<dyn Memberships>, roles: Arc<dyn Roles>, resolve: Arc<dyn Resolve>) -> Self {
Self { inner: Arc::new(GateInner { memberships, roles, resolve, liveness: None, generation: GrantsGeneration::new() }) }
}
pub fn with_generation(self, generation: GrantsGeneration) -> Self {
let i = &self.inner;
Self {
inner: Arc::new(GateInner {
memberships: i.memberships.clone(),
roles: i.roles.clone(),
resolve: i.resolve.clone(),
liveness: i.liveness.clone(),
generation,
}),
}
}
pub fn generation(&self) -> &GrantsGeneration {
&self.inner.generation
}
pub fn moved(&self, why: GrantsMove) -> u64 {
self.inner.generation.moved(why)
}
pub fn with_liveness(self, liveness: Arc<dyn Liveness>) -> Self {
let i = &self.inner;
Self {
inner: Arc::new(GateInner {
memberships: i.memberships.clone(),
roles: i.roles.clone(),
resolve: i.resolve.clone(),
liveness: Some(liveness),
generation: i.generation.clone(),
}),
}
}
pub fn alive(&self, caller: &AuthContext) -> Result<(), String> {
if caller.principal().is_none() {
return Ok(());
}
self.alive_named(caller)
}
fn alive_named(&self, caller: &AuthContext) -> Result<(), String> {
if caller.expired() {
return Err("your sign-in has expired: sign in again".into());
}
match &self.inner.liveness {
Some(l) => l.alive(caller),
None => Ok(()),
}
}
pub fn lists(&self, role: &RoleName, grant: &Grant) -> bool {
role.as_str() == ADMIN || self.inner.roles.grants(role).is_some_and(|g| g.contains(grant))
}
pub fn roles_listing(&self, grant: &Grant) -> Vec<RoleName> {
let mut out: Vec<RoleName> = self
.inner
.roles
.names()
.into_iter()
.filter(|r| r.as_str() != ADMIN && self.lists(r, grant))
.collect();
out.push(RoleName::new(ADMIN));
out
}
fn entry_allows(&self, entry: &RoleOrGrant, grant: &Grant) -> bool {
match entry {
RoleOrGrant::Grant(g) => g == grant,
RoleOrGrant::Role(r) => self.lists(r, grant),
}
}
fn caller_of(caller: Option<&AuthContext>) -> Option<(Principal, Vec<Ceiling>)> {
let ctx = caller?;
let principal = ctx.principal()?;
let layers = Ceiling::layers_of(ctx).unwrap_or_else(|_| vec![Ceiling::default()]);
Some((principal, layers))
}
fn chain_of(&self, name: &str) -> Option<Vec<ScopeRef>> {
let mut chain = self.inner.resolve.chain(name)?;
chain.retain(|s| s.is_everywhere() || s.is_data());
Some(chain)
}
fn address_for<'c>(call: Option<&'c DispatchedCall>, grant: &Grant) -> Option<&'c CallAddress> {
call.filter(|c| c.grant() == grant).map(DispatchedCall::at)
}
fn as_data(scope: &ScopeRef) -> Option<&ScopeRef> {
(scope.is_everywhere() || scope.is_data()).then_some(scope)
}
fn opens(scope: &ScopeRef, at: &CallAddress) -> bool {
scope.is_everywhere() || (scope.is_address() && scope.covers_address(at))
}
fn within(&self, inner: &ScopeRef, outer: &ScopeRef) -> bool {
if outer.is_everywhere() {
return true;
}
if !inner.is_data() || !outer.is_data() {
return false;
}
if inner == outer {
return true;
}
match inner {
ScopeRef::Named(name) => self.chain_of(name).is_some_and(|c| c.contains(outer)),
ScopeRef::Everywhere => false,
}
}
fn meet(&self, a: Vec<ScopeRef>, b: Vec<ScopeRef>) -> Vec<ScopeRef> {
if a.iter().any(ScopeRef::is_everywhere) {
return b;
}
if b.iter().any(ScopeRef::is_everywhere) {
return a;
}
let mut out = BTreeSet::new();
for x in &a {
for y in &b {
if self.within(x, y) {
out.insert(x.clone());
} else if self.within(y, x) {
out.insert(y.clone());
}
}
}
out.into_iter().collect()
}
fn normal(scopes: impl IntoIterator<Item = ScopeRef>) -> Vec<ScopeRef> {
let set: BTreeSet<ScopeRef> = scopes.into_iter().collect();
if set.contains(&ScopeRef::Everywhere) {
vec![ScopeRef::Everywhere]
} else {
set.into_iter().collect()
}
}
fn held_on_for(&self, principal: &Principal, layers: &[Ceiling], grant: &Grant) -> Vec<ScopeRef> {
let held = self.inner.memberships.held(principal);
self.held_on_in(held.iter().map(|m| (&m.role, &m.scope)), layers, grant)
}
fn held_on_in<'a>(
&self,
held: impl Iterator<Item = (&'a RoleName, &'a ScopeRef)>,
layers: &[Ceiling],
grant: &Grant,
) -> Vec<ScopeRef> {
let mut acc = Self::normal(
held.filter(|(role, _)| self.lists(role, grant)).filter_map(|(_, scope)| Self::as_data(scope).cloned()),
);
for layer in layers {
if acc.is_empty() {
break;
}
let allowed = Self::normal(
layer
.0
.iter()
.filter(|(rg, _)| self.entry_allows(rg, grant))
.filter_map(|(_, s)| Self::as_data(s).cloned()),
);
acc = self.meet(acc, allowed);
}
acc
}
pub fn held_on(&self, caller: &AuthContext, grant: &Grant) -> Vec<ScopeRef> {
match Self::caller_of(Some(caller)) {
Some((p, layers)) => self.held_on_for(&p, &layers, grant),
None => Vec::new(),
}
}
pub fn fingerprint(&self, caller: &AuthContext) -> Option<Fingerprint> {
let (principal, layers) = Self::caller_of(Some(caller))?;
let mut held: Vec<(RoleName, ScopeRef)> =
self.inner.memberships.held(&principal).into_iter().map(|m| (m.role, m.scope)).collect();
held.sort();
held.dedup();
Some(Fingerprint { held, layers })
}
pub fn held_on_by(&self, who: &Fingerprint, grant: &Grant) -> Vec<ScopeRef> {
self.held_on_in(who.held.iter().map(|(r, s)| (r, s)), &who.layers, grant)
}
pub fn check(&self, caller: Option<&AuthContext>, grant: &Grant, target: Option<&str>) -> Result<Reach, Refusal> {
self.check_in(caller, grant, target)
}
fn check_in(&self, caller: Option<&AuthContext>, grant: &Grant, target: Option<&str>) -> Result<Reach, Refusal> {
let Some((principal, layers)) = Self::caller_of(caller) else {
return Err(Refusal::Unauthenticated);
};
if let Some(ctx) = caller {
self.alive_named(ctx).map_err(|reason| Refusal::Ended { reason })?;
}
let held_on = self.held_on_for(&principal, &layers, grant);
let (allowed, scope) = match target {
None => (!held_on.is_empty(), ScopeRef::Everywhere),
Some(t) => match self.chain_of(t) {
None => (false, ScopeRef::named(t)),
Some(chain) => {
let in_chain =
|s: &ScopeRef| Self::as_data(s).is_some_and(|d| d.is_everywhere() || chain.contains(d));
let by_membership = self
.inner
.memberships
.held(&principal)
.iter()
.any(|m| in_chain(&m.scope) && self.lists(&m.role, grant));
let by_ceiling = layers
.iter()
.all(|layer| layer.0.iter().any(|(rg, s)| in_chain(s) && self.entry_allows(rg, grant)));
let scope = chain.first().cloned().unwrap_or_else(|| ScopeRef::named(t));
(by_membership && by_ceiling, scope)
}
},
};
if allowed {
Ok(Reach { held_on: held_on.into(), live: Some(self.live(caller, grant, None, false)) })
} else {
Err(Refusal::MissingGrant { grant: grant.clone(), scope, roles: self.roles_listing(grant), held_on })
}
}
fn live(&self, caller: Option<&AuthContext>, grant: &Grant, call: Option<&DispatchedCall>, everywhere: bool) -> Live {
Live { gate: self.clone(), caller: caller.cloned(), grant: grant.clone(), everywhere, call: call.cloned() }
}
pub fn check_everywhere(&self, caller: Option<&AuthContext>, grant: &Grant) -> Result<Reach, Refusal> {
self.everywhere_in(caller, grant, None)
}
pub fn check_everywhere_at(&self, caller: Option<&AuthContext>, call: &DispatchedCall) -> Result<Reach, Refusal> {
self.everywhere_in(caller, call.grant(), Some(call))
}
fn everywhere_in(
&self,
caller: Option<&AuthContext>,
grant: &Grant,
call: Option<&DispatchedCall>,
) -> Result<Reach, Refusal> {
match Self::address_for(call, grant) {
None => self.on_everywhere(caller, grant),
Some(at) => self.at_door(caller, grant, call, at),
}
}
fn on_everywhere(&self, caller: Option<&AuthContext>, grant: &Grant) -> Result<Reach, Refusal> {
let reach = match self.check_in(caller, grant, None) {
Ok(reach) => reach,
Err(Refusal::MissingGrant { grant, roles, held_on, .. }) => {
return Err(Refusal::MissingGrant { grant, scope: ScopeRef::Everywhere, roles, held_on })
}
Err(other) => return Err(other),
};
if !reach.is_everywhere() {
return Err(Refusal::MissingGrant {
grant: grant.clone(),
scope: ScopeRef::Everywhere,
roles: self.roles_listing(grant),
held_on: reach.held_on.into_owned(),
});
}
let live = reach.live.map(|live| Live { everywhere: true, ..live });
Ok(Reach { held_on: reach.held_on, live })
}
fn at_door(
&self,
caller: Option<&AuthContext>,
grant: &Grant,
call: Option<&DispatchedCall>,
at: &CallAddress,
) -> Result<Reach, Refusal> {
let Some((principal, layers)) = Self::caller_of(caller) else {
return Err(Refusal::Unauthenticated);
};
if let Some(ctx) = caller {
self.alive_named(ctx).map_err(|reason| Refusal::Ended { reason })?;
}
let held = self.inner.memberships.held(&principal);
let by_membership = held.iter().any(|m| Self::opens(&m.scope, at) && self.lists(&m.role, grant));
let by_ceiling =
layers.iter().all(|layer| layer.0.iter().any(|(rg, s)| Self::opens(s, at) && self.entry_allows(rg, grant)));
let held_on = self.held_on_in(held.iter().map(|m| (&m.role, &m.scope)), &layers, grant);
if by_membership && by_ceiling {
Ok(Reach { held_on: held_on.into(), live: Some(self.live(caller, grant, call, true)) })
} else {
Err(Refusal::MissingGrant {
grant: grant.clone(),
scope: ScopeRef::named(format!("/{}", at.activation())),
roles: self.roles_listing(grant),
held_on,
})
}
}
pub fn reach_of_public(&self, caller: Option<&AuthContext>, grant: &Grant) -> Reach {
self.check_in(caller, grant, None).unwrap_or_else(|_| Reach {
held_on: std::borrow::Cow::Borrowed(&[]),
live: Some(self.live(caller, grant, None, false)),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
const ADA: &str = "key:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const BOB: &str = "key:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
#[derive(Default)]
struct Members(Mutex<Vec<Membership>>);
impl Members {
fn grant(&self, who: &str, role: &str, scope: &str) {
self.0.lock().unwrap().push(Membership {
principal: who.parse().unwrap(),
role: RoleName::new(role),
scope: ScopeRef::parse(scope),
});
}
fn revoke_all(&self) {
self.0.lock().unwrap().clear();
}
}
impl Memberships for Members {
fn held(&self, who: &Principal) -> Vec<Membership> {
self.0.lock().unwrap().iter().filter(|m| &m.principal == who).cloned().collect()
}
}
struct Shortcodes;
impl Resolve for Shortcodes {
fn chain(&self, target: &str) -> Option<Vec<ScopeRef>> {
let code = target.split_once('-').map(|(c, _)| c).unwrap_or(target);
let mut chain = Vec::new();
if target.contains('-') {
chain.push(ScopeRef::named(target));
}
match code {
"MENGER" | "IDENTITY" => {
chain.push(ScopeRef::named(code));
chain.push(ScopeRef::named("PLEXUS"));
}
"PLEXUS" => chain.push(ScopeRef::named("PLEXUS")),
_ => return None,
}
chain.push(ScopeRef::Everywhere);
Some(chain)
}
}
fn roles() -> RoleTable {
RoleTable::new()
.define("viewer", ["tickets.get", "tickets.list"])
.unwrap()
.define("editor", ["viewer", "tickets.set_status"])
.unwrap()
}
fn gate(members: &Arc<Members>) -> Gate {
Gate::new(members.clone(), Arc::new(roles()), Arc::new(Shortcodes))
}
fn who(p: &str) -> AuthContext {
AuthContext::for_principal(&p.parse().unwrap(), "s1", vec![], serde_json::Value::Null)
}
fn with_ceiling(p: &str, ceiling: serde_json::Value) -> AuthContext {
AuthContext::for_principal(&p.parse().unwrap(), "s1", vec![], serde_json::json!({ CEILING_KEY: ceiling }))
}
fn g(s: &str) -> Grant {
Grant::new(s)
}
#[test]
fn a_grant_no_role_lists_is_refused_to_all_but_admin() {
let m = Arc::new(Members::default());
m.grant(ADA, "editor", "*");
m.grant(BOB, "admin", "MENGER");
let gate = gate(&m);
let err = gate.check(Some(&who(ADA)), &g("members.grant"), Some("MENGER-1")).unwrap_err();
assert_eq!(
err,
Refusal::MissingGrant {
grant: g("members.grant"),
scope: ScopeRef::named("MENGER-1"),
roles: vec![RoleName::new("admin")],
held_on: vec![],
}
);
assert!(gate.check(Some(&who(BOB)), &g("members.grant"), Some("MENGER-1")).is_ok());
assert!(gate.check(Some(&who(BOB)), &g("members.grant"), Some("IDENTITY-1")).is_err());
}
#[test]
fn held_on_a_scope_allows_targets_in_its_chain_only() {
let m = Arc::new(Members::default());
m.grant(ADA, "editor", "MENGER");
let gate = gate(&m);
let reach = gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("MENGER-12")).unwrap();
assert_eq!(reach.held_on(), &[ScopeRef::named("MENGER")]);
let err = gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("IDENTITY-1")).unwrap_err();
assert_eq!(
err,
Refusal::MissingGrant {
grant: g("tickets.set_status"),
scope: ScopeRef::named("IDENTITY-1"),
roles: vec![RoleName::new("editor"), RoleName::new("admin")],
held_on: vec![ScopeRef::named("MENGER")],
}
);
assert_eq!(err.to_string(), "needs tickets.set_status on IDENTITY-1");
assert!(gate.check(Some(&who(ADA)), &g("tickets.get"), Some("NOPE-1")).is_err());
}
#[test]
fn held_on_everywhere_allows_any_target_and_reach_is_everywhere() {
let m = Arc::new(Members::default());
m.grant(ADA, "viewer", "*");
m.grant(ADA, "viewer", "MENGER");
let gate = gate(&m);
let reach = gate.check(Some(&who(ADA)), &g("tickets.get"), Some("IDENTITY-3")).unwrap();
assert!(reach.is_everywhere());
assert_eq!(reach.held_on(), &[ScopeRef::Everywhere]);
assert!(gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap().is_everywhere());
assert!(gate.check(Some(&who(ADA)), &g("tickets.set_status"), Some("IDENTITY-3")).is_err());
}
#[test]
fn without_a_target_held_anywhere_suffices_and_reach_says_where() {
let m = Arc::new(Members::default());
m.grant(ADA, "viewer", "MENGER");
m.grant(ADA, "viewer", "IDENTITY");
let gate = gate(&m);
let reach = gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap();
assert_eq!(reach.held_on(), &[ScopeRef::named("IDENTITY"), ScopeRef::named("MENGER")]);
assert!(reach.allows("MENGER-4"));
assert!(!reach.allows("PLEXUS-1"));
let err = gate.check(Some(&who(BOB)), &g("tickets.list"), None).unwrap_err();
assert!(matches!(err, Refusal::MissingGrant { ref scope, .. } if scope.is_everywhere()));
}
#[test]
fn a_ceiling_narrows_the_membership() {
let m = Arc::new(Members::default());
m.grant(ADA, "editor", "MENGER");
let gate = gate(&m);
let narrowed = with_ceiling(ADA, serde_json::json!(["editor@MENGER-12"]));
assert!(gate.check(Some(&narrowed), &g("tickets.set_status"), Some("MENGER-12")).is_ok());
assert!(gate.check(Some(&narrowed), &g("tickets.set_status"), Some("MENGER-13")).is_err());
let reach = gate.check(Some(&narrowed), &g("tickets.list"), None).unwrap();
assert_eq!(reach.held_on(), &[ScopeRef::named("MENGER-12")]);
let only_get = with_ceiling(ADA, serde_json::json!([["tickets.get@*"]]));
assert!(gate.check(Some(&only_get), &g("tickets.get"), Some("MENGER-1")).is_ok());
let err = gate.check(Some(&only_get), &g("tickets.set_status"), Some("MENGER-1")).unwrap_err();
assert!(matches!(err, Refusal::MissingGrant { ref held_on, .. } if held_on.is_empty()));
let layered = with_ceiling(ADA, serde_json::json!([["editor@*"], ["viewer@MENGER"]]));
assert!(gate.check(Some(&layered), &g("tickets.get"), Some("MENGER-1")).is_ok());
assert!(gate.check(Some(&layered), &g("tickets.set_status"), Some("MENGER-1")).is_err());
let wider = with_ceiling(ADA, serde_json::json!(["editor@IDENTITY"]));
assert!(gate.check(Some(&wider), &g("tickets.get"), Some("IDENTITY-1")).is_err());
let bad = with_ceiling(ADA, serde_json::json!("editor@*"));
assert!(gate.check(Some(&bad), &g("tickets.get"), Some("MENGER-1")).is_err());
}
#[test]
fn role_inclusion_flattens_and_must_name_an_earlier_role() {
let r = roles();
let editor = r.grants(&RoleName::new("editor")).unwrap();
assert!(editor.contains(&g("tickets.get")) && editor.contains(&g("tickets.set_status")));
let viewer = r.grants(&RoleName::new("viewer")).unwrap();
assert!(!viewer.contains(&g("tickets.set_status")));
assert_eq!(
RoleTable::new().define("editor", ["viewer"]).unwrap_err(),
RoleTableError::UnknownRole { role: "editor".into(), includes: "viewer".into() }
);
assert_eq!(r.grants(&RoleName::new("admin")), Some(GrantSet::All));
let merged = RoleTable::from_lists([("editor", vec!["tickets.get"]), ("editor", vec!["comments.add"])]);
let e = merged.grants(&RoleName::new("editor")).unwrap();
assert!(e.contains(&g("tickets.get")) && e.contains(&g("comments.add")));
}
#[test]
fn anonymous_is_unauthenticated() {
let m = Arc::new(Members::default());
let gate = gate(&m);
assert_eq!(gate.check(None, &g("tickets.get"), Some("MENGER-1")).unwrap_err(), Refusal::Unauthenticated);
assert_eq!(
gate.check(Some(&AuthContext::anonymous()), &g("tickets.list"), None).unwrap_err(),
Refusal::Unauthenticated
);
assert!(gate.reach_of_public(None, &g("auth.login")).is_empty());
}
#[test]
fn a_live_reach_follows_grants_as_they_stand() {
let m = Arc::new(Members::default());
m.grant(ADA, "viewer", "MENGER");
let gate = gate(&m);
let reach = gate.check(Some(&who(ADA)), &g("tickets.list"), None).unwrap();
assert!(reach.allows("MENGER-1"));
assert!(reach.current().is_some());
m.revoke_all();
assert!(!reach.allows("MENGER-1"));
assert!(reach.current().is_none());
assert!(Reach::everywhere().allows("ANY-1") && Reach::everywhere().current().is_some());
}
#[test]
fn scope_refs_and_ceilings_round_trip() {
assert_eq!(serde_json::to_string(&ScopeRef::Everywhere).unwrap(), "\"*\"");
assert_eq!(serde_json::from_str::<ScopeRef>("\"MENGER\"").unwrap(), ScopeRef::named("MENGER"));
let c = Ceiling::parse(["editor@MENGER-12", "tickets.get@*"]).unwrap();
assert_eq!(c.0[0], (RoleOrGrant::Role(RoleName::new("editor")), ScopeRef::named("MENGER-12")));
assert_eq!(c.0[1], (RoleOrGrant::Grant(g("tickets.get")), ScopeRef::Everywhere));
assert_eq!(c.text(), vec!["editor@MENGER-12", "tickets.get@*"]);
assert!(Ceiling::parse(["editor"]).is_err());
}
#[derive(Default)]
struct Switch(std::sync::atomic::AtomicBool);
impl Liveness for Switch {
fn alive(&self, _: &AuthContext) -> Result<(), String> {
if self.0.load(std::sync::atomic::Ordering::SeqCst) {
Err("you have signed out: sign in again".into())
} else {
Ok(())
}
}
}
#[test]
fn a_session_that_ended_holds_nothing() {
let m = Arc::new(Members::default());
m.grant(ADA, "admin", "*");
let out = Arc::new(Switch::default());
let gate = gate(&m).with_liveness(out.clone());
let reach = gate.check(Some(&who(ADA)), &g("auth.grant"), None).expect("admin before sign-out");
assert!(reach.allows("MENGER-1"));
out.0.store(true, std::sync::atomic::Ordering::SeqCst);
let ended = Refusal::Ended { reason: "you have signed out: sign in again".into() };
assert_eq!(gate.check(Some(&who(ADA)), &g("auth.grant"), None).unwrap_err(), ended);
assert_eq!(gate.check(Some(&who(ADA)), &g("tickets.get"), Some("MENGER-1")).unwrap_err(), ended);
assert!(!reach.allows("MENGER-1"), "a stream's next event sees it");
assert!(reach.current().is_none());
assert!(gate.reach_of_public(Some(&who(ADA)), &g("auth.grant")).is_empty());
assert_eq!(gate.check(None, &g("auth.grant"), None).unwrap_err(), Refusal::Unauthenticated);
}
#[test]
fn an_expired_sign_in_holds_nothing() {
let m = Arc::new(Members::default());
m.grant(ADA, "admin", "*");
let gate = gate(&m);
let past = AuthContext::for_principal(&ADA.parse().unwrap(), "s1", vec![], serde_json::json!({ "expires_at": 1 }));
assert!(matches!(gate.check(Some(&past), &g("auth.grant"), None), Err(Refusal::Ended { .. })));
let future = AuthContext::for_principal(&ADA.parse().unwrap(), "s1", vec![], serde_json::json!({ "expires_at": i64::MAX }));
assert!(gate.check(Some(&future), &g("auth.grant"), None).is_ok());
}
#[test]
fn a_fingerprint_is_what_the_answers_read() {
let m = Arc::new(Members::default());
m.grant(ADA, "viewer", "IDENTITY");
m.grant(ADA, "editor", "MENGER");
m.grant(BOB, "editor", "MENGER");
m.grant(BOB, "viewer", "IDENTITY");
m.grant(BOB, "editor", "MENGER");
let gate = gate(&m);
let (ada, bob) = (gate.fingerprint(&who(ADA)).unwrap(), gate.fingerprint(&who(BOB)).unwrap());
assert_eq!(ada, bob, "the same holdings, in another order and once more: one fingerprint");
assert_eq!(gate.fingerprint(&AuthContext::anonymous()), None);
let narrow = with_ceiling(ADA, serde_json::json!(["editor@MENGER-12"]));
let narrowed = gate.fingerprint(&narrow).unwrap();
assert_ne!(narrowed, ada, "a ceiling: another fingerprint");
let unreadable = gate.fingerprint(&with_ceiling(ADA, serde_json::json!("editor@*"))).unwrap();
assert_ne!(unreadable, ada, "an unreadable ceiling allows nothing: not the unbounded caller's");
for (ctx, fp) in [(&who(ADA), &ada), (&narrow, &narrowed), (&with_ceiling(ADA, serde_json::json!("editor@*")), &unreadable)] {
for grant in ["tickets.get", "tickets.set_status", "tickets.delete", "members.grant"] {
assert_eq!(gate.held_on_by(fp, &g(grant)), gate.held_on(ctx, &g(grant)), "{grant}");
}
}
assert_eq!(gate.held_on_by(&narrowed, &g("tickets.get")), vec![ScopeRef::named("MENGER-12")]);
m.revoke_all();
assert_ne!(gate.fingerprint(&who(ADA)).unwrap(), ada, "a revoke: another fingerprint");
}
#[test]
fn a_whole_service_method_needs_its_grant_on_everywhere() {
let m = Arc::new(Members::default());
m.grant(ADA, "admin", "MENGER-5");
m.grant(BOB, "admin", "*");
let gate = gate(&m);
let grow = g("dyn.grow");
assert_eq!(gate.check(Some(&who(ADA)), &grow, None).unwrap().held_on(), [ScopeRef::named("MENGER-5")]);
match gate.check_everywhere(Some(&who(ADA)), &grow) {
Err(Refusal::MissingGrant { scope, held_on, .. }) => {
assert_eq!(scope, ScopeRef::Everywhere);
assert_eq!(held_on, [ScopeRef::named("MENGER-5")]);
}
other => panic!("a scoped admin: {other:?}"),
}
let reach = gate.check_everywhere(Some(&who(BOB)), &grow).unwrap();
assert!(reach.is_everywhere());
for ceiling in [serde_json::json!(["admin@MENGER-5"]), serde_json::json!(["viewer@*"]), serde_json::json!("admin@*")] {
let capped = with_ceiling(BOB, ceiling.clone());
assert!(gate.check_everywhere(Some(&capped), &grow).is_err(), "ceiling {ceiling}");
}
assert!(gate.check_everywhere(Some(&with_ceiling(BOB, serde_json::json!(["dyn.grow@*"]))), &grow).is_ok());
assert!(gate.check_everywhere(Some(&with_ceiling(ADA, serde_json::json!(["admin@*"]))), &grow).is_err(), "a ceiling never widens");
assert_eq!(gate.check_everywhere(None, &grow).err(), Some(Refusal::Unauthenticated));
m.revoke_all();
m.grant(BOB, "admin", "MENGER");
assert!(reach.current().is_none());
assert!(reach.recheck().is_err());
assert!(!reach.allows("MENGER-1"));
}
#[test]
fn a_dispatched_call_opens_its_door_for_its_own_grant_only() {
let m = Arc::new(Members::default());
m.grant(ADA, "admin", "/dyn.connect");
let gate = gate(&m);
let connect = DispatchedCall::new(CallAddress::new("dyn", "connect").unwrap(), g("dyn.connect"));
assert!(gate.everywhere_in(Some(&who(ADA)), &g("dyn.connect"), Some(&connect)).is_ok());
assert!(gate.everywhere_in(Some(&who(ADA)), &g("dyn.disconnect"), Some(&connect)).is_err());
assert!(gate.everywhere_in(Some(&who(ADA)), &g("auth.grant"), Some(&connect)).is_err());
}
}