use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::jsonrpc::{ConnectionContext, Router, RpcError};
use super::session::PermissionBroker;
pub const PERMISSION_RESPOND_METHOD: &str = "session.permission.respond";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PermissionDecision {
AllowOnce,
AllowForSession { pattern: Option<String> },
Deny,
}
impl PermissionDecision {
pub fn as_str(&self) -> &'static str {
match self {
Self::AllowOnce => "allow_once",
Self::AllowForSession { .. } => "allow_for_session",
Self::Deny => "deny",
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct PermissionRespondParams {
pub session_id: String,
pub request_id: String,
pub decision: String,
#[serde(default)]
pub pattern: Option<String>,
}
impl PermissionRespondParams {
pub fn decision(&self) -> Result<PermissionDecision, RpcError> {
match self.decision.as_str() {
"allow_once" => Ok(PermissionDecision::AllowOnce),
"allow_for_session" => Ok(PermissionDecision::AllowForSession {
pattern: self.pattern.clone(),
}),
"deny" => Ok(PermissionDecision::Deny),
other => Err(RpcError::invalid_params(format!(
"unknown permission decision '{other}' — expected one of \
allow_once, allow_for_session, deny"
))),
}
}
}
pub fn register(router: &mut Router, broker: Arc<PermissionBroker>) {
router.register(
PERMISSION_RESPOND_METHOD,
move |params: Value, _ctx: ConnectionContext| {
let broker = Arc::clone(&broker);
async move {
let params: PermissionRespondParams =
serde_json::from_value(params).map_err(|e| {
RpcError::invalid_params(format!("{PERMISSION_RESPOND_METHOD}: {e}"))
})?;
let decision = params.decision()?;
broker.respond(¶ms.session_id, ¶ms.request_id, decision)?;
Ok(json!({"accepted": true}))
}
},
);
}