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",
258            names()
259        )),
260    }
261}
262
263/// The model alias an agent should ask for: the configured one, else the
264/// first alias that looks made for that agent, else none (the agent's own
265/// default, which the project must then allow).
266pub fn pick_model(agent: Agent, configured: Option<&str>, available: &[String]) -> Option<String> {
267    if let Some(model) = configured.map(str::trim).filter(|m| !m.is_empty()) {
268        return Some(model.to_string());
269    }
270    let hints: &[&str] = match agent {
271        Agent::ClaudeCode => &["claude", "sonnet", "opus"],
272        Agent::Codex => &["codex", "gpt"],
273        _ => &[],
274    };
275    hints.iter().find_map(|hint| {
276        available
277            .iter()
278            .find(|alias| alias.to_ascii_lowercase().contains(hint))
279            .cloned()
280    })
281}
282
283/// Whose key it is: the issuer and subject of the developer's access token.
284/// A key is the person's, so one kept for somebody else who logged in on this
285/// machine before must not be handed out. Empty for a token that is not a
286/// readable JWT, which then cannot be told apart from another such token.
287pub fn account_of(token: &str) -> String {
288    use base64::Engine;
289    #[derive(Deserialize)]
290    struct Claims {
291        #[serde(default)]
292        iss: String,
293        sub: String,
294    }
295    let mut parts = token.split('.');
296    let (Some(_), Some(payload), Some(_), None) =
297        (parts.next(), parts.next(), parts.next(), parts.next())
298    else {
299        return String::new();
300    };
301    base64::engine::general_purpose::URL_SAFE_NO_PAD
302        .decode(payload.trim_end_matches('='))
303        .ok()
304        .and_then(|bytes| serde_json::from_slice::<Claims>(&bytes).ok())
305        .filter(|claims| !claims.sub.is_empty())
306        .map(|claims| format!("{}|{}", claims.iss, claims.sub))
307        .unwrap_or_default()
308}
309
310/// One stored personal key.
311#[derive(Clone, Serialize, Deserialize)]
312struct StoredKey {
313    console_url: String,
314    project_id: String,
315    /// [`account_of`] the token it was issued for.
316    #[serde(default)]
317    account: String,
318    secret: String,
319    expires_at: i64,
320}
321
322impl StoredKey {
323    fn is_for(&self, console_url: &str, project_id: &str, account: &str) -> bool {
324        self.console_url == base(console_url)
325            && self.project_id == project_id
326            && self.account == account
327    }
328}
329
330/// The personal keys `visdom` holds, one per console, project and account.
331#[derive(Clone)]
332pub struct KeyStore {
333    path: PathBuf,
334}
335
336pub fn key_store_path_in(config_root: &Path) -> PathBuf {
337    config_root.join("visdom").join("gateway-keys.json")
338}
339
340/// Held while a key is looked up, issued and stored; released when dropped.
341pub struct KeyStoreLock(#[allow(dead_code)] std::fs::File);
342
343impl KeyStore {
344    pub fn at(path: PathBuf) -> KeyStore {
345        KeyStore { path }
346    }
347
348    fn load(&self) -> Vec<StoredKey> {
349        std::fs::read_to_string(&self.path)
350            .ok()
351            .and_then(|text| serde_json::from_str(&text).ok())
352            .unwrap_or_default()
353    }
354
355    /// Wait for this store to be free of every other `visdom` process, and
356    /// take it. Issuing a key revokes the previous one, so two sessions
357    /// starting together must not both issue: the second waits here and then
358    /// finds the first one's key.
359    pub fn lock(&self) -> std::io::Result<KeyStoreLock> {
360        let dir = self.path.parent().unwrap_or(Path::new("."));
361        std::fs::create_dir_all(dir)?;
362        let file = std::fs::OpenOptions::new()
363            .create(true)
364            .truncate(false)
365            .write(true)
366            .open(self.path.with_extension("lock"))?;
367        file.lock()?;
368        Ok(KeyStoreLock(file))
369    }
370
371    /// The stored key of `account` for this console and project, when it has
372    /// at least [`MIN_KEY_SECONDS_LEFT`] left.
373    pub fn usable(
374        &self,
375        console_url: &str,
376        project_id: &str,
377        account: &str,
378        now: i64,
379    ) -> Option<IssuedKey> {
380        self.load()
381            .into_iter()
382            .find(|k| k.is_for(console_url, project_id, account))
383            .filter(|k| k.expires_at - now >= MIN_KEY_SECONDS_LEFT)
384            .map(|k| IssuedKey {
385                secret: k.secret,
386                expires_at: k.expires_at,
387            })
388    }
389
390    /// Keep `key`, replacing the one for the same console and project
391    /// (whoever's it was: this machine's user is now `account`) and dropping
392    /// keys that have expired. The file is the user's alone.
393    pub fn keep(
394        &self,
395        console_url: &str,
396        project_id: &str,
397        account: &str,
398        key: &IssuedKey,
399        now: i64,
400    ) -> Result<(), String> {
401        let mut keys: Vec<StoredKey> = self
402            .load()
403            .into_iter()
404            .filter(|k| k.expires_at > now)
405            .filter(|k| !(k.console_url == base(console_url) && k.project_id == project_id))
406            .collect();
407        keys.push(StoredKey {
408            console_url: base(console_url).to_string(),
409            project_id: project_id.to_string(),
410            account: account.to_string(),
411            secret: key.secret.clone(),
412            expires_at: key.expires_at,
413        });
414        let text = serde_json::to_string(&keys).map_err(|e| e.to_string())?;
415        write_private(&self.path, &text)
416            .map_err(|e| format!("cannot write {}: {e}", self.path.display()))
417    }
418
419    /// Forget every kept key (on logout). The keys stay valid at the gateway
420    /// until they expire; they are only no longer on this machine.
421    pub fn clear(&self) -> std::io::Result<()> {
422        match std::fs::remove_file(&self.path) {
423            Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
424            _ => Ok(()),
425        }
426    }
427}
428
429/// Write `text` to `path` so that it is never readable by anyone else: a new
430/// file created with the user's permissions only, then moved into place.
431fn write_private(path: &Path, text: &str) -> std::io::Result<()> {
432    use std::io::Write;
433    let dir = path.parent().unwrap_or(Path::new("."));
434    std::fs::create_dir_all(dir)?;
435    let tmp = path.with_extension(format!("tmp{}", std::process::id()));
436    let _ = std::fs::remove_file(&tmp);
437    let mut options = std::fs::OpenOptions::new();
438    options.write(true).create_new(true);
439    #[cfg(unix)]
440    {
441        use std::os::unix::fs::OpenOptionsExt;
442        options.mode(0o600);
443    }
444    let written = options
445        .open(&tmp)
446        .and_then(|mut file| file.write_all(text.as_bytes()));
447    match written.and_then(|()| std::fs::rename(&tmp, path)) {
448        Ok(()) => Ok(()),
449        Err(e) => {
450            let _ = std::fs::remove_file(&tmp);
451            Err(e)
452        }
453    }
454}
455
456/// A key from [`ensure_key`].
457pub struct EnsuredKey {
458    pub key: IssuedKey,
459    /// Issued just now, rather than found in the store.
460    pub issued: bool,
461}
462
463/// The developer's key for `project_id`: the stored one while it lasts, else a
464/// new one, which is then stored (a key that cannot be stored is an error). `rejected` is a key the gateway no longer
465/// takes (revoked by a newer one issued elsewhere): the stored key is used
466/// only if it is another one.
467///
468/// Looking, issuing and storing happen under the store's lock, so sessions
469/// starting side by side end up sharing one key instead of revoking each
470/// other's.
471pub async fn ensure_key(
472    http: &reqwest::Client,
473    console_url: &str,
474    token: &str,
475    project_id: &str,
476    store: &KeyStore,
477    now: i64,
478    rejected: Option<&str>,
479) -> Result<EnsuredKey, String> {
480    let account = account_of(token);
481    // Waiting for another process must not hold up this runtime's thread.
482    let locking = store.clone();
483    let lock = tokio::task::spawn_blocking(move || locking.lock())
484        .await
485        .map_err(|e| e.to_string())
486        .and_then(|locked| locked.map_err(|e| e.to_string()));
487    let stored = store
488        .usable(console_url, project_id, &account, now)
489        .filter(|key| Some(key.secret.as_str()) != rejected);
490    if let Some(key) = stored {
491        return Ok(EnsuredKey { key, issued: false });
492    }
493    // A kept key is read without the lock just as well. A new one is not
494    // issued without it: issuing revokes the key another session, issuing at
495    // the same moment, is about to use.
496    let _lock = lock.map_err(|why| {
497        format!(
498            "the personal AI Gateway key store {} could not be locked: {why}",
499            store.path.display()
500        )
501    })?;
502    let key = issue_key(http, console_url, token, project_id, now).await?;
503    // A key that is not kept is issued again by the next session, and by the
504    // agent's own key helper, each time revoking the one in use: that is no
505    // working gateway session.
506    store
507        .keep(console_url, project_id, &account, &key, now)
508        .map_err(|why| format!("the personal AI Gateway key could not be kept: {why}"))?;
509    Ok(EnsuredKey { key, issued: true })
510}
511
512#[cfg(test)]
513mod tests {
514    use super::*;
515    use crate::test_http::MockServer;
516
517    fn project(id: &str, slug: &str) -> OpenProject {
518        OpenProject {
519            id: id.to_string(),
520            slug: slug.to_string(),
521            name: slug.to_uppercase(),
522        }
523    }
524
525    #[tokio::test]
526    async fn the_llm_address_comes_from_the_consoles_settings() {
527        let http = reqwest::Client::new();
528        let server = MockServer::start(&[(
529            "GET /api/settings",
530            200,
531            r#"{"llmGatewayUrl":"https://llm.example.com/","mcpGatewayUrl":"https://mcp.example.com","suite":[],"controlPlaneUrl":null}"#,
532        )]);
533        assert_eq!(
534            llm_gateway_url(&http, &format!("{}/", server.url), "tok").await,
535            Ok("https://llm.example.com".to_string())
536        );
537        assert_eq!(
538            server.requests()[0].authorization.as_deref(),
539            Some("Bearer tok")
540        );
541    }
542
543    #[tokio::test]
544    async fn open_projects_are_listed_with_the_persons_token() {
545        let http = reqwest::Client::new();
546        let server = MockServer::start(&[(
547            "GET /api/me/keys",
548            200,
549            r#"{"hours":24,"projects":[{"id":"p-1","slug":"alpha","name":"Alpha","budget":null}],"keys":[]}"#,
550        )]);
551        assert_eq!(
552            open_projects(&http, &server.url, "tok").await,
553            Ok(vec![OpenProject {
554                id: "p-1".to_string(),
555                slug: "alpha".to_string(),
556                name: "Alpha".to_string()
557            }])
558        );
559    }
560
561    #[tokio::test]
562    async fn a_key_is_issued_for_the_project() {
563        let http = reqwest::Client::new();
564        let server = MockServer::start(&[(
565            "POST /api/me/keys",
566            201,
567            r#"{"secret":"sk-abc","id":"hash","name":"personal-x-1","expiresAt":"2026-11-20T10:00:00.250000+00:00"}"#,
568        )]);
569        let key = issue_key(&http, &server.url, "tok", "p-1", 0)
570            .await
571            .unwrap();
572        assert_eq!(key.secret, "sk-abc");
573        assert_eq!(
574            key.expires_at,
575            chrono::DateTime::parse_from_rfc3339("2026-11-20T10:00:00Z")
576                .unwrap()
577                .timestamp()
578        );
579        let asked = &server.requests()[0];
580        assert_eq!(asked.authorization.as_deref(), Some("Bearer tok"));
581        assert_eq!(asked.body, r#"{"projectId":"p-1"}"#);
582    }
583
584    #[tokio::test]
585    async fn the_consoles_refusal_is_passed_on_in_its_words() {
586        let http = reqwest::Client::new();
587        let server = MockServer::start(&[
588            (
589                "POST /api/me/keys",
590                400,
591                r#"{"error":"Alpha does not allow personal keys; ask an operator to switch them on (Budgets)"}"#,
592            ),
593            ("GET /api/me/keys", 401, ""),
594        ]);
595        let err = issue_key(&http, &server.url, "tok", "p-1", 0)
596            .await
597            .err()
598            .unwrap();
599        assert!(err.contains("does not allow personal keys"), "{err}");
600        assert!(err.contains("HTTP 400"), "{err}");
601        let err = open_projects(&http, &server.url, "tok").await.unwrap_err();
602        assert!(err.contains("did not accept this login"), "{err}");
603        let err = open_projects(&http, "http://127.0.0.1:1", "tok")
604            .await
605            .unwrap_err();
606        assert!(err.contains("did not answer"), "{err}");
607    }
608
609    #[test]
610    fn expiry_is_read_in_the_forms_the_gateway_uses() {
611        let at = chrono::DateTime::parse_from_rfc3339("2026-11-20T10:00:00Z")
612            .unwrap()
613            .timestamp();
614        assert_eq!(expiry_seconds(Some("2026-11-20T10:00:00Z"), 0), at);
615        assert_eq!(expiry_seconds(Some("2026-11-20T11:00:00+01:00"), 0), at);
616        assert_eq!(expiry_seconds(Some("2026-11-20T10:00:00.123456"), 0), at);
617        // Not stated, or not understood: a short assumed life.
618        assert_eq!(expiry_seconds(None, 1000), 1000 + UNKNOWN_EXPIRY_SECONDS);
619        assert_eq!(
620            expiry_seconds(Some("tomorrow"), 1000),
621            1000 + UNKNOWN_EXPIRY_SECONDS
622        );
623    }
624
625    #[tokio::test]
626    async fn models_are_the_aliases_the_key_may_call() {
627        let http = reqwest::Client::new();
628        let server = MockServer::start(&[(
629            "GET /v1/models",
630            200,
631            r#"{"object":"list","data":[{"id":"gpt-general","object":"model"},{"id":"claude-sonnet","object":"model"}]}"#,
632        )]);
633        assert_eq!(
634            models(&http, &server.url, "sk-abc").await,
635            Ok(vec!["gpt-general".to_string(), "claude-sonnet".to_string()])
636        );
637        assert_eq!(
638            server.requests()[0].authorization.as_deref(),
639            Some("Bearer sk-abc")
640        );
641    }
642
643    #[test]
644    fn the_project_is_the_configured_one_or_the_only_one() {
645        let one = [project("p-1", "alpha")];
646        let two = [project("p-1", "alpha"), project("p-2", "beta")];
647        assert_eq!(pick_project(None, &one).unwrap().id, "p-1");
648        assert_eq!(pick_project(Some(" beta "), &two).unwrap().id, "p-2");
649        assert_eq!(pick_project(Some("p-2"), &two).unwrap().slug, "beta");
650        assert_eq!(pick_project(Some("BETA"), &two).unwrap().id, "p-2");
651        let err = pick_project(None, &two).unwrap_err();
652        assert!(
653            err.contains("alpha, beta") && err.contains("`project` under `[gateway]`"),
654            "{err}"
655        );
656        let err = pick_project(Some("gamma"), &two).unwrap_err();
657        assert!(
658            err.contains("`gamma`") && err.contains("alpha, beta"),
659            "{err}"
660        );
661        let err = pick_project(Some("alpha"), &[]).unwrap_err();
662        assert!(err.contains("personal keys on"), "{err}");
663    }
664
665    #[test]
666    fn the_model_is_the_configured_one_or_one_named_for_the_agent() {
667        let aliases: Vec<String> = ["demo-assistant", "gpt-general", "claude-sonnet"]
668            .map(String::from)
669            .to_vec();
670        assert_eq!(
671            pick_model(Agent::ClaudeCode, None, &aliases).as_deref(),
672            Some("claude-sonnet")
673        );
674        assert_eq!(
675            pick_model(Agent::Codex, None, &aliases).as_deref(),
676            Some("gpt-general")
677        );
678        assert_eq!(
679            pick_model(Agent::Codex, Some(" local-coder "), &aliases).as_deref(),
680            Some("local-coder")
681        );
682        assert_eq!(
683            pick_model(Agent::ClaudeCode, None, &["local-coder".to_string()]),
684            None
685        );
686    }
687
688    #[test]
689    fn a_stored_key_is_reused_until_shortly_before_it_expires() {
690        let tmp = tempfile::tempdir().unwrap();
691        let store = KeyStore::at(key_store_path_in(tmp.path()));
692        let key = IssuedKey {
693            secret: "sk-abc".to_string(),
694            expires_at: 10_000,
695        };
696        assert!(store
697            .usable("https://gw.example.com", "p-1", "", 0)
698            .is_none());
699        store
700            .keep("https://gw.example.com/", "p-1", "", &key, 0)
701            .unwrap();
702        let again = store
703            .usable("https://gw.example.com", "p-1", "", 0)
704            .unwrap();
705        assert_eq!(again.secret, "sk-abc");
706        // Another project or console has its own key.
707        assert!(store
708            .usable("https://gw.example.com", "p-2", "", 0)
709            .is_none());
710        assert!(store
711            .usable("https://other.example.com", "p-1", "", 0)
712            .is_none());
713        // Close to expiry it is no longer handed out.
714        let late = 10_000 - MIN_KEY_SECONDS_LEFT + 1;
715        assert!(store
716            .usable("https://gw.example.com", "p-1", "", late)
717            .is_none());
718        assert!(store
719            .usable("https://gw.example.com", "p-1", "", late - 1)
720            .is_some());
721    }
722
723    #[test]
724    fn keeping_a_key_replaces_the_old_one_and_drops_expired_ones() {
725        let tmp = tempfile::tempdir().unwrap();
726        let store = KeyStore::at(key_store_path_in(tmp.path()));
727        let key = |secret: &str, expires_at| IssuedKey {
728            secret: secret.to_string(),
729            expires_at,
730        };
731        store
732            .keep("https://gw", "p-1", "", &key("old", 5_000), 0)
733            .unwrap();
734        store
735            .keep("https://gw", "p-2", "", &key("other", 9_000), 0)
736            .unwrap();
737        store
738            .keep("https://gw", "p-1", "", &key("new", 90_000), 6_000)
739            .unwrap();
740        assert_eq!(
741            store.usable("https://gw", "p-1", "", 6_000).unwrap().secret,
742            "new"
743        );
744        assert_eq!(
745            store.usable("https://gw", "p-2", "", 6_000).unwrap().secret,
746            "other"
747        );
748        store
749            .keep("https://gw", "p-3", "", &key("third", 99_000), 9_500)
750            .unwrap();
751        assert_eq!(store.load().len(), 2, "the expired p-2 key is gone");
752    }
753
754    #[cfg(unix)]
755    #[test]
756    fn the_key_file_is_the_users_alone() {
757        use std::os::unix::fs::PermissionsExt;
758        let tmp = tempfile::tempdir().unwrap();
759        let path = key_store_path_in(tmp.path());
760        let store = KeyStore::at(path.clone());
761        let key = IssuedKey {
762            secret: "sk-abc".to_string(),
763            expires_at: 10_000,
764        };
765        store.keep("https://gw", "p-1", "", &key, 0).unwrap();
766        store.keep("https://gw", "p-2", "", &key, 0).unwrap();
767        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
768        assert_eq!(mode & 0o777, 0o600);
769    }
770
771    #[tokio::test]
772    async fn a_key_is_issued_once_and_then_reused() {
773        let http = reqwest::Client::new();
774        let tmp = tempfile::tempdir().unwrap();
775        let store = KeyStore::at(key_store_path_in(tmp.path()));
776        let server = MockServer::start(&[(
777            "POST /api/me/keys",
778            201,
779            r#"{"secret":"sk-abc","id":"h","name":"n","expiresAt":"2026-11-20T10:00:00Z"}"#,
780        )]);
781        let now = chrono::DateTime::parse_from_rfc3339("2026-11-19T10:00:00Z")
782            .unwrap()
783            .timestamp();
784        let first = ensure_key(&http, &server.url, "tok", "p-1", &store, now, None)
785            .await
786            .unwrap();
787        assert_eq!((first.key.secret.as_str(), first.issued), ("sk-abc", true));
788        let second = ensure_key(&http, &server.url, "tok", "p-1", &store, now + 3600, None)
789            .await
790            .unwrap();
791        assert_eq!(
792            (second.key.secret.as_str(), second.issued),
793            ("sk-abc", false)
794        );
795        assert_eq!(server.routes(), ["POST /api/me/keys"], "issued once");
796        // A day later it has expired: a new one is issued.
797        ensure_key(&http, &server.url, "tok", "p-1", &store, now + 86_400, None)
798            .await
799            .unwrap();
800        assert_eq!(server.routes().len(), 2);
801    }
802
803    /// A JWT as Keycloak issues one, unsigned: only its claims are read here.
804    fn token_of(iss: &str, sub: &str) -> String {
805        use base64::Engine;
806        let part = |json: String| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json);
807        format!(
808            "{}.{}.signature",
809            part(r#"{"alg":"RS256"}"#.to_string()),
810            part(format!(r#"{{"iss":"{iss}","sub":"{sub}","exp":1}}"#))
811        )
812    }
813
814    #[test]
815    fn the_account_is_the_tokens_issuer_and_subject() {
816        let alice = token_of("https://idp/realms/visdom", "alice-id");
817        assert_eq!(account_of(&alice), "https://idp/realms/visdom|alice-id");
818        assert_ne!(
819            account_of(&alice),
820            account_of(&token_of("https://idp/realms/visdom", "bob-id"))
821        );
822        assert_ne!(
823            account_of(&alice),
824            account_of(&token_of("https://idp/realms/other", "alice-id"))
825        );
826        // Not a JWT, or one without a subject: no account.
827        for opaque in ["person-access-token", "a.b.c", "a.b", "", "a.b.c.d"] {
828            assert_eq!(account_of(opaque), "", "{opaque}");
829        }
830        assert_eq!(account_of(&token_of("https://idp", "")), "");
831    }
832
833    #[tokio::test]
834    async fn a_kept_key_is_not_handed_to_another_account() {
835        let http = reqwest::Client::new();
836        let tmp = tempfile::tempdir().unwrap();
837        let store = KeyStore::at(key_store_path_in(tmp.path()));
838        let server = MockServer::start(&[
839            (
840                "POST /api/me/keys",
841                201,
842                r#"{"secret":"sk-alice","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
843            ),
844            (
845                "POST /api/me/keys",
846                201,
847                r#"{"secret":"sk-bob","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
848            ),
849        ]);
850        let alice = token_of("https://idp", "alice-id");
851        let bob = token_of("https://idp", "bob-id");
852        let first = ensure_key(&http, &server.url, &alice, "p-1", &store, 0, None)
853            .await
854            .unwrap();
855        assert_eq!(first.key.secret, "sk-alice");
856        // Bob logs in on the same machine: Alice's key is not his.
857        let second = ensure_key(&http, &server.url, &bob, "p-1", &store, 0, None)
858            .await
859            .unwrap();
860        assert_eq!(
861            (second.key.secret.as_str(), second.issued),
862            ("sk-bob", true)
863        );
864        let asked = server.requests();
865        assert_eq!(asked.len(), 2);
866        assert_eq!(asked[1].authorization, Some(format!("Bearer {bob}")));
867        // And Alice's is gone from the file, not kept beside his.
868        assert!(store
869            .usable(&server.url, "p-1", &account_of(&alice), 0)
870            .is_none());
871        assert_eq!(store.load().len(), 1);
872    }
873
874    #[tokio::test]
875    async fn a_rejected_key_is_replaced_unless_somebody_already_did() {
876        let http = reqwest::Client::new();
877        let tmp = tempfile::tempdir().unwrap();
878        let store = KeyStore::at(key_store_path_in(tmp.path()));
879        let server = MockServer::start(&[(
880            "POST /api/me/keys",
881            201,
882            r#"{"secret":"sk-new","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
883        )]);
884        let old = IssuedKey {
885            secret: "sk-old".to_string(),
886            expires_at: 4_000_000_000,
887        };
888        store.keep(&server.url, "p-1", "", &old, 0).unwrap();
889        // The gateway refused sk-old: the stored copy is not offered again.
890        let renewed = ensure_key(&http, &server.url, "tok", "p-1", &store, 0, Some("sk-old"))
891            .await
892            .unwrap();
893        assert_eq!(
894            (renewed.key.secret.as_str(), renewed.issued),
895            ("sk-new", true)
896        );
897        // Another session that also saw sk-old refused finds the new one.
898        let other = ensure_key(&http, &server.url, "tok", "p-1", &store, 0, Some("sk-old"))
899            .await
900            .unwrap();
901        assert_eq!((other.key.secret.as_str(), other.issued), ("sk-new", false));
902        assert_eq!(server.routes().len(), 1);
903    }
904
905    /// Issuing revokes the previous key, so sessions starting together must
906    /// end up with one key: the later ones wait and find the first one's.
907    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
908    async fn sessions_starting_together_issue_one_key() {
909        let tmp = tempfile::tempdir().unwrap();
910        let store = KeyStore::at(key_store_path_in(tmp.path()));
911        let server = MockServer::start(&[
912            (
913                "POST /api/me/keys",
914                201,
915                r#"{"secret":"sk-first","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
916            ),
917            (
918                "POST /api/me/keys",
919                201,
920                r#"{"secret":"sk-second","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
921            ),
922        ]);
923        let starts = (0..6).map(|_| {
924            let (store, url) = (store.clone(), server.url.clone());
925            tokio::spawn(async move {
926                let http = reqwest::Client::new();
927                ensure_key(&http, &url, "tok", "p-1", &store, 0, None)
928                    .await
929                    .unwrap()
930                    .key
931                    .secret
932            })
933        });
934        let mut secrets = Vec::new();
935        for start in starts.collect::<Vec<_>>() {
936            secrets.push(start.await.unwrap());
937        }
938        assert_eq!(secrets, ["sk-first"; 6]);
939        assert_eq!(server.routes(), ["POST /api/me/keys"]);
940    }
941
942    #[tokio::test]
943    async fn a_gateway_that_refuses_the_key_is_told_from_one_that_is_away() {
944        let http = reqwest::Client::new();
945        let server = MockServer::start(&[
946            ("GET /v1/models", 401, r#"{"error":"bad key"}"#),
947            ("GET /v1/models", 403, ""),
948            ("GET /v1/models", 500, ""),
949            ("GET /v1/models", 200, "not json"),
950        ]);
951        for (rejected, said) in [
952            (true, "did not accept the personal key (HTTP 401)"),
953            (true, "HTTP 403"),
954            (false, "HTTP 500"),
955            (false, "unreadable answer"),
956        ] {
957            let err = models(&http, &server.url, "sk").await.unwrap_err();
958            assert_eq!(err.rejected, rejected, "{}", err.why);
959            assert!(err.why.contains(said), "{}", err.why);
960        }
961        let err = models(&http, "http://127.0.0.1:1", "sk").await.unwrap_err();
962        assert!(
963            !err.rejected && err.why.contains("did not answer"),
964            "{}",
965            err.why
966        );
967    }
968
969    #[cfg(unix)]
970    #[tokio::test]
971    async fn a_key_that_cannot_be_kept_is_an_error() {
972        let http = reqwest::Client::new();
973        let tmp = tempfile::tempdir().unwrap();
974        // The store's file cannot be replaced: a directory is in its place.
975        let store = KeyStore::at(key_store_path_in(tmp.path()));
976        std::fs::create_dir_all(&store.path).unwrap();
977        let server = MockServer::start(&[(
978            "POST /api/me/keys",
979            201,
980            r#"{"secret":"sk-abc","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
981        )]);
982        let err = ensure_key(&http, &server.url, "tok", "p-1", &store, 0, None)
983            .await
984            .err()
985            .unwrap();
986        assert!(err.contains("could not be kept"), "{err}");
987        assert!(!err.contains("sk-abc"), "{err}");
988    }
989
990    /// Issuing revokes the key in use, so it is not done without the lock
991    /// that keeps two sessions from doing it at once; a kept key needs none.
992    #[tokio::test]
993    async fn no_key_is_issued_while_the_store_cannot_be_locked() {
994        let http = reqwest::Client::new();
995        let tmp = tempfile::tempdir().unwrap();
996        let store = KeyStore::at(key_store_path_in(tmp.path()));
997        // The lock file cannot be opened: a directory is in its place.
998        std::fs::create_dir_all(store.path.with_extension("lock")).unwrap();
999        let server = MockServer::start(&[(
1000            "POST /api/me/keys",
1001            201,
1002            r#"{"secret":"sk-abc","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
1003        )]);
1004        let err = ensure_key(&http, &server.url, "tok", "p-1", &store, 0, None)
1005            .await
1006            .err()
1007            .unwrap();
1008        assert!(err.contains("could not be locked"), "{err}");
1009        assert!(server.routes().is_empty(), "{:?}", server.routes());
1010
1011        let kept = IssuedKey {
1012            secret: "sk-kept".to_string(),
1013            expires_at: 1_000_000,
1014        };
1015        let account = account_of("tok");
1016        store.keep(&server.url, "p-1", &account, &kept, 0).unwrap();
1017        let ensured = ensure_key(&http, &server.url, "tok", "p-1", &store, 0, None)
1018            .await
1019            .unwrap();
1020        assert_eq!(ensured.key.secret, "sk-kept");
1021        assert!(!ensured.issued);
1022        assert!(server.routes().is_empty(), "{:?}", server.routes());
1023    }
1024
1025    #[test]
1026    fn clearing_the_store_forgets_every_key() {
1027        let tmp = tempfile::tempdir().unwrap();
1028        let store = KeyStore::at(key_store_path_in(tmp.path()));
1029        assert!(store.clear().is_ok(), "nothing to forget is fine");
1030        let key = IssuedKey {
1031            secret: "sk-abc".to_string(),
1032            expires_at: 10_000,
1033        };
1034        store.keep("https://gw", "p-1", "", &key, 0).unwrap();
1035        store.clear().unwrap();
1036        assert!(store.usable("https://gw", "p-1", "", 0).is_none());
1037    }
1038}