use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use tokio::sync::oneshot;
use crate::jsonrpc::RpcError;
use super::config::CompiledGlob;
use super::protocol::PermissionDecision;
enum AllowanceSubject {
Any,
Literal(String),
Glob(CompiledGlob),
}
impl AllowanceSubject {
fn matches(&self, subject: Option<&str>) -> bool {
match (self, subject) {
(Self::Any, _) => true,
(Self::Literal(literal), Some(s)) => literal == s,
(Self::Glob(glob), Some(s)) => glob.is_match(s),
(Self::Literal(_) | Self::Glob(_), None) => false,
}
}
}
struct Allowance {
tool: String,
subject: AllowanceSubject,
}
#[derive(Default)]
pub struct SessionPermissions {
pending: Mutex<HashMap<String, oneshot::Sender<PermissionDecision>>>,
remembered: Mutex<Vec<Allowance>>,
}
impl SessionPermissions {
pub(crate) fn register(&self, request_id: &str) -> oneshot::Receiver<PermissionDecision> {
let (tx, rx) = oneshot::channel();
if let Ok(mut pending) = self.pending.lock() {
pending.insert(request_id.to_string(), tx);
}
rx
}
pub(crate) fn forget(&self, request_id: &str) {
if let Ok(mut pending) = self.pending.lock() {
pending.remove(request_id);
}
}
pub fn respond(&self, request_id: &str, decision: PermissionDecision) -> Result<(), RpcError> {
let sender = self
.pending
.lock()
.ok()
.and_then(|mut pending| pending.remove(request_id));
let Some(sender) = sender else {
return Err(RpcError::invalid_params(format!(
"no pending permission request with id '{request_id}'"
)));
};
sender.send(decision).map_err(|_| {
RpcError::internal(format!(
"permission request '{request_id}' is no longer awaited"
))
})
}
pub(crate) fn is_remembered(&self, tool: &str, subjects: &[String]) -> bool {
let Ok(remembered) = self.remembered.lock() else {
return false;
};
let covered = |subject: Option<&str>| {
remembered
.iter()
.any(|a| a.tool == tool && a.subject.matches(subject))
};
if subjects.is_empty() {
covered(None)
} else {
subjects.iter().all(|s| covered(Some(s)))
}
}
pub(crate) fn remember(&self, tool: &str, subjects: &[String], pattern: Option<&str>) {
let grants: Vec<AllowanceSubject> = match pattern {
Some(p) => match CompiledGlob::compile(p) {
Ok(glob) => vec![AllowanceSubject::Glob(glob)],
Err(reason) => {
tracing::warn!(
tool = %tool,
pattern = %p,
"permission: allow-for-session pattern is not a valid glob ({reason}) — \
allowing this call but remembering nothing"
);
return;
}
},
None if subjects.is_empty() => vec![AllowanceSubject::Any],
None => subjects
.iter()
.map(|s| AllowanceSubject::Literal(s.clone()))
.collect(),
};
if let Ok(mut remembered) = self.remembered.lock() {
remembered.extend(grants.into_iter().map(|subject| Allowance {
tool: tool.to_string(),
subject,
}));
}
}
}
#[derive(Default)]
pub struct PermissionBroker {
sessions: Mutex<HashMap<String, Arc<SessionPermissions>>>,
}
impl std::fmt::Debug for PermissionBroker {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let sessions = self.sessions.lock().map(|s| s.len()).unwrap_or(0);
f.debug_struct("PermissionBroker")
.field("sessions", &sessions)
.finish()
}
}
impl PermissionBroker {
pub fn new() -> Self {
Self::default()
}
pub fn session(&self, session_id: &str) -> Arc<SessionPermissions> {
let mut sessions = self
.sessions
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
Arc::clone(
sessions
.entry(session_id.to_string())
.or_insert_with(|| Arc::new(SessionPermissions::default())),
)
}
pub fn respond(
&self,
session_id: &str,
request_id: &str,
decision: PermissionDecision,
) -> Result<(), RpcError> {
let existing = self
.sessions
.lock()
.ok()
.and_then(|sessions| sessions.get(session_id).cloned());
match existing {
Some(state) => state.respond(request_id, decision),
None => Err(RpcError::invalid_params(format!(
"session '{session_id}' has no pending permission requests"
))),
}
}
}