Skip to main content

lean_ctx_cloud/
gateway.rs

1// SPDX-License-Identifier: Apache-2.0
2//! LeanCTX Cloud model gateway key (`POST /v1/gateway/key`): a short-lived
3//! key with which this computer's sessions run on models from LeanCTX, paid
4//! from the team's balance.
5//!
6//! Asked only when a local reader (LeanCTX Code) asks for it; the key is
7//! handed to that reader and never written to disk, cached or logged
8//! ([`GatewayKey`]'s `Debug` hides it). The reader keeps it in memory until
9//! `expires_at`.
10//!
11//! The cloud answers (contract W1):
12//! - `200 {schema, base_url, key, expires_at, models}` → [`GatewayAnswer::Ready`]
13//!   (fields Cloud adds later are ignored; `schema`, when sent, must be
14//!   [`KEY_SCHEMA`]);
15//! - `429 quota_exceeded` (`model_credit_usd_micros`) → [`GatewayAnswer::Stopped`];
16//! - `429 rate_limited` with `reason: gateway_keys` (this computer already
17//!   holds the most live keys Cloud allows) → [`GatewayAnswer::TooManyKeys`];
18//! - `403 forbidden` or `403 plan_required` (no plan or trial) →
19//!   [`GatewayAnswer::Forbidden`];
20//! - `503 not_configured`, or `404` from a cloud without the route →
21//!   [`GatewayAnswer::NotConfigured`].
22//!
23//! Anything else is a [`CloudError`].
24
25use std::fmt;
26
27use lean_ctx_time::UtcDateTime;
28use serde::{Deserialize, Serialize};
29use serde_json::Value;
30
31use crate::CloudError;
32use crate::config::CloudConfig;
33use crate::state::CloudStore;
34
35/// The cloud route (under `/v1`).
36const PATH: &str = "/gateway/key";
37/// Largest answer read; a key document is a few hundred bytes.
38const MAX_ANSWER_BYTES: usize = 16 * 1024;
39/// Longest key accepted.
40const MAX_KEY_LEN: usize = 4096;
41/// Longest base URL accepted.
42const MAX_URL_LEN: usize = 2048;
43/// The quota a stopped balance names.
44pub const BALANCE_RESOURCE: &str = "model_credit_usd_micros";
45/// Longest wait passed on (a day); a larger one is a broken answer.
46const RETRY_AFTER_CAP_S: u64 = 86_400;
47/// The `reason` of a `429 rate_limited` refused because this computer
48/// already holds the most live keys.
49pub const KEY_LIMIT_REASON: &str = "gateway_keys";
50/// The `schema` of a key document.
51pub const KEY_SCHEMA: &str = "leanctx.cloud.gateway_key.v1";
52
53/// A key the gateway handed out. Cloud answers grow additively, so fields
54/// not named here (`schema`, `models`, later ones) are not kept.
55#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub struct GatewayKey {
57    /// Where sessions send model requests (`https://…`).
58    pub base_url: String,
59    /// The bearer key; secret.
60    pub key: String,
61    /// When the key stops working (RFC 3339).
62    pub expires_at: String,
63}
64
65impl fmt::Debug for GatewayKey {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.debug_struct("GatewayKey")
68            .field("base_url", &self.base_url)
69            .field("key", &"<redacted>")
70            .field("expires_at", &self.expires_at)
71            .finish()
72    }
73}
74
75/// What the gateway said.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum GatewayAnswer {
78    /// A key for sessions.
79    Ready(GatewayKey),
80    /// The balance is used up; nothing runs until it is topped up.
81    Stopped {
82        /// `next_step: top_up`: a top-up helps.
83        top_up: bool,
84        /// Seconds after which asking again may help.
85        retry_after_s: Option<u64>,
86    },
87    /// This computer already holds the most live keys Cloud allows; a new
88    /// one comes once one of them expires (reuse a held key until then).
89    TooManyKeys {
90        /// Seconds after which asking again may help.
91        retry_after_s: Option<u64>,
92    },
93    /// This person may not use the team's balance.
94    Forbidden,
95    /// The cloud does not offer the gateway (not configured, or older).
96    NotConfigured,
97}
98
99/// Ask the connected cloud for a gateway key.
100pub fn request(store: &CloudStore, config: &CloudConfig) -> Result<GatewayAnswer, CloudError> {
101    let session = crate::scheduler::connected_session(store, config)?;
102    let (status, body) = session.with_client(|client| {
103        let (status, body) = client.send_answer("POST", PATH, None, MAX_ANSWER_BYTES)?;
104        // A refused token goes through the session's refresh.
105        if status == 401 {
106            return Err(CloudError::from_response(status, &body));
107        }
108        Ok((status, body))
109    })?;
110    classify(status, &body, UtcDateTime::now())
111}
112
113/// The answer of `status` and `body`, checked against `now`.
114fn classify(status: u16, body: &Value, now: UtcDateTime) -> Result<GatewayAnswer, CloudError> {
115    let code = body["error"]["code"].as_str().unwrap_or_default();
116    let retry_after_s = || {
117        body["error"]["retry_after_s"]
118            .as_u64()
119            .map(|s| s.min(RETRY_AFTER_CAP_S))
120    };
121    match status {
122        200 | 201 => ready(body, now).map(GatewayAnswer::Ready),
123        429 if code == "quota_exceeded" => Ok(GatewayAnswer::Stopped {
124            top_up: body["error"]["next_step"].as_str() == Some("top_up"),
125            retry_after_s: retry_after_s(),
126        }),
127        429 if code == "rate_limited"
128            && body["error"]["reason"].as_str() == Some(KEY_LIMIT_REASON) =>
129        {
130            Ok(GatewayAnswer::TooManyKeys {
131                retry_after_s: retry_after_s(),
132            })
133        }
134        403 if code == "forbidden" || code == "plan_required" => Ok(GatewayAnswer::Forbidden),
135        503 if code == "not_configured" => Ok(GatewayAnswer::NotConfigured),
136        404 if code.is_empty() || code == "not_found" => Ok(GatewayAnswer::NotConfigured),
137        _ => Err(CloudError::from_response(status, body)),
138    }
139}
140
141fn ready(body: &Value, now: UtcDateTime) -> Result<GatewayKey, CloudError> {
142    let bad = |why: &str| CloudError::Protocol(format!("gateway key: {why}"));
143    match body.get("schema") {
144        None => {}
145        Some(Value::String(schema)) if schema == KEY_SCHEMA => {}
146        Some(_) => return Err(bad("unknown schema")),
147    }
148    if body.get("models").is_some_and(|m| !m.is_array()) {
149        return Err(bad("models is not a list"));
150    }
151    let key: GatewayKey =
152        serde_json::from_value(body.clone()).map_err(|_| bad("not a key document"))?;
153    if !key.base_url.starts_with("https://")
154        || key.base_url.len() > MAX_URL_LEN
155        || key.base_url.chars().any(char::is_whitespace)
156    {
157        return Err(bad("base_url is not an https URL"));
158    }
159    if key.key.is_empty()
160        || key.key.len() > MAX_KEY_LEN
161        || !key.key.chars().all(|c| c.is_ascii_graphic())
162    {
163        return Err(bad("key is malformed"));
164    }
165    let expires = UtcDateTime::parse_from_rfc3339(&key.expires_at)
166        .map_err(|_| bad("expires_at is not RFC 3339"))?;
167    if expires <= now {
168        return Err(bad("key already expired"));
169    }
170    Ok(key)
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use serde_json::json;
177
178    fn now() -> UtcDateTime {
179        UtcDateTime::parse_from_rfc3339("2026-11-18T12:00:00Z").expect("time")
180    }
181
182    fn key_doc() -> Value {
183        json!({
184            "base_url": "https://gateway.example/v1",
185            "key": "gk_abc123",
186            "expires_at": "2026-11-18T13:00:00Z"
187        })
188    }
189
190    #[test]
191    fn a_key_is_handed_on_and_never_shown_in_debug() {
192        let answer = classify(200, &key_doc(), now()).expect("ready");
193        let GatewayAnswer::Ready(key) = &answer else {
194            panic!("not ready: {answer:?}");
195        };
196        assert_eq!(key.base_url, "https://gateway.example/v1");
197        assert_eq!(key.key, "gk_abc123");
198        let shown = format!("{answer:?}");
199        assert!(!shown.contains("gk_abc123"), "{shown}");
200        assert!(shown.contains("<redacted>"), "{shown}");
201    }
202
203    #[test]
204    fn a_used_up_balance_stops_with_the_top_up_step() {
205        let body = json!({"error": {
206            "code": "quota_exceeded", "resource": BALANCE_RESOURCE,
207            "next_step": "top_up", "retry_after_s": 999_999_999u64
208        }});
209        assert_eq!(
210            classify(429, &body, now()).expect("stopped"),
211            GatewayAnswer::Stopped {
212                top_up: true,
213                retry_after_s: Some(RETRY_AFTER_CAP_S)
214            }
215        );
216    }
217
218    #[test]
219    fn the_key_limit_is_its_own_answer_not_a_used_up_balance() {
220        let body = json!({"error": {
221            "code": "rate_limited", "reason": KEY_LIMIT_REASON,
222            "message": "this Host already holds 32 live gateway keys; reuse one until it expires",
223            "retry_after_s": 30
224        }});
225        assert_eq!(
226            classify(429, &body, now()).expect("too many keys"),
227            GatewayAnswer::TooManyKeys {
228                retry_after_s: Some(30)
229            }
230        );
231        // any wait Cloud names passes through unchanged (Cloud sends 30 today)
232        for wait in [1u64, 1_800, 3_600] {
233            let body = json!({"error": {
234                "code": "rate_limited", "reason": KEY_LIMIT_REASON, "retry_after_s": wait
235            }});
236            assert_eq!(
237                classify(429, &body, now()).expect("too many keys"),
238                GatewayAnswer::TooManyKeys {
239                    retry_after_s: Some(wait)
240                }
241            );
242        }
243        let no_wait = json!({"error": {"code": "rate_limited", "reason": KEY_LIMIT_REASON}});
244        assert_eq!(
245            classify(429, &no_wait, now()).expect("too many keys"),
246            GatewayAnswer::TooManyKeys {
247                retry_after_s: None
248            }
249        );
250        let huge = json!({"error": {
251            "code": "rate_limited", "reason": KEY_LIMIT_REASON,
252            "retry_after_s": 999_999_999u64
253        }});
254        assert_eq!(
255            classify(429, &huge, now()).expect("capped"),
256            GatewayAnswer::TooManyKeys {
257                retry_after_s: Some(RETRY_AFTER_CAP_S)
258            }
259        );
260    }
261
262    #[test]
263    fn other_rate_limits_stay_errors() {
264        let limited = |reason: Value| json!({"error": {"code": "rate_limited", "reason": reason, "retry_after_s": 5}});
265        assert!(classify(429, &limited(Value::Null), now()).is_err());
266        assert!(classify(429, &limited(json!("daily_jobs")), now()).is_err());
267        assert!(classify(429, &limited(json!(KEY_LIMIT_REASON.to_uppercase())), now()).is_err());
268        // the reason alone, under another code or status, is not the key limit
269        let other_code = json!({"error": {"code": "busy", "reason": KEY_LIMIT_REASON}});
270        assert!(classify(429, &other_code, now()).is_err());
271        assert!(classify(503, &limited(json!(KEY_LIMIT_REASON)), now()).is_err());
272    }
273
274    #[test]
275    fn refusals_and_missing_gateways_are_answers_not_errors() {
276        let err = |code: &str| json!({"error": {"code": code}});
277        assert_eq!(
278            classify(403, &err("forbidden"), now()).expect("forbidden"),
279            GatewayAnswer::Forbidden
280        );
281        // no plan or trial: the same next step for the reader
282        assert_eq!(
283            classify(403, &err("plan_required"), now()).expect("no plan"),
284            GatewayAnswer::Forbidden
285        );
286        assert!(classify(403, &err("csrf"), now()).is_err());
287        assert_eq!(
288            classify(503, &err("not_configured"), now()).expect("off"),
289            GatewayAnswer::NotConfigured
290        );
291        assert_eq!(
292            classify(404, &Value::Null, now()).expect("older cloud"),
293            GatewayAnswer::NotConfigured
294        );
295    }
296
297    #[test]
298    fn other_failures_stay_errors() {
299        // a real outage is not "not configured"
300        assert!(classify(503, &Value::Null, now()).is_err());
301        assert!(classify(500, &json!({"error": {"code": "internal"}}), now()).is_err());
302    }
303
304    #[test]
305    fn a_broken_or_stale_key_is_refused() {
306        let with = |field: &str, value: Value| {
307            let mut doc = key_doc();
308            doc[field] = value;
309            classify(200, &doc, now())
310        };
311        assert!(with("base_url", json!("http://gateway.example")).is_err());
312        assert!(with("key", json!("")).is_err());
313        assert!(with("key", json!("has space")).is_err());
314        assert!(with("expires_at", json!("tomorrow")).is_err());
315        assert!(with("expires_at", json!("2026-11-18T11:59:59Z")).is_err());
316        assert!(with("schema", json!("leanctx.cloud.gateway_key.v2")).is_err());
317        assert!(with("schema", json!("leanctx.cloud.gateway_key-v1")).is_err());
318        assert!(with("schema", json!(1)).is_err());
319        assert!(with("models", json!("gpt")).is_err());
320        let mut no_key = key_doc();
321        no_key.as_object_mut().expect("object").remove("key");
322        assert!(classify(200, &no_key, now()).is_err());
323        // a field Cloud adds later does not break the key
324        assert!(with("extra", json!(1)).is_ok());
325    }
326
327    #[test]
328    fn the_cloud_key_document_is_ready() {
329        // the exact 200 answer of LeanCTX Cloud's `POST /v1/gateway/key`
330        let body = json!({
331            "schema": "leanctx.cloud.gateway_key.v1",
332            "base_url": "https://cloud.leanctx.com/gateway/v1",
333            "key": "cloud_g_k1",
334            "expires_at": "2026-11-18T13:00:00Z",
335            "models": ["claude-sonnet-4-5", "gpt-5-mini"]
336        });
337        assert_eq!(
338            classify(200, &body, now()).expect("ready"),
339            GatewayAnswer::Ready(GatewayKey {
340                base_url: "https://cloud.leanctx.com/gateway/v1".into(),
341                key: "cloud_g_k1".into(),
342                expires_at: "2026-11-18T13:00:00Z".into(),
343            })
344        );
345        let mut no_models = body.clone();
346        no_models["models"] = json!([]);
347        assert!(classify(200, &no_models, now()).is_ok());
348    }
349}