1use 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
35const PATH: &str = "/gateway/key";
37const MAX_ANSWER_BYTES: usize = 16 * 1024;
39const MAX_KEY_LEN: usize = 4096;
41const MAX_URL_LEN: usize = 2048;
43pub const BALANCE_RESOURCE: &str = "model_credit_usd_micros";
45const RETRY_AFTER_CAP_S: u64 = 86_400;
47pub const KEY_LIMIT_REASON: &str = "gateway_keys";
50pub const KEY_SCHEMA: &str = "leanctx.cloud.gateway_key.v1";
52
53#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
56pub struct GatewayKey {
57 pub base_url: String,
59 pub key: String,
61 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#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum GatewayAnswer {
78 Ready(GatewayKey),
80 Stopped {
82 top_up: bool,
84 retry_after_s: Option<u64>,
86 },
87 TooManyKeys {
90 retry_after_s: Option<u64>,
92 },
93 Forbidden,
95 NotConfigured,
97}
98
99pub 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 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
113fn 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 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 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 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 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 assert!(with("extra", json!(1)).is_ok());
325 }
326
327 #[test]
328 fn the_cloud_key_document_is_ready() {
329 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}