trusty_code/permissions/session.rs
1//! Per-session permission state and the daemon-wide broker (#7948).
2//!
3//! Why: an `ask` suspends a tool call inside a spawned task, while the answer
4//! arrives on a JSON-RPC connection that knows only a session id. Both sides
5//! need one shared rendezvous, and `allow_for_session` grants must live exactly
6//! as long as the session that granted them.
7//! What: `SessionPermissions` (pending requests plus remembered grants) and
8//! `PermissionBroker` (session id -> `SessionPermissions`).
9//! Test: `permissions::tests::gate_tests`, `permissions::tests::protocol_tests`.
10
11use std::collections::HashMap;
12use std::sync::{Arc, Mutex};
13
14use tokio::sync::oneshot;
15
16use crate::jsonrpc::RpcError;
17
18use super::config::CompiledGlob;
19use super::protocol::PermissionDecision;
20
21/// What a remembered `allow_for_session` grant covers.
22///
23/// Why: a bare grant covers exactly the subject that was asked about, and a
24/// client pattern covers a glob. Keeping them separate avoids escaping a
25/// literal into a glob, which is easy to get wrong in the widening direction.
26enum AllowanceSubject {
27 /// A grant for a call with no subject (an MCP tool).
28 Any,
29 Literal(String),
30 Glob(CompiledGlob),
31}
32
33impl AllowanceSubject {
34 fn matches(&self, subject: Option<&str>) -> bool {
35 match (self, subject) {
36 (Self::Any, _) => true,
37 (Self::Literal(literal), Some(s)) => literal == s,
38 (Self::Glob(glob), Some(s)) => glob.is_match(s),
39 (Self::Literal(_) | Self::Glob(_), None) => false,
40 }
41 }
42}
43
44/// One remembered `allow_for_session` grant.
45struct Allowance {
46 tool: String,
47 subject: AllowanceSubject,
48}
49
50/// One session's live permission state.
51///
52/// Why: reached from the agent loop (which waits) and from
53/// `session.permission.respond` (which answers); sharing one `Arc` is the
54/// whole mechanism.
55/// What: `pending` maps a request id to the sender the waiting gate holds;
56/// `remembered` holds this session's grants and is never shared across
57/// sessions. A poisoned lock never widens: registration drops the sender (the
58/// waiting gate resolves to deny) and a remembered-grant lookup reports "not
59/// remembered" (the call is asked about again).
60/// Test: `allow_for_session_is_remembered_for_a_later_matching_call`,
61/// `allow_for_session_does_not_leak_across_sessions`,
62/// `abandoned_request_resolves_to_deny`.
63#[derive(Default)]
64pub struct SessionPermissions {
65 pending: Mutex<HashMap<String, oneshot::Sender<PermissionDecision>>>,
66 remembered: Mutex<Vec<Allowance>>,
67}
68
69impl SessionPermissions {
70 /// Register a request and hand back the receiver the gate awaits.
71 pub(crate) fn register(&self, request_id: &str) -> oneshot::Receiver<PermissionDecision> {
72 let (tx, rx) = oneshot::channel();
73 if let Ok(mut pending) = self.pending.lock() {
74 pending.insert(request_id.to_string(), tx);
75 }
76 rx
77 }
78
79 /// Drop a request that is no longer awaited (timeout path).
80 pub(crate) fn forget(&self, request_id: &str) {
81 if let Ok(mut pending) = self.pending.lock() {
82 pending.remove(request_id);
83 }
84 }
85
86 /// Deliver a client's answer to the waiting gate.
87 ///
88 /// Why: a request id nobody waits on (already answered, or timed out) is a
89 /// client error, not an internal one.
90 /// Test: `respond_to_unknown_request_is_an_error`,
91 /// `respond_resolves_the_waiting_gate`.
92 pub fn respond(&self, request_id: &str, decision: PermissionDecision) -> Result<(), RpcError> {
93 let sender = self
94 .pending
95 .lock()
96 .ok()
97 .and_then(|mut pending| pending.remove(request_id));
98 let Some(sender) = sender else {
99 return Err(RpcError::invalid_params(format!(
100 "no pending permission request with id '{request_id}'"
101 )));
102 };
103 sender.send(decision).map_err(|_| {
104 RpcError::internal(format!(
105 "permission request '{request_id}' is no longer awaited"
106 ))
107 })
108 }
109
110 /// Whether earlier grants cover this call — EVERY subject must be covered.
111 pub(crate) fn is_remembered(&self, tool: &str, subjects: &[String]) -> bool {
112 let Ok(remembered) = self.remembered.lock() else {
113 return false;
114 };
115 let covered = |subject: Option<&str>| {
116 remembered
117 .iter()
118 .any(|a| a.tool == tool && a.subject.matches(subject))
119 };
120 if subjects.is_empty() {
121 covered(None)
122 } else {
123 subjects.iter().all(|s| covered(Some(s)))
124 }
125 }
126
127 /// Record an `allow_for_session` grant.
128 ///
129 /// Why: `pattern` is the client's choice of how wide the grant is. An
130 /// absent pattern grants exactly this call's subjects and nothing else.
131 /// What: an uncompilable pattern is dropped with a warning — the approval
132 /// still stands for THIS call, it is simply not remembered.
133 /// Test: `bare_allow_for_session_grants_only_that_subject`,
134 /// `allow_for_session_pattern_grants_the_glob`,
135 /// `unusable_allow_for_session_pattern_remembers_nothing`.
136 pub(crate) fn remember(&self, tool: &str, subjects: &[String], pattern: Option<&str>) {
137 let grants: Vec<AllowanceSubject> = match pattern {
138 Some(p) => match CompiledGlob::compile(p) {
139 Ok(glob) => vec![AllowanceSubject::Glob(glob)],
140 Err(reason) => {
141 tracing::warn!(
142 tool = %tool,
143 pattern = %p,
144 "permission: allow-for-session pattern is not a valid glob ({reason}) — \
145 allowing this call but remembering nothing"
146 );
147 return;
148 }
149 },
150 None if subjects.is_empty() => vec![AllowanceSubject::Any],
151 None => subjects
152 .iter()
153 .map(|s| AllowanceSubject::Literal(s.clone()))
154 .collect(),
155 };
156 if let Ok(mut remembered) = self.remembered.lock() {
157 remembered.extend(grants.into_iter().map(|subject| Allowance {
158 tool: tool.to_string(),
159 subject,
160 }));
161 }
162 }
163}
164
165/// The daemon-wide map of per-session permission state.
166///
167/// Why: the rendezvous between a waiting gate and `session.permission.respond`.
168/// Built once in `crate::serve::build_router` and cloned where needed (like
169/// `SharedWorkstreamStore`) rather than a process-global, so a test builds its own.
170/// Test: `permissions::tests::protocol_tests`.
171#[derive(Default)]
172pub struct PermissionBroker {
173 sessions: Mutex<HashMap<String, Arc<SessionPermissions>>>,
174}
175
176/// Opaque `Debug`: reports only how many sessions hold state, so formatting a
177/// struct that carries the broker never prints an unapproved subject.
178impl std::fmt::Debug for PermissionBroker {
179 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180 let sessions = self.sessions.lock().map(|s| s.len()).unwrap_or(0);
181 f.debug_struct("PermissionBroker")
182 .field("sessions", &sessions)
183 .finish()
184 }
185}
186
187impl PermissionBroker {
188 /// Construct an empty broker.
189 pub fn new() -> Self {
190 Self::default()
191 }
192
193 /// This session's state, created on first use, so a session that never
194 /// asks never allocates.
195 /// Test: `broker_hands_the_same_state_back_for_one_session`.
196 pub fn session(&self, session_id: &str) -> Arc<SessionPermissions> {
197 let mut sessions = self
198 .sessions
199 .lock()
200 .unwrap_or_else(std::sync::PoisonError::into_inner);
201 Arc::clone(
202 sessions
203 .entry(session_id.to_string())
204 .or_insert_with(|| Arc::new(SessionPermissions::default())),
205 )
206 }
207
208 /// Answer a pending request for `session_id`.
209 /// Test: `respond_to_unknown_session_is_an_error`.
210 pub fn respond(
211 &self,
212 session_id: &str,
213 request_id: &str,
214 decision: PermissionDecision,
215 ) -> Result<(), RpcError> {
216 let existing = self
217 .sessions
218 .lock()
219 .ok()
220 .and_then(|sessions| sessions.get(session_id).cloned());
221 match existing {
222 Some(state) => state.respond(request_id, decision),
223 None => Err(RpcError::invalid_params(format!(
224 "session '{session_id}' has no pending permission requests"
225 ))),
226 }
227 }
228}