use std::{
fmt,
path::{Path, PathBuf},
};
use rho_protocol::ClientEnvironment;
use crate::caller_context::{Access, CallerContext, Scope, Workspaces};
pub(crate) const DEFAULT_MAX_DEPTH: u32 = 3;
pub(crate) const DEFAULT_MAX_SESSIONS: u32 = crate::config::DEFAULT_AGENT_CONCURRENCY as u32;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum Action {
List,
Read,
New,
Prompt,
Steer,
Cancel,
Wait,
}
impl Action {
pub(crate) const ALL: [Self; 7] = [
Self::List,
Self::Read,
Self::New,
Self::Prompt,
Self::Steer,
Self::Cancel,
Self::Wait,
];
pub(crate) fn name(self) -> &'static str {
match self {
Self::List => "list",
Self::Read => "read",
Self::New => "new",
Self::Prompt => "prompt",
Self::Steer => "steer",
Self::Cancel => "cancel",
Self::Wait => "wait",
}
}
pub(crate) fn from_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|action| action.name() == name)
}
pub(crate) fn needs(self) -> Access {
match self {
Self::List | Self::Read | Self::Wait => Access::Read,
Self::New | Self::Prompt | Self::Steer | Self::Cancel => Access::Write,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) enum Holder {
Local,
Token(String),
Session(rho_protocol::SessionId),
}
impl fmt::Display for Holder {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Local => formatter.write_str("this server's caller"),
Self::Token(name) => write!(formatter, "token {name:?}"),
Self::Session(session) => write!(formatter, "session {session}"),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Grant {
pub(crate) holder: Holder,
pub(crate) scope: Scope,
}
impl Grant {
pub(crate) fn local(access: Access) -> Self {
Self {
holder: Holder::Local,
scope: Scope {
access,
workspaces: Workspaces::Any,
},
}
}
pub(crate) fn permit(&self, action: Action) -> Result<(), Refusal> {
if self.scope.access >= action.needs() {
return Ok(());
}
Err(Refusal::Access {
holder: self.holder.clone(),
action,
has: self.scope.access,
})
}
pub(crate) fn reach(&self, workspace: &Path) -> Result<(), Refusal> {
match &self.scope.workspaces {
Workspaces::Only(allowed) if !self.scope.workspaces.allows(workspace) => {
Err(Refusal::Workspace {
holder: self.holder.clone(),
workspace: workspace.to_path_buf(),
allowed: allowed.clone(),
})
}
_ => Ok(()),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Caller {
pub(crate) grant: Grant,
pub(crate) depth: u32,
pub(crate) session: Option<rho_protocol::SessionId>,
pub(crate) environment: ClientEnvironment,
}
impl Caller {
pub(crate) fn new(
grant: Grant,
context: &CallerContext,
environment: ClientEnvironment,
) -> Self {
Self {
grant: Grant {
scope: grant.scope.intersect(&context.scope),
..grant
},
depth: context.depth,
session: None,
environment,
}
}
pub(crate) fn session(
session: rho_protocol::SessionId,
context: &CallerContext,
environment: ClientEnvironment,
) -> Self {
let grant = Grant {
holder: Holder::Session(session.clone()),
scope: Scope::FULL,
};
Self {
session: Some(session),
..Self::new(grant, context, environment)
}
}
pub(crate) fn child_context(&self) -> CallerContext {
CallerContext {
depth: self.depth.saturating_add(1),
scope: self.grant.scope.clone(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Limits {
pub(crate) max_depth: u32,
pub(crate) max_sessions: u32,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_depth: DEFAULT_MAX_DEPTH,
max_sessions: DEFAULT_MAX_SESSIONS,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub(crate) enum Refusal {
#[error(
"{holder} has {} access; `{}` needs {}",
has.name(),
action.name(),
action.needs().name()
)]
Access {
holder: Holder,
action: Action,
has: Access,
},
#[error(
"{holder} may not reach workspace {}; it may reach: {}",
workspace.display(),
list_paths(allowed)
)]
Workspace {
holder: Holder,
workspace: PathBuf,
allowed: Vec<PathBuf>,
},
#[error(
"session depth budget: limit {limit}, asked {asked}; a session at depth {} may not start or prompt another",
asked - 1
)]
Depth { limit: u32, asked: u32 },
#[error("concurrent sessions budget for {holder}: limit {limit}, asked {asked}")]
Sessions {
holder: Holder,
limit: u32,
asked: u32,
},
}
fn list_paths(paths: &[PathBuf]) -> String {
if paths.is_empty() {
return "no workspace".to_owned();
}
paths
.iter()
.map(|path| path.display().to_string())
.collect::<Vec<_>>()
.join(", ")
}
#[cfg(test)]
#[path = "policy_tests.rs"]
mod tests;