Skip to main content

trusty_code/permissions/
protocol.rs

1//! The `session.permission.respond` JSON-RPC method and its wire types
2//! (#7948).
3//!
4//! Why: an `ask` rule suspends a tool call inside a spawned task; a client
5//! releases it with this request. It lives beside the gate because it writes
6//! into the permission broker, not the session registry.
7//! What: `PermissionDecision` (the three answers), `PermissionRespondParams`
8//! (the flat wire shape), and `register`.
9//!
10//! Trust model (#7948): `session.permission.respond` accepts an answer for ANY
11//! session from ANY connection that can reach the daemon's RPC surface. It
12//! checks neither that the caller is attached to the session nor who the
13//! caller is. This matches every other RPC method today. Revisit it before the
14//! daemon serves more than one tenant.
15//! Test: `permissions::tests::protocol_tests` — the whole module.
16
17use std::sync::Arc;
18
19use serde::{Deserialize, Serialize};
20use serde_json::{Value, json};
21
22use crate::jsonrpc::{ConnectionContext, Router, RpcError};
23
24use super::session::PermissionBroker;
25
26/// The JSON-RPC method name clients call to answer a permission request.
27pub const PERMISSION_RESPOND_METHOD: &str = "session.permission.respond";
28
29/// A client's answer to one `Event::PermissionRequested`.
30///
31/// Why: "yes, once" and "yes, stop asking for this" are the pair every
32/// interactive prompt offers; collapsing them either nags or over-grants.
33/// What: `AllowForSession.pattern` is the client's choice of grant width;
34/// absent, the grant covers exactly the subject that was asked about. Grants
35/// die with the session.
36/// Test: `decision_from_params_maps_every_word`.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "snake_case")]
39pub enum PermissionDecision {
40    AllowOnce,
41    AllowForSession { pattern: Option<String> },
42    Deny,
43}
44
45impl PermissionDecision {
46    /// The stable wire word for this decision.
47    /// Test: `decision_from_params_maps_every_word`.
48    pub fn as_str(&self) -> &'static str {
49        match self {
50            Self::AllowOnce => "allow_once",
51            Self::AllowForSession { .. } => "allow_for_session",
52            Self::Deny => "deny",
53        }
54    }
55}
56
57/// `session.permission.respond`'s parameters.
58///
59/// What: `session_id`/`request_id` come off the rendered
60/// `Event::PermissionRequested`; `decision` is `allow_once` |
61/// `allow_for_session` | `deny`; `pattern` applies only to `allow_for_session`.
62/// Test: `respond_rejects_an_unknown_decision_word`,
63/// `respond_resolves_a_pending_request`.
64#[derive(Debug, Clone, Deserialize)]
65pub struct PermissionRespondParams {
66    pub session_id: String,
67    pub request_id: String,
68    pub decision: String,
69    #[serde(default)]
70    pub pattern: Option<String>,
71}
72
73impl PermissionRespondParams {
74    /// Map the flat wire words onto a [`PermissionDecision`]; an unknown word
75    /// is `-32602`, never a guessed allow or deny.
76    /// Test: `decision_from_params_maps_every_word`,
77    /// `respond_rejects_an_unknown_decision_word`.
78    pub fn decision(&self) -> Result<PermissionDecision, RpcError> {
79        match self.decision.as_str() {
80            "allow_once" => Ok(PermissionDecision::AllowOnce),
81            "allow_for_session" => Ok(PermissionDecision::AllowForSession {
82                pattern: self.pattern.clone(),
83            }),
84            "deny" => Ok(PermissionDecision::Deny),
85            other => Err(RpcError::invalid_params(format!(
86                "unknown permission decision '{other}' — expected one of \
87                 allow_once, allow_for_session, deny"
88            ))),
89        }
90    }
91}
92
93/// Register `session.permission.respond` onto `router`.
94///
95/// Why: one call in `crate::serve::build_router`, closed over the daemon's
96/// single broker.
97/// What: parses the params, maps the decision, and hands it to the broker. A
98/// request id nobody waits on (already answered, or timed out) is `-32602`.
99/// Test: `register_wires_the_respond_method`,
100/// `respond_rejects_an_unknown_request_id`.
101pub fn register(router: &mut Router, broker: Arc<PermissionBroker>) {
102    router.register(
103        PERMISSION_RESPOND_METHOD,
104        move |params: Value, _ctx: ConnectionContext| {
105            let broker = Arc::clone(&broker);
106            async move {
107                let params: PermissionRespondParams =
108                    serde_json::from_value(params).map_err(|e| {
109                        RpcError::invalid_params(format!("{PERMISSION_RESPOND_METHOD}: {e}"))
110                    })?;
111                let decision = params.decision()?;
112                broker.respond(&params.session_id, &params.request_id, decision)?;
113                Ok(json!({"accepted": true}))
114            }
115        },
116    );
117}