1use axum::body::Body;
24use axum::extract::{MatchedPath, State};
25use axum::http::{Method, Request, StatusCode};
26use axum::middleware::Next;
27use axum::response::{IntoResponse, Response};
28
29use super::caller::Caller;
30use super::route_table::{policy, Policy};
31use super::AppState;
32use crate::backend::rpc::action_record::{ActionRecord, Target};
33use crate::backend::rpc::actor::Actor;
34
35const SERVICE_ROUTE: &str = "/agentmux/service";
37const SERVICE_BODY_MAX: usize = 2 * 1024 * 1024;
40const SERVICE_REPLY_MAX: usize = 32 * 1024 * 1024;
42const MAX_FIELD: usize = 200;
43
44const QUIET: &[&str] = &[
47 "object.GetObject", "object.GetObjects",
48 "client.GetClientData", "client.GetTab", "client.GetAllConnStatus", "client.FocusWindow", "client.TelemetryUpdate",
49 "window.GetWindow", "window.FindWindowByLabel", "window.SaveSessionSnapshot", "window.TakeRestoredWindows",
50 "window.ListClosedWindows", "window.WindowAgents", "window.PlaceWindowSlots", "window.SetWindowPosAndSize",
51 "window.SetWindowOpacity", "window.SetWindowTopology", "window.MarkWindowOpen", "window.InheritWindowAppearance",
52 "workspace.GetWorkspace", "workspace.ListWorkspaces", "workspace.ListUserWorkspaces", "workspace.UserWorkspaceAgents",
53 "workspace.ExportUserWorkspace", "workspace.PreviewImport", "workspace.SetActiveTab", "workspace.Flush",
54 "block.GetControllerStatus", "block.SaveTerminalState", "block.SendCommand", "userinput.SendUserInputResponse",
55 "shell.ListActive", "cron.ListActive", "subagent.ListActive", "subagent.ListDispatches", "subagent.GetHistory",
56 "subagent.GetInfo", "history.List", "history.ListForAgent", "history.Get",
57];
58const META_WRITE: &str = "object.UpdateObjectMeta";
60const QUIET_META_KEYS: &[&str] = &[
63 "term:ambient_summary", "term:ambient_summary_at", "term:ambient_summary_turn", "term:osc_title", "term:restored_summary",
64 "term:last_prompt", "term:last_prompt_at", "term:human_turns", "term:next_prompt_suggestion", "term:next_prompt_suggestion_gen",
65 "term:question_timer", "term:awaiting_user", "term:awaiting_confirm", "cmd:cwd",
66];
67const QUIET_SERVICES: &[&str] = &["credential", "host_ipc"];
70
71#[derive(Debug, PartialEq)]
73enum Quiet {
74 No,
76 Always,
78 UnlessFailed,
80}
81
82struct ServiceCall {
84 names: String,
85 object: Option<String>,
86 keys: Option<Vec<String>>,
87}
88
89impl ServiceCall {
90 fn quiet(&self) -> Quiet {
92 if self.names == META_WRITE {
93 let quiet = self.keys.as_ref().is_some_and(|keys| !keys.is_empty() && keys.iter().all(|k| QUIET_META_KEYS.contains(&k.as_str())));
94 return if quiet { Quiet::Always } else { Quiet::No };
95 }
96 if QUIET.contains(&self.names.as_str()) {
97 Quiet::Always
98 } else if self.names.split_once('.').is_some_and(|(service, _)| QUIET_SERVICES.contains(&service)) {
99 Quiet::UnlessFailed
100 } else {
101 Quiet::No
102 }
103 }
104
105 fn subject(&self) -> String {
107 let mut subject = self.names.clone();
108 if let Some(object) = &self.object {
109 subject.push_str(&format!(" object={object}"));
110 }
111 if let Some(keys) = &self.keys {
112 subject.push_str(&format!(" keys={}", keys.join(",")));
113 }
114 subject
115 }
116}
117
118pub(crate) fn path_params(template: &str, path: &str) -> Vec<String> {
120 template
121 .split('/')
122 .zip(path.split('/'))
123 .filter_map(|(t, p)| t.strip_prefix(':').map(|name| (name, p)))
124 .filter(|(_, value)| !value.is_empty())
125 .map(|(name, value)| format!("{name}={}", value.chars().take(MAX_FIELD).collect::<String>()))
126 .collect()
127}
128
129fn service_call(body: &[u8]) -> Option<ServiceCall> {
131 let serde_json::Value::Object(fields) = serde_json::from_slice(body).ok()? else { return None };
132 let name = |key: &str| fields.get(key)?.as_str().map(|s| s.chars().take(MAX_FIELD).collect::<String>());
133 let names = format!("{}.{}", name("service")?, name("method")?);
134 let args = fields.get("args").and_then(|a| a.as_array());
135 let (mut object, mut keys) = (None, None);
136 if names == META_WRITE {
137 object = args.and_then(|a| a.first()).and_then(|v| v.as_str()).map(|s| s.chars().take(MAX_FIELD).collect());
138 keys = args
139 .and_then(|a| a.get(1))
140 .and_then(|v| v.as_object())
141 .map(|meta| meta.keys().map(|k| k.chars().take(MAX_FIELD).collect()).collect());
142 }
143 Some(ServiceCall { names, object, keys })
144}
145
146fn service_failure(reply: &[u8]) -> Option<String> {
149 let serde_json::Value::Object(fields) = serde_json::from_slice(reply).ok()? else { return None };
150 let ok = fields.get("success").and_then(|v| v.as_bool()).unwrap_or(false);
151 (!ok).then(|| "service call failed".to_string())
152}
153
154fn is_write(method: &Method) -> bool {
155 !matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS | Method::TRACE | Method::CONNECT)
156}
157
158pub(super) async fn record_action(State(state): State<AppState>, mut req: Request<Body>, next: Next) -> Response {
160 if !is_write(req.method()) {
161 return next.run(req).await;
162 }
163 let Some(template) = req.extensions().get::<MatchedPath>().map(|m| m.as_str().to_string()) else {
164 return next.run(req).await;
165 };
166 let command = format!("{} {template}", req.method());
167 let policy = policy(&command);
168 let caller = req.extensions().get::<Caller>().cloned();
169 if policy == Some(Policy::Never) {
170 return next.run(req).await;
171 }
172 let untokened = caller.as_ref().and_then(Caller::uid).is_none();
175 if policy == Some(Policy::Plumbing) && untokened && template != SERVICE_ROUTE {
176 return next.run(req).await;
177 }
178 let mut subject = path_params(&template, req.uri().path());
179 let mut refused = None;
180 let mut quiet_unless_failed = false;
181 if template == SERVICE_ROUTE {
182 let (parts, body) = req.into_parts();
183 match axum::body::to_bytes(body, SERVICE_BODY_MAX).await {
184 Ok(bytes) => {
185 let call = service_call(&bytes);
186 req = Request::from_parts(parts, Body::from(bytes));
187 match call.as_ref().filter(|_| untokened).map(ServiceCall::quiet) {
188 Some(Quiet::Always) => return next.run(req).await,
189 Some(Quiet::UnlessFailed) => quiet_unless_failed = true,
190 _ => {}
191 }
192 subject.extend(call.map(|c| c.subject()));
193 }
194 Err(_) => {
195 refused = Some((StatusCode::PAYLOAD_TOO_LARGE, "request body too large").into_response());
196 req = Request::from_parts(parts, Body::empty());
197 }
198 }
199 }
200 let request_id = req.headers().get("x-request-id").and_then(|v| v.to_str().ok()).unwrap_or_default().to_string();
201 let response = match refused {
202 Some(r) => r,
203 None => next.run(req).await,
204 };
205 let status = response.status();
206 let mut error = (status.as_u16() >= 400).then(|| format!("HTTP {}", status.as_u16()));
207 if policy == Some(Policy::Handler) && error.is_none() {
210 return response;
211 }
212 let mut response = response;
214 if template == SERVICE_ROUTE && error.is_none() {
215 let (parts, body) = response.into_parts();
216 match axum::body::to_bytes(body, SERVICE_REPLY_MAX).await {
217 Ok(bytes) => {
218 error = service_failure(&bytes);
219 response = Response::from_parts(parts, Body::from(bytes));
220 }
221 Err(_) => {
222 error = Some("unreadable reply".to_string());
223 response = (StatusCode::INTERNAL_SERVER_ERROR, "reply too large").into_response();
224 }
225 }
226 }
227 if quiet_unless_failed && error.is_none() {
228 return response;
229 }
230 let store = state.mstore.clone();
231 tokio::task::spawn_blocking(move || {
233 let actor = match caller.as_ref().and_then(Caller::uid) {
234 Some(uid) => Actor::Agent(store.agent_names_by_id(uid).ok().flatten().map(|row| row.slug).unwrap_or_else(|| uid.to_string())),
235 None => Actor::Unproven,
236 };
237 let subject = (!subject.is_empty()).then(|| subject.join(" ").chars().take(MAX_FIELD * 2).collect());
238 let record = ActionRecord { actor, command, target: Target { agent: None, block_id: None, subject }, request_id, error };
239 crate::backend::reactive::get_global_handler().audit_action(&record);
240 });
241 response
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 #[test]
249 fn a_routes_path_parameters_are_read_from_the_path() {
250 assert_eq!(path_params("/agentmux/work/:id/heartbeat", "/agentmux/work/t-9/heartbeat"), vec!["id=t-9"]);
251 assert_eq!(path_params("/a/:x/b/:y", "/a/1/b/2"), vec!["x=1", "y=2"]);
252 assert!(path_params("/api/v1/tab/new", "/api/v1/tab/new").is_empty());
253 assert_eq!(path_params("/a/:id", "/a/").len(), 0);
254 }
255
256 #[test]
257 fn only_the_service_and_method_names_are_read_from_a_service_call() {
258 let subject = |body: &[u8]| service_call(body).map(|c| c.subject());
259 assert_eq!(subject(br#"{"service":"window","method":"CloseWindow","args":["secret"]}"#).as_deref(), Some("window.CloseWindow"));
260 assert_eq!(subject(br#"{"service":"window"}"#), None);
261 assert_eq!(subject(b"not json"), None);
262 let meta = subject(br#"{"service":"object","method":"UpdateObjectMeta","args":["block:b1",{"controller":"s3cret","cmd:cwd":"/x"}]}"#).unwrap();
263 assert!(meta.starts_with("object.UpdateObjectMeta object=block:b1 keys=") && meta.contains("controller") && meta.contains("cmd:cwd"), "{meta}");
264 assert!(!meta.contains("s3cret") && !meta.contains("/x"), "{meta}");
265 }
266
267 #[test]
268 fn a_service_call_with_no_token_is_recorded_unless_it_is_a_read_or_the_windows_bookkeeping() {
269 let quiet = |service: &str, method: &str| {
270 let body = serde_json::json!({"service": service, "method": method, "args": []}).to_string();
271 service_call(body.as_bytes()).unwrap().quiet() == Quiet::Always
272 };
273 assert!(quiet("object", "GetObject") && quiet("window", "SetWindowPosAndSize") && quiet("history", "List"));
274 for (service, method) in [("client", "AgreeTos"), ("object", "QuitAgent"), ("object", "ShutdownAgent"), ("agent", "define"), ("history", "Delete"), ("workspace", "DeleteWorkspace"), ("object", "NewMethod")] {
275 assert!(!quiet(service, method), "{service}.{method}");
276 }
277 }
278
279 #[test]
280 fn the_hosts_plumbing_is_quiet_only_while_it_succeeds() {
281 let quiet = |service: &str, method: &str| {
282 let body = serde_json::json!({"service": service, "method": method, "args": []}).to_string();
283 service_call(body.as_bytes()).unwrap().quiet()
284 };
285 assert_eq!(quiet("credential", "Fill"), Quiet::UnlessFailed);
286 assert_eq!(quiet("host_ipc", "Register"), Quiet::UnlessFailed);
287 assert_eq!(quiet("object", "GetObject"), Quiet::Always);
288 assert_eq!(quiet("object", "QuitAgent"), Quiet::No);
289 }
290
291 #[test]
292 fn a_meta_write_is_quiet_only_when_every_key_is_one_the_window_keeps_for_itself() {
293 let meta = |keys: serde_json::Value| {
294 let body = serde_json::json!({"service": "object", "method": "UpdateObjectMeta", "args": ["block:b1", keys]}).to_string();
295 service_call(body.as_bytes()).unwrap().quiet() == Quiet::Always
296 };
297 assert!(meta(serde_json::json!({"term:osc_title": "x", "term:human_turns": 3, "term:last_prompt": null})));
298 assert!(!meta(serde_json::json!({"term:osc_title": "x", "controller": "term"})));
299 assert!(!meta(serde_json::json!({"cmd:env": {"A": "b"}})));
300 assert!(!meta(serde_json::json!({})));
301 let no_meta = serde_json::json!({"service": "object", "method": "UpdateObjectMeta", "args": ["block:b1"]}).to_string();
302 assert_eq!(service_call(no_meta.as_bytes()).unwrap().quiet(), Quiet::No);
303 }
304
305 #[test]
306 fn a_service_reply_without_success_is_a_failure_and_its_text_is_not_kept() {
307 let failed = service_failure(br#"{"error":"invalid type: string \"s3cret\""}"#).unwrap();
308 assert!(!failed.contains("s3cret"), "{failed}");
309 assert!(service_failure(br#"{"success":false}"#).is_some());
310 assert_eq!(service_failure(br#"{"success":true,"data":1}"#), None);
311 assert_eq!(service_failure(b"not json"), None);
312 }
313
314 #[test]
315 fn reads_are_not_writes() {
316 assert!(!is_write(&Method::GET) && !is_write(&Method::OPTIONS) && !is_write(&Method::HEAD));
317 assert!(is_write(&Method::POST) && is_write(&Method::PUT) && is_write(&Method::PATCH) && is_write(&Method::DELETE));
318 }
319}