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//!
11//! A subscription key (`billing = subscription`) is the other kind: it only
12//! works with the developer's own Claude subscription token, lives about 30
13//! days, and a new one revokes nothing. Claude Code gets it once, in a header
14//! fixed when it starts, so it is renewed a week before it expires, and the
15//! older ones are kept until they expire for `visdom logout` to revoke.
16
17use std::path::{Path, PathBuf};
18
19use serde::{Deserialize, Serialize};
20use tracevault_cli::agent::Agent;
21
22use crate::billing::Billing;
23
24/// A key with less than this left is replaced rather than handed out.
25pub const MIN_KEY_SECONDS_LEFT: i64 = 15 * 60;
26
27/// A subscription key with less than this left is replaced rather than
28/// handed out: a session started with it keeps it to its end. (Of a key that
29/// lives shorter than twice this, half its life.)
30pub const MIN_SUBSCRIPTION_KEY_SECONDS_LEFT: i64 = 7 * 24 * 60 * 60;
31
32/// Assumed lifetime of a key whose expiry the console did not state in a form
33/// this version reads. Short, so a wrong guess costs one early renewal.
34const UNKNOWN_EXPIRY_SECONDS: i64 = 60 * 60;
35
36/// A project the developer may issue themselves a personal key for.
37#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
38pub struct OpenProject {
39    /// The Control Plane project id.
40    pub id: String,
41    pub slug: String,
42    pub name: String,
43    /// The project's model aliases, each with whether the gateway takes a
44    /// call paid by a Claude subscription on it. `None`: the gateway does not
45    /// say (a version from before the list).
46    #[serde(default)]
47    pub models: Option<Vec<ProjectModel>>,
48}
49
50/// One alias of a project's allow-list, as `GET /api/me/keys` lists it.
51#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
52pub struct ProjectModel {
53    pub alias: String,
54    /// Served by direct Anthropic deployments only: the gateway takes a call
55    /// paid by a Claude subscription on it, and refuses one on any other
56    /// alias (HTTP 403, code `subscription_model`).
57    #[serde(default)]
58    pub subscription: bool,
59}
60
61impl OpenProject {
62    /// The aliases a call paid by a Claude subscription may use, when the
63    /// gateway says which.
64    pub fn subscription_aliases(&self) -> Option<Vec<String>> {
65        self.models.as_ref().map(|models| {
66            models
67                .iter()
68                .filter(|m| m.subscription)
69                .map(|m| m.alias.clone())
70                .collect()
71        })
72    }
73}
74
75/// Whether the gateway takes calls paid by a Claude subscription, as its
76/// console publishes it (`subscriptionTraffic` in `GET /api/settings`).
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum SubscriptionTraffic {
79    Allowed,
80    /// The deployment refuses them (`VISDOM_SUBSCRIPTION_TRAFFIC=deny`).
81    Denied,
82    /// The console says nothing about it: a gateway from before the setting,
83    /// which does not support subscription traffic either. A value this
84    /// version does not know is read the same way.
85    Unpublished,
86}
87
88impl SubscriptionTraffic {
89    /// Whether a session paid by a Claude subscription can go through it.
90    pub fn supported(self) -> bool {
91        self == SubscriptionTraffic::Allowed
92    }
93}
94
95/// The code the console and the gateway refuse subscription traffic with
96/// while the deployment denies it.
97pub const SUBSCRIPTION_TRAFFIC_DENIED: &str = "subscription_traffic_denied";
98
99/// What the console's settings say about the gateway.
100#[derive(Clone, Debug, PartialEq, Eq)]
101pub struct ConsoleSettings {
102    /// The LLM gateway's public address.
103    pub llm_url: String,
104    pub subscription_traffic: SubscriptionTraffic,
105}
106
107/// The machine-readable code of a refusal (`{"code": …}` as the console
108/// answers, or `{"error": {"code": …}}` as the LLM gateway does), if any.
109fn refusal_code(body: &str) -> Option<String> {
110    let value: serde_json::Value = serde_json::from_str(body).ok()?;
111    value
112        .get("code")
113        .or_else(|| value.get("error").and_then(|e| e.get("code")))
114        .and_then(|c| c.as_str())
115        .map(String::from)
116}
117
118/// A personal key as issued.
119#[derive(Clone, PartialEq, Eq)]
120pub struct IssuedKey {
121    pub secret: String,
122    /// Unix seconds.
123    pub expires_at: i64,
124    /// The console's id of the key, to revoke it by.
125    pub id: Option<String>,
126}
127
128/// The console's refusal, in its own words when it gave any. A refusal
129/// because the deployment denies subscription traffic is
130/// [`crate::subscription::NOT_SUPPORTED`], word for word.
131fn refusal(what: &str, status: reqwest::StatusCode, body: &str) -> String {
132    if refusal_code(body).as_deref() == Some(SUBSCRIPTION_TRAFFIC_DENIED) {
133        return crate::subscription::NOT_SUPPORTED.to_string();
134    }
135    #[derive(Deserialize)]
136    struct Refusal {
137        error: String,
138    }
139    let said = serde_json::from_str::<Refusal>(body)
140        .map(|r| r.error)
141        .unwrap_or_default();
142    let code = status.as_u16();
143    match (said.is_empty(), code) {
144        (false, _) => format!("{what}: {said} (HTTP {code})"),
145        (true, 401) => format!("{what}: the AI Gateway did not accept this login (HTTP 401)"),
146        (true, _) => format!("{what}: HTTP {code}"),
147    }
148}
149
150async fn read(
151    what: &str,
152    console_url: &str,
153    request: reqwest::RequestBuilder,
154) -> Result<String, String> {
155    let response = request
156        .send()
157        .await
158        .map_err(|e| format!("{what}: the AI Gateway ({console_url}) did not answer: {e}"))?;
159    let status = response.status();
160    let body = response.text().await.unwrap_or_default();
161    if status.is_success() {
162        Ok(body)
163    } else {
164        Err(refusal(what, status, &body))
165    }
166}
167
168fn parse<T: for<'de> Deserialize<'de>>(what: &str, body: &str) -> Result<T, String> {
169    serde_json::from_str(body).map_err(|e| format!("{what}: unreadable answer ({e})"))
170}
171
172fn base(url: &str) -> &str {
173    url.trim_end_matches('/')
174}
175
176/// The LLM gateway's public address and whether it takes subscription
177/// traffic, from the console's settings.
178pub async fn console_settings(
179    http: &reqwest::Client,
180    console_url: &str,
181    token: &str,
182) -> Result<ConsoleSettings, String> {
183    #[derive(Deserialize)]
184    #[serde(rename_all = "camelCase")]
185    struct Settings {
186        llm_gateway_url: String,
187        #[serde(default)]
188        subscription_traffic: Option<serde_json::Value>,
189    }
190    let what = "cannot read the AI Gateway's address";
191    let request = http
192        .get(format!("{}/api/settings", base(console_url)))
193        .bearer_auth(token);
194    let settings: Settings = parse(what, &read(what, console_url, request).await?)?;
195    let url = base(&settings.llm_gateway_url).to_string();
196    if !crate::components::bazaar::is_http_url(&url) {
197        return Err(format!("{what}: `{url}` is not an http(s) URL"));
198    }
199    let subscription_traffic = match settings
200        .subscription_traffic
201        .as_ref()
202        .and_then(|v| v.as_str())
203    {
204        Some("allowed") => SubscriptionTraffic::Allowed,
205        Some("denied") => SubscriptionTraffic::Denied,
206        _ => SubscriptionTraffic::Unpublished,
207    };
208    Ok(ConsoleSettings {
209        llm_url: url,
210        subscription_traffic,
211    })
212}
213
214/// The projects the developer may issue a personal key for.
215pub async fn open_projects(
216    http: &reqwest::Client,
217    console_url: &str,
218    token: &str,
219) -> Result<Vec<OpenProject>, String> {
220    #[derive(Deserialize)]
221    struct Mine {
222        projects: Vec<OpenProject>,
223    }
224    let what = "cannot list your AI Gateway projects";
225    let request = http
226        .get(format!("{}/api/me/keys", base(console_url)))
227        .bearer_auth(token);
228    Ok(parse::<Mine>(what, &read(what, console_url, request).await?)?.projects)
229}
230
231/// Unix seconds of an expiry as the console states it (RFC 3339, or the same
232/// without an offset, meaning UTC).
233fn expiry_seconds(expires_at: Option<&str>, now: i64) -> i64 {
234    let parsed = expires_at.and_then(|text| {
235        chrono::DateTime::parse_from_rfc3339(text)
236            .map(|t| t.timestamp())
237            .or_else(|_| {
238                chrono::NaiveDateTime::parse_from_str(text, "%Y-%m-%dT%H:%M:%S%.f")
239                    .map(|t| t.and_utc().timestamp())
240            })
241            .ok()
242    });
243    parsed.unwrap_or(now + UNKNOWN_EXPIRY_SECONDS)
244}
245
246/// Issue the developer a personal key of the kind `billing` for
247/// `project_id`. An ordinary key revokes their previous ordinary one for that
248/// project; a subscription key revokes nothing.
249///
250/// A subscription key that comes back as anything else (a console from before
251/// subscription keys ignores the request's `billing`) is revoked again and is
252/// an error: such a key would let the project pay.
253pub async fn issue_key(
254    http: &reqwest::Client,
255    console_url: &str,
256    token: &str,
257    project_id: &str,
258    billing: Billing,
259    now: i64,
260) -> Result<IssuedKey, String> {
261    #[derive(Deserialize)]
262    #[serde(rename_all = "camelCase")]
263    struct Issued {
264        secret: String,
265        #[serde(default)]
266        id: Option<String>,
267        #[serde(default)]
268        expires_at: Option<String>,
269        #[serde(default)]
270        billing: Option<String>,
271    }
272    let what = match billing {
273        Billing::Project => "cannot get a personal AI Gateway key",
274        Billing::Subscription => "cannot get a subscription key from the AI Gateway",
275    };
276    // An ordinary key is asked for as before subscription keys existed.
277    let body = match billing {
278        Billing::Project => serde_json::json!({ "projectId": project_id }),
279        Billing::Subscription => {
280            serde_json::json!({ "projectId": project_id, "billing": billing.name() })
281        }
282    };
283    let request = http
284        .post(format!("{}/api/me/keys", base(console_url)))
285        .bearer_auth(token)
286        .json(&body);
287    let issued: Issued = parse(what, &read(what, console_url, request).await?)?;
288    if issued.secret.trim().is_empty() {
289        return Err(format!("{what}: the answer carried no key"));
290    }
291    let id = issued.id.filter(|id| !id.trim().is_empty());
292    if billing == Billing::Subscription && issued.billing.as_deref() != Some(billing.name()) {
293        if let Some(id) = &id {
294            // Best effort: the key is not used either way.
295            let _ = revoke_key(http, console_url, token, id).await;
296        }
297        return Err(format!(
298            "{what}: this AI Gateway issued an ordinary personal key instead, so it does not \
299             support billing = subscription yet (its console needs a newer version). Use \
300             --billing project, or set billing to project"
301        ));
302    }
303    Ok(IssuedKey {
304        expires_at: expiry_seconds(issued.expires_at.as_deref(), now),
305        secret: issued.secret,
306        id,
307    })
308}
309
310/// Revoke the developer's key `id` at the console. A key the console no
311/// longer has (expired, or revoked already) is gone, which is what was asked.
312pub async fn revoke_key(
313    http: &reqwest::Client,
314    console_url: &str,
315    token: &str,
316    id: &str,
317) -> Result<(), String> {
318    let what = "cannot revoke an AI Gateway key";
319    let mut url = url::Url::parse(&format!("{}/api/me/keys", base(console_url)))
320        .map_err(|e| format!("{what}: `{console_url}` is not a URL ({e})"))?;
321    url.path_segments_mut()
322        .map_err(|()| format!("{what}: `{console_url}` is not an http(s) URL"))?
323        .push(id);
324    let response = http
325        .delete(url)
326        .bearer_auth(token)
327        .send()
328        .await
329        .map_err(|e| format!("{what}: the AI Gateway ({console_url}) did not answer: {e}"))?;
330    let status = response.status();
331    // The console answers 400 for a key of yours it does not have.
332    if status.is_success() || matches!(status.as_u16(), 400 | 404) {
333        return Ok(());
334    }
335    let body = response.text().await.unwrap_or_default();
336    Err(refusal(what, status, &body))
337}
338
339/// Why the LLM gateway's models could not be listed.
340#[derive(Clone, Debug, PartialEq, Eq)]
341pub struct ModelsError {
342    pub why: String,
343    /// The gateway answered that it does not take this key (HTTP 401 or 403):
344    /// another key may work where this one does not.
345    pub rejected: bool,
346}
347
348/// The model aliases `key` may call. This is also the proof that the LLM
349/// gateway answers and takes the key, before an agent is pointed at it.
350pub async fn models(
351    http: &reqwest::Client,
352    llm_url: &str,
353    key: &str,
354) -> Result<Vec<String>, ModelsError> {
355    #[derive(Deserialize)]
356    struct Model {
357        id: String,
358    }
359    #[derive(Deserialize)]
360    struct List {
361        data: Vec<Model>,
362    }
363    let what = "cannot list the AI Gateway's models";
364    let failed = |why: String, rejected: bool| ModelsError { why, rejected };
365    let response = http
366        .get(format!("{}/v1/models", base(llm_url)))
367        .bearer_auth(key)
368        .send()
369        .await
370        .map_err(|e| {
371            failed(
372                format!("{what}: the AI Gateway ({llm_url}) did not answer: {e}"),
373                false,
374            )
375        })?;
376    let status = response.status();
377    let body = response.text().await.unwrap_or_default();
378    if !status.is_success() {
379        if refusal_code(&body).as_deref() == Some(SUBSCRIPTION_TRAFFIC_DENIED) {
380            // Another key would be refused the same way.
381            return Err(failed(
382                crate::subscription::NOT_SUPPORTED.to_string(),
383                false,
384            ));
385        }
386        let rejected = matches!(status.as_u16(), 401 | 403);
387        let why = if rejected {
388            format!(
389                "{what}: the AI Gateway did not accept the personal key (HTTP {})",
390                status.as_u16()
391            )
392        } else {
393            format!("{what}: HTTP {}", status.as_u16())
394        };
395        return Err(failed(why, rejected));
396    }
397    let list: List = parse(what, &body).map_err(|why| failed(why, false))?;
398    Ok(list.data.into_iter().map(|m| m.id).collect())
399}
400
401/// The project to use: the configured one (its slug, id or name), else the
402/// only one there is. Otherwise the choice is the developer's, and the error
403/// names what to choose from.
404pub fn pick_project(configured: Option<&str>, open: &[OpenProject]) -> Result<OpenProject, String> {
405    let names = || {
406        open.iter()
407            .map(|p| p.slug.as_str())
408            .collect::<Vec<_>>()
409            .join(", ")
410    };
411    if open.is_empty() {
412        return Err(
413            "no AI Gateway project lets you issue a personal key: ask a project operator to \
414             switch personal keys on (Budgets) and to grant you access"
415                .to_string(),
416        );
417    }
418    match configured.map(str::trim).filter(|c| !c.is_empty()) {
419        Some(wanted) => open
420            .iter()
421            .find(|p| p.slug == wanted || p.id == wanted || p.name == wanted)
422            .cloned()
423            .ok_or_else(|| {
424                format!(
425                    "AI Gateway project `{wanted}` does not let you issue a personal key (you \
426                     can for: {})",
427                    names()
428                )
429            }),
430        None if open.len() == 1 => Ok(open[0].clone()),
431        None => Err(format!(
432            "several AI Gateway projects are open to you ({}): set `project` under \
433             `[gateway]` in .visdom/config.toml or in your visdom config, or \
434             VISDOM_GATEWAY_PROJECT (`visdom init` asks and saves it)",
435            names()
436        )),
437    }
438}
439
440/// The model alias an agent should ask for: the configured one, else the
441/// first alias that looks made for that agent, else none (the agent's own
442/// default, which the project must then allow).
443pub fn pick_model(agent: Agent, configured: Option<&str>, available: &[String]) -> Option<String> {
444    if let Some(model) = configured.map(str::trim).filter(|m| !m.is_empty()) {
445        return Some(model.to_string());
446    }
447    let hints: &[&str] = match agent {
448        Agent::ClaudeCode => &["claude", "sonnet", "opus"],
449        Agent::Codex => &["codex", "gpt"],
450        _ => &[],
451    };
452    hints.iter().find_map(|hint| {
453        available
454            .iter()
455            .find(|alias| alias.to_ascii_lowercase().contains(hint))
456            .cloned()
457    })
458}
459
460/// Whose key it is: the issuer and subject of the developer's access token.
461/// A key is the person's, so one kept for somebody else who logged in on this
462/// machine before must not be handed out. Empty for a token that is not a
463/// readable JWT, which then cannot be told apart from another such token.
464pub fn account_of(token: &str) -> String {
465    use base64::Engine;
466    #[derive(Deserialize)]
467    struct Claims {
468        #[serde(default)]
469        iss: String,
470        sub: String,
471    }
472    let mut parts = token.split('.');
473    let (Some(_), Some(payload), Some(_), None) =
474        (parts.next(), parts.next(), parts.next(), parts.next())
475    else {
476        return String::new();
477    };
478    base64::engine::general_purpose::URL_SAFE_NO_PAD
479        .decode(payload.trim_end_matches('='))
480        .ok()
481        .and_then(|bytes| serde_json::from_slice::<Claims>(&bytes).ok())
482        .filter(|claims| !claims.sub.is_empty())
483        .map(|claims| format!("{}|{}", claims.iss, claims.sub))
484        .unwrap_or_default()
485}
486
487/// One stored personal key.
488#[derive(Clone, Serialize, Deserialize)]
489struct StoredKey {
490    console_url: String,
491    project_id: String,
492    /// [`account_of`] the token it was issued for.
493    #[serde(default)]
494    account: String,
495    secret: String,
496    expires_at: i64,
497    /// The key's kind; a key kept before there were kinds is ordinary.
498    #[serde(default)]
499    billing: Billing,
500    /// The console's id of the key, to revoke it by on logout.
501    #[serde(default, skip_serializing_if = "Option::is_none")]
502    id: Option<String>,
503    /// Unix seconds when it was kept, which is when it was issued.
504    #[serde(default)]
505    issued_at: i64,
506    /// The gateway refused it (revoked elsewhere): never handed out again,
507    /// but kept until it expires, for logout to revoke.
508    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
509    refused: bool,
510}
511
512impl StoredKey {
513    fn is_for(&self, console_url: &str, project_id: &str, account: &str, billing: Billing) -> bool {
514        self.console_url == base(console_url)
515            && self.project_id == project_id
516            && self.account == account
517            && self.billing == billing
518    }
519
520    /// Whether it is still handed out at `now`, rather than replaced.
521    fn lasts(&self, now: i64) -> bool {
522        !self.refused
523            && self.expires_at - now >= renew_before(self.billing, self.issued_at, self.expires_at)
524    }
525}
526
527/// How long before it expires a key of the kind `billing` is replaced. A
528/// subscription key the console gives a short life (shorter than twice
529/// [`MIN_SUBSCRIPTION_KEY_SECONDS_LEFT`]) is replaced at half its life, not
530/// at once.
531fn renew_before(billing: Billing, issued_at: i64, expires_at: i64) -> i64 {
532    match billing {
533        Billing::Project => MIN_KEY_SECONDS_LEFT,
534        Billing::Subscription => {
535            let life = expires_at - issued_at;
536            if issued_at > 0 && life > 0 {
537                MIN_SUBSCRIPTION_KEY_SECONDS_LEFT.min(life / 2)
538            } else {
539                MIN_SUBSCRIPTION_KEY_SECONDS_LEFT
540            }
541        }
542    }
543}
544
545/// A kept key, as `visdom logout` revokes it.
546#[derive(Clone, Debug, PartialEq, Eq)]
547pub struct KeptKey {
548    pub console_url: String,
549    pub account: String,
550    pub id: Option<String>,
551    pub billing: Billing,
552    pub expires_at: i64,
553}
554
555/// The personal keys `visdom` holds, one per console, project and account.
556#[derive(Clone)]
557pub struct KeyStore {
558    path: PathBuf,
559}
560
561pub fn key_store_path_in(config_root: &Path) -> PathBuf {
562    config_root.join("visdom").join("gateway-keys.json")
563}
564
565/// Held while a key is looked up, issued and stored; released when dropped.
566pub struct KeyStoreLock(#[allow(dead_code)] std::fs::File);
567
568impl KeyStore {
569    pub fn at(path: PathBuf) -> KeyStore {
570        KeyStore { path }
571    }
572
573    fn load(&self) -> Vec<StoredKey> {
574        std::fs::read_to_string(&self.path)
575            .ok()
576            .and_then(|text| serde_json::from_str(&text).ok())
577            .unwrap_or_default()
578    }
579
580    /// Wait for this store to be free of every other `visdom` process, and
581    /// take it. Issuing a key revokes the previous one, so two sessions
582    /// starting together must not both issue: the second waits here and then
583    /// finds the first one's key.
584    pub fn lock(&self) -> std::io::Result<KeyStoreLock> {
585        let dir = self.path.parent().unwrap_or(Path::new("."));
586        std::fs::create_dir_all(dir)?;
587        let file = std::fs::OpenOptions::new()
588            .create(true)
589            .truncate(false)
590            .write(true)
591            .open(self.path.with_extension("lock"))?;
592        file.lock()?;
593        Ok(KeyStoreLock(file))
594    }
595
596    /// The stored key of the kind `billing` of `account` for this console
597    /// and project, when it has enough left: [`MIN_KEY_SECONDS_LEFT`], or for
598    /// a subscription key [`MIN_SUBSCRIPTION_KEY_SECONDS_LEFT`]. Of several,
599    /// the one that lasts longest.
600    pub fn usable(
601        &self,
602        console_url: &str,
603        project_id: &str,
604        account: &str,
605        billing: Billing,
606        now: i64,
607    ) -> Option<IssuedKey> {
608        self.load()
609            .into_iter()
610            .filter(|k| k.is_for(console_url, project_id, account, billing))
611            .filter(|k| k.lasts(now))
612            .max_by_key(|k| k.expires_at)
613            .map(|k| IssuedKey {
614                secret: k.secret,
615                expires_at: k.expires_at,
616                id: k.id,
617            })
618    }
619
620    /// The stored key of the kind `billing` of `account` for this console
621    /// and project that lasts longest, if any has not expired and was not
622    /// refused, however little it has left: what a check tries, changing
623    /// nothing. (A launch replaces one inside its renewal window; see
624    /// [`Self::usable`].)
625    pub fn unexpired(
626        &self,
627        console_url: &str,
628        project_id: &str,
629        account: &str,
630        billing: Billing,
631        now: i64,
632    ) -> Option<IssuedKey> {
633        self.load()
634            .into_iter()
635            .filter(|k| k.is_for(console_url, project_id, account, billing))
636            .filter(|k| !k.refused && k.expires_at > now)
637            .max_by_key(|k| k.expires_at)
638            .map(|k| IssuedKey {
639                secret: k.secret,
640                expires_at: k.expires_at,
641                id: k.id,
642            })
643    }
644
645    /// Keep `key` of the kind `billing`, dropping keys that have expired. An
646    /// ordinary key replaces the one for the same console and project
647    /// (whoever's it was: this machine's user is now `account`), as issuing
648    /// it revoked that one. A subscription key revoked nothing: `account`'s
649    /// earlier ones stay until they expire, for logout to revoke; another
650    /// account's go. The file is the user's alone.
651    pub fn keep(
652        &self,
653        console_url: &str,
654        project_id: &str,
655        account: &str,
656        billing: Billing,
657        key: &IssuedKey,
658        now: i64,
659    ) -> Result<(), String> {
660        let replaced = |k: &StoredKey| {
661            k.console_url == base(console_url)
662                && k.project_id == project_id
663                && k.billing == billing
664                && (billing == Billing::Project || k.account != account)
665        };
666        let mut keys: Vec<StoredKey> = self
667            .load()
668            .into_iter()
669            .filter(|k| k.expires_at > now)
670            .filter(|k| !replaced(k))
671            .collect();
672        keys.push(StoredKey {
673            console_url: base(console_url).to_string(),
674            project_id: project_id.to_string(),
675            account: account.to_string(),
676            secret: key.secret.clone(),
677            expires_at: key.expires_at,
678            billing,
679            id: key.id.clone(),
680            issued_at: now,
681            refused: false,
682        });
683        let text = serde_json::to_string(&keys).map_err(|e| e.to_string())?;
684        write_private(&self.path, &text)
685            .map_err(|e| format!("cannot write {}: {e}", self.path.display()))
686    }
687
688    /// Mark the kept key `secret` as refused by the gateway: it is not handed
689    /// out again, but stays for logout to revoke. Call under [`Self::lock`].
690    pub fn refuse(&self, secret: &str) -> Result<(), String> {
691        let mut keys = self.load();
692        let Some(key) = keys.iter_mut().find(|k| k.secret == secret) else {
693            return Ok(());
694        };
695        key.refused = true;
696        let text = serde_json::to_string(&keys).map_err(|e| e.to_string())?;
697        write_private(&self.path, &text)
698            .map_err(|e| format!("cannot write {}: {e}", self.path.display()))
699    }
700
701    /// Every kept key that has not expired at `now`.
702    pub fn kept(&self, now: i64) -> Vec<KeptKey> {
703        self.load()
704            .into_iter()
705            .filter(|k| k.expires_at > now)
706            .map(|k| KeptKey {
707                console_url: k.console_url,
708                account: k.account,
709                id: k.id,
710                billing: k.billing,
711                expires_at: k.expires_at,
712            })
713            .collect()
714    }
715
716    /// Forget every kept key (on logout, after [`revoke_kept`]).
717    pub fn clear(&self) -> std::io::Result<()> {
718        match std::fs::remove_file(&self.path) {
719            Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
720            _ => Ok(()),
721        }
722    }
723}
724
725/// Write `text` to `path` so that it is never readable by anyone else: a new
726/// file created with the user's permissions only, then moved into place.
727fn write_private(path: &Path, text: &str) -> std::io::Result<()> {
728    use std::io::Write;
729    let dir = path.parent().unwrap_or(Path::new("."));
730    std::fs::create_dir_all(dir)?;
731    let tmp = path.with_extension(format!("tmp{}", std::process::id()));
732    let _ = std::fs::remove_file(&tmp);
733    let mut options = std::fs::OpenOptions::new();
734    options.write(true).create_new(true);
735    #[cfg(unix)]
736    {
737        use std::os::unix::fs::OpenOptionsExt;
738        options.mode(0o600);
739    }
740    let written = options
741        .open(&tmp)
742        .and_then(|mut file| file.write_all(text.as_bytes()));
743    match written.and_then(|()| std::fs::rename(&tmp, path)) {
744        Ok(()) => Ok(()),
745        Err(e) => {
746            let _ = std::fs::remove_file(&tmp);
747            Err(e)
748        }
749    }
750}
751
752/// A key from [`ensure_key`].
753pub struct EnsuredKey {
754    pub key: IssuedKey,
755    /// Issued just now, rather than found in the store.
756    pub issued: bool,
757}
758
759/// The developer's key for `project_id`: the stored one while it lasts, else a
760/// new one, which is then stored (a key that cannot be stored is an error). `rejected` is a key the gateway no longer
761/// takes (revoked by a newer one issued elsewhere): the stored key is used
762/// only if it is another one.
763///
764/// Looking, issuing and storing happen under the store's lock, so sessions
765/// starting side by side end up sharing one key instead of revoking each
766/// other's.
767#[allow(clippy::too_many_arguments)]
768pub async fn ensure_key(
769    http: &reqwest::Client,
770    console_url: &str,
771    token: &str,
772    project_id: &str,
773    billing: Billing,
774    store: &KeyStore,
775    now: i64,
776    rejected: Option<&str>,
777) -> Result<EnsuredKey, String> {
778    let account = account_of(token);
779    // Waiting for another process must not hold up this runtime's thread.
780    let locking = store.clone();
781    let lock = tokio::task::spawn_blocking(move || locking.lock())
782        .await
783        .map_err(|e| e.to_string())
784        .and_then(|locked| locked.map_err(|e| e.to_string()));
785    // A key the gateway refused is not offered again by any later session
786    // (a subscription key stays kept, and may outlast its replacement).
787    if let (Some(secret), Ok(_)) = (rejected, &lock) {
788        let _ = store.refuse(secret);
789    }
790    let stored = store
791        .usable(console_url, project_id, &account, billing, now)
792        .filter(|key| Some(key.secret.as_str()) != rejected);
793    if let Some(key) = stored {
794        return Ok(EnsuredKey { key, issued: false });
795    }
796    // A kept key is read without the lock just as well. A new one is not
797    // issued without it: issuing revokes the key another session, issuing at
798    // the same moment, is about to use.
799    let _lock = lock.map_err(|why| {
800        format!(
801            "the personal AI Gateway key store {} could not be locked: {why}",
802            store.path.display()
803        )
804    })?;
805    let key = issue_key(http, console_url, token, project_id, billing, now).await?;
806    // A key that is not kept is issued again by the next session, and by the
807    // agent's own key helper, each time revoking the one in use: that is no
808    // working gateway session.
809    store
810        .keep(console_url, project_id, &account, billing, &key, now)
811        .map_err(|why| format!("the personal AI Gateway key could not be kept: {why}"))?;
812    Ok(EnsuredKey { key, issued: true })
813}
814
815/// Revoke at their consoles the kept keys of the person whose access token
816/// is `token` (on `visdom logout`, before the store is cleared). What could
817/// not be revoked is returned as warnings; such a key stays valid at the
818/// gateway until it expires. Keys of another account are not this token's
819/// to revoke.
820pub async fn revoke_kept(
821    http: &reqwest::Client,
822    store: &KeyStore,
823    token: &str,
824    now: i64,
825) -> Vec<String> {
826    let account = account_of(token);
827    let mut warnings = Vec::new();
828    for key in store.kept(now).into_iter().filter(|k| k.account == account) {
829        let Some(id) = &key.id else { continue };
830        if let Err(why) = revoke_key(http, &key.console_url, token, id).await {
831            warnings.push(format!(
832                "{why}; the {} key stays valid until it expires (revoke it in the AI Gateway \
833                 console under My API key)",
834                match key.billing {
835                    Billing::Project => "personal",
836                    Billing::Subscription => "subscription",
837                }
838            ));
839        }
840    }
841    warnings
842}
843
844#[cfg(test)]
845mod tests {
846    use super::*;
847    use crate::test_http::MockServer;
848
849    fn project(id: &str, slug: &str) -> OpenProject {
850        OpenProject {
851            id: id.to_string(),
852            slug: slug.to_string(),
853            name: slug.to_uppercase(),
854            models: None,
855        }
856    }
857
858    #[tokio::test]
859    async fn the_llm_address_comes_from_the_consoles_settings() {
860        let http = reqwest::Client::new();
861        let server = MockServer::start(&[(
862            "GET /api/settings",
863            200,
864            r#"{"llmGatewayUrl":"https://llm.example.com/","mcpGatewayUrl":"https://mcp.example.com","suite":[],"controlPlaneUrl":null}"#,
865        )]);
866        assert_eq!(
867            console_settings(&http, &format!("{}/", server.url), "tok").await,
868            Ok(ConsoleSettings {
869                llm_url: "https://llm.example.com".to_string(),
870                // A console from before the setting: not supported.
871                subscription_traffic: SubscriptionTraffic::Unpublished,
872            })
873        );
874        assert_eq!(
875            server.requests()[0].authorization.as_deref(),
876            Some("Bearer tok")
877        );
878    }
879
880    #[tokio::test]
881    async fn the_settings_say_whether_subscription_traffic_is_taken() {
882        let http = reqwest::Client::new();
883        for (said, read) in [
884            (r#""allowed""#, SubscriptionTraffic::Allowed),
885            (r#""denied""#, SubscriptionTraffic::Denied),
886            (r#""maybe""#, SubscriptionTraffic::Unpublished),
887            ("null", SubscriptionTraffic::Unpublished),
888            ("true", SubscriptionTraffic::Unpublished),
889        ] {
890            let body = format!(
891                r#"{{"llmGatewayUrl":"https://llm.example.com","subscriptionTraffic":{said}}}"#
892            );
893            let server = MockServer::start(&[("GET /api/settings", 200, &body)]);
894            let settings = console_settings(&http, &server.url, "tok").await.unwrap();
895            assert_eq!(settings.subscription_traffic, read, "{said}");
896        }
897        assert!(SubscriptionTraffic::Allowed.supported());
898        assert!(!SubscriptionTraffic::Denied.supported());
899        assert!(!SubscriptionTraffic::Unpublished.supported());
900    }
901
902    #[tokio::test]
903    async fn a_projects_models_say_which_take_a_subscription() {
904        let http = reqwest::Client::new();
905        let server = MockServer::start(&[(
906            "GET /api/me/keys",
907            200,
908            r#"{"projects":[{"id":"p-1","slug":"alpha","name":"Alpha","models":[{"alias":"claude-sonnet","subscription":true},{"alias":"gpt-general","subscription":false}]}],"keys":[]}"#,
909        )]);
910        let open = open_projects(&http, &server.url, "tok").await.unwrap();
911        assert_eq!(
912            open[0].subscription_aliases(),
913            Some(vec!["claude-sonnet".to_string()])
914        );
915        assert_eq!(project("p-2", "beta").subscription_aliases(), None);
916    }
917
918    #[tokio::test]
919    async fn a_denied_subscription_key_is_the_platforms_message() {
920        let http = reqwest::Client::new();
921        let server = MockServer::start(&[(
922            "POST /api/me/keys",
923            403,
924            r#"{"error":"This gateway does not take subscription traffic (VISDOM_SUBSCRIPTION_TRAFFIC=deny), so it issues no subscription keys; use an ordinary personal key","code":"subscription_traffic_denied"}"#,
925        )]);
926        let err = issue_key(&http, &server.url, "tok", "p-1", Billing::Subscription, 0)
927            .await
928            .err()
929            .unwrap();
930        assert_eq!(err, crate::subscription::NOT_SUPPORTED);
931        let server = MockServer::start(&[(
932            "GET /v1/models",
933            403,
934            r#"{"error":{"message":"no","type":"permission_error","code":"subscription_traffic_denied"}}"#,
935        )]);
936        let err = models(&http, &server.url, "sk").await.unwrap_err();
937        assert_eq!(err.why, crate::subscription::NOT_SUPPORTED);
938        assert!(!err.rejected, "another key would not help");
939    }
940
941    #[tokio::test]
942    async fn open_projects_are_listed_with_the_persons_token() {
943        let http = reqwest::Client::new();
944        let server = MockServer::start(&[(
945            "GET /api/me/keys",
946            200,
947            r#"{"hours":24,"projects":[{"id":"p-1","slug":"alpha","name":"Alpha","budget":null}],"keys":[]}"#,
948        )]);
949        assert_eq!(
950            open_projects(&http, &server.url, "tok").await,
951            Ok(vec![OpenProject {
952                id: "p-1".to_string(),
953                slug: "alpha".to_string(),
954                name: "Alpha".to_string(),
955                models: None,
956            }])
957        );
958    }
959
960    #[tokio::test]
961    async fn a_key_is_issued_for_the_project() {
962        let http = reqwest::Client::new();
963        let server = MockServer::start(&[(
964            "POST /api/me/keys",
965            201,
966            r#"{"secret":"sk-abc","id":"hash","name":"personal-x-1","expiresAt":"2026-11-20T10:00:00.250000+00:00"}"#,
967        )]);
968        let key = issue_key(&http, &server.url, "tok", "p-1", Billing::Project, 0)
969            .await
970            .unwrap();
971        assert_eq!(key.secret, "sk-abc");
972        assert_eq!(
973            key.expires_at,
974            chrono::DateTime::parse_from_rfc3339("2026-11-20T10:00:00Z")
975                .unwrap()
976                .timestamp()
977        );
978        let asked = &server.requests()[0];
979        assert_eq!(asked.authorization.as_deref(), Some("Bearer tok"));
980        assert_eq!(asked.body, r#"{"projectId":"p-1"}"#);
981    }
982
983    #[tokio::test]
984    async fn the_consoles_refusal_is_passed_on_in_its_words() {
985        let http = reqwest::Client::new();
986        let server = MockServer::start(&[
987            (
988                "POST /api/me/keys",
989                400,
990                r#"{"error":"Alpha does not allow personal keys; ask an operator to switch them on (Budgets)"}"#,
991            ),
992            ("GET /api/me/keys", 401, ""),
993        ]);
994        let err = issue_key(&http, &server.url, "tok", "p-1", Billing::Project, 0)
995            .await
996            .err()
997            .unwrap();
998        assert!(err.contains("does not allow personal keys"), "{err}");
999        assert!(err.contains("HTTP 400"), "{err}");
1000        let err = open_projects(&http, &server.url, "tok").await.unwrap_err();
1001        assert!(err.contains("did not accept this login"), "{err}");
1002        let err = open_projects(&http, "http://127.0.0.1:1", "tok")
1003            .await
1004            .unwrap_err();
1005        assert!(err.contains("did not answer"), "{err}");
1006    }
1007
1008    #[test]
1009    fn expiry_is_read_in_the_forms_the_gateway_uses() {
1010        let at = chrono::DateTime::parse_from_rfc3339("2026-11-20T10:00:00Z")
1011            .unwrap()
1012            .timestamp();
1013        assert_eq!(expiry_seconds(Some("2026-11-20T10:00:00Z"), 0), at);
1014        assert_eq!(expiry_seconds(Some("2026-11-20T11:00:00+01:00"), 0), at);
1015        assert_eq!(expiry_seconds(Some("2026-11-20T10:00:00.123456"), 0), at);
1016        // Not stated, or not understood: a short assumed life.
1017        assert_eq!(expiry_seconds(None, 1000), 1000 + UNKNOWN_EXPIRY_SECONDS);
1018        assert_eq!(
1019            expiry_seconds(Some("tomorrow"), 1000),
1020            1000 + UNKNOWN_EXPIRY_SECONDS
1021        );
1022    }
1023
1024    #[tokio::test]
1025    async fn models_are_the_aliases_the_key_may_call() {
1026        let http = reqwest::Client::new();
1027        let server = MockServer::start(&[(
1028            "GET /v1/models",
1029            200,
1030            r#"{"object":"list","data":[{"id":"gpt-general","object":"model"},{"id":"claude-sonnet","object":"model"}]}"#,
1031        )]);
1032        assert_eq!(
1033            models(&http, &server.url, "sk-abc").await,
1034            Ok(vec!["gpt-general".to_string(), "claude-sonnet".to_string()])
1035        );
1036        assert_eq!(
1037            server.requests()[0].authorization.as_deref(),
1038            Some("Bearer sk-abc")
1039        );
1040    }
1041
1042    #[test]
1043    fn the_project_is_the_configured_one_or_the_only_one() {
1044        let one = [project("p-1", "alpha")];
1045        let two = [project("p-1", "alpha"), project("p-2", "beta")];
1046        assert_eq!(pick_project(None, &one).unwrap().id, "p-1");
1047        assert_eq!(pick_project(Some(" beta "), &two).unwrap().id, "p-2");
1048        assert_eq!(pick_project(Some("p-2"), &two).unwrap().slug, "beta");
1049        assert_eq!(pick_project(Some("BETA"), &two).unwrap().id, "p-2");
1050        let err = pick_project(None, &two).unwrap_err();
1051        assert!(
1052            err.contains("alpha, beta") && err.contains("`project` under `[gateway]`"),
1053            "{err}"
1054        );
1055        let err = pick_project(Some("gamma"), &two).unwrap_err();
1056        assert!(
1057            err.contains("`gamma`") && err.contains("alpha, beta"),
1058            "{err}"
1059        );
1060        let err = pick_project(Some("alpha"), &[]).unwrap_err();
1061        assert!(err.contains("personal keys on"), "{err}");
1062    }
1063
1064    #[test]
1065    fn the_model_is_the_configured_one_or_one_named_for_the_agent() {
1066        let aliases: Vec<String> = ["demo-assistant", "gpt-general", "claude-sonnet"]
1067            .map(String::from)
1068            .to_vec();
1069        assert_eq!(
1070            pick_model(Agent::ClaudeCode, None, &aliases).as_deref(),
1071            Some("claude-sonnet")
1072        );
1073        assert_eq!(
1074            pick_model(Agent::Codex, None, &aliases).as_deref(),
1075            Some("gpt-general")
1076        );
1077        assert_eq!(
1078            pick_model(Agent::Codex, Some(" local-coder "), &aliases).as_deref(),
1079            Some("local-coder")
1080        );
1081        assert_eq!(
1082            pick_model(Agent::ClaudeCode, None, &["local-coder".to_string()]),
1083            None
1084        );
1085    }
1086
1087    #[test]
1088    fn a_stored_key_is_reused_until_shortly_before_it_expires() {
1089        let tmp = tempfile::tempdir().unwrap();
1090        let store = KeyStore::at(key_store_path_in(tmp.path()));
1091        let key = IssuedKey {
1092            secret: "sk-abc".to_string(),
1093            expires_at: 10_000,
1094            id: None,
1095        };
1096        assert!(store
1097            .usable("https://gw.example.com", "p-1", "", Billing::Project, 0)
1098            .is_none());
1099        store
1100            .keep(
1101                "https://gw.example.com/",
1102                "p-1",
1103                "",
1104                Billing::Project,
1105                &key,
1106                0,
1107            )
1108            .unwrap();
1109        let again = store
1110            .usable("https://gw.example.com", "p-1", "", Billing::Project, 0)
1111            .unwrap();
1112        assert_eq!(again.secret, "sk-abc");
1113        // Another project or console has its own key.
1114        assert!(store
1115            .usable("https://gw.example.com", "p-2", "", Billing::Project, 0)
1116            .is_none());
1117        assert!(store
1118            .usable("https://other.example.com", "p-1", "", Billing::Project, 0)
1119            .is_none());
1120        // Close to expiry it is no longer handed out.
1121        let late = 10_000 - MIN_KEY_SECONDS_LEFT + 1;
1122        assert!(store
1123            .usable("https://gw.example.com", "p-1", "", Billing::Project, late)
1124            .is_none());
1125        assert!(store
1126            .usable(
1127                "https://gw.example.com",
1128                "p-1",
1129                "",
1130                Billing::Project,
1131                late - 1
1132            )
1133            .is_some());
1134    }
1135
1136    #[test]
1137    fn keeping_a_key_replaces_the_old_one_and_drops_expired_ones() {
1138        let tmp = tempfile::tempdir().unwrap();
1139        let store = KeyStore::at(key_store_path_in(tmp.path()));
1140        let key = |secret: &str, expires_at| IssuedKey {
1141            secret: secret.to_string(),
1142            expires_at,
1143            id: None,
1144        };
1145        store
1146            .keep(
1147                "https://gw",
1148                "p-1",
1149                "",
1150                Billing::Project,
1151                &key("old", 5_000),
1152                0,
1153            )
1154            .unwrap();
1155        store
1156            .keep(
1157                "https://gw",
1158                "p-2",
1159                "",
1160                Billing::Project,
1161                &key("other", 9_000),
1162                0,
1163            )
1164            .unwrap();
1165        store
1166            .keep(
1167                "https://gw",
1168                "p-1",
1169                "",
1170                Billing::Project,
1171                &key("new", 90_000),
1172                6_000,
1173            )
1174            .unwrap();
1175        assert_eq!(
1176            store
1177                .usable("https://gw", "p-1", "", Billing::Project, 6_000)
1178                .unwrap()
1179                .secret,
1180            "new"
1181        );
1182        assert_eq!(
1183            store
1184                .usable("https://gw", "p-2", "", Billing::Project, 6_000)
1185                .unwrap()
1186                .secret,
1187            "other"
1188        );
1189        store
1190            .keep(
1191                "https://gw",
1192                "p-3",
1193                "",
1194                Billing::Project,
1195                &key("third", 99_000),
1196                9_500,
1197            )
1198            .unwrap();
1199        assert_eq!(store.load().len(), 2, "the expired p-2 key is gone");
1200    }
1201
1202    #[cfg(unix)]
1203    #[test]
1204    fn the_key_file_is_the_users_alone() {
1205        use std::os::unix::fs::PermissionsExt;
1206        let tmp = tempfile::tempdir().unwrap();
1207        let path = key_store_path_in(tmp.path());
1208        let store = KeyStore::at(path.clone());
1209        let key = IssuedKey {
1210            secret: "sk-abc".to_string(),
1211            expires_at: 10_000,
1212            id: None,
1213        };
1214        store
1215            .keep("https://gw", "p-1", "", Billing::Project, &key, 0)
1216            .unwrap();
1217        store
1218            .keep("https://gw", "p-2", "", Billing::Project, &key, 0)
1219            .unwrap();
1220        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1221        assert_eq!(mode & 0o777, 0o600);
1222    }
1223
1224    #[tokio::test]
1225    async fn a_key_is_issued_once_and_then_reused() {
1226        let http = reqwest::Client::new();
1227        let tmp = tempfile::tempdir().unwrap();
1228        let store = KeyStore::at(key_store_path_in(tmp.path()));
1229        let server = MockServer::start(&[(
1230            "POST /api/me/keys",
1231            201,
1232            r#"{"secret":"sk-abc","id":"h","name":"n","expiresAt":"2026-11-20T10:00:00Z"}"#,
1233        )]);
1234        let now = chrono::DateTime::parse_from_rfc3339("2026-11-19T10:00:00Z")
1235            .unwrap()
1236            .timestamp();
1237        let first = ensure_key(
1238            &http,
1239            &server.url,
1240            "tok",
1241            "p-1",
1242            Billing::Project,
1243            &store,
1244            now,
1245            None,
1246        )
1247        .await
1248        .unwrap();
1249        assert_eq!((first.key.secret.as_str(), first.issued), ("sk-abc", true));
1250        let second = ensure_key(
1251            &http,
1252            &server.url,
1253            "tok",
1254            "p-1",
1255            Billing::Project,
1256            &store,
1257            now + 3600,
1258            None,
1259        )
1260        .await
1261        .unwrap();
1262        assert_eq!(
1263            (second.key.secret.as_str(), second.issued),
1264            ("sk-abc", false)
1265        );
1266        assert_eq!(server.routes(), ["POST /api/me/keys"], "issued once");
1267        // A day later it has expired: a new one is issued.
1268        ensure_key(
1269            &http,
1270            &server.url,
1271            "tok",
1272            "p-1",
1273            Billing::Project,
1274            &store,
1275            now + 86_400,
1276            None,
1277        )
1278        .await
1279        .unwrap();
1280        assert_eq!(server.routes().len(), 2);
1281    }
1282
1283    /// A JWT as Keycloak issues one, unsigned: only its claims are read here.
1284    fn token_of(iss: &str, sub: &str) -> String {
1285        use base64::Engine;
1286        let part = |json: String| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json);
1287        format!(
1288            "{}.{}.signature",
1289            part(r#"{"alg":"RS256"}"#.to_string()),
1290            part(format!(r#"{{"iss":"{iss}","sub":"{sub}","exp":1}}"#))
1291        )
1292    }
1293
1294    #[test]
1295    fn the_account_is_the_tokens_issuer_and_subject() {
1296        let alice = token_of("https://idp/realms/visdom", "alice-id");
1297        assert_eq!(account_of(&alice), "https://idp/realms/visdom|alice-id");
1298        assert_ne!(
1299            account_of(&alice),
1300            account_of(&token_of("https://idp/realms/visdom", "bob-id"))
1301        );
1302        assert_ne!(
1303            account_of(&alice),
1304            account_of(&token_of("https://idp/realms/other", "alice-id"))
1305        );
1306        // Not a JWT, or one without a subject: no account.
1307        for opaque in ["person-access-token", "a.b.c", "a.b", "", "a.b.c.d"] {
1308            assert_eq!(account_of(opaque), "", "{opaque}");
1309        }
1310        assert_eq!(account_of(&token_of("https://idp", "")), "");
1311    }
1312
1313    #[tokio::test]
1314    async fn a_kept_key_is_not_handed_to_another_account() {
1315        let http = reqwest::Client::new();
1316        let tmp = tempfile::tempdir().unwrap();
1317        let store = KeyStore::at(key_store_path_in(tmp.path()));
1318        let server = MockServer::start(&[
1319            (
1320                "POST /api/me/keys",
1321                201,
1322                r#"{"secret":"sk-alice","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
1323            ),
1324            (
1325                "POST /api/me/keys",
1326                201,
1327                r#"{"secret":"sk-bob","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
1328            ),
1329        ]);
1330        let alice = token_of("https://idp", "alice-id");
1331        let bob = token_of("https://idp", "bob-id");
1332        let first = ensure_key(
1333            &http,
1334            &server.url,
1335            &alice,
1336            "p-1",
1337            Billing::Project,
1338            &store,
1339            0,
1340            None,
1341        )
1342        .await
1343        .unwrap();
1344        assert_eq!(first.key.secret, "sk-alice");
1345        // Bob logs in on the same machine: Alice's key is not his.
1346        let second = ensure_key(
1347            &http,
1348            &server.url,
1349            &bob,
1350            "p-1",
1351            Billing::Project,
1352            &store,
1353            0,
1354            None,
1355        )
1356        .await
1357        .unwrap();
1358        assert_eq!(
1359            (second.key.secret.as_str(), second.issued),
1360            ("sk-bob", true)
1361        );
1362        let asked = server.requests();
1363        assert_eq!(asked.len(), 2);
1364        assert_eq!(asked[1].authorization, Some(format!("Bearer {bob}")));
1365        // And Alice's is gone from the file, not kept beside his.
1366        assert!(store
1367            .usable(&server.url, "p-1", &account_of(&alice), Billing::Project, 0)
1368            .is_none());
1369        assert_eq!(store.load().len(), 1);
1370    }
1371
1372    #[tokio::test]
1373    async fn a_rejected_key_is_replaced_unless_somebody_already_did() {
1374        let http = reqwest::Client::new();
1375        let tmp = tempfile::tempdir().unwrap();
1376        let store = KeyStore::at(key_store_path_in(tmp.path()));
1377        let server = MockServer::start(&[(
1378            "POST /api/me/keys",
1379            201,
1380            r#"{"secret":"sk-new","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
1381        )]);
1382        let old = IssuedKey {
1383            secret: "sk-old".to_string(),
1384            expires_at: 4_000_000_000,
1385            id: None,
1386        };
1387        store
1388            .keep(&server.url, "p-1", "", Billing::Project, &old, 0)
1389            .unwrap();
1390        // The gateway refused sk-old: the stored copy is not offered again.
1391        let renewed = ensure_key(
1392            &http,
1393            &server.url,
1394            "tok",
1395            "p-1",
1396            Billing::Project,
1397            &store,
1398            0,
1399            Some("sk-old"),
1400        )
1401        .await
1402        .unwrap();
1403        assert_eq!(
1404            (renewed.key.secret.as_str(), renewed.issued),
1405            ("sk-new", true)
1406        );
1407        // Another session that also saw sk-old refused finds the new one.
1408        let other = ensure_key(
1409            &http,
1410            &server.url,
1411            "tok",
1412            "p-1",
1413            Billing::Project,
1414            &store,
1415            0,
1416            Some("sk-old"),
1417        )
1418        .await
1419        .unwrap();
1420        assert_eq!((other.key.secret.as_str(), other.issued), ("sk-new", false));
1421        assert_eq!(server.routes().len(), 1);
1422    }
1423
1424    /// Issuing revokes the previous key, so sessions starting together must
1425    /// end up with one key: the later ones wait and find the first one's.
1426    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1427    async fn sessions_starting_together_issue_one_key() {
1428        let tmp = tempfile::tempdir().unwrap();
1429        let store = KeyStore::at(key_store_path_in(tmp.path()));
1430        let server = MockServer::start(&[
1431            (
1432                "POST /api/me/keys",
1433                201,
1434                r#"{"secret":"sk-first","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
1435            ),
1436            (
1437                "POST /api/me/keys",
1438                201,
1439                r#"{"secret":"sk-second","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
1440            ),
1441        ]);
1442        let starts = (0..6).map(|_| {
1443            let (store, url) = (store.clone(), server.url.clone());
1444            tokio::spawn(async move {
1445                let http = reqwest::Client::new();
1446                ensure_key(&http, &url, "tok", "p-1", Billing::Project, &store, 0, None)
1447                    .await
1448                    .unwrap()
1449                    .key
1450                    .secret
1451            })
1452        });
1453        let mut secrets = Vec::new();
1454        for start in starts.collect::<Vec<_>>() {
1455            secrets.push(start.await.unwrap());
1456        }
1457        assert_eq!(secrets, ["sk-first"; 6]);
1458        assert_eq!(server.routes(), ["POST /api/me/keys"]);
1459    }
1460
1461    #[tokio::test]
1462    async fn a_gateway_that_refuses_the_key_is_told_from_one_that_is_away() {
1463        let http = reqwest::Client::new();
1464        let server = MockServer::start(&[
1465            ("GET /v1/models", 401, r#"{"error":"bad key"}"#),
1466            ("GET /v1/models", 403, ""),
1467            ("GET /v1/models", 500, ""),
1468            ("GET /v1/models", 200, "not json"),
1469        ]);
1470        for (rejected, said) in [
1471            (true, "did not accept the personal key (HTTP 401)"),
1472            (true, "HTTP 403"),
1473            (false, "HTTP 500"),
1474            (false, "unreadable answer"),
1475        ] {
1476            let err = models(&http, &server.url, "sk").await.unwrap_err();
1477            assert_eq!(err.rejected, rejected, "{}", err.why);
1478            assert!(err.why.contains(said), "{}", err.why);
1479        }
1480        let err = models(&http, "http://127.0.0.1:1", "sk").await.unwrap_err();
1481        assert!(
1482            !err.rejected && err.why.contains("did not answer"),
1483            "{}",
1484            err.why
1485        );
1486    }
1487
1488    #[cfg(unix)]
1489    #[tokio::test]
1490    async fn a_key_that_cannot_be_kept_is_an_error() {
1491        let http = reqwest::Client::new();
1492        let tmp = tempfile::tempdir().unwrap();
1493        // The store's file cannot be replaced: a directory is in its place.
1494        let store = KeyStore::at(key_store_path_in(tmp.path()));
1495        std::fs::create_dir_all(&store.path).unwrap();
1496        let server = MockServer::start(&[(
1497            "POST /api/me/keys",
1498            201,
1499            r#"{"secret":"sk-abc","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
1500        )]);
1501        let err = ensure_key(
1502            &http,
1503            &server.url,
1504            "tok",
1505            "p-1",
1506            Billing::Project,
1507            &store,
1508            0,
1509            None,
1510        )
1511        .await
1512        .err()
1513        .unwrap();
1514        assert!(err.contains("could not be kept"), "{err}");
1515        assert!(!err.contains("sk-abc"), "{err}");
1516    }
1517
1518    /// Issuing revokes the key in use, so it is not done without the lock
1519    /// that keeps two sessions from doing it at once; a kept key needs none.
1520    #[tokio::test]
1521    async fn no_key_is_issued_while_the_store_cannot_be_locked() {
1522        let http = reqwest::Client::new();
1523        let tmp = tempfile::tempdir().unwrap();
1524        let store = KeyStore::at(key_store_path_in(tmp.path()));
1525        // The lock file cannot be opened: a directory is in its place.
1526        std::fs::create_dir_all(store.path.with_extension("lock")).unwrap();
1527        let server = MockServer::start(&[(
1528            "POST /api/me/keys",
1529            201,
1530            r#"{"secret":"sk-abc","id":"h","name":"n","expiresAt":"2099-01-01T00:00:00Z"}"#,
1531        )]);
1532        let err = ensure_key(
1533            &http,
1534            &server.url,
1535            "tok",
1536            "p-1",
1537            Billing::Project,
1538            &store,
1539            0,
1540            None,
1541        )
1542        .await
1543        .err()
1544        .unwrap();
1545        assert!(err.contains("could not be locked"), "{err}");
1546        assert!(server.routes().is_empty(), "{:?}", server.routes());
1547
1548        let kept = IssuedKey {
1549            secret: "sk-kept".to_string(),
1550            expires_at: 1_000_000,
1551            id: None,
1552        };
1553        let account = account_of("tok");
1554        store
1555            .keep(&server.url, "p-1", &account, Billing::Project, &kept, 0)
1556            .unwrap();
1557        let ensured = ensure_key(
1558            &http,
1559            &server.url,
1560            "tok",
1561            "p-1",
1562            Billing::Project,
1563            &store,
1564            0,
1565            None,
1566        )
1567        .await
1568        .unwrap();
1569        assert_eq!(ensured.key.secret, "sk-kept");
1570        assert!(!ensured.issued);
1571        assert!(server.routes().is_empty(), "{:?}", server.routes());
1572    }
1573
1574    #[test]
1575    fn clearing_the_store_forgets_every_key() {
1576        let tmp = tempfile::tempdir().unwrap();
1577        let store = KeyStore::at(key_store_path_in(tmp.path()));
1578        assert!(store.clear().is_ok(), "nothing to forget is fine");
1579        let key = IssuedKey {
1580            secret: "sk-abc".to_string(),
1581            expires_at: 10_000,
1582            id: None,
1583        };
1584        store
1585            .keep("https://gw", "p-1", "", Billing::Project, &key, 0)
1586            .unwrap();
1587        store.clear().unwrap();
1588        assert!(store
1589            .usable("https://gw", "p-1", "", Billing::Project, 0)
1590            .is_none());
1591    }
1592
1593    const DAY: i64 = 24 * 60 * 60;
1594
1595    fn subscription_answer(secret: &str, id: &str, expires_at: &str) -> String {
1596        format!(
1597            r#"{{"secret":"{secret}","id":"{id}","name":"subscription-dev-1","expiresAt":"{expires_at}","billing":"subscription"}}"#
1598        )
1599    }
1600
1601    #[tokio::test]
1602    async fn a_subscription_key_is_asked_for_by_its_kind() {
1603        let http = reqwest::Client::new();
1604        let answer = subscription_answer("sk-sub", "hash-1", "2026-12-26T10:00:00Z");
1605        let server = MockServer::start(&[("POST /api/me/keys", 201, &answer)]);
1606        let key = issue_key(&http, &server.url, "tok", "p-1", Billing::Subscription, 0)
1607            .await
1608            .unwrap();
1609        assert_eq!(key.secret, "sk-sub");
1610        assert_eq!(key.id.as_deref(), Some("hash-1"));
1611        let asked = &server.requests()[0];
1612        assert_eq!(
1613            asked.body,
1614            r#"{"projectId":"p-1","billing":"subscription"}"#
1615        );
1616        assert_eq!(asked.authorization.as_deref(), Some("Bearer tok"));
1617    }
1618
1619    /// A console from before subscription keys ignores `billing` and issues
1620    /// an ordinary key, which would let the project pay: it is revoked again,
1621    /// and the answer is an error.
1622    #[tokio::test]
1623    async fn an_ordinary_key_given_for_a_subscription_is_given_back() {
1624        let http = reqwest::Client::new();
1625        let server = MockServer::start(&[
1626            (
1627                "POST /api/me/keys",
1628                201,
1629                r#"{"secret":"sk-ordinary","id":"hash-2","name":"personal-dev-1","expiresAt":"2099-01-01T00:00:00Z"}"#,
1630            ),
1631            ("DELETE /api/me/keys/hash-2", 204, ""),
1632        ]);
1633        let err = issue_key(&http, &server.url, "tok", "p-1", Billing::Subscription, 0)
1634            .await
1635            .err()
1636            .unwrap();
1637        assert!(
1638            err.contains("does not support billing = subscription"),
1639            "{err}"
1640        );
1641        assert!(!err.contains("sk-ordinary"), "{err}");
1642        assert_eq!(
1643            server.routes(),
1644            ["POST /api/me/keys", "DELETE /api/me/keys/hash-2"]
1645        );
1646    }
1647
1648    #[test]
1649    fn a_subscription_key_is_renewed_a_week_before_it_expires() {
1650        let tmp = tempfile::tempdir().unwrap();
1651        let store = KeyStore::at(key_store_path_in(tmp.path()));
1652        let key = |secret: &str, expires_at| IssuedKey {
1653            secret: secret.to_string(),
1654            expires_at,
1655            id: Some(format!("id-{secret}")),
1656        };
1657        let issued = 1_000_000;
1658        let expires = issued + 30 * DAY;
1659        let sub = Billing::Subscription;
1660        store
1661            .keep(
1662                "https://gw",
1663                "p-1",
1664                "a",
1665                sub,
1666                &key("first", expires),
1667                issued,
1668            )
1669            .unwrap();
1670        // Kinds are kept apart.
1671        assert!(store
1672            .usable("https://gw", "p-1", "a", Billing::Project, issued)
1673            .is_none());
1674        let week = MIN_SUBSCRIPTION_KEY_SECONDS_LEFT;
1675        assert_eq!(
1676            store
1677                .usable("https://gw", "p-1", "a", sub, expires - week)
1678                .unwrap()
1679                .secret,
1680            "first"
1681        );
1682        assert!(store
1683            .usable("https://gw", "p-1", "a", sub, expires - week + 1)
1684            .is_none());
1685        // A check still finds it, until it expires or is refused.
1686        assert_eq!(
1687            store
1688                .unexpired("https://gw", "p-1", "a", sub, expires - 1)
1689                .unwrap()
1690                .secret,
1691            "first"
1692        );
1693        assert!(store
1694            .unexpired("https://gw", "p-1", "a", sub, expires)
1695            .is_none());
1696        // The next one does not replace it in the store: the first stays
1697        // until it expires, for logout to revoke, and the new one is used.
1698        let now = expires - week + 1;
1699        store
1700            .keep(
1701                "https://gw",
1702                "p-1",
1703                "a",
1704                sub,
1705                &key("second", now + 30 * DAY),
1706                now,
1707            )
1708            .unwrap();
1709        assert_eq!(
1710            store
1711                .usable("https://gw", "p-1", "a", sub, now)
1712                .unwrap()
1713                .secret,
1714            "second"
1715        );
1716        let kept = store.kept(now);
1717        assert_eq!(kept.len(), 2, "{kept:?}");
1718        assert!(kept.iter().all(|k| k.billing == sub));
1719        // An ordinary key for the same project does not touch them.
1720        store
1721            .keep(
1722                "https://gw",
1723                "p-1",
1724                "a",
1725                Billing::Project,
1726                &key("plain", now + DAY),
1727                now,
1728            )
1729            .unwrap();
1730        assert_eq!(store.kept(now).len(), 3);
1731        // Once expired, it is dropped with the next write.
1732        store
1733            .keep(
1734                "https://gw",
1735                "p-2",
1736                "a",
1737                sub,
1738                &key("other", expires + 60 * DAY),
1739                expires + 1,
1740            )
1741            .unwrap();
1742        let left: Vec<_> = store.kept(expires + 1);
1743        assert_eq!(left.len(), 2, "{left:?}");
1744        // Another account's subscription keys go when this one keeps its own.
1745        store
1746            .keep(
1747                "https://gw",
1748                "p-2",
1749                "b",
1750                sub,
1751                &key("bobs", expires + 60 * DAY),
1752                expires + 2,
1753            )
1754            .unwrap();
1755        assert!(store
1756            .usable("https://gw", "p-2", "a", sub, expires + 2)
1757            .is_none());
1758    }
1759
1760    #[test]
1761    fn a_short_lived_subscription_key_is_renewed_at_half_its_life() {
1762        assert_eq!(
1763            renew_before(Billing::Subscription, 1000, 1000 + 30 * DAY),
1764            MIN_SUBSCRIPTION_KEY_SECONDS_LEFT
1765        );
1766        assert_eq!(
1767            renew_before(Billing::Subscription, 1000, 1000 + 4 * DAY),
1768            2 * DAY
1769        );
1770        assert_eq!(
1771            renew_before(Billing::Subscription, 0, 30 * DAY),
1772            MIN_SUBSCRIPTION_KEY_SECONDS_LEFT,
1773            "issue time unknown"
1774        );
1775        assert_eq!(renew_before(Billing::Project, 0, DAY), MIN_KEY_SECONDS_LEFT);
1776    }
1777
1778    #[tokio::test]
1779    async fn a_subscription_key_is_issued_once_and_shared() {
1780        let http = reqwest::Client::new();
1781        let tmp = tempfile::tempdir().unwrap();
1782        let store = KeyStore::at(key_store_path_in(tmp.path()));
1783        let answer = subscription_answer("sk-sub", "h", "2099-01-01T00:00:00Z");
1784        let server = MockServer::start(&[("POST /api/me/keys", 201, &answer)]);
1785        let sub = Billing::Subscription;
1786        for issued in [true, false] {
1787            let ensured = ensure_key(&http, &server.url, "tok", "p-1", sub, &store, 0, None)
1788                .await
1789                .unwrap();
1790            assert_eq!(
1791                (ensured.key.secret.as_str(), ensured.issued),
1792                ("sk-sub", issued)
1793            );
1794        }
1795        assert_eq!(server.routes(), ["POST /api/me/keys"]);
1796        // An ordinary key for the same project is its own.
1797        assert!(store
1798            .usable(&server.url, "p-1", "", Billing::Project, 0)
1799            .is_none());
1800    }
1801
1802    #[tokio::test]
1803    async fn logout_revokes_the_kept_keys_of_the_person_at_their_console() {
1804        let http = reqwest::Client::new();
1805        let tmp = tempfile::tempdir().unwrap();
1806        let store = KeyStore::at(key_store_path_in(tmp.path()));
1807        let server = MockServer::start(&[
1808            ("DELETE /api/me/keys/sub-1", 204, ""),
1809            (
1810                "DELETE /api/me/keys/sub%2F2",
1811                400,
1812                r#"{"error":"No such personal key of yours"}"#,
1813            ),
1814            ("DELETE /api/me/keys/plain-1", 500, ""),
1815        ]);
1816        let alice = token_of("https://idp", "alice-id");
1817        let account = account_of(&alice);
1818        let key = |id: Option<&str>, expires_at| IssuedKey {
1819            secret: "sk".to_string(),
1820            expires_at,
1821            id: id.map(String::from),
1822        };
1823        let sub = Billing::Subscription;
1824        store
1825            .keep(
1826                &server.url,
1827                "p-1",
1828                &account,
1829                sub,
1830                &key(Some("sub-1"), 100),
1831                0,
1832            )
1833            .unwrap();
1834        store
1835            .keep(
1836                &server.url,
1837                "p-1",
1838                &account,
1839                sub,
1840                &key(Some("sub/2"), 200),
1841                0,
1842            )
1843            .unwrap();
1844        store
1845            .keep(
1846                &server.url,
1847                "p-1",
1848                &account,
1849                Billing::Project,
1850                &key(Some("plain-1"), 100),
1851                0,
1852            )
1853            .unwrap();
1854        // Kept before keys had ids: nothing to revoke it by.
1855        store
1856            .keep(
1857                &server.url,
1858                "p-2",
1859                &account,
1860                Billing::Project,
1861                &key(None, 100),
1862                0,
1863            )
1864            .unwrap();
1865        // Somebody else's, and an expired one: not asked about.
1866        store
1867            .keep(&server.url, "p-3", "other", sub, &key(Some("bobs"), 100), 0)
1868            .unwrap();
1869        let warnings = revoke_kept(&http, &store, &alice, 50).await;
1870        let mut asked = server.routes();
1871        asked.sort();
1872        assert_eq!(
1873            asked,
1874            [
1875                "DELETE /api/me/keys/plain-1",
1876                "DELETE /api/me/keys/sub%2F2",
1877                "DELETE /api/me/keys/sub-1"
1878            ]
1879        );
1880        for request in server.requests() {
1881            assert_eq!(request.authorization, Some(format!("Bearer {alice}")));
1882        }
1883        assert_eq!(warnings.len(), 1, "{warnings:?}");
1884        assert!(warnings[0].contains("HTTP 500"), "{warnings:?}");
1885        assert!(
1886            warnings[0].contains("personal key stays valid"),
1887            "{warnings:?}"
1888        );
1889    }
1890
1891    /// A subscription key the gateway refused is not handed out again, even
1892    /// when it would outlast its replacement; it stays kept for logout.
1893    #[tokio::test]
1894    async fn a_refused_subscription_key_does_not_come_back() {
1895        let http = reqwest::Client::new();
1896        let tmp = tempfile::tempdir().unwrap();
1897        let store = KeyStore::at(key_store_path_in(tmp.path()));
1898        let answer = subscription_answer("sk-new", "h-new", "2099-01-01T00:00:00Z");
1899        let server = MockServer::start(&[("POST /api/me/keys", 201, &answer)]);
1900        let sub = Billing::Subscription;
1901        let old = IssuedKey {
1902            secret: "sk-old".to_string(),
1903            expires_at: 9_000_000_000,
1904            id: Some("h-old".to_string()),
1905        };
1906        store.keep(&server.url, "p-1", "", sub, &old, 0).unwrap();
1907        let renewed = ensure_key(
1908            &http,
1909            &server.url,
1910            "tok",
1911            "p-1",
1912            sub,
1913            &store,
1914            0,
1915            Some("sk-old"),
1916        )
1917        .await
1918        .unwrap();
1919        assert_eq!(
1920            (renewed.key.secret.as_str(), renewed.issued),
1921            ("sk-new", true)
1922        );
1923        // The next session, which was not told, gets the new one too.
1924        let next = ensure_key(&http, &server.url, "tok", "p-1", sub, &store, 0, None)
1925            .await
1926            .unwrap();
1927        assert_eq!((next.key.secret.as_str(), next.issued), ("sk-new", false));
1928        assert_eq!(server.routes().len(), 1);
1929        let ids: Vec<_> = store.kept(0).into_iter().filter_map(|k| k.id).collect();
1930        assert_eq!(ids, ["h-old", "h-new"]);
1931    }
1932}