Skip to main content

agentmux_srv/server/
agent_only.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Routes that act for an agent (its jobs and its work queue) are served only
5//! to a request that carries an agent's token, and the agent a request names
6//! (`agent_id`, `created_by`, `agent`) has to be the one that token belongs to. The
7//! handlers used to take the acting agent from those body fields, or record
8//! the action as the operator's when there was no token. The window reaches
9//! the same state over its RPC socket, not these routes.
10
11use axum::body::Body;
12use axum::extract::State;
13use axum::http::{Request, StatusCode};
14use axum::middleware::Next;
15use axum::response::{IntoResponse, Response};
16use axum::Json;
17
18use super::caller::Caller;
19use super::AppState;
20
21/// More than any task or job a route here takes; a bigger body is refused unread.
22const MAX_BODY: usize = 16 * 1024 * 1024;
23
24fn refuse(status: StatusCode, error: &str) -> Response {
25    (status, Json(serde_json::json!({ "ok": false, "error": error }))).into_response()
26}
27
28/// The agent names a JSON body gives as the one acting (`agent` is what claims and posts call it).
29fn named_actors(body: &[u8]) -> Vec<String> {
30    let Ok(serde_json::Value::Object(fields)) = serde_json::from_slice(body) else {
31        return Vec::new();
32    };
33    ["agent_id", "created_by", "agent"]
34        .iter()
35        .filter_map(|key| fields.get(*key)?.as_str())
36        .map(|name| name.trim().to_string())
37        .filter(|name| !name.is_empty())
38        .collect()
39}
40
41/// Layered inside `caller_middleware`: refuses a request that isn't [`Caller::Agent`], or that names
42/// another agent than its token's as the one acting.
43pub(super) async fn require_agent_token(State(state): State<AppState>, req: Request<Body>, next: Next) -> Response {
44    let Some(uid) = req.extensions().get::<Caller>().and_then(Caller::uid).map(str::to_string) else {
45        return refuse(
46            StatusCode::FORBIDDEN,
47            "FORBIDDEN: this acts for an agent, so the request must carry that agent's token (AGENTMUX_AGENT_TOKEN)",
48        );
49    };
50    let (parts, body) = req.into_parts();
51    let Ok(bytes) = axum::body::to_bytes(body, MAX_BODY).await else {
52        return refuse(StatusCode::PAYLOAD_TOO_LARGE, "request body too large");
53    };
54    let names = named_actors(&bytes);
55    if !names.is_empty() {
56        let store = state.mstore.clone();
57        let own = tokio::task::spawn_blocking(move || names.iter().all(|name| super::actor::proven_slug(&store, &uid, name).is_some())).await;
58        if !own.unwrap_or(false) {
59            return refuse(
60                StatusCode::FORBIDDEN,
61                "FORBIDDEN: this acts for the agent the request's token belongs to, and the request names another",
62            );
63        }
64    }
65    next.run(Request::from_parts(parts, Body::from(bytes))).await
66}
67
68#[cfg(test)]
69mod tests {
70    use super::named_actors;
71
72    #[test]
73    fn the_names_a_body_gives_as_acting() {
74        assert_eq!(named_actors(br#"{"agent_id":" a1 ","created_by":"b","title":"x"}"#), vec!["a1", "b"]);
75        assert!(named_actors(br#"{"agent_id":"","title":"x"}"#).is_empty());
76        assert!(named_actors(b"not json").is_empty());
77        assert!(named_actors(br#"["agent_id"]"#).is_empty());
78        assert!(named_actors(br#"{"agent_id":7}"#).is_empty());
79    }
80}