agentmux_srv/server/
agent_only.rs1use 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
21const 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
28fn 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
41pub(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}