Skip to main content

agentmux_srv/server/
http_action.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The record of what each HTTP caller did: one line in the audit log for every call of a
5//! state-changing route (`POST`, `PUT`, `PATCH`, `DELETE`), saying who made it, which route, what
6//! it acted on (the route's path parameters) and how it went (the response's status). The websocket
7//! RPC has the same record (`backend::rpc::action_record`); both end in the same audit line.
8//!
9//! It is made in one place, a layer under the authentication layers, so a handler cannot forget it
10//! and a route nobody decided is recorded ([`super::route_table`]: a write route does not compile
11//! without its decision). The caller is whoever the request's agent token names
12//! (`Caller::Agent`); a request without one is `unproven`, never the operator: nothing on an HTTP
13//! request proves the window made it. A request's contents are never recorded; the one body read is
14//! the service call's `service` and `method` names.
15//!
16//! A service call with no agent token is recorded as `unproven`, not skipped, so a process that merely
17//! holds the instance key leaves a line. The window's own reads and bookkeeping ([`QUIET`]) are the
18//! exception; a method not named there is recorded. The host's own plumbing ([`QUIET_SERVICES`]) is quiet
19//! only while it succeeds: a call of it that is refused or fails is recorded. A write of an object's meta is left out only when every
20//! key it writes is one the window keeps for itself ([`QUIET_META_KEYS`]); any other write is recorded with the
21//! object and the key names, never the values.
22
23use 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
35/// The generic service call: its `service` and `method` say what it does.
36const SERVICE_ROUTE: &str = "/agentmux/service";
37/// The largest service call read for its two names; a bigger one is refused with 413, as the
38/// route's own body limit would, and the refusal is recorded.
39const SERVICE_BODY_MAX: usize = 2 * 1024 * 1024;
40/// The largest service reply read for its verdict.
41const SERVICE_REPLY_MAX: usize = 32 * 1024 * 1024;
42const MAX_FIELD: usize = 200;
43
44/// The `service.method` calls that are not recorded when they carry no agent token: reads, and the window's
45/// own bookkeeping, which it makes constantly. A method in no list is recorded.
46const 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];
58/// The generic write of an object's meta, whose arguments are the object and the keys to set.
59const META_WRITE: &str = "object.UpdateObjectMeta";
60/// The meta keys the window writes constantly for itself (titles, activity summaries, prompts, timers, the
61/// shell's directory); a write of only these, with no agent token, is not recorded.
62const 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];
67/// The services that are the host's own plumbing (the credential bridge, the host's registration): a call of
68/// them with no agent token is not recorded while it succeeds, and is when it is refused or fails.
69const QUIET_SERVICES: &[&str] = &["credential", "host_ipc"];
70
71/// How a service call with no agent token is left out of the record.
72#[derive(Debug, PartialEq)]
73enum Quiet {
74    /// Recorded.
75    No,
76    /// Never recorded.
77    Always,
78    /// Recorded only when the reply says it was refused or failed.
79    UnlessFailed,
80}
81
82/// A service call's names, and for a write of an object's meta, the object and the keys it sets.
83struct ServiceCall {
84    names: String,
85    object: Option<String>,
86    keys: Option<Vec<String>>,
87}
88
89impl ServiceCall {
90    /// How the call, with no agent token, is left out of the record.
91    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    /// What the record says the call acted on: the names, and a meta write's object and key names (never values).
106    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
118/// The values a request's path gives for the route's `:name` parameters, as `name=value`.
119pub(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
129/// A service call from its body, when it names a service and a method.
130fn 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
146/// Whether a service reply says the call failed. The reply's own `error` text is not kept: it can
147/// quote the request's values. (`success` is left out of a failed reply, so a reply without it failed.)
148fn 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
158/// Layered inside `caller_middleware`: records the call once the route has answered.
159pub(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    // The window's own calls and the host's cannot be told from a process that merely holds the
173    // key, so these routes are recorded when an agent's token is on the request.
174    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    // A route that records its own successes still has its refusals recorded here, since it may
208    // refuse before it gets to its own record.
209    if policy == Some(Policy::Handler) && error.is_none() {
210        return response;
211    }
212    // A service call answers 200 with its own verdict in the body.
213    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    // Off the reply path: naming the agent reads the store.
232    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}