Skip to main content

agentmux_srv_core/backend/vault/
route_key.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The key of a model route (`backend::model_gateway`), read for the gateway to add upstream. The value
5//! goes into one outgoing request and is not returned to any caller that could show it to an agent.
6//! The person approved the agent's use of the route when it was made, so this asks no one; it records
7//! the use under the agent's name, once per agent and route every few minutes, not once per request.
8
9use super::{kinds, record, seal, Store};
10use agentmux_common::time::now_ms;
11use std::collections::HashMap;
12use std::sync::{Mutex, OnceLock};
13
14/// The activity line for a use, listed with the other uses of a value.
15pub const USED: &str = "sent to a model route";
16/// How often a use by the same agent of the same route is written to the activity log.
17const RECORD_EVERY_MS: i64 = 10 * 60 * 1000;
18
19pub struct RouteKey {
20    pub value: zeroize::Zeroizing<String>,
21    pub label: String,
22}
23
24fn last_recorded() -> &'static Mutex<HashMap<(String, String), i64>> {
25    static LAST: OnceLock<Mutex<HashMap<(String, String), i64>>> = OnceLock::new();
26    LAST.get_or_init(Default::default)
27}
28
29fn due(agent: &str, route: &str, now: i64) -> bool {
30    let mut last = last_recorded().lock().unwrap();
31    let at = last.entry((agent.to_string(), route.to_string())).or_insert(i64::MIN);
32    let due = now.saturating_sub(*at) >= RECORD_EVERY_MS;
33    if due {
34        *at = now;
35    }
36    due
37}
38
39/// The `api-key` entry whose label starts with `label_prefix` (case does not matter).
40fn entry_for(store: &Store, label_prefix: &str) -> Result<crate::backend::storage::vault::VaultRow, String> {
41    let prefix = label_prefix.to_lowercase();
42    store
43        .vault_list()
44        .map_err(|e| e.to_string())?
45        .into_iter()
46        .find(|r| r.kind == "api-key" && r.label.to_lowercase().starts_with(&prefix))
47        .ok_or_else(|| format!("the Vault has no api-key entry labelled \"{label_prefix}\""))
48}
49
50/// Whether the Vault has the entry, without opening it.
51pub fn present(store: &Store, label_prefix: &str) -> bool {
52    entry_for(store, label_prefix).is_ok()
53}
54
55/// The entry's value, and its label.
56pub fn for_route(store: &Store, label_prefix: &str, agent: &str, route: &str) -> Result<RouteKey, String> {
57    let row = entry_for(store, label_prefix)?;
58    let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {} has an unknown kind", row.id))?;
59    let key = seal::key(false)?;
60    let parts = seal::open(&key, &row.id, &row.sealed)?;
61    let value = parts.get(kind.parts[0]).ok_or_else(|| format!("{} has no value saved", row.label))?;
62    let value = zeroize::Zeroizing::new(value.to_string());
63    if due(agent, route, now_ms()) {
64        if let Err(e) = store.vault_touch(&row.id, now_ms()) {
65            tracing::warn!(error = %e, "vault: couldn't note a route key's use");
66        }
67        record(store, &row.id, &row.label, agent, USED, route, "done");
68    }
69    Ok(RouteKey { value, label: row.label })
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn a_key_is_present_when_an_api_key_entry_has_the_label() {
78        crate::backend::vault::seal::use_test_key();
79        let store = Store::open_in_memory().unwrap();
80        store.apply_identity_schema_for_tests().unwrap();
81        assert!(!present(&store, "OpenRouter API key"));
82        let other: crate::backend::vault::NewEntry = serde_json::from_value(serde_json::json!({ "kind": "note", "label": "OpenRouter API key", "parts": { "text": "x" } })).unwrap();
83        crate::backend::vault::create(&store, other).unwrap();
84        assert!(!present(&store, "OpenRouter API key"), "a note is not an api-key entry");
85        let key: crate::backend::vault::NewEntry = serde_json::from_value(serde_json::json!({ "kind": "api-key", "label": "openrouter api key (shared)", "parts": { "value": "sk-test" } })).unwrap();
86        crate::backend::vault::create(&store, key).unwrap();
87        assert!(present(&store, "OpenRouter API key"), "case and a longer label do not matter");
88        assert_eq!(&**for_route(&store, "OpenRouter API key", "rk-present", "openrouter").unwrap().value, "sk-test");
89    }
90
91    #[test]
92    fn a_use_is_written_down_once_per_window() {
93        let t = 1_000_000_000;
94        assert!(due("rk-agent", "openrouter", t));
95        assert!(!due("rk-agent", "openrouter", t + 1_000));
96        assert!(due("rk-other", "openrouter", t + 1_000), "another agent has its own line");
97        assert!(due("rk-agent", "openrouter", t + RECORD_EVERY_MS));
98    }
99}