agentmux_srv/server/
caller.rs1use axum::body::Body;
23use axum::extract::State;
24use axum::http::Request;
25use axum::middleware::Next;
26use axum::response::Response;
27
28use super::{AppState, ReactiveAuthVia};
29
30pub(crate) const AGENT_TOKEN_HEADER: &str = "X-Agent-Token";
33
34#[derive(Debug, Clone, PartialEq, Eq)]
37pub(crate) enum Caller {
38 Agent { uid: String },
40 Unattributed,
43}
44
45impl Caller {
46 pub(crate) fn uid(&self) -> Option<&str> {
48 match self {
49 Caller::Agent { uid } => Some(uid),
50 Caller::Unattributed => None,
51 }
52 }
53}
54
55pub(crate) fn attributed_uid(caller: Option<&Caller>) -> String {
59 caller
60 .and_then(Caller::uid)
61 .map(str::to_string)
62 .unwrap_or_default()
63}
64
65pub(crate) enum Lookup {
70 Index(Option<String>),
71 NoIndex,
74}
75
76pub(crate) fn derive_caller(
77 token: Option<&str>,
78 full_key: bool,
79 lookup: impl FnOnce(&str) -> Lookup,
80) -> Caller {
81 let Some(token) = token.map(str::trim).filter(|t| !t.is_empty()) else {
82 return Caller::Unattributed;
83 };
84 if !full_key {
85 crate::backend::agent_resolve::record_uid_fallback("m4.token_on_lan_key");
86 return Caller::Unattributed;
87 }
88 match lookup(token) {
89 Lookup::Index(Some(uid)) => Caller::Agent { uid },
90 Lookup::Index(None) => {
91 crate::backend::agent_resolve::record_uid_fallback("m4.token_unknown");
92 Caller::Unattributed
93 }
94 Lookup::NoIndex => {
95 crate::backend::agent_resolve::record_uid_fallback("m4.token_index_unavailable");
96 Caller::Unattributed
97 }
98 }
99}
100
101pub(crate) async fn caller_middleware(
109 State(state): State<AppState>,
110 mut req: Request<Body>,
111 next: Next,
112) -> Response {
113 let full_key = req.extensions().get::<ReactiveAuthVia>() == Some(&ReactiveAuthVia::FullAuthKey);
114 let pinned = req
118 .extensions()
119 .get::<crate::backend::container::credential::ContainerGrant>()
120 .map(|g| g.agent_token.clone());
121 let header = if req.uri().path() == "/ws" || req.method() == axum::http::Method::OPTIONS {
122 None
123 } else {
124 req.headers()
125 .get(AGENT_TOKEN_HEADER)
126 .and_then(|v| v.to_str().ok())
127 };
128 let token = match &pinned {
129 Some(agent_token) => agent_token.as_deref(),
130 None => header,
131 };
132 let caller = derive_caller(token, full_key, |t| match state.mstore.token_index() {
133 Some(index) => Lookup::Index(index.uid_for(t)),
134 None => Lookup::NoIndex,
135 });
136 req.extensions_mut().insert(caller);
137 next.run(req).await
138}
139
140pub(crate) async fn handle_identity_fallbacks(
148 State(state): State<AppState>,
149 caller: Option<axum::Extension<Caller>>,
150) -> axum::Json<serde_json::Value> {
151 let counters: serde_json::Map<String, serde_json::Value> =
152 crate::backend::agent_resolve::uid_fallback_counts()
153 .into_iter()
154 .map(|(site, n)| (site.to_string(), serde_json::json!(n)))
155 .collect();
156 let registrations = state.reactive_handler.list_agents();
159 let mstore = state.mstore.clone();
160 let gauges = tokio::task::spawn_blocking(move || {
162 crate::backend::identity_spawn::live_gauges(
163 ®istrations,
164 |block| crate::backend::blockcontroller::get_controller(block).is_some(),
165 |block| crate::backend::identity_spawn::store_block_has_row(&mstore, block),
166 )
167 })
168 .await
169 .ok();
170 let (tokenless_or_unknown, unidentified) = match gauges {
171 Some((t, u)) => (serde_json::json!(t), serde_json::json!(u)),
172 None => (serde_json::Value::Null, serde_json::Value::Null),
173 };
174 let caller_uid = caller.as_ref().and_then(|c| c.0.uid().map(str::to_string));
175 axum::Json(serde_json::json!({
176 "boot_id": state.boot_id.to_string(),
180 "caller": caller_uid,
181 "counters": counters,
182 "gauges": {
183 "live.tokenless_or_unknown": tokenless_or_unknown,
184 "live.unidentified": unidentified,
185 },
186 }))
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192
193 fn index(token: &str) -> Lookup {
194 Lookup::Index((token == "tok-y").then(|| "uid-y".to_string()))
195 }
196
197 #[test]
198 fn a_known_token_on_the_full_key_is_the_agent() {
199 assert_eq!(
200 derive_caller(Some("tok-y"), true, index),
201 Caller::Agent {
202 uid: "uid-y".into()
203 }
204 );
205 }
206
207 #[test]
208 fn no_token_is_unattributed() {
209 assert_eq!(derive_caller(None, true, index), Caller::Unattributed);
210 assert_eq!(derive_caller(Some(" "), true, index), Caller::Unattributed);
211 }
212
213 #[test]
216 fn an_unknown_token_is_unattributed_not_refused() {
217 assert_eq!(
218 derive_caller(Some("tok-gone"), true, index),
219 Caller::Unattributed
220 );
221 }
222
223 #[test]
224 fn a_missing_index_is_unattributed() {
225 assert_eq!(
226 derive_caller(Some("tok-y"), true, |_| Lookup::NoIndex),
227 Caller::Unattributed
228 );
229 }
230
231 #[test]
233 fn a_token_on_a_lan_key_request_is_ignored() {
234 assert_eq!(
235 derive_caller(Some("tok-y"), false, index),
236 Caller::Unattributed
237 );
238 }
239}