Skip to main content

agentmux_srv/server/
model_gateway_key.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The gateway's key route: an agent's own Anthropic API key, an account of Connectors > Accounts.
5//!
6//! The agent is pointed at `/api/v1/model/anthropic/...` with a token that names it and the account
7//! (`token::token_for_account`). Each request is checked against the agent's *current* link to that account, so a
8//! switch or an unlink ends the token's use at once, and the key is read from the keychain here, for the one
9//! request, and sent as `x-api-key`. The agent's environment, files and processes never hold it.
10
11use 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
18/// The key to send upstream, and the name the person gave its account (for the messages that name it).
19pub(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
28/// The key of the account `grant` spends, when the agent is still linked to it. BLOCKING (store and keychain reads).
29fn 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
47/// [`read`] off the async runtime.
48pub(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
57/// The model a request names, for counting its answer at that family's price.
58pub(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
62/// An error answer from Anthropic (a rejected key, a used-up credit), with the account's name added to its message, so
63/// the failure the agent shows names the account and nothing of the key. Other answers are returned as they are.
64/// `Err` holds the finished answer, `Ok` the response to relay as it is.
65pub(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
95/// What the container listener tells when a key account's token is shown by a peer other than its container.
96pub(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
100/// A gateway token was shown by a peer other than the container it was made for (or with no proof of which it was from, `peer`
101/// none): one Audit row, naming the agent and the account's display name or the route, and never the token. The token has
102/// already ended.
103pub(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    // From the listener's middleware: off the async runtime, as the key lookup is.
116    match tokio::runtime::Handle::try_current() {
117        Ok(runtime) => {
118            runtime.spawn_blocking(write);
119        }
120        Err(_) => write(),
121    }
122}