agentmux_srv/server/
model_gateway_key.rs1use super::*;
12use crate::backend::model_gateway::token::Grant;
13use axum::body::Body;
14use axum::http::{header, HeaderMap, StatusCode};
15use serde_json::Value;
16use zeroize::Zeroizing;
17
18pub(super) struct KeyAccount {
20 pub key: Zeroizing<String>,
21 pub name: String,
22}
23
24fn label_of(account: &crate::backend::storage::identities::IdentityAccount) -> String {
25 [&account.display_name, &account.name].into_iter().find(|n| !n.trim().is_empty()).cloned().unwrap_or_default()
26}
27
28fn read(state: &AppState, grant: &Grant) -> Result<KeyAccount, (StatusCode, &'static str, String)> {
30 let gone = || (StatusCode::FORBIDDEN, "permission_error", "this agent is no longer on that API key account".to_string());
31 let links = state.identity_store.agent_identity_list_for_agent(&grant.def_id).map_err(|_| gone())?;
32 let linked = links.iter().any(|l| l.account_id == grant.account && l.provider.eq_ignore_ascii_case(crate::backend::model_gateway::catalog::KEY_ROUTE_ID));
33 if grant.account.is_empty() || !linked {
34 return Err(gone());
35 }
36 let account = match crate::identity::resolver::inject::resolve_account_for_spawn(&state.id_store, &grant.account) {
37 Ok(Some((a, _))) if a.kind == "api_key" => a,
38 _ => return Err(gone()),
39 };
40 let name = label_of(&account);
41 match crate::identity::resolver::secret::resolve_account_secret(&account, &state.id_store, &state.identity_store) {
42 Ok(value) => Ok(KeyAccount { key: Zeroizing::new(value), name }),
43 Err(_) => Err((StatusCode::SERVICE_UNAVAILABLE, "api_error", format!("the API key account \"{name}\" has no usable key; add it again in Connectors > Accounts"))),
44 }
45}
46
47pub(super) async fn key_of(state: &AppState, grant: &Grant) -> Result<KeyAccount, Response> {
49 let (st, gr) = (state.clone(), grant.clone());
50 match tokio::task::spawn_blocking(move || read(&st, &gr)).await {
51 Ok(Ok(key)) => Ok(key),
52 Ok(Err((status, kind, why))) => Err(super::model_gateway_handlers::denied(Some(&grant), &grant.route, status, kind, &why)),
53 Err(_) => Err(super::model_gateway_handlers::refuse(StatusCode::INTERNAL_SERVER_ERROR, "api_error", "the key lookup failed")),
54 }
55}
56
57pub(super) fn requested_model(body: &[u8]) -> String {
59 serde_json::from_slice::<Value>(body).ok().and_then(|v| v.get("model").and_then(Value::as_str).map(str::to_string)).unwrap_or_default()
60}
61
62pub(super) async fn named_error(response: reqwest::Response, name: &str) -> Result<reqwest::Response, Response> {
66 let streaming = response.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|v| v.starts_with("text/event-stream"));
67 if !response.status().is_client_error() || streaming || name.is_empty() {
68 return Ok(response);
69 }
70 let status = response.status();
71 let mut headers = HeaderMap::new();
72 for (n, v) in response.headers() {
73 if ![header::CONTENT_LENGTH, header::TRANSFER_ENCODING, header::CONTENT_ENCODING, header::CONNECTION].contains(n) {
74 headers.append(n.clone(), v.clone());
75 }
76 }
77 let bytes = response.bytes().await.unwrap_or_default();
78 let named = match serde_json::from_slice::<Value>(&bytes) {
79 Ok(mut json) => {
80 if let Some(message) = json.pointer_mut("/error/message") {
81 if let Some(text) = message.as_str() {
82 *message = Value::String(format!("{text} (AgentMux API key account \"{name}\")"));
83 }
84 }
85 serde_json::to_vec(&json).unwrap_or_else(|_| bytes.to_vec())
86 }
87 Err(_) => bytes.to_vec(),
88 };
89 let mut out = Response::new(Body::from(named));
90 *out.status_mut() = status;
91 *out.headers_mut() = headers;
92 Err(out)
93}
94
95pub(super) fn foreign_use_reporter(state: AppState) -> crate::backend::container::listener::ForeignUse {
97 std::sync::Arc::new(move |grant, peer| audit_foreign_use(&state, grant, Some(peer)))
98}
99
100pub(super) fn audit_foreign_use(state: &AppState, grant: &Grant, peer: Option<std::net::IpAddr>) {
104 let (state, grant) = (state.clone(), grant.clone());
105 let write = move || {
106 let name = crate::identity::resolver::inject::resolve_account_for_spawn(&state.id_store, &grant.account).ok().flatten().map(|(a, _)| label_of(&a)).unwrap_or_default();
107 let what = if grant.account.is_empty() { format!("the model route \"{}\"", grant.route) } else { format!("the API key account \"{name}\"") };
108 let from = match peer {
109 Some(peer) => format!("came from {peer}, which is not the container its token was made for"),
110 None => "came with no proof of which container it was from".to_string(),
111 };
112 let reason = format!("a request on {what} {from}; refused, and the token is ended");
113 state.reactive_handler.log_fleet_action_audit(None, &grant.agent, "", "gateway.key_use_refused", false, Some("refused"), &uuid::Uuid::new_v4().to_string(), Some(&reason));
114 };
115 match tokio::runtime::Handle::try_current() {
117 Ok(runtime) => {
118 runtime.spawn_blocking(write);
119 }
120 Err(_) => write(),
121 }
122}