use crate::{
ActionKind, Answer, Basis, Decision, Grant, GrantId, Grantee, KindSet, Level, TreePath,
};
pub const PREFIX: &str = "agent-answer:";
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum AnswerScope {
Workspace,
App { app: String },
Kind { app: String, kind: String },
Action {
app: String,
kind: String,
action: String,
},
Resource {
app: String,
kind: String,
resource: String,
action: String,
},
}
impl AnswerScope {
#[must_use]
pub fn app(app: impl Into<String>) -> Self {
Self::App { app: app.into() }
}
#[must_use]
pub fn kind(app: impl Into<String>, kind: impl Into<String>) -> Self {
Self::Kind {
app: app.into(),
kind: kind.into(),
}
}
#[must_use]
pub fn action(
app: impl Into<String>,
kind: impl Into<String>,
action: impl Into<String>,
) -> Self {
Self::Action {
app: app.into(),
kind: kind.into(),
action: action.into(),
}
}
#[must_use]
pub fn resource(
app: impl Into<String>,
kind: impl Into<String>,
resource: impl Into<String>,
action: impl Into<String>,
) -> Self {
Self::Resource {
app: app.into(),
kind: kind.into(),
resource: resource.into(),
action: action.into(),
}
}
#[must_use]
pub fn node(&self, workspace: &str) -> TreePath {
let workspace = TreePath::workspace(workspace);
match self {
Self::Workspace => workspace,
Self::App { app } => workspace.app(app),
Self::Kind { app, kind } => workspace.app(app).kind(kind),
Self::Action { app, kind, action } => {
workspace.app(app).kind(kind).rest().action(action)
}
Self::Resource {
app,
kind,
resource,
action,
} => workspace
.app(app)
.kind(kind)
.resource(resource)
.rest()
.action(action),
}
}
#[must_use]
pub fn of_node(node: &TreePath) -> Option<Self> {
use crate::Segment;
match node.segments() {
[Segment::Name(Level::Workspace, _)] => Some(Self::Workspace),
[
Segment::Name(Level::Workspace, _),
Segment::Name(Level::App, app),
] => Some(Self::app(app)),
[
Segment::Name(Level::Workspace, _),
Segment::Name(Level::App, app),
Segment::Name(Level::Kind, kind),
] => Some(Self::kind(app, kind)),
[
Segment::Name(Level::Workspace, _),
Segment::Name(Level::App, app),
Segment::Name(Level::Kind, kind),
Segment::Rest,
Segment::Name(Level::Action, action),
] => Some(Self::action(app, kind, action)),
[
Segment::Name(Level::Workspace, _),
Segment::Name(Level::App, app),
Segment::Name(Level::Kind, kind),
Segment::Name(Level::Resource, resource),
Segment::Rest,
Segment::Name(Level::Action, action),
] => Some(Self::resource(app, kind, resource, action)),
_ => None,
}
}
#[must_use]
pub fn key(&self) -> String {
match self {
Self::Workspace => "workspace".to_owned(),
Self::App { app } => format!("app:{app}"),
Self::Kind { app, kind } => format!("kind:{app}:{kind}"),
Self::Action { app, kind, action } => format!("action:{app}:{kind}:{action}"),
Self::Resource {
app,
kind,
resource,
action,
} => format!("resource:{app}:{kind}:{resource}:{action}"),
}
}
#[must_use]
pub fn parse(key: &str) -> Option<Self> {
if let Some(rest) = key.strip_prefix("resource:") {
let mut parts = rest.splitn(3, ':');
let (app, kind, rest) = (parts.next()?, parts.next()?, parts.next()?);
let (resource, action) = rest.rsplit_once(':')?;
return [app, kind, resource, action]
.iter()
.all(|part| !part.is_empty())
.then(|| Self::resource(app, kind, resource, action));
}
let mut parts = key.split(':');
match (
parts.next()?,
parts.next(),
parts.next(),
parts.next(),
parts.next(),
) {
("workspace", None, None, None, None) => Some(Self::Workspace),
("app", Some(app), None, None, None) if !app.is_empty() => Some(Self::app(app)),
("kind", Some(app), Some(kind), None, None) if !app.is_empty() && !kind.is_empty() => {
Some(Self::kind(app, kind))
}
("action", Some(app), Some(kind), Some(action), None)
if !app.is_empty() && !kind.is_empty() && !action.is_empty() =>
{
Some(Self::action(app, kind, action))
}
_ => None,
}
}
}
#[must_use]
pub fn grant_id(agent: &str, scope: &AnswerScope, kind: ActionKind) -> GrantId {
GrantId(format!("{PREFIX}{agent}:{}:{kind}", scope.key()))
}
#[must_use]
pub fn agent_key(agent: &str, person: &str) -> String {
format!("{person}/{agent}")
}
#[must_use]
pub fn stop_grant_id(agent: &str, person: &str) -> GrantId {
GrantId(format!(
"{PREFIX}{}:workspace:all",
agent_key(agent, person)
))
}
#[must_use]
#[track_caller]
pub fn stop_grant(workspace: &str, agent: &str, person: &str) -> Grant {
Grant::new(
stop_grant_id(agent, person).0,
Grantee::agent(agent, person),
AnswerScope::Workspace.node(workspace),
KindSet::ALL,
Answer::Deny,
Grantee::person(person),
)
}
#[must_use]
pub fn is_answer(grant: &Grant) -> bool {
let id = grant.id.as_str();
(id.starts_with(PREFIX)
&& matches!(
grant.grantee,
Grantee::Member(crate::MemberId::Agent { .. }) | Grantee::App(_)
))
|| crate::is_session_answer(grant)
}
#[must_use]
#[track_caller]
pub fn grant(
workspace: &str,
(agent, person): (&str, &str),
(scope, kind): (&AnswerScope, ActionKind),
answer: Answer,
granted_by: Grantee,
) -> Grant {
answer_grant(
workspace,
Grantee::agent(agent, person),
(scope, kind),
answer,
granted_by,
)
}
#[must_use]
pub fn answer_grant(
workspace: &str,
delegate: Grantee,
(scope, kind): (&AnswerScope, ActionKind),
answer: Answer,
granted_by: Grantee,
) -> Grant {
let key = match &delegate {
Grantee::Member(crate::MemberId::Agent { id, person }) => agent_key(id, person.as_str()),
Grantee::App(app) => format!("app:{app}"),
other => other.to_string(),
};
Grant::new(
grant_id(&key, scope, kind).0,
delegate,
scope.node(workspace),
KindSet::of(kind),
answer,
granted_by,
)
}
#[must_use]
pub const fn default_answer(kind: ActionKind, consequential: bool) -> Answer {
match kind {
_ if consequential => Answer::Ask,
ActionKind::Read | ActionKind::Undoable => Answer::Allow,
ActionKind::Outside => Answer::Ask,
}
}
pub const WORKSPACE_APP: &str = "tilo.workspace";
pub const ACCOUNT_APP: &str = "tilo.host";
#[must_use]
pub fn may_give(scope: Option<&AnswerScope>, kind: ActionKind, answer: Answer) -> bool {
kind != ActionKind::Outside
|| answer != Answer::Allow
|| scope.is_some_and(|scope| match scope {
AnswerScope::Action { .. } | AnswerScope::Resource { .. } => true,
AnswerScope::App { app } | AnswerScope::Kind { app, .. } => {
[ACCOUNT_APP, WORKSPACE_APP].contains(&app.as_str())
}
AnswerScope::Workspace => false,
})
}
#[must_use]
pub fn held_to_contract(decision: &Decision<'_>, consequential: bool) -> Answer {
if !consequential || decision.answer != Answer::Allow {
return decision.answer;
}
match decision.basis {
Basis::Grant(grant)
if is_answer(grant)
&& matches!(
AnswerScope::of_node(&grant.node),
Some(AnswerScope::Action { .. } | AnswerScope::Resource { .. })
) =>
{
Answer::Allow
}
_ => Answer::Ask,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_answer_on_one_resource_leaves_another_asking() {
let scope = AnswerScope::resource("browser", "site", "https://a.example", "download");
let node = scope.node("w");
let path = |site: &str| {
TreePath::workspace("w")
.app("browser")
.kind("site")
.resource(site)
.action("download")
};
assert!(node.covers(&path("https://a.example")));
assert!(!node.covers(&path("https://b.example")));
assert_eq!(AnswerScope::parse(&scope.key()), Some(scope.clone()));
assert_eq!(AnswerScope::of_node(&node), Some(scope.clone()));
assert!(may_give(Some(&scope), ActionKind::Outside, Answer::Allow));
assert!(!may_give(
Some(&AnswerScope::app("browser")),
ActionKind::Outside,
Answer::Allow
));
}
}