use std::cmp::Ordering;
use tilo_app_id::AppId;
use crate::{
ActionKind, Answer, Context, Grant, GrantId, Grantee, KindSet, Level, Lifetime, TreePath,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Basis<'g> {
Grant(&'g Grant),
Capped(Cap),
RootOnly(Cap),
Owner,
OwnRecord,
NoGrant,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Decision<'g> {
pub answer: Answer,
pub basis: Basis<'g>,
}
impl<'g> Decision<'g> {
#[must_use]
pub const fn answered_at_root(&self) -> bool {
matches!(self.basis, Basis::RootOnly(_)) && matches!(self.answer, Answer::Ask)
}
#[must_use]
pub const fn grant(&self) -> Option<&'g Grant> {
match self.basis {
Basis::Grant(grant) => Some(grant),
_ => None,
}
}
}
pub fn decide<'g>(
grants: impl IntoIterator<Item = &'g Grant>,
grantees: &[Grantee],
node: &TreePath,
kind: ActionKind,
cx: &Context<'_>,
) -> Decision<'g> {
let node = &*crate::roles::decided_node(node);
let workspace_root = node.id_at(Level::Kind) == Some(crate::roles::WORKSPACE_KIND);
let mut best: Option<&'g Grant> = None;
for grant in grants {
if !grant.kinds.contains(kind)
|| !names(grant, grantees, cx)
|| !cx.covers(&grant.node, node)
|| !grant.is_live(cx)
{
continue;
}
let better = best.is_none_or(|held| {
grant.node.cmp_specificity(&held.node).then_with(|| {
if workspace_root {
held.answer.cmp(&grant.answer)
} else {
compare_content_rules(grant, held)
}
}) == Ordering::Greater
});
if better {
best = Some(grant);
}
}
best.map_or(
Decision {
answer: Answer::Deny,
basis: Basis::NoGrant,
},
|grant| Decision {
answer: grant.answer,
basis: Basis::Grant(grant),
},
)
}
fn compare_content_rules(candidate: &Grant, current: &Grant) -> Ordering {
let priority = |rule: &Grant| {
if rule.grantee.person_id().is_some() {
2
} else {
u8::from(matches!(rule.grantee, Grantee::CustomRole(_)))
}
};
priority(candidate).cmp(&priority(current)).then_with(|| {
if matches!(candidate.grantee, Grantee::CustomRole(_)) {
candidate.answer.cmp(¤t.answer)
} else {
current.answer.cmp(&candidate.answer)
}
})
}
#[must_use]
pub fn names(grant: &Grant, grantees: &[Grantee], cx: &Context<'_>) -> bool {
if cx.grantee_matches(&grant.grantee, grantees) {
return true;
}
if crate::roles::is_role_grant(grant) {
return false;
}
grant.grantee.role_of().is_some_and(|wanted| {
grantees
.iter()
.any(|held| held.role_of().is_some_and(|held| held.includes(wanted)))
})
}
#[derive(Clone, Debug, Default)]
pub struct Party<'g> {
pub grantees: Vec<Grantee>,
pub grants: Vec<&'g Grant>,
pub owns: Vec<TreePath>,
pub own_records: Vec<(TreePath, KindSet)>,
pub held_off: Vec<&'g Grant>,
pub cap: Option<Cap>,
pub delegated: Vec<&'g Grant>,
pub narrowing: Vec<&'g Grant>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Cap {
pub content: Answer,
pub outside: Answer,
pub governance: Answer,
pub root_only: Answer,
pub why: &'static str,
}
impl Cap {
pub const FOREIGN_DEVICE: Self = Self {
content: Answer::Allow,
outside: Answer::Ask,
governance: Answer::Deny,
root_only: Answer::Deny,
why: "this computer is not one of the person's own Tilo devices, so from it they \
change content, are asked before reaching outside the workspace, and leave its \
members and settings to a device of their own",
};
pub const ROOTLESS_DEVICE: Self = Self {
content: Answer::Allow,
outside: Answer::Allow,
governance: Answer::Allow,
root_only: Answer::Ask,
why: "only a device of the person's that keeps their identity signs this, so it is \
asked and carried out there",
};
#[must_use]
pub const fn root_only(self) -> Decision<'static> {
Decision {
answer: self.root_only,
basis: Basis::RootOnly(self),
}
}
fn answer(self, node: &TreePath, kind: ActionKind) -> Answer {
if node.id_at(Level::Kind) == Some(crate::roles::WORKSPACE_KIND) {
return match kind {
ActionKind::Read => Answer::Allow,
ActionKind::Undoable | ActionKind::Outside => self.governance,
};
}
match kind {
ActionKind::Read | ActionKind::Undoable => self.content,
ActionKind::Outside => self.outside,
}
}
}
impl<'g> Party<'g> {
#[must_use]
pub fn new(grantees: Vec<Grantee>, grants: impl IntoIterator<Item = &'g Grant>) -> Self {
Self {
grantees,
grants: grants.into_iter().collect(),
owns: Vec::new(),
own_records: Vec::new(),
held_off: Vec::new(),
cap: None,
delegated: Vec::new(),
narrowing: Vec::new(),
}
}
#[must_use]
pub const fn capped(mut self, cap: Cap) -> Self {
self.cap = Some(cap);
self
}
#[must_use]
pub fn owning(mut self, node: TreePath) -> Self {
self.owns.push(node);
self
}
#[must_use]
pub fn owning_records(mut self, records: Vec<(TreePath, KindSet)>) -> Self {
self.own_records.extend(records);
self
}
#[must_use]
pub fn held_off_by(mut self, denies: impl IntoIterator<Item = &'g Grant>) -> Self {
self.held_off.extend(
denies
.into_iter()
.filter(|grant| grant.answer == Answer::Deny),
);
self
}
#[must_use]
pub fn with_grants(mut self, grants: impl IntoIterator<Item = &'g Grant>) -> Self {
self.grants.extend(grants);
self
}
#[must_use]
pub fn narrowed_by(
mut self,
grants: impl IntoIterator<Item = &'g Grant>,
answers: impl IntoIterator<Item = &'g Grant>,
) -> Self {
self.delegated.extend(grants);
self.narrowing.extend(answers);
self
}
#[must_use]
pub fn decide(&self, node: &TreePath, kind: ActionKind, cx: &Context<'_>) -> Decision<'g> {
let held = self.decide_grants(node, kind, cx);
match self.cap {
Some(cap) => {
let answer = cap.answer(node, kind);
if answer < held.answer {
Decision {
answer,
basis: Basis::Capped(cap),
}
} else {
held
}
}
None => held,
}
}
fn decide_grants(&self, node: &TreePath, kind: ActionKind, cx: &Context<'_>) -> Decision<'g> {
let node = &*crate::roles::decided_node(node);
if kind == ActionKind::Read && crate::roles::in_unread_record(node) {
return Decision {
answer: Answer::Deny,
basis: Basis::NoGrant,
};
}
let device_settings = crate::roles::is_device_settings(node);
if !device_settings
&& !crate::roles::in_private_record(node)
&& self.owns.iter().any(|owned| cx.covers(owned, node))
{
return Decision {
answer: Answer::Allow,
basis: Basis::Owner,
};
}
if let Some(deny) = self.held_off.iter().copied().find(|grant| {
grant.kinds.contains(kind) && cx.covers(&grant.node, node) && grant.is_live(cx)
}) {
return Decision {
answer: Answer::Deny,
basis: Basis::Grant(deny),
};
}
if device_settings {
if self.owns_device_settings(node) {
return Decision {
answer: Answer::Allow,
basis: Basis::OwnRecord,
};
}
let shared = self
.deciding(cx)
.filter(|grant| grant.grantee.as_member().is_some());
return decide(shared, &self.grantees, node, kind, cx);
}
if self
.own_records
.iter()
.any(|(own, kinds)| kinds.contains(kind) && cx.covers(own, node))
{
return Decision {
answer: Answer::Allow,
basis: Basis::OwnRecord,
};
}
decide(self.deciding(cx), &self.grantees, node, kind, cx)
}
fn owns_device_settings(&self, node: &TreePath) -> bool {
let Some(workspace) = node.id_at(Level::Workspace) else {
return false;
};
self.grantees
.iter()
.filter_map(Grantee::person_id)
.any(|person| {
crate::roles::workspace_of_person(person).is_some_and(|own| own == workspace)
})
}
fn deciding<'s>(&'s self, cx: &'s Context<'_>) -> impl Iterator<Item = &'g Grant> + 's {
let narrowed = self.narrowing.iter().any(|answer| answer.is_live(cx));
let delegated: &[&'g Grant] = if narrowed { &[] } else { &self.delegated };
self.grants
.iter()
.chain(delegated)
.copied()
.filter(move |grant| names(grant, &self.grantees, cx))
}
fn effective(&self) -> EffectiveParty {
let cx = Context::at(0);
EffectiveParty {
grantees: self.grantees.clone(),
grants: self.deciding(&cx).cloned().collect(),
owns: self.owns.clone(),
own_records: self.own_records.clone(),
held_off: self.held_off.iter().copied().cloned().collect(),
cap: self.cap,
delegated: self.delegated.iter().copied().cloned().collect(),
narrowing: self.narrowing.iter().copied().cloned().collect(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Effective {
parties: Vec<EffectiveParty>,
people: usize,
app: Option<AppId>,
app_kinds: Option<Vec<String>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct EffectiveParty {
grantees: Vec<Grantee>,
grants: Vec<Grant>,
owns: Vec<TreePath>,
own_records: Vec<(TreePath, KindSet)>,
held_off: Vec<Grant>,
cap: Option<Cap>,
delegated: Vec<Grant>,
narrowing: Vec<Grant>,
}
#[derive(Clone, Debug, Default)]
pub struct Authority<'g> {
pub person: Party<'g>,
pub bounds: Vec<Party<'g>>,
pub people: usize,
pub app: Option<&'g AppId>,
pub app_kinds: Option<&'g [String]>,
}
impl<'g> Authority<'g> {
#[must_use]
pub const fn person(person: Party<'g>) -> Self {
Self {
person,
bounds: Vec::new(),
people: 1,
app: None,
app_kinds: None,
}
}
#[must_use]
pub fn in_app(mut self, kinds: &'g [String]) -> Self {
self.app_kinds = Some(kinds);
self
}
#[must_use]
pub fn bounded_by(mut self, bound: Party<'g>) -> Self {
self.bounds.push(bound);
self
}
#[must_use]
pub fn effective(&self) -> Effective {
Effective {
parties: std::iter::once(&self.person)
.chain(&self.bounds)
.map(Party::effective)
.collect(),
people: self.people,
app: self.app.cloned(),
app_kinds: self.app_kinds.map(<[String]>::to_vec),
}
}
#[must_use]
pub fn decide(&self, node: &TreePath, kind: ActionKind, cx: &Context<'_>) -> Verdict<'g> {
let mut parts = Vec::with_capacity(self.bounds.len().saturating_add(1));
parts.push(self.person.decide(node, kind, cx));
parts.extend(self.bounds.iter().map(|bound| bound.decide(node, kind, cx)));
let mut answer = if self.answers_in_advance(&parts) {
Answer::Allow
} else {
parts
.iter()
.map(|part| part.answer)
.min()
.unwrap_or(Answer::Deny)
};
if self.unowned_actor_reads_own_record(node, kind) {
answer = Answer::Deny;
}
if let (Some(app), Some(kinds)) = (self.app, self.app_kinds)
&& node.id_at(Level::App) == Some(app.as_str())
&& match node.id_at(Level::Kind) {
Some(of) => !kinds.iter().any(|declared| declared == of),
None => node.id_at(Level::Resource).is_none(),
}
{
answer = Answer::Deny;
}
Verdict {
answer,
node: node.clone(),
kind,
parts,
people: self.people,
}
}
}
impl Authority<'_> {
#[must_use]
pub fn acts_within(&self, node: &TreePath, cx: &Context<'_>) -> bool {
let allows = |at: &TreePath| {
[ActionKind::Read, ActionKind::Undoable]
.into_iter()
.any(|kind| self.decide(at, kind, cx).answer == Answer::Allow)
};
allows(node)
|| std::iter::once(&self.person)
.chain(&self.bounds)
.flat_map(|party| party.deciding(cx))
.filter(|grant| grant.answer == Answer::Allow && grant.is_live(cx))
.filter_map(|grant| node.toward(&grant.node))
.any(|at| allows(&at))
}
fn unowned_actor_reads_own_record(&self, node: &TreePath, kind: ActionKind) -> bool {
kind == ActionKind::Read
&& self.people == 0
&& crate::roles::in_private_record(&crate::roles::decided_node(node))
}
#[must_use]
pub fn answer(
&self,
node: &TreePath,
kind: ActionKind,
privileged: bool,
cx: &Context<'_>,
) -> Answer {
if self.unowned_actor_reads_own_record(node, kind) {
return Answer::Deny;
}
let person = self.person.decide(node, kind, cx).answer;
if privileged && self.people <= 1 && person == Answer::Ask {
return Answer::Deny;
}
if privileged
&& self
.bounds
.iter()
.take(self.people.saturating_sub(1))
.any(|bound| bound.decide(node, kind, cx).answer == Answer::Ask)
{
return Answer::Deny;
}
if person == Answer::Ask
&& let [bound] = self.bounds.as_slice()
{
let parts = [
Decision {
answer: person,
basis: Basis::NoGrant,
},
bound.decide(node, kind, cx),
];
if self.answers_in_advance(&parts) {
return Answer::Allow;
}
}
self.bounds
.iter()
.map(|bound| bound.decide(node, kind, cx).answer)
.fold(person, Answer::min)
}
#[must_use]
pub fn answered_in_advance(&self, verdict: &Verdict<'_>) -> bool {
verdict.parts.iter().skip(self.people.max(1)).any(|part| {
part.answer == Answer::Allow
&& matches!(part.basis, Basis::Grant(grant)
if set_by_its_person(grant)
&& self.person.grantees.contains(&grant.granted_by)
&& matches!(
crate::agent_answers::AnswerScope::of_node(&grant.node),
Some(
crate::agent_answers::AnswerScope::Action { .. }
| crate::agent_answers::AnswerScope::Resource { .. }
)
))
})
}
fn answers_in_advance(&self, parts: &[Decision<'_>]) -> bool {
let [person, agent] = parts else {
return false;
};
self.people == 1
&& person.answer == Answer::Ask
&& agent.answer == Answer::Allow
&& matches!(agent.basis, Basis::Grant(grant)
if set_by_its_person(grant)
&& self.person.grantees.contains(&grant.granted_by)
&& matches!(
crate::agent_answers::AnswerScope::of_node(&grant.node),
Some(
crate::agent_answers::AnswerScope::Action { .. }
| crate::agent_answers::AnswerScope::Resource { .. }
)
))
}
}
fn set_by_its_person(grant: &Grant) -> bool {
crate::agent_answers::is_answer(grant)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Refuser {
Settings,
Workspace,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Verdict<'g> {
pub answer: Answer,
pub node: TreePath,
pub kind: ActionKind,
pub parts: Vec<Decision<'g>>,
pub people: usize,
}
impl<'g> Verdict<'g> {
#[must_use]
pub fn privileged(mut self) -> Self {
if self
.parts
.iter()
.take(self.people.max(1))
.any(|person| person.answer == Answer::Ask)
{
self.answer = Answer::Deny;
}
self
}
pub fn once_grants(&self) -> impl Iterator<Item = &'g Grant> + '_ {
self.parts
.iter()
.filter_map(Decision::grant)
.filter(|grant| grant.lifetime == Lifetime::Once)
}
#[must_use]
pub fn spent(&self) -> Vec<GrantId> {
if self.answer == Answer::Deny {
return Vec::new();
}
self.once_grants().map(|grant| grant.id.clone()).collect()
}
#[must_use]
pub fn refused_by(&self) -> Option<Refuser> {
if self.answer != Answer::Deny {
return None;
}
let denies = |part: &&Decision<'_>| part.answer == Answer::Deny;
if self
.parts
.iter()
.take(self.people)
.any(|part| denies(&part))
{
return Some(Refuser::Workspace);
}
let mut delegations = self
.parts
.iter()
.skip(self.people)
.filter(denies)
.peekable();
let settings = delegations.peek().is_some()
&& delegations.all(|part| part.grant().is_some_and(set_by_its_person));
Some(if settings {
Refuser::Settings
} else {
Refuser::Workspace
})
}
#[must_use]
pub fn deciding(&self) -> Option<&Decision<'g>> {
self.parts.iter().find(|part| part.answer == self.answer)
}
#[must_use]
pub fn explain(&self) -> String {
let outcome = match self.answer {
Answer::Allow => "Allowed",
Answer::Ask => "Asks first",
Answer::Deny => "Not allowed",
};
let who = |index: usize| {
if index < self.people {
"the person's grants".to_owned()
} else {
"the grants of those acting for them".to_owned()
}
};
let index = self
.parts
.iter()
.position(|part| part.answer == self.answer)
.unwrap_or(0);
let reason = match self.parts.get(index).map(|part| part.basis) {
Some(Basis::Owner) => "the person owns the workspace".to_owned(),
Some(Basis::OwnRecord) => format!("{} is theirs alone", self.node),
Some(Basis::Capped(cap) | Basis::RootOnly(cap)) => cap.why.to_owned(),
Some(Basis::Grant(grant)) => format!(
"{} give {} on {} the answer \"{}\" (grant {})",
who(index),
self.kind.phrase(),
grant.node,
grant.answer,
grant.id
),
Some(Basis::NoGrant) | None => {
format!(
"{} do not cover {} on {}",
who(index),
self.kind.phrase(),
self.node
)
}
};
format!("{outcome}: {reason}.")
}
}