Skip to main content

visdom_cli/
gateway.rs

1//! The AI Gateway, as a developer's agent uses it: the console issues the
2//! developer a short-lived personal key for a project, and the agent calls the
3//! LLM gateway with it.
4//!
5//! A new personal key revokes the developer's previous one for that project,
6//! so a key is kept (in visdom's own config directory, readable by the user
7//! only) and reused until shortly before it expires: sessions started side by
8//! side share it instead of cutting each other off. A kept key belongs to the
9//! account it was issued for and is not handed to another.
10
11use std::path::{Path, PathBuf};
12
13use serde::{Deserialize, Serialize};
14use tracevault_cli::agent::Agent;
15
16/// A key with less than this left is replaced rather than handed out.
17pub const MIN_KEY_SECONDS_LEFT: i64 = 15 * 60;
18
19/// Assumed lifetime of a key whose expiry the console did not state in a form
20/// this version reads. Short, so a wrong guess costs one early renewal.
21const UNKNOWN_EXPIRY_SECONDS: i64 = 60 * 60;
22
23/// A project the developer may issue themselves a personal key for.
24#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
25pub struct OpenProject {
26    /// The Control Plane project id.
27    pub id: String,
28    pub slug: String,
29    pub name: String,
30}
31
32/// A personal key as issued.
33#[derive(Clone, PartialEq, Eq)]
34pub struct IssuedKey {
35    pub secret: String,
36    /// Unix seconds.
37    pub expires_at: i64,
38}
39
40/// The console's refusal, in its own words when it gave any.
41fn refusal(what: &str, status: reqwest::StatusCode, body: &str) -> String {
42    #[derive(Deserialize)]
43    struct Refusal {
44        error: String,
45    }
46    let said = serde_json::from_str::<Refusal>(body)
47        .map(|r| r.error)
48        .unwrap_or_default();
49    let code = status.as_u16();
50    match (said.is_empty(), code) {
51        (false, _) => format!("{what}: {said} (HTTP {code})"),
52        (true, 401) => format!("{what}: the AI Gateway did not accept this login (HTTP 401)"),
53        (true, _) => format!("{what}: HTTP {code}"),
54    }
55}
56
57async fn read(
58    what: &str,
59    console_url: &str,
60    request: reqwest::RequestBuilder,
61) -> Result<String, String> {
62    let response = request
63        .send()
64        .await
65        .map_err(|e| format!("{what}: the AI Gateway ({console_url}) did not answer: {e}"))?;
66    let status = response.status();
67    let body = response.text().await.unwrap_or_default();
68    if status.is_success() {
69        Ok(body)
70    } else {
71        Err(refusal(what, status, &body))
72    }
73}
74
75fn parse<T: for<'de> Deserialize<'de>>(what: &str, body: &str) -> Result<T, String> {
76    serde_json::from_str(body).map_err(|e| format!("{what}: unreadable answer ({e})"))
77}
78
79fn base(url: &str) -> &str {
80    url.trim_end_matches('/')
81}
82
83/// The LLM gateway's public address, from the console's settings.
84pub async fn llm_gateway_url(
85    http: &reqwest::Client,
86    console_url: &str,
87    token: &str,
88) -> Result<String, String> {
89    #[derive(Deserialize)]
90    #[serde(rename_all = "camelCase")]
91    struct Settings {
92        llm_gateway_url: String,
93    }
94    let what = "cannot read the AI Gateway's address";
95    let request = http
96        .get(format!("{}/api/settings", base(console_url)))
97        .bearer_auth(token);
98    let settings: Settings = parse(what, &read(what, console_url, request).await?)?;
99    let url = base(&settings.llm_gateway_url).to_string();
100    if crate::components::bazaar::is_http_url(&url) {
101        Ok(url)
102    } else {
103        Err(format!("{what}: `{url}` is not an http(s) URL"))
104    }
105}
106
107/// The projects the developer may issue a personal key for.
108pub async fn open_projects(
109    http: &reqwest::Client,
110    console_url: &str,
111    token: &str,
112) -> Result<Vec<OpenProject>, String> {
113    #[derive(Deserialize)]
114    struct Mine {
115        projects: Vec<OpenProject>,
116    }
117    let what = "cannot list your AI Gateway projects";
118    let request = http
119        .get(format!("{}/api/me/keys", base(console_url)))
120        .bearer_auth(token);
121    Ok(parse::<Mine>(what, &read(what, console_url, request).await?)?.projects)
122}
123
124/// Unix seconds of an expiry as the console states it (RFC 3339, or the same
125/// without an offset, meaning UTC).
126fn expiry_seconds(expires_at: Option<&str>, now: i64) -> i64 {
127    let parsed = expires_at.and_then(|text| {
128        chrono::DateTime::parse_from_rfc3339(text)
129            .map(|t| t.timestamp())
130            .or_else(|_| {
131                chrono::NaiveDateTime::parse_from_str(text, "%Y-%m-%dT%H:%M:%S%.f")
132                    .map(|t| t.and_utc().timestamp())
133            })
134            .ok()
135    });
136    parsed.unwrap_or(now + UNKNOWN_EXPIRY_SECONDS)
137}
138
139/// Issue the developer a personal key for `project_id`. This revokes their
140/// previous one for that project.
141pub async fn issue_key(
142    http: &reqwest::Client,
143    console_url: &str,
144    token: &str,
145    project_id: &str,
146    now: i64,
147) -> Result<IssuedKey, String> {
148    #[derive(Deserialize)]
149    #[serde(rename_all = "camelCase")]
150    struct Issued {
151        secret: String,
152        #[serde(default)]
153        expires_at: Option<String>,
154    }
155    let what = "cannot get a personal AI Gateway key";
156    let request = http
157        .post(format!("{}/api/me/keys", base(console_url)))
158        .bearer_auth(token)
159        .json(&serde_json::json!({ "projectId": project_id }));
160    let issued: Issued = parse(what, &read(what, console_url, request).await?)?;
161    if issued.secret.trim().is_empty() {
162        return Err(format!("{what}: the answer carried no key"));
163    }
164    Ok(IssuedKey {
165        expires_at: expiry_seconds(issued.expires_at.as_deref(), now),
166        secret: issued.secret,
167    })
168}
169
170/// Why the LLM gateway's models could not be listed.
171#[derive(Clone, Debug, PartialEq, Eq)]
172pub struct ModelsError {
173    pub why: String,
174    /// The gateway answered that it does not take this key (HTTP 401 or 403):
175    /// another key may work where this one does not.
176    pub rejected: bool,
177}
178
179/// The model aliases `key` may call. This is also the proof that the LLM
180/// gateway answers and takes the key, before an agent is pointed at it.
181pub async fn models(
182    http: &reqwest::Client,
183    llm_url: &str,
184    key: &str,
185) -> Result<Vec<String>, ModelsError> {
186    #[derive(Deserialize)]
187    struct Model {
188        id: String,
189    }
190    #[derive(Deserialize)]
191    struct List {
192        data: Vec<Model>,
193    }
194    let what = "cannot list the AI Gateway's models";
195    let failed = |why: String, rejected: bool| ModelsError { why, rejected };
196    let response = http
197        .get(format!("{}/v1/models", base(llm_url)))
198        .bearer_auth(key)
199        .send()
200        .await
201        .map_err(|e| {
202            failed(
203                format!("{what}: the AI Gateway ({llm_url}) did not answer: {e}"),
204                false,
205            )
206        })?;
207    let status = response.status();
208    let body = response.text().await.unwrap_or_default();
209    if !status.is_success() {
210        let rejected = matches!(status.as_u16(), 401 | 403);
211        let why = if rejected {
212            format!(
213                "{what}: the AI Gateway did not accept the personal key (HTTP {})",
214                status.as_u16()
215            )
216        } else {
217            format!("{what}: HTTP {}", status.as_u16())
218        };
219        return Err(failed(why, rejected));
220    }
221    let list: List = parse(what, &body).map_err(|why| failed(why, false))?;
222    Ok(list.data.into_iter().map(|m| m.id).collect())
223}
224
225/// The project to use: the configured one (its slug, id or name), else the
226/// only one there is. Otherwise the choice is the developer's, and the error
227/// names what to choose from.
228pub fn pick_project(configured: Option<&str>, open: &[OpenProject]) -> Result<OpenProject, String> {
229    let names = || {
230        open.iter()
231            .map(|p| p.slug.as_str())
232            .collect::<Vec<_>>()
233            .join(", ")
234    };
235    if open.is_empty() {
236        return Err(
237            "no AI Gateway project lets you issue a personal key: ask a project operator to \
238             switch personal keys on (Budgets) and to grant you access"
239                .to_string(),
240        );
241    }
242    match configured.map(str::trim).filter(|c| !c.is_empty()) {
243        Some(wanted) => open
244            .iter()
245            .find(|p| p.slug == wanted || p.id == wanted || p.name == wanted)
246            .cloned()
247            .ok_or_else(|| {
248                format!(
249                    "AI Gateway project `{wanted}` does not let you issue a personal key (you \
250                     can for: {})",
251                    names()
252                )
253            }),
254        None if open.len() == 1 => Ok(open[0].clone()),
255        None => Err(format!(
256            "several AI Gateway projects are open to you ({}): set `project` under \
257             `[gateway]` in .visdom/config.toml or in your visdom config, or \
258             VISDOM_GATEWAY_PROJECT (`visdom init` asks and saves it)",
259            names()
260        )),
261    }
262}
263
264/// The model alias an agent should ask for: the configured one, else the
265/// first alias that looks made for that agent, else none (the agent's own
266/// default, which the project must then allow).
267pub fn pick_model(agent: Agent, configured: Option<&str>, available: &[String]) -> Option<String> {
268    if let Some(model) = configured.map(str::trim).filter(|m| !m.is_empty()) {
269        return Some(model.to_string());
270    }
271    let hints: &[&str] = match agent {
272        Agent::ClaudeCode => &["claude", "sonnet", "opus"],
273        Agent::Codex => &["codex", "gpt"],
274        _ => &[],
275    };
276    hints.iter().find_map(|hint| {
277        available
278            .iter()
279            .find(|alias| alias.to_ascii_lowercase().contains(hint))
280            .cloned()
281    })
282}
283
284/// Whose key it is: the issuer and subject of the developer's access token.
285/// A key is the person's, so one kept for somebody else who logged in on this
286/// machine before must not be handed out. Empty for a token that is not a
287/// readable JWT, which then cannot be told apart from another such token.
288pub fn account_of(token: &str) -> String {
289    use base64::Engine;
290    #[derive(Deserialize)]
291    struct Claims {
292        #[serde(default)]
293        iss: String,
294        sub: String,
295    }
296    let mut parts = token.split('.');
297    let (Some(_), Some(payload), Some(_), None) =
298        (parts.next(), parts.next(), parts.next(), parts.next())
299    else {
300        return String::new();
301    };
302    base64::engine::general_purpose::URL_SAFE_NO_PAD
303        .decode(payload.trim_end_matches('='))
304        .ok()
305        .and_then(|bytes| serde_json::from_slice::<Claims>(&bytes).ok())
306        .filter(|claims| !claims.sub.is_empty())
307        .map(|claims| format!("{}|{}", claims.iss, claims.sub))
308        .unwrap_or_default()
309}
310
311/// One stored personal key.
312#[derive(Clone, Serialize, Deserialize)]
313struct StoredKey {
314    console_url: String,
315    project_id: String,
316    /// [`account_of`] the token it was issued for.
317    #[serde(default)]
318    account: String,
319    secret: String,
320    expires_at: i64,
321}
322
323impl StoredKey {
324    fn is_for(&self, console_url: &str, project_id: &str, account: &str) -> bool {
325        self.console_url == base(console_url)
326            && self.project_id == project_id
327            && self.account == account
328    }
329}
330
331/// The personal keys `visdom` holds, one per console, project and account.
332#[derive(Clone)]
333pub struct KeyStore {
334    path: PathBuf,
335}
336
337pub fn key_store_path_in(config_root: &Path) -> PathBuf {
338    config_root.join("visdom").join("gateway-keys.json")
339}
340
341/// Held while a key is looked up, issued and stored; released when dropped.
342pub struct KeyStoreLock(#[allow(dead_code)] std::fs::File);
343
344impl KeyStore {
345    pub fn at(path: PathBuf) -> KeyStore {
346        KeyStore { path }
347    }
348
349    fn load(&self) -> Vec<StoredKey> {
350        std::fs::read_to_string(&self.path)
351            .ok()
352            .and_then(|text| serde_json::from_str(&text).ok())
353            .unwrap_or_default()
354    }
355
356    /// Wait for this store to be free of every other `visdom` process, and
357    /// take it. Issuing a key revokes the previous one, so two sessions
358    /// starting together must not both issue: the second waits here and then
359    /// finds the first one's key.
360    pub fn lock(&self) -> std::io::Result<KeyStoreLock> {
361        let dir = self.path.parent().unwrap_or(Path::new("."));
362        std::fs::create_dir_all(dir)?;
363        let file = std::fs::OpenOptions::new()
364            .create(true)
365            .truncate(false)
366            .write(true)
367            .open(self.path.with_extension("lock"))?;
368        file.lock()?;
369        Ok(KeyStoreLock(file))
370    }
371
372    /// The stored key of `account` for this console and project, when it has
373    /// at least [`MIN_KEY_SECONDS_LEFT`] left.
374    pub fn usable(
375        &self,
376        console_url: &str,
377        project_id: &str,
378        account: &str,
379        now: i64,
380    ) -> Option<IssuedKey> {
381        self.load()
382            .into_iter()
383            .find(|k| k.is_for(console_url, project_id, account))
384            .filter(|k| k.expires_at - now >= MIN_KEY_SECONDS_LEFT)
385            .map(|k| IssuedKey {
386                secret: k.secret,
387                expires_at: k.expires_at,
388            })
389    }
390
391    /// Keep `key`, replacing the one for the same console and project
392    /// (whoever's it was: this machine's user is now `account`) and dropping
393    /// keys that have expired. The file is the user's alone.
394    pub fn keep(
395        &self,
396        console_url: &str,
397        project_id: &str,
398        account: &str,
399        key: &IssuedKey,
400        now: i64,
401    ) -> Result<(), String> {
402        let mut keys: Vec<StoredKey> = self
403            .load()
404            .into_iter()
405            .filter(|k| k.expires_at > now)
406            .filter(|k| !(k.console_url == base(console_url) && k.project_id == project_id))
407            .collect();
408        keys.push(StoredKey {
409            console_url: base(console_url).to_string(),
410            project_id: project_id.to_string(),
411            account: account.to_string(),
412            secret: key.secret.clone(),
413            expires_at: key.expires_at,
414        });
415        let text = serde_json::to_string(&keys).map_err(|e| e.to_string())?;
416        write_private(&self.path, &text)
417            .map_err(|e| format!("cannot write {}: {e}", self.path.display()))
418    }
419
420    /// Forget every kept key (on logout). The keys stay valid at the gateway
421    /// until they expire; they are only no longer on this machine.
422    pub fn clear(&self) -> std::io::Result<()> {
423        match std::fs::remove_file(&self.path) {
424            Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
425            _ => Ok(()),
426        }
427    }
428}
429
430/// Write `text` to `path` so that it is never readable by anyone else: a new
431/// file created with the user's permissions only, then moved into place.
432fn write_private(path: &Path, text: &str) -> std::io::Result<()> {
433    use std::io::Write;
434    let dir = path.parent().unwrap_or(Path::new("."));
435    std::fs::create_dir_all(dir)?;
436    let tmp = path.with_extension(format!("tmp{}", std::process::id()));
437    let _ = std::fs::remove_file(&tmp);
438    let mut options = std::fs::OpenOptions::new();
439    options.write(true).create_new(true);
440    #[cfg(unix)]
441    {
442        use std::os::unix::fs::OpenOptionsExt;
443        options.mode(0o600);
444    }
445    let written = options
446        .open(&tmp)
447        .and_then(|mut file| file.write_all(text.as_bytes()));
448    match written.and_then(|()| std::fs::rename(&tmp, path)) {
449        Ok(()) => Ok(()),
450        Err(e) => {
451            let _ = std::fs::remove_file(&tmp);
452            Err(e)
453        }
454    }
455}
456
457/// A key from [`ensure_key`].
458pub struct EnsuredKey {
459    pub key: IssuedKey,
460    /// Issued just now, rather than found in the store.
461    pub issued: bool,
462}
463
464/// The developer's key for `project_id`: the stored one while it lasts, else a
465/// new one, which is then stored (a key that cannot be stored is an error). `rejected` is a key the gateway no longer
466/// takes (revoked by a newer one issued elsewhere): the stored key is used
467/// only if it is another one.
468///
469/// Looking, issuing and storing happen under the store's lock, so sessions
470/// starting side by side end up sharing one key instead of revoking each
471/// other's.
472pub async fn ensure_key(
473    http: &reqwest::Client,
474    console_url: &str,
475    token: &str,
476    project_id: &str,
477    store: &KeyStore,
478    now: i64,
479    rejected: Option<&str>,
480) -> Result<EnsuredKey, String> {
481    let account = account_of(token);
482    // Waiting for another process must not hold up this runtime's thread.
483    let locking = store.clone();
484    let lock = tokio::task::spawn_blocking(move || locking.lock())
485        .await
486        .map_err(|e| e.to_string())
487        .and_then(|locked| locked.map_err(|e| e.to_string()));
488    let stored = store
489        .usable(console_url, project_id, &account, now)
490        .filter(|key| Some(key.secret.as_str()) != rejected);
491    if let Some(key) = stored {
492        return Ok(EnsuredKey { key, issued: false });
493    }
494    // A kept key is read without the lock just as well. A new one is not
495    // issued without it: issuing revokes the key another session, issuing at
496    // the same moment, is about to use.
497    let _lock = lock.map_err(|why| {
498        format!(
499            "the personal AI Gateway key store {} could not be locked: {why}",
500            store.path.display()
501        )
502    })?;
503    let key = issue_key(http, console_url, token, project_id, now).await?;
504    // A key that is not kept is issued again by the next session, and by the
505    // agent's own key helper, each time revoking the one in use: that is no
506    // working gateway session.
507    store
508        .keep(console_url, project_id, &account, &key, now)
509        .map_err(|why| format!("the personal AI Gateway key could not be kept: {why}"))?;
510    Ok(EnsuredKey { key, issued: true })
511}
512
513#[cfg(test)]
514mod tests {
515    use super::*;
516    use crate::test_http::MockServer;
517
518    fn project(id: &str, slug: &str) -> OpenProject {
519        OpenProject {
520            id: id.to_string(),
521            slug: slug.to_string(),
522            name: slug.to_uppercase(),
523        }
524    }
525
526    #[tokio::test]
527    async fn the_llm_address_comes_from_the_consoles_settings() {
528        let http = reqwest::Client::new();
529        let server = MockServer::start(&[(
530            "GET /api/settings",
531            200,
532            r#"{"llmGatewayUrl":"https://llm.example.com/","mcpGatewayUrl":"https://mcp.example.com","suite":[],"controlPlaneUrl":null}"#,
533        )]);
534        assert_eq!(
535            llm_gateway_url(&http, &format!("{}/", server.url), "tok").await,
536            Ok("https://llm.example.com".to_string())
537        );
538        assert_eq!(
539            server.requests()[0].authorization.as_deref(),
540            Some("Bearer tok")
541        );
542    }
543
544    #[tokio::test]
545    async fn open_projects_are_listed_with_the_persons_token() {
546        let http = reqwest::Client::new();
547        let server = MockServer::start(&[(
548            "GET /api/me/keys",
549            200,
550            r#"{"hours":24,"projects":[{"id":"p-1","slug":"alpha","name":"Alpha","budget":null}],"keys":[]}"#,
551        )]);
552        assert_eq!(
553            open_projects(&http, &server.url, "tok").await,
554            Ok(vec![OpenProject {
555                id: "p-1".to_string(),
556                slug: "alpha".to_string(),
557                name: "Alpha".to_string()
558            }])
559        );
560    }
561
562    #[tokio::test]
563    async fn a_key_is_issued_for_the_project() {
564        let http = reqwest::Client::new();
565        let server = MockServer::start(&[(
566            "POST /api/me/keys",
567            201,
568            r#"{"secret":"sk-abc","id":"hash","name":"personal-x-1","expiresAt":"2026-11-20T10:00:00.250000+00:00"}"#,
569        )]);
570        let key = issue_key(&http, &server.url, "tok", "p-1", 0)
571            .await
572            .unwrap();
573        assert_eq!(key.secret, "sk-abc");
574        assert_eq!(
575            key.expires_at,
576            chrono::DateTime::parse_from_rfc3339("2026-11-20T10:00:00Z")
577                .unwrap()
578                .timestamp()
579        );
580        let asked = &server.requests()[0];
581        assert_eq!(asked.authorization.as_deref(), Some("Bearer tok"));
582        assert_eq!(asked.body, r#"{"projectId":"p-1"}"#);
583    }
584
585    #[tokio::test]
586    async fn the_consoles_refusal_is_passed_on_in_its_words() {
587        let http = reqwest::Client::new();
588        let server = MockServer::start(&[
589            (
590                "POST /api/me/keys",
591                400,
592                r#"{"error":"Alpha does not allow personal keys; ask an operator to switch them on (Budgets)"}"#,
593            ),
594            ("GET /api/me/keys", 401, ""),
595        ]);
596        let err = issue_key(&http, &server.url, "tok", "p-1", 0)
597            .await
598            .err()
599            .unwrap();
600        assert!(err.contains("does not allow personal keys"), "{err}");
601        assert!(err.contains("HTTP 400"), "{err}");
602        let err = open_projects(&http, &server.url, "tok").await.unwrap_err();
603        assert!(err.contains("did not accept this login"), "{err}");
604        let err = open_projects(&http, "http://127.0.0.1:1", "tok")
605            .await
606            .unwrap_err();
607        assert!(err.contains("did not answer"), "{err}");
608    }
609
610    #[test]
611    fn expiry_is_read_in_the_forms_the_gateway_uses() {
612        let at = chrono::DateTime::parse_from_rfc3339("2026-11-20T10:00:00Z")
613            .unwrap()
614            .timestamp();
615        assert_eq!(expiry_seconds(Some("2026-11-20T10:00:00Z"), 0), at);
616        assert_eq!(expiry_seconds(Some("2026-11-20T11:00:00+01:00"), 0), at);
617        assert_eq!(expiry_seconds(Some("2026-11-20T10:00:00.123456"), 0), at);
618        // Not stated, or not understood: a short assumed life.
619        assert_eq!(expiry_seconds(None, 1000), 1000 + UNKNOWN_EXPIRY_SECONDS);
620        assert_eq!(
621            expiry_seconds(Some("tomorrow"), 1000),
622            1000 + UNKNOWN_EXPIRY_SECONDS
623        );
624    }
625
626    #[tokio::test]
627    async fn models_are_the_aliases_the_key_may_call() {
628        let http = reqwest::Client::new();
629        let server = MockServer::start(&[(
630            "GET /v1/models",
631            200,
632            r#"{"object":"list","data":[{"id":"gpt-general","object":"model"},{"id":"claude-sonnet","object":"model"}]}"#,
633        )]);
634        assert_eq!(
635            models(&http, &server.url, "sk-abc").await,
636            Ok(vec!["gpt-general".to_string(), "claude-sonnet".to_string()])
637        );
638        assert_eq!(
639            server.requests()[0].authorization.as_deref(),
640            Some("Bearer sk-abc")
641        );
642    }
643
644    #[test]
645    fn the_project_is_the_configured_one_or_the_only_one() {
646        let one = [project("p-1", "alpha")];
647        let two = [project("p-1", "alpha"), project("p-2", "beta")];
648        assert_eq!(pick_project(None, &one).unwrap().id, "p-1");
649        assert_eq!(pick_project(Some(" beta "), &two).unwrap().id, "p-2");
650        assert_eq!(pick_project(Some("p-2"), &two).unwrap().slug, "beta");
651        assert_eq!(pick_project(Some("BETA"), &two).unwrap().id, "p-2");
652        let err = pick_project(None, &two).unwrap_err();
653        assert!(
654            err.contains("alpha, beta") && err.contains("`project` under `[gateway]`"),
655            "{err}"
656        );
657        let err = pick_project(Some("gamma"), &two).unwrap_err();
658        assert!(
659            err.contains("`gamma`") && err.contains("alpha, beta"),
660            "{err}"
661        );
662        let err = pick_project(Some("alpha"), &[]).unwrap_err();
663        assert!(err.contains("personal keys on"), "{err}");
664    }
665
666    #[test]
667    fn the_model_is_the_configured_one_or_one_named_for_the_agent() {
668        let aliases: Vec<String> = ["demo-assistant", "gpt-general", "claude-sonnet"]
669            .map(String::from)
670            .to_vec();
671        assert_eq!(
672            pick_model(Agent::ClaudeCode, None, &aliases).as_deref(),
673            Some("claude-sonnet")
674        );
675        assert_eq!(
676            pick_model(Agent::Codex, None, &aliases).as_deref(),
677            Some("gpt-general")
678        );
679        assert_eq!(
680            pick_model(Agent::Codex, Some(" local-coder "), &aliases).as_deref(),
681            Some("local-coder")
682        );
683        assert_eq!(
684            pick_model(Agent::ClaudeCode, None, &["local-coder".to_string()]),
685            None
686        );
687    }
688
689    #[test]
690    fn a_stored_key_is_reused_until_shortly_before_it_expires() {
691        let tmp = tempfile::tempdir().unwrap();
692        let store = KeyStore::at(key_store_path_in(tmp.path()));
693        let key = IssuedKey {
694            secret: "sk-abc".to_string(),
695            expires_at: 10_000,
696        };
697        assert!(store
698            .usable("https://gw.example.com", "p-1", "", 0)
699            .is_none());
700        store
701            .keep("https://gw.example.com/", "p-1", "", &key, 0)
702            .unwrap();
703        let again = store
704            .usable("https://gw.example.com", "p-1", "", 0)
705            .unwrap();
706        assert_eq!(again.secret, "sk-abc");
707        // Another project or console has its own key.
708        assert!(store
709            .usable("https://gw.example.com", "p-2", "", 0)
710            .is_none());
711        assert!(store
712            .usable("https://other.example.com", "p-1", "", 0)
713            .is_none());
714        // Close to expiry it is no longer handed out.
715        let late = 10_000 - MIN_KEY_SECONDS_LEFT + 1;
716        assert!(store
717            .usable("https://gw.example.com", "p-1", "", late)
718            .is_none());
719        assert!(store
720            .usable("https://gw.example.com", "p-1", "", late - 1)
721            .is_some());
722    }
723
724    #[test]
725    fn keeping_a_key_replaces_the_old_one_and_drops_expired_ones() {
726        let tmp = tempfile::tempdir().unwrap();
727        let store = KeyStore::at(key_store_path_in(tmp.path()));
728        let key = |secret: &str, expires_at| IssuedKey {
729            secret: secret.to_string(),
730            expires_at,
731        };
732        store
733            .keep("https://gw", "p-1", "", &key("old", 5_000), 0)
734            .unwrap();
735        store
736            .keep("https://gw", "p-2", "", &key("other", 9_000), 0)
737            .unwrap();
738        store
739            .keep("https://gw", "p-1", "", &key("new", 90_000), 6_000)
740            .unwrap();
741        assert_eq!(
742            store.usable("https://gw", "p-1", "", 6_000).unwrap().secret,
743            "new"
744        );
745        assert_eq!(
746            store.usable("https://gw", "p-2", "", 6_000).unwrap().secret,
747            "other"
748        );
749        store
750            .keep("https://gw", "p-3", "", &key("third", 99_000), 9_500)
751            .unwrap();
752        assert_eq!(store.load().len(), 2, "the expired p-2 key is gone");
753    }
754
755    #[cfg(unix)]
756    #[test]
757    fn the_key_file_is_the_users_alone() {
758        use std::os::unix::fs::PermissionsExt;
759        let tmp = tempfile::tempdir().unwrap();
760        let path = key_store_path_in(tmp.path());
761        let store = KeyStore::at(path.clone());
762        let key = IssuedKey {
763            secret: "sk-abc".to_string(),
764            expires_at: 10_000,
765        };
766        store.keep("https://gw", "p-1", "", &key, 0).unwrap();
767        store.keep("https://gw", "p-2", "", &key, 0).unwrap();
768        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
769        assert_eq!(mode & 0o777, 0o600);
770    }
771
772    #[tokio::test]
773    async fn a_key_is_issued_once_and_then_reused() {
774        let http = reqwest::Client::new();
775        let tmp = tempfile::tempdir().unwrap();
776        let store = KeyStore::at(key_store_path_in(tmp.path()));
777        let server = MockServer::start(&[(
778            "POST /api/me/keys",
779            201,
780            r#"{"secret":"sk-abc","id":"h","name":"n","expiresAt":"2026-11-20T10:00:00Z"}"#,
781        )]);
782        let now = chrono::DateTime::parse_from_rfc3339("2026-11-19T10:00:00Z")
783            .unwrap()
784            .timestamp();
785        let first = ensure_key(&http, &server.url, "tok", "p-1", &store, now, None)
786            .await
787            .unwrap();
788        assert_eq!((first.key.secret.as_str(), first.issued), ("sk-abc", true));
789        let second = ensure_key(&http, &server.url, "tok", "p-1", &store, now + 3600, None)
790            .await
791            .unwrap();
792        assert_eq!(
793            (second.key.secret.as_str(), second.issued),
794            ("sk-abc", false)
795        );
796        assert_eq!(server.routes(), ["POST /api/me/keys"], "issued once");
797        // A day later it has expired: a new one is issued.
798        ensure_key(&http, &server.url, "tok", "p-1", &store, now + 86_400, None)
799            .await
800            .unwrap();
801        assert_eq!(server.routes().len(), 2);
802    }
803
804    /// A JWT as Keycloak issues one, unsigned: only its claims are read here.
805    fn token_of(iss: &str, sub: &str) -> String {
806        use base64::Engine;
807        let part = |json: String| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json);
808        format!(
809            "{}.{}.signature",
810            part(r#"{"alg":"RS256"}"#.to_string()),
811            part(format!(r#"{{"iss":"{iss}","sub":"{sub}","exp":1}}"#))
812        )
813    }
814
815    #[test]
816    fn the_account_is_the_tokens_issuer_and_subject() {
817        let alice = token_of("https://idp/realms/visdom", "alice-id");
818        assert_eq!(account_of(&alice), "https://idp/realms/visdom|alice-id");
819        assert_ne!(
820            account_of(&alice),
821            account_of(&token_of("https://idp/realms/visdom", "bob-id"))
822        );
823        assert_ne!(
824            account_of(&alice),
825            account_of(&token_of("https://idp/realms/other", "alice-id"))
826        );
827        // Not a JWT, or one without a subject: no account.
828        for opaque in ["person-access-token", "a.b.c", "a.b", "", "a.b.c.d"] {
829            assert_eq!(account_of(opaque), "", "{opaque}");
830        }
831        assert_eq!(account_of(&token_of("https://idp", "")), "");
832    }
833
834    #[tokio::test]
835    async fn a_kept_key_is_not_handed_to_another_account() {
836        let http = reqwest::Client::new();
837        let tmp = tempfile::tempdir().unwrap();
838        let store = KeyStore::at(key_store_path_in(tmp.path()));
839        let server = MockServer::start(&[
840            (
841                "POST /api/me/keys",
842                201,
843                r#"{"secret":"sk-alice","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
844            ),
845            (
846                "POST /api/me/keys",
847                201,
848                r#"{"secret":"sk-bob","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
849            ),
850        ]);
851        let alice = token_of("https://idp", "alice-id");
852        let bob = token_of("https://idp", "bob-id");
853        let first = ensure_key(&http, &server.url, &alice, "p-1", &store, 0, None)
854            .await
855            .unwrap();
856        assert_eq!(first.key.secret, "sk-alice");
857        // Bob logs in on the same machine: Alice's key is not his.
858        let second = ensure_key(&http, &server.url, &bob, "p-1", &store, 0, None)
859            .await
860            .unwrap();
861        assert_eq!(
862            (second.key.secret.as_str(), second.issued),
863            ("sk-bob", true)
864        );
865        let asked = server.requests();
866        assert_eq!(asked.len(), 2);
867        assert_eq!(asked[1].authorization, Some(format!("Bearer {bob}")));
868        // And Alice's is gone from the file, not kept beside his.
869        assert!(store
870            .usable(&server.url, "p-1", &account_of(&alice), 0)
871            .is_none());
872        assert_eq!(store.load().len(), 1);
873    }
874
875    #[tokio::test]
876    async fn a_rejected_key_is_replaced_unless_somebody_already_did() {
877        let http = reqwest::Client::new();
878        let tmp = tempfile::tempdir().unwrap();
879        let store = KeyStore::at(key_store_path_in(tmp.path()));
880        let server = MockServer::start(&[(
881            "POST /api/me/keys",
882            201,
883            r#"{"secret":"sk-new","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
884        )]);
885        let old = IssuedKey {
886            secret: "sk-old".to_string(),
887            expires_at: 4_000_000_000,
888        };
889        store.keep(&server.url, "p-1", "", &old, 0).unwrap();
890        // The gateway refused sk-old: the stored copy is not offered again.
891        let renewed = ensure_key(&http, &server.url, "tok", "p-1", &store, 0, Some("sk-old"))
892            .await
893            .unwrap();
894        assert_eq!(
895            (renewed.key.secret.as_str(), renewed.issued),
896            ("sk-new", true)
897        );
898        // Another session that also saw sk-old refused finds the new one.
899        let other = ensure_key(&http, &server.url, "tok", "p-1", &store, 0, Some("sk-old"))
900            .await
901            .unwrap();
902        assert_eq!((other.key.secret.as_str(), other.issued), ("sk-new", false));
903        assert_eq!(server.routes().len(), 1);
904    }
905
906    /// Issuing revokes the previous key, so sessions starting together must
907    /// end up with one key: the later ones wait and find the first one's.
908    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
909    async fn sessions_starting_together_issue_one_key() {
910        let tmp = tempfile::tempdir().unwrap();
911        let store = KeyStore::at(key_store_path_in(tmp.path()));
912        let server = MockServer::start(&[
913            (
914                "POST /api/me/keys",
915                201,
916                r#"{"secret":"sk-first","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
917            ),
918            (
919                "POST /api/me/keys",
920                201,
921                r#"{"secret":"sk-second","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
922            ),
923        ]);
924        let starts = (0..6).map(|_| {
925            let (store, url) = (store.clone(), server.url.clone());
926            tokio::spawn(async move {
927                let http = reqwest::Client::new();
928                ensure_key(&http, &url, "tok", "p-1", &store, 0, None)
929                    .await
930                    .unwrap()
931                    .key
932                    .secret
933            })
934        });
935        let mut secrets = Vec::new();
936        for start in starts.collect::<Vec<_>>() {
937            secrets.push(start.await.unwrap());
938        }
939        assert_eq!(secrets, ["sk-first"; 6]);
940        assert_eq!(server.routes(), ["POST /api/me/keys"]);
941    }
942
943    #[tokio::test]
944    async fn a_gateway_that_refuses_the_key_is_told_from_one_that_is_away() {
945        let http = reqwest::Client::new();
946        let server = MockServer::start(&[
947            ("GET /v1/models", 401, r#"{"error":"bad key"}"#),
948            ("GET /v1/models", 403, ""),
949            ("GET /v1/models", 500, ""),
950            ("GET /v1/models", 200, "not json"),
951        ]);
952        for (rejected, said) in [
953            (true, "did not accept the personal key (HTTP 401)"),
954            (true, "HTTP 403"),
955            (false, "HTTP 500"),
956            (false, "unreadable answer"),
957        ] {
958            let err = models(&http, &server.url, "sk").await.unwrap_err();
959            assert_eq!(err.rejected, rejected, "{}", err.why);
960            assert!(err.why.contains(said), "{}", err.why);
961        }
962        let err = models(&http, "http://127.0.0.1:1", "sk").await.unwrap_err();
963        assert!(
964            !err.rejected && err.why.contains("did not answer"),
965            "{}",
966            err.why
967        );
968    }
969
970    #[cfg(unix)]
971    #[tokio::test]
972    async fn a_key_that_cannot_be_kept_is_an_error() {
973        let http = reqwest::Client::new();
974        let tmp = tempfile::tempdir().unwrap();
975        // The store's file cannot be replaced: a directory is in its place.
976        let store = KeyStore::at(key_store_path_in(tmp.path()));
977        std::fs::create_dir_all(&store.path).unwrap();
978        let server = MockServer::start(&[(
979            "POST /api/me/keys",
980            201,
981            r#"{"secret":"sk-abc","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
982        )]);
983        let err = ensure_key(&http, &server.url, "tok", "p-1", &store, 0, None)
984            .await
985            .err()
986            .unwrap();
987        assert!(err.contains("could not be kept"), "{err}");
988        assert!(!err.contains("sk-abc"), "{err}");
989    }
990
991    /// Issuing revokes the key in use, so it is not done without the lock
992    /// that keeps two sessions from doing it at once; a kept key needs none.
993    #[tokio::test]
994    async fn no_key_is_issued_while_the_store_cannot_be_locked() {
995        let http = reqwest::Client::new();
996        let tmp = tempfile::tempdir().unwrap();
997        let store = KeyStore::at(key_store_path_in(tmp.path()));
998        // The lock file cannot be opened: a directory is in its place.
999        std::fs::create_dir_all(store.path.with_extension("lock")).unwrap();
1000        let server = MockServer::start(&[(
1001            "POST /api/me/keys",
1002            201,
1003            r#"{"secret":"sk-abc","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
1004        )]);
1005        let err = ensure_key(&http, &server.url, "tok", "p-1", &store, 0, None)
1006            .await
1007            .err()
1008            .unwrap();
1009        assert!(err.contains("could not be locked"), "{err}");
1010        assert!(server.routes().is_empty(), "{:?}", server.routes());
1011
1012        let kept = IssuedKey {
1013            secret: "sk-kept".to_string(),
1014            expires_at: 1_000_000,
1015        };
1016        let account = account_of("tok");
1017        store.keep(&server.url, "p-1", &account, &kept, 0).unwrap();
1018        let ensured = ensure_key(&http, &server.url, "tok", "p-1", &store, 0, None)
1019            .await
1020            .unwrap();
1021        assert_eq!(ensured.key.secret, "sk-kept");
1022        assert!(!ensured.issued);
1023        assert!(server.routes().is_empty(), "{:?}", server.routes());
1024    }
1025
1026    #[test]
1027    fn clearing_the_store_forgets_every_key() {
1028        let tmp = tempfile::tempdir().unwrap();
1029        let store = KeyStore::at(key_store_path_in(tmp.path()));
1030        assert!(store.clear().is_ok(), "nothing to forget is fine");
1031        let key = IssuedKey {
1032            secret: "sk-abc".to_string(),
1033            expires_at: 10_000,
1034        };
1035        store.keep("https://gw", "p-1", "", &key, 0).unwrap();
1036        store.clear().unwrap();
1037        assert!(store.usable("https://gw", "p-1", "", 0).is_none());
1038    }
1039}