Skip to main content

lean_ctx_cloud/
models_access.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The subscription models through the Cloud models gateway (mz6,
3//! `docs/model-access-subscription.md` §4): the connector's
4//! [`CloudTokenSource`] for the proxy's built-in `leanctx` provider, and the
5//! catalog of `lean-ctx models` and of the Local Read kind
6//! `cloud.models.catalog` ([`read_catalog`]).
7//!
8//! Order of every admission, each step before the next one may run:
9//! Cloud on, enrolled, the models origin on the Cloud host (a foreign
10//! `models_url` is refused before any token is read or minted), lease valid
11//! or in grace and granting `models.subscription`, no hold of the models
12//! path ([`throttle::Scope::Models`]), then the instance token.
13
14use std::sync::{Arc, Mutex, OnceLock};
15
16use lean_ctx_time::UtcDateTime;
17use serde_json::Value;
18
19use super::CloudError;
20use super::auth::Session;
21use super::config::CloudConfig;
22use super::keyset_v3::{KeySetV3, Purpose};
23use super::state::CloudStore;
24use super::throttle::{self, Scope};
25use lean_ctx::core::cloud_models::{
26    CloudTokenSource, ModelsAdmission, ModelsRefusal, models_origin, set_cloud_token_source,
27};
28use lean_ctx_protocol::cloud::lease::{CloudRight, LeaseState};
29
30/// The models origin of the instance in `store`, or why there is none.
31/// Reads only the instance record and the config, never a token.
32pub fn origin_for(store: &CloudStore, config: &CloudConfig) -> Result<String, ModelsRefusal> {
33    if config.enabled == Some(false) {
34        return Err(ModelsRefusal::Unavailable);
35    }
36    let instance = store
37        .instance()
38        .ok()
39        .flatten()
40        .ok_or(ModelsRefusal::Unavailable)?;
41    models_origin(&instance.url, config.models_url.as_deref()).map_err(ModelsRefusal::OriginRefused)
42}
43
44/// The local answer while `throttle` holds the models path: the status and
45/// code the gateway gave (quota 429, plan 402, else policy 403).
46fn held(store: &CloudStore, throttle: &throttle::Throttle, now: UtcDateTime) -> ModelsRefusal {
47    let retry_after_s = lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&throttle.until)
48        .ok()
49        .and_then(|until| u64::try_from((until.to_utc() - now).num_seconds()).ok())
50        .unwrap_or(1)
51        .max(1);
52    let (status, code) = match throttle::models_hold_kind(store, now) {
53        throttle::HoldKind::Quota => (429, "quota_exceeded"),
54        throttle::HoldKind::Plan => (402, "plan_required"),
55        throttle::HoldKind::Policy => (403, "policy_denied"),
56    };
57    ModelsRefusal::Held {
58        status,
59        code: code.into(),
60        retry_after_s,
61        line: format!(
62            "waiting for LeanCTX Cloud until {}: {}",
63            throttle.until, throttle.line
64        ),
65    }
66}
67
68/// Everything before the token: config, origin pin, lease right, holds.
69/// `Ok` names the origin, whether the call is a probe, and the session.
70fn admit_without_token(
71    store: &CloudStore,
72    config: &CloudConfig,
73    now: UtcDateTime,
74) -> Result<(String, bool, Session), ModelsRefusal> {
75    let origin = origin_for(store, config)?;
76    let instance = store
77        .instance()
78        .ok()
79        .flatten()
80        .ok_or(ModelsRefusal::Unavailable)?;
81    let root = super::root_cert::trust_root(store, config, &instance.url)
82        .map_err(|_| ModelsRefusal::Unavailable)?;
83    let session = Session::load(store.clone(), root).map_err(|_| ModelsRefusal::Unavailable)?;
84    if !matches!(
85        session.lease.state_at(now),
86        LeaseState::Valid | LeaseState::Grace
87    ) || !session.lease.lease.grants(CloudRight::ModelsSubscription)
88    {
89        return Err(ModelsRefusal::Unavailable);
90    }
91    let holding = throttle::holding(store, Scope::Models, now);
92    if throttle::check(store, Scope::Models, now).is_err()
93        && let Some(throttle) = &holding
94    {
95        return Err(held(store, throttle, now));
96    }
97    // Held but let through: the hourly probe of a quota throttle.
98    Ok((origin, holding.is_some(), session))
99}
100
101/// Record what a gateway refusal says about the models path at `now`.
102pub fn note_answer_at(
103    store: &CloudStore,
104    status: u16,
105    retry_after: Option<&str>,
106    body: &[u8],
107    now: UtcDateTime,
108) {
109    if !matches!(status, 402 | 403 | 409 | 429) {
110        return;
111    }
112    let mut value: Value = serde_json::from_slice(body).unwrap_or(Value::Null);
113    // A 429 whose body is no JSON object (an edge page) becomes
114    // `{"error":{"retry_after_s":N}}`: it decodes to `RateLimited`, which
115    // sets no throttle here ([`throttle::of_error`]), exactly as the bare
116    // body did. Only a decoded `quota_exceeded` holds the models path.
117    super::transport::honour_retry_after(status, retry_after, &mut value);
118    let error = CloudError::from_response(status, &value);
119    let _ = throttle::note_on(store, Some(Scope::Models), error, now);
120}
121
122struct CloudModelsSource {
123    /// One token mint at a time: concurrent requests share the cache.
124    mint: Mutex<()>,
125}
126
127impl CloudModelsSource {
128    fn store_and_config() -> Option<(CloudStore, CloudConfig)> {
129        let store = CloudStore::open().ok()?;
130        let config = lean_ctx::core::config::Config::load().cloud.clone();
131        Some((store, config))
132    }
133}
134
135impl CloudTokenSource for CloudModelsSource {
136    fn admit_route(&self, fresh_token: bool) -> Result<ModelsAdmission, ModelsRefusal> {
137        let (store, config) = Self::store_and_config().ok_or(ModelsRefusal::Unavailable)?;
138        let (origin, probe, session) = admit_without_token(&store, &config, UtcDateTime::now())?;
139        let token = {
140            let _one = self
141                .mint
142                .lock()
143                .unwrap_or_else(std::sync::PoisonError::into_inner);
144            session.bearer_token(fresh_token)
145        };
146        match token {
147            Ok(token) => Ok(ModelsAdmission {
148                origin,
149                token,
150                probe,
151            }),
152            Err(error) => {
153                tracing::warn!("cloud models: no instance token: {error}");
154                Err(ModelsRefusal::TokenUnavailable)
155            }
156        }
157    }
158
159    fn note_answer(&self, status: u16, retry_after: Option<&str>, body: &[u8]) {
160        if let Ok(store) = CloudStore::open() {
161            note_answer_at(&store, status, retry_after, body, UtcDateTime::now());
162        }
163    }
164
165    fn note_passed(&self) {
166        if let Ok(store) = CloudStore::open() {
167            throttle::passed(&store, Scope::Models);
168        }
169    }
170}
171
172/// Register the connector as this process's subscription-model token
173/// source (once).
174pub fn ensure_registered() {
175    static REGISTERED: OnceLock<()> = OnceLock::new();
176    REGISTERED.get_or_init(|| {
177        set_cloud_token_source(Arc::new(CloudModelsSource {
178            mint: Mutex::new(()),
179        }));
180    });
181}
182
183/// One row of `lean-ctx models`.
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub struct CatalogRow {
186    pub id: String,
187    pub display_name: String,
188    pub vendor: String,
189    pub origin_country: String,
190    pub status: String,
191    /// `provider country[/region]`, in fallback order.
192    pub hosts: Vec<String>,
193}
194
195/// Catalog text for the terminal: no control characters, at most 80 chars.
196fn terminal_safe(s: &str) -> String {
197    s.chars()
198        .map(|c| if c.is_control() { ' ' } else { c })
199        .take(80)
200        .collect()
201}
202
203fn text(v: &Value, key: &str) -> String {
204    terminal_safe(v[key].as_str().unwrap_or("?"))
205}
206
207/// The rows of a catalog document (`leanctx.cloud.model-catalog/v1`).
208/// Display only: nothing is served or refused on these rows.
209pub fn catalog_rows(document: &Value) -> Result<Vec<CatalogRow>, CloudError> {
210    if document["schema"].as_str() != Some("leanctx.cloud.model-catalog/v1") {
211        return Err(CloudError::Protocol(
212            "model catalog: unknown or missing schema".into(),
213        ));
214    }
215    let models = document["models"]
216        .as_array()
217        .ok_or_else(|| CloudError::Protocol("model catalog: no models".into()))?;
218    Ok(models
219        .iter()
220        .map(|m| CatalogRow {
221            id: text(m, "id"),
222            display_name: text(m, "display_name"),
223            vendor: text(m, "vendor"),
224            origin_country: text(m, "origin_country"),
225            status: text(m, "status"),
226            hosts: m["hosts"]
227                .as_array()
228                .map(|hosts| {
229                    hosts
230                        .iter()
231                        .map(|h| {
232                            let region = h["host_region"]
233                                .as_str()
234                                .map(|r| format!("/{}", terminal_safe(r)))
235                                .unwrap_or_default();
236                            format!(
237                                "{} {}{region}",
238                                text(h, "provider"),
239                                text(h, "host_country")
240                            )
241                        })
242                        .collect()
243                })
244                .unwrap_or_default(),
245        })
246        .collect())
247}
248
249/// The connected instance's session.
250fn connected_session() -> Result<Session, CloudError> {
251    let store = CloudStore::open()?;
252    let config = lean_ctx::core::config::Config::load().cloud.clone();
253    let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
254    let root = super::root_cert::trust_root(&store, &config, &instance.url)?;
255    Session::load(store, root)
256}
257
258/// `GET /v1/models/catalog` with this instance's credentials.
259pub fn fetch_catalog() -> Result<Vec<CatalogRow>, CloudError> {
260    let session = connected_session()?;
261    let document = session.with_client(|client| client.get("/models/catalog"))?;
262    catalog_rows(&document)
263}
264
265/// Signing domain of the catalog Cloud serves (Cloud `cloud_wire::models`).
266pub const CATALOG_DOMAIN: &str = "leanctx.cloud.model-catalog.v1\n";
267
268/// Path of the LeanCTX gateway below the Cloud origin (Cloud
269/// `routes::gateway::GATEWAY_BASE_PATH`): an OpenAI-compatible base URL.
270pub const GATEWAY_BASE_PATH: &str = "/gateway/v1";
271
272/// Whether `document` is signed by a key set v3 `policy` key valid at
273/// `received_at` (ms): Ed25519 (`verify_strict`) over [`CATALOG_DOMAIN`] ‖
274/// canonical JSON of the document without `signature` (128 hex), with the
275/// key named by `key_id`, as the effective policy is verified.
276///
277/// `None` when the document carries no `signature` (nothing to verify);
278/// `Some(false)` when it does but no stored key verifies it.
279pub fn catalog_verified(
280    document: &Value,
281    keyset: Option<&KeySetV3>,
282    received_at: u64,
283) -> Option<bool> {
284    let signature = document.get("signature")?;
285    let verifies = || -> Option<bool> {
286        let mut bytes = [0u8; 64];
287        hex::decode_to_slice(signature.as_str()?, &mut bytes).ok()?;
288        let key = keyset?
289            .key_for(document["key_id"].as_str()?, Purpose::Policy, received_at)
290            .ok()?;
291        let input =
292            lean_ctx_protocol::cloud::signing_input_without_signature(CATALOG_DOMAIN, document)
293                .ok()?;
294        Some(
295            key.verify_strict(&input, &ed25519_dalek::Signature::from_bytes(&bytes))
296                .is_ok(),
297        )
298    };
299    Some(verifies() == Some(true))
300}
301
302/// The catalog as Cloud served it, with what the engine knows beside it.
303#[derive(Debug, Clone, PartialEq)]
304pub struct CatalogRead {
305    /// `GET /v1/models/catalog`, unchanged.
306    pub document: Value,
307    /// [`catalog_verified`].
308    pub verified: Option<bool>,
309    /// The lease is valid or in grace and grants `models.subscription`.
310    pub models_subscription: bool,
311    /// The LeanCTX gateway of the enrolled Cloud (`<cloud>/gateway/v1`).
312    pub gateway_base_url: String,
313}
314
315/// The gateway base URL of a Cloud enrolled at `cloud_url`.
316pub fn gateway_base_url(cloud_url: &str) -> String {
317    format!(
318        "{}{GATEWAY_BASE_PATH}",
319        cloud_url.trim().trim_end_matches('/')
320    )
321}
322
323/// How long a catalog `key_id` that the fetched key set still lacked is not
324/// fetched again.
325const UNKNOWN_KEY_TTL: std::time::Duration = std::time::Duration::from_secs(60);
326
327/// Bound on the remembered unknown keys; the oldest entries are dropped
328/// first when it is reached.
329const UNKNOWN_KEY_CAP: usize = 32;
330
331/// Negative cache of catalog signing keys the key set did not hold, keyed by
332/// Cloud URL and `key_id`.
333#[derive(Debug, Default)]
334struct UnknownKeys(std::collections::HashMap<String, std::time::Instant>);
335
336impl UnknownKeys {
337    fn recently_missed(&self, key: &str, now: std::time::Instant) -> bool {
338        self.0
339            .get(key)
340            .is_some_and(|at| now.saturating_duration_since(*at) < UNKNOWN_KEY_TTL)
341    }
342
343    fn remember(&mut self, key: String, now: std::time::Instant) {
344        self.0
345            .retain(|_, at| now.saturating_duration_since(*at) < UNKNOWN_KEY_TTL);
346        while self.0.len() >= UNKNOWN_KEY_CAP {
347            let Some(oldest) = self
348                .0
349                .iter()
350                .min_by_key(|(_, at)| **at)
351                .map(|(k, _)| k.clone())
352            else {
353                break;
354            };
355            self.0.remove(&oldest);
356        }
357        self.0.insert(key, now);
358    }
359}
360
361fn lock_unknown_keys() -> std::sync::MutexGuard<'static, UnknownKeys> {
362    static UNKNOWN: std::sync::OnceLock<std::sync::Mutex<UnknownKeys>> = std::sync::OnceLock::new();
363    UNKNOWN
364        .get_or_init(Default::default)
365        .lock()
366        .unwrap_or_else(std::sync::PoisonError::into_inner)
367}
368
369/// `GET /v1/models/catalog` as the connected instance, verified against
370/// the stored key set v3 (fetched once when it does not know the key).
371pub fn read_catalog() -> Result<CatalogRead, CloudError> {
372    let session = connected_session()?;
373    let document = session.with_client(|client| client.get("/models/catalog"))?;
374    if !document.is_object() {
375        return Err(CloudError::Protocol(
376            "model catalog: not a JSON object".into(),
377        ));
378    }
379    let now = UtcDateTime::now();
380    let verified = if document.get("signature").is_some() {
381        // A key the stored set does not know yet (a rotation): fetch once.
382        // A key the fetched set still lacks (or a failed fetch) is not
383        // fetched again for UNKNOWN_KEY_TTL, so repeated reads of a catalog
384        // signed with an unknown key do not hit `GET /keys` every time.
385        let key_id = document["key_id"].as_str().unwrap_or_default();
386        let knows = |set: &KeySetV3| set.keys.iter().any(|k| k.key_id == key_id);
387        let stored = super::keyset_v3::load(&session.store, session.root_key());
388        let keyset = match stored {
389            Some(set) if knows(&set) => Some(set),
390            stored => {
391                let miss_key = format!("{}\n{key_id}", session.instance.url);
392                let at = std::time::Instant::now();
393                if lock_unknown_keys().recently_missed(&miss_key, at) {
394                    stored
395                } else if let Ok(set) = super::keyset_v3::refresh(&session) {
396                    if !knows(&set) {
397                        lock_unknown_keys().remember(miss_key, at);
398                    }
399                    Some(set)
400                } else {
401                    lock_unknown_keys().remember(miss_key, at);
402                    stored
403                }
404            }
405        };
406        let received_at = u64::try_from(now.timestamp_millis()).unwrap_or(0);
407        catalog_verified(&document, keyset.as_ref(), received_at)
408    } else {
409        None
410    };
411    let models_subscription = matches!(
412        session.lease.state_at(now),
413        LeaseState::Valid | LeaseState::Grace
414    ) && session.lease.lease.grants(CloudRight::ModelsSubscription);
415    Ok(CatalogRead {
416        document,
417        verified,
418        models_subscription,
419        gateway_base_url: gateway_base_url(&session.instance.url),
420    })
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426
427    fn store_enrolled_at(url: &str) -> (tempfile::TempDir, CloudStore) {
428        let dir = tempfile::tempdir().unwrap();
429        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
430        store
431            .write_config(
432                super::super::state::INSTANCE_FILE,
433                &serde_json::json!({
434                    "instance_id": "ins_test",
435                    "org_id": "org_test",
436                    "org_name": "Test",
437                    "label": "test",
438                    "url": url,
439                    "org_salt_id": "salt_test",
440                    "enrolled_at": "2026-11-10T00:00:00Z",
441                }),
442            )
443            .unwrap();
444        (dir, store)
445    }
446
447    /// A `models_url` on a foreign host is refused before the session, the
448    /// lease or the token are touched: this store has no lease, no keys and
449    /// no token, and the answer is still the origin refusal.
450    #[test]
451    fn a_foreign_models_url_is_refused_before_any_token() {
452        let (_dir, store) = store_enrolled_at("https://cloud.example.com");
453        let config = CloudConfig {
454            models_url: Some("https://models.evil.example".into()),
455            ..CloudConfig::default()
456        };
457        let refused = admit_without_token(&store, &config, UtcDateTime::now())
458            .err()
459            .expect("refused");
460        assert!(
461            matches!(refused, ModelsRefusal::OriginRefused(ref why) if why.contains("evil.example")),
462            "{refused:?}"
463        );
464        assert!(
465            store
466                .read_config::<Value>(super::super::state::TOKEN_FILE)
467                .unwrap()
468                .is_none(),
469            "no token was minted or cached"
470        );
471        // The default origin passes the pin and then needs the lease.
472        let refused = admit_without_token(&store, &CloudConfig::default(), UtcDateTime::now())
473            .err()
474            .expect("refused");
475        assert_eq!(refused, ModelsRefusal::Unavailable);
476    }
477
478    /// A 429 edge page (no JSON object) with Retry-After is a rate limit,
479    /// not a quota: the models path is not held, as before the header was read.
480    #[test]
481    fn a_rate_limit_page_without_json_holds_nothing() {
482        let (_dir, store) = store_enrolled_at("https://cloud.example.com");
483        let now = UtcDateTime::now();
484        for body in [&b"<html>Too Many Requests</html>"[..], b"[]", b"\"busy\""] {
485            note_answer_at(&store, 429, Some("120"), body, now);
486            assert!(throttle::holding(&store, Scope::Models, now).is_none());
487            assert!(throttle::check(&store, Scope::Models, now).is_ok());
488        }
489    }
490
491    /// The gateway's hard cap (429 `quota_exceeded` for the month's model
492    /// credit) holds the models path until Retry-After, and only that path.
493    #[test]
494    fn a_credit_cap_holds_the_models_path_until_retry_after() {
495        let (_dir, store) = store_enrolled_at("https://cloud.example.com");
496        let now = lean_ctx_time::OffsetDateTime::parse_from_rfc3339("2026-11-10T12:00:00Z")
497            .unwrap()
498            .to_utc();
499        let body = serde_json::json!({"error": {
500            "code": "quota_exceeded",
501            "message": "the month's model credit is used up",
502            "resource": "model_credit_usd_micros",
503            "limit": 20_000_000u64,
504            "used": 20_000_000u64,
505        }});
506        note_answer_at(&store, 429, Some("120"), body.to_string().as_bytes(), now);
507        let throttle = throttle::holding(&store, Scope::Models, now).expect("models held");
508        assert_eq!(throttle.until, "2026-11-10T12:02:00Z", "Retry-After 120");
509        assert_eq!(throttle.scopes, ["models"]);
510        assert!(throttle::holding(&store, Scope::Sync, now).is_none());
511        match held(&store, &throttle, now) {
512            ModelsRefusal::Held {
513                status,
514                code,
515                retry_after_s,
516                ..
517            } => {
518                assert_eq!(
519                    (status, code.as_str(), retry_after_s),
520                    (429, "quota_exceeded", 120)
521                );
522            }
523            other => panic!("{other:?}"),
524        }
525        let later = now + lean_ctx_time::Duration::seconds(121);
526        assert!(
527            throttle::check(&store, Scope::Models, later).is_ok(),
528            "ends at Retry-After"
529        );
530    }
531
532    fn policy_signer() -> ed25519_dalek::SigningKey {
533        ed25519_dalek::SigningKey::from_bytes(&[7u8; 32])
534    }
535
536    /// C0 `key_id`: `hex(blake3(public key))[..16]`.
537    fn key_id_of(key: &ed25519_dalek::SigningKey) -> String {
538        blake3::hash(key.verifying_key().as_bytes()).to_hex()[..16].to_string()
539    }
540
541    fn keyset_with(key: &ed25519_dalek::SigningKey, purposes: Vec<Purpose>) -> KeySetV3 {
542        use base64::Engine as _;
543        KeySetV3 {
544            schema: super::super::keyset_v3::KEYSET_V3_SCHEMA.into(),
545            keys: vec![super::super::keyset_v3::KeyV3 {
546                key_id: key_id_of(key),
547                public_key: base64::engine::general_purpose::URL_SAFE_NO_PAD
548                    .encode(key.verifying_key().as_bytes()),
549                purposes,
550                created_at: 1_000,
551                revoked_at: None,
552            }],
553            signatures: Vec::new(),
554            signature: String::new(),
555        }
556    }
557
558    /// A catalog signed as Cloud signs it (`model_catalog::signed`).
559    fn signed_catalog(key: &ed25519_dalek::SigningKey) -> Value {
560        use ed25519_dalek::Signer as _;
561        let mut doc = serde_json::json!({
562            "schema": "leanctx.cloud.model-catalog/v1",
563            "catalog_version": "2026-11-20.1",
564            "price_version": "2026-11-20.1",
565            "models": [{
566                "id": "leanctx/open-model",
567                "display_name": "Open Model",
568                "vendor": "Example",
569                "origin_country": "FR",
570                "status": "unpriced",
571                "plans": ["personal", "team"],
572                "hosts": [{"provider": "example", "host_country": "DE"}]
573            }],
574            "direct": []
575        });
576        doc["key_id"] = key_id_of(key).into();
577        let input = lean_ctx_protocol::cloud::signing_input_without_signature(CATALOG_DOMAIN, &doc)
578            .unwrap();
579        doc["signature"] = hex::encode(key.sign(&input).to_bytes()).into();
580        doc
581    }
582
583    #[test]
584    fn a_catalog_signed_by_the_policy_key_verifies() {
585        let key = policy_signer();
586        let doc = signed_catalog(&key);
587        let set = keyset_with(&key, vec![Purpose::Policy]);
588        assert_eq!(catalog_verified(&doc, Some(&set), 2_000), Some(true));
589    }
590
591    #[test]
592    fn a_changed_or_foreign_catalog_does_not_verify() {
593        let key = policy_signer();
594        let set = keyset_with(&key, vec![Purpose::Policy]);
595        let mut changed = signed_catalog(&key);
596        changed["models"][0]["status"] = "available".into();
597        assert_eq!(catalog_verified(&changed, Some(&set), 2_000), Some(false));
598        // signed by a key the set does not hold
599        let other = ed25519_dalek::SigningKey::from_bytes(&[9u8; 32]);
600        assert_eq!(
601            catalog_verified(&signed_catalog(&other), Some(&set), 2_000),
602            Some(false)
603        );
604        let doc = signed_catalog(&key);
605        // a key without the policy purpose, one created after receipt, no set
606        let event_only = keyset_with(&key, vec![Purpose::Event]);
607        assert_eq!(
608            catalog_verified(&doc, Some(&event_only), 2_000),
609            Some(false)
610        );
611        assert_eq!(catalog_verified(&doc, Some(&set), 500), Some(false));
612        assert_eq!(catalog_verified(&doc, None, 2_000), Some(false));
613        let mut bad_hex = doc.clone();
614        bad_hex["signature"] = "zz".into();
615        assert_eq!(catalog_verified(&bad_hex, Some(&set), 2_000), Some(false));
616    }
617
618    #[test]
619    fn an_unsigned_catalog_is_neither_verified_nor_refused() {
620        let mut doc = signed_catalog(&policy_signer());
621        doc.as_object_mut().unwrap().remove("signature");
622        let set = keyset_with(&policy_signer(), vec![Purpose::Policy]);
623        assert_eq!(catalog_verified(&doc, Some(&set), 2_000), None);
624    }
625
626    #[test]
627    fn an_unknown_key_is_not_fetched_again_within_the_ttl() {
628        let start = std::time::Instant::now();
629        let mut unknown = UnknownKeys::default();
630        assert!(!unknown.recently_missed("cloud\nk1", start));
631        unknown.remember("cloud\nk1".into(), start);
632        assert!(unknown.recently_missed("cloud\nk1", start + UNKNOWN_KEY_TTL / 2));
633        assert!(!unknown.recently_missed("cloud\nk1", start + UNKNOWN_KEY_TTL));
634        assert!(!unknown.recently_missed("cloud\nk2", start));
635        // bounded: the oldest entry makes room
636        for i in 0..UNKNOWN_KEY_CAP + 3 {
637            let at = start + std::time::Duration::from_millis(u64::try_from(i).unwrap());
638            unknown.remember(format!("cloud\nkey{i}"), at);
639        }
640        assert_eq!(unknown.0.len(), UNKNOWN_KEY_CAP);
641        assert!(!unknown.0.contains_key("cloud\nkey0"));
642    }
643
644    #[test]
645    fn the_gateway_base_url_is_on_the_enrolled_cloud() {
646        assert_eq!(
647            gateway_base_url("https://cloud.leanctx.com/"),
648            "https://cloud.leanctx.com/gateway/v1"
649        );
650        assert_eq!(
651            gateway_base_url("http://127.0.0.1:8080"),
652            "http://127.0.0.1:8080/gateway/v1"
653        );
654    }
655}