Skip to main content

lean_ctx/core/
cloud_models.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The seam through which the local proxy serves the subscription models
3//! (mz6, `docs/model-access-subscription.md` §4).
4//!
5//! The built-in registry provider [`PROVIDER_ID`] forwards to the Cloud models
6//! gateway with the instance's short-lived `cloud_i_` access token. The proxy
7//! and the Cloud connector are sibling crates, so the connector registers the
8//! one process-wide [`CloudTokenSource`] (as it does the runtime
9//! `LeaseSource`) and the proxy asks it, never the Cloud crate directly.
10//!
11//! The token opens every engine route of Cloud, so it may only go to the
12//! models origin [`models_origin`] derives from the enrolled Cloud URL.
13
14use std::sync::{Arc, RwLock};
15
16/// Registry id of the built-in subscription-model provider.
17pub use crate::core::config::LEANCTX_PROVIDER_ID as PROVIDER_ID;
18
19/// Error code of the local 403 while the lease does not grant the right
20/// `models.subscription` (or the models origin is refused).
21pub const UNAVAILABLE_CODE: &str = "subscription_models_unavailable";
22
23/// Error code of the local 503 when no instance token can be had.
24pub const TOKEN_UNAVAILABLE_CODE: &str = "cloud_token_unavailable";
25
26/// What a request to the gateway may carry now.
27pub struct ModelsAdmission {
28    /// The models origin (`https://models.<cloud host>`), no trailing slash.
29    pub origin: String,
30    /// The instance access token (`cloud_i_…`).
31    pub token: zeroize::Zeroizing<String>,
32    /// A held route lets this one request through as a probe: its success
33    /// must be reported ([`CloudTokenSource::note_passed`]) to end the hold.
34    pub probe: bool,
35}
36
37// The token is a credential: debug output never shows it.
38impl std::fmt::Debug for ModelsAdmission {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.debug_struct("ModelsAdmission")
41            .field("origin", &self.origin)
42            .field("token", &"[redacted]")
43            .field("probe", &self.probe)
44            .finish()
45    }
46}
47
48/// Why a request is answered locally instead of going to the gateway.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub enum ModelsRefusal {
51    /// Not connected, Cloud paused, revoked, lease lapsed or without the
52    /// right `models.subscription`: 403 [`UNAVAILABLE_CODE`].
53    Unavailable,
54    /// The configured `[cloud] models_url` is not on the Cloud host: 403
55    /// [`UNAVAILABLE_CODE`]; checked before any token is read or minted.
56    OriginRefused(String),
57    /// An earlier gateway refusal (402/403/429) holds the `leanctx` routes
58    /// until `retry_after_s` from now (throttle style).
59    Held {
60        status: u16,
61        code: String,
62        retry_after_s: u64,
63        line: String,
64    },
65    /// No token could be minted: 503 [`TOKEN_UNAVAILABLE_CODE`].
66    TokenUnavailable,
67}
68
69/// Where the subscription-model access comes from (the Cloud connector).
70/// Every method may block (file reads, a token mint); the proxy calls them
71/// off the async runtime and bounds the wait.
72pub trait CloudTokenSource: Send + Sync {
73    /// Lease right, origin pin, holds, then the token; `fresh_token` mints
74    /// a new one (the gateway answered 401 to the cached one).
75    fn admit_route(&self, fresh_token: bool) -> Result<ModelsAdmission, ModelsRefusal>;
76    /// The gateway answered `status` (non-2xx) with `body`: record the hold
77    /// it sets, if any.
78    fn note_answer(&self, status: u16, retry_after: Option<&str>, body: &[u8]);
79    /// A probe passed: the holds of the `leanctx` routes end.
80    fn note_passed(&self);
81}
82
83static SOURCE: RwLock<Option<Arc<dyn CloudTokenSource>>> = RwLock::new(None);
84
85/// Registers the process-wide source. A later call replaces it.
86pub fn set_cloud_token_source(source: Arc<dyn CloudTokenSource>) {
87    *SOURCE
88        .write()
89        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(source);
90}
91
92/// The registered source; `None` without a Cloud connector.
93pub fn cloud_token_source() -> Option<Arc<dyn CloudTokenSource>> {
94    SOURCE
95        .read()
96        .unwrap_or_else(std::sync::PoisonError::into_inner)
97        .clone()
98}
99
100fn is_loopback(host: &str) -> bool {
101    let host = host.trim_start_matches('[').trim_end_matches(']');
102    host == "localhost"
103        || host
104            .parse::<std::net::IpAddr>()
105            .is_ok_and(|ip| ip.is_loopback())
106}
107
108fn origin_of(url: &reqwest::Url) -> String {
109    url.origin().ascii_serialization()
110}
111
112/// The models origin for an instance enrolled at `cloud_url`.
113///
114/// Without `models_url` it is `https://models.<cloud host>` (a loopback Cloud,
115/// as in tests, serves the models itself). A configured `models_url` is
116/// honoured only when it is a bare origin whose host equals the Cloud host or
117/// is a direct subdomain of it, over HTTPS; loopback is allowed for tests.
118/// Anything else is refused: the token must never reach a foreign host.
119pub fn models_origin(cloud_url: &str, models_url: Option<&str>) -> Result<String, String> {
120    let cloud =
121        reqwest::Url::parse(cloud_url.trim()).map_err(|e| format!("LeanCTX Cloud URL: {e}"))?;
122    let cloud_host = cloud
123        .host_str()
124        .ok_or("LeanCTX Cloud URL has no host")?
125        .to_ascii_lowercase();
126    let Some(raw) = models_url.map(str::trim).filter(|s| !s.is_empty()) else {
127        if is_loopback(&cloud_host) {
128            return Ok(origin_of(&cloud));
129        }
130        if cloud.scheme() != "https" {
131            return Err("LeanCTX Cloud URL is not https".into());
132        }
133        let port = cloud.port().map(|p| format!(":{p}")).unwrap_or_default();
134        return Ok(format!("https://models.{cloud_host}{port}"));
135    };
136    let url = reqwest::Url::parse(raw).map_err(|e| format!("models_url: {e}"))?;
137    if !matches!(url.path(), "" | "/")
138        || url.query().is_some()
139        || url.fragment().is_some()
140        || !url.username().is_empty()
141        || url.password().is_some()
142    {
143        return Err("models_url must be a bare origin (scheme, host, port)".into());
144    }
145    let host = url
146        .host_str()
147        .ok_or("models_url has no host")?
148        .to_ascii_lowercase();
149    if is_loopback(&host) && matches!(url.scheme(), "http" | "https") {
150        return Ok(origin_of(&url));
151    }
152    if url.scheme() != "https" {
153        return Err("models_url must use https".into());
154    }
155    let direct_subdomain = host
156        .strip_suffix(&cloud_host)
157        .and_then(|rest| rest.strip_suffix('.'))
158        .is_some_and(|label| !label.is_empty() && !label.contains('.'));
159    if host == cloud_host || direct_subdomain {
160        Ok(origin_of(&url))
161    } else {
162        Err(format!(
163            "models_url host {host} is not the LeanCTX Cloud host {cloud_host} or a direct subdomain of it"
164        ))
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    #[test]
173    fn the_models_origin_stays_on_the_cloud_host() {
174        let cloud = "https://cloud.example.com";
175        assert_eq!(
176            models_origin(cloud, None).unwrap(),
177            "https://models.cloud.example.com"
178        );
179        for ok in [
180            "https://models.cloud.example.com",
181            "https://gw.cloud.example.com/",
182            "https://cloud.example.com:8443",
183            "http://127.0.0.1:9000",
184        ] {
185            assert!(
186                models_origin(cloud, Some(ok)).is_ok(),
187                "{ok} must be honoured"
188            );
189        }
190        for refused in [
191            "https://models.evil.example",
192            "https://cloud.example.com.evil.example",
193            "https://a.b.cloud.example.com",
194            "https://evilcloud.example.com",
195            "http://models.cloud.example.com",
196            "https://models.cloud.example.com/v1",
197            "https://user@models.cloud.example.com",
198        ] {
199            assert!(
200                models_origin(cloud, Some(refused)).is_err(),
201                "{refused} must be refused"
202            );
203        }
204        assert_eq!(
205            models_origin("http://127.0.0.1:7000", None).unwrap(),
206            "http://127.0.0.1:7000"
207        );
208        assert!(models_origin("http://cloud.example.com", None).is_err());
209    }
210}