Skip to main content

lean_ctx_cloud/
transport.rs

1// SPDX-License-Identifier: Apache-2.0
2//! HTTP transport to the Cloud engine API (`<origin>/v1`).
3//!
4//! HTTPS only (loopback may use http), redirects refused, bounded response
5//! bodies, `Cloud-Protocol` checked on every answer. Tokens travel only in
6//! the `Authorization` header and never reach an error message.
7
8use std::time::Duration;
9
10use serde_json::Value;
11use zeroize::Zeroizing;
12
13use super::CloudError;
14use super::config::normalize_origin;
15use lean_ctx_protocol::cloud::{
16    CLOUD_API_PREFIX, HEADER_IDEMPOTENCY_KEY, HEADER_INSTANCE, HEADER_MIN_ENGINE, HEADER_NAMES,
17    HEADER_PROTOCOL, MAX_BODY_BYTES, NAMES_VAULT, parse_protocol_header,
18};
19
20/// `User-Agent` of every request.
21pub fn user_agent() -> String {
22    format!("lean-ctx/{}", env!("CARGO_PKG_VERSION"))
23}
24
25/// A client bound to one Cloud origin, optionally authenticated.
26pub struct CloudClient {
27    origin: String,
28    agent: ureq::Agent,
29    auth: Option<(String, Zeroizing<String>)>,
30    /// The minor of the last 2.x `Cloud-Protocol` answer; `u16::MAX` until
31    /// one came.
32    answered_minor: std::sync::atomic::AtomicU16,
33}
34
35/// The C0 protocol every request carries, the enrollment included. Cloud
36/// accepts only major 2 and answers `426` for a missing or malformed header
37/// or another major. From 2.1 an enrollment carries key set v3 and the
38/// policy bundle no TOML org policy. Cloud answers `2.<min(minor, 2)>`: a
39/// 2.2 answer allows the 2.2 writes (doc nodes, decision anchors), which
40/// the engine gates on the answered minor (`relay_v2::protocol_minor`).
41pub const PROTOCOL_V2: &str = "2.2";
42
43/// The protocol major this engine speaks and accepts in an answer.
44const PROTOCOL_MAJOR: u16 = 2;
45
46/// Why an answer's `Cloud-Protocol` is refused: only a 2.x Cloud is spoken
47/// to, and the error names the protocol required.
48fn incompatible(peer: &str) -> Option<CloudError> {
49    match parse_protocol_header(peer) {
50        Some((PROTOCOL_MAJOR, _)) => None,
51        Some((major, minor)) => Some(CloudError::Protocol(format!(
52            "The Cloud speaks protocol {major}.{minor}; this instance requires Cloud-Protocol \
53             {PROTOCOL_MAJOR}.x: upgrade the Cloud server"
54        ))),
55        None => Some(CloudError::Protocol(format!(
56            "The Cloud sent no valid protocol version; this instance requires Cloud-Protocol \
57             {PROTOCOL_MAJOR}.x"
58        ))),
59    }
60}
61
62/// A 2xx or 304 answer.
63#[derive(Debug, Clone, PartialEq)]
64pub struct CloudResponse {
65    pub status: u16,
66    /// `Value::Null` for 204/304.
67    pub body: Value,
68    pub etag: Option<String>,
69}
70
71impl CloudClient {
72    /// The minor version of the last 2.x answer this client got (`2.2` →
73    /// `Some(2)`); `None` before any answer.
74    pub fn answered_minor(&self) -> Option<u16> {
75        let minor = self
76            .answered_minor
77            .load(std::sync::atomic::Ordering::Relaxed);
78        (minor != u16::MAX).then_some(minor)
79    }
80
81    pub fn new(origin: &str) -> Result<Self, CloudError> {
82        let origin = normalize_origin(origin)?;
83        let agent: ureq::Agent = ureq::config::Config::builder()
84            .tls_config(lean_ctx::core::http_client::platform_tls_config())
85            .http_status_as_error(false)
86            .max_redirects(0)
87            .timeout_resolve(Some(Duration::from_secs(5)))
88            .timeout_connect(Some(Duration::from_secs(10)))
89            .timeout_recv_response(Some(Duration::from_secs(30)))
90            .build()
91            .into();
92        Ok(Self {
93            origin,
94            agent,
95            auth: None,
96            answered_minor: std::sync::atomic::AtomicU16::new(u16::MAX),
97        })
98    }
99
100    /// A client whose every request ends within `total` (resolve, connect,
101    /// send and receive together): the bounded calls made from a tool call
102    /// (C5c, rule 3 exception).
103    pub fn bounded(origin: &str, total: Duration) -> Result<Self, CloudError> {
104        let origin = normalize_origin(origin)?;
105        let agent: ureq::Agent = ureq::config::Config::builder()
106            .tls_config(lean_ctx::core::http_client::platform_tls_config())
107            .http_status_as_error(false)
108            .max_redirects(0)
109            .timeout_global(Some(total))
110            .build()
111            .into();
112        Ok(Self {
113            origin,
114            agent,
115            auth: None,
116            answered_minor: std::sync::atomic::AtomicU16::new(u16::MAX),
117        })
118    }
119
120    /// Authenticate subsequent requests as `instance_id`.
121    pub fn with_token(mut self, instance_id: &str, access_token: &str) -> Self {
122        self.auth = Some((
123            instance_id.to_string(),
124            Zeroizing::new(access_token.to_string()),
125        ));
126        self
127    }
128
129    pub fn origin(&self) -> &str {
130        &self.origin
131    }
132
133    pub fn get(&self, path: &str) -> Result<Value, CloudError> {
134        Ok(self.send("GET", path, None, &[], MAX_BODY_BYTES)?.body)
135    }
136
137    /// `POST` with a fresh `Idempotency-Key`.
138    pub fn post(&self, path: &str, body: &Value) -> Result<Value, CloudError> {
139        let key = uuid::Uuid::new_v4().simple().to_string();
140        self.post_idempotent(path, body, &key)
141    }
142
143    /// `POST` with a caller-chosen `Idempotency-Key` (outbox item id).
144    pub fn post_idempotent(
145        &self,
146        path: &str,
147        body: &Value,
148        key: &str,
149    ) -> Result<Value, CloudError> {
150        Ok(self
151            .send(
152                "POST",
153                path,
154                Some(body),
155                &[(HEADER_IDEMPOTENCY_KEY, key)],
156                MAX_BODY_BYTES,
157            )?
158            .body)
159    }
160
161    pub fn delete(&self, path: &str) -> Result<(), CloudError> {
162        self.send("DELETE", path, None, &[], MAX_BODY_BYTES)
163            .map(|_| ())
164    }
165
166    /// Any request; `extra` headers win over the defaults, `max_body` bounds
167    /// the response. 2xx and 304 are `Ok`, everything else maps to [`CloudError`].
168    pub fn send(
169        &self,
170        method: &str,
171        path: &str,
172        body: Option<&Value>,
173        extra: &[(&str, &str)],
174        max_body: usize,
175    ) -> Result<CloudResponse, CloudError> {
176        let (status, etag, _, value) = self.exchange(method, path, body, extra, max_body)?;
177        if (200..300).contains(&status) || status == 304 {
178            if (200..300).contains(&status) && status != 204 && value.is_null() {
179                return Err(CloudError::Protocol(format!(
180                    "{method} {path}: body is not JSON"
181                )));
182            }
183            return Ok(CloudResponse {
184                status,
185                body: value,
186                etag,
187            });
188        }
189        Err(CloudError::from_response(status, &value))
190    }
191
192    /// `GET` of raw bytes (at most `max_body`), e.g. a file Cloud stores.
193    pub fn get_bytes(&self, path: &str, max_body: usize) -> Result<Vec<u8>, CloudError> {
194        let (status, _, bytes, value) = self.exchange("GET", path, None, &[], max_body)?;
195        if (200..300).contains(&status) {
196            return Ok(bytes);
197        }
198        Err(CloudError::from_response(status, &value))
199    }
200
201    /// Any request, answering its status and JSON body even when that is an
202    /// error, for C0 2.0 routes whose `error.reason` the caller words
203    /// itself; transport failures are still errors.
204    pub fn send_answer(
205        &self,
206        method: &str,
207        path: &str,
208        body: Option<&Value>,
209        max_body: usize,
210    ) -> Result<(u16, Value), CloudError> {
211        self.send_answer_with(method, path, body, &[], max_body)
212    }
213
214    /// [`Self::send_answer`] with `extra` headers, which win over the
215    /// defaults (as [`Self::send`]); a caller's `Idempotency-Key`, as
216    /// [`Self::post_idempotent`] sends it.
217    pub fn send_answer_with(
218        &self,
219        method: &str,
220        path: &str,
221        body: Option<&Value>,
222        extra: &[(&str, &str)],
223        max_body: usize,
224    ) -> Result<(u16, Value), CloudError> {
225        let (status, _, _, value) = self.exchange(method, path, body, extra, max_body)?;
226        Ok((status, value))
227    }
228
229    /// `PUT` of raw bytes (`application/octet-stream`), answering its status
230    /// and JSON body even when that is an error (E51 bundle upload).
231    pub fn put_bytes_answer(
232        &self,
233        path: &str,
234        bytes: &[u8],
235        max_body: usize,
236    ) -> Result<(u16, Value), CloudError> {
237        let (status, _, _, value) = self.exchange_raw(
238            "PUT",
239            path,
240            Some((bytes, "application/octet-stream")),
241            &[],
242            max_body,
243        )?;
244        Ok((status, value))
245    }
246
247    /// A JSON body the caller already encoded (`application/json`), answering
248    /// its status and JSON body even when that is an error. The caller owns
249    /// the buffer and can wipe it; the HTTP stack may still copy it while
250    /// sending (runner `add`, local-read-v1 §45).
251    pub fn send_json_bytes_answer(
252        &self,
253        method: &str,
254        path: &str,
255        body: &[u8],
256        max_body: usize,
257    ) -> Result<(u16, Value), CloudError> {
258        let (status, _, _, value) = self.exchange_raw(
259            method,
260            path,
261            Some((body, "application/json")),
262            &[],
263            max_body,
264        )?;
265        Ok((status, value))
266    }
267
268    /// `GET` of raw bytes (at most `max_body`), answering the status and the
269    /// bytes; an error body is parsed as JSON (`Null` when it is none).
270    pub fn get_bytes_answer(
271        &self,
272        path: &str,
273        max_body: usize,
274    ) -> Result<(u16, Vec<u8>, Value), CloudError> {
275        let (status, _, bytes, value) = self.exchange_raw("GET", path, None, &[], max_body)?;
276        Ok((status, bytes, value))
277    }
278
279    /// One request: its status, `ETag`, body bytes and the body as JSON
280    /// (`Null` when it is none); `426` and an incompatible protocol are errors.
281    fn exchange(
282        &self,
283        method: &str,
284        path: &str,
285        body: Option<&Value>,
286        extra: &[(&str, &str)],
287        max_body: usize,
288    ) -> Result<(u16, Option<String>, Vec<u8>, Value), CloudError> {
289        let encoded = match (method, body) {
290            ("GET", _) | ("DELETE", None) => None,
291            (_, Some(body)) => Some(
292                serde_json::to_vec(body)
293                    .map_err(|e| CloudError::Protocol(format!("encode request: {e}")))?,
294            ),
295            (_, None) => Some(Vec::new()),
296        };
297        self.exchange_raw(
298            method,
299            path,
300            encoded.as_deref().map(|bytes| (bytes, "application/json")),
301            extra,
302            max_body,
303        )
304    }
305
306    /// [`Self::exchange`] with a body already encoded: `(bytes, content type)`.
307    fn exchange_raw(
308        &self,
309        method: &str,
310        path: &str,
311        body: Option<(&[u8], &str)>,
312        extra: &[(&str, &str)],
313        max_body: usize,
314    ) -> Result<(u16, Option<String>, Vec<u8>, Value), CloudError> {
315        let url = format!("{}{CLOUD_API_PREFIX}{path}", self.origin);
316        let user_agent = user_agent();
317        let bearer = self
318            .auth
319            .as_ref()
320            .map(|(_, token)| Zeroizing::new(format!("Bearer {}", token.as_str())));
321        let mut headers: Vec<(&str, &str)> = vec![
322            (HEADER_PROTOCOL, PROTOCOL_V2),
323            (HEADER_NAMES, NAMES_VAULT),
324            ("User-Agent", &user_agent),
325        ];
326        if let (Some((instance, _)), Some(bearer)) = (&self.auth, &bearer) {
327            headers.push((HEADER_INSTANCE, instance));
328            headers.push(("Authorization", bearer));
329        }
330        headers.retain(|(name, _)| !extra.iter().any(|(e, _)| e.eq_ignore_ascii_case(name)));
331        headers.extend_from_slice(extra);
332
333        let result = match (method, body) {
334            ("GET", _) => with_headers(self.agent.get(&url), &headers).call(),
335            ("DELETE", None) => with_headers(self.agent.delete(&url), &headers).call(),
336            // A DELETE that names what it releases (`DELETE /v1/stop`
337            // `{confirm, note}`): the body is sent as for a POST.
338            ("DELETE", Some((bytes, content_type))) => {
339                with_headers(self.agent.delete(&url).force_send_body(), &headers)
340                    .header("Content-Type", content_type)
341                    .send(bytes)
342            }
343            (_, body) => {
344                let (bytes, content_type) = body.unwrap_or((&[], "application/json"));
345                let request = match method {
346                    "PUT" => self.agent.put(&url),
347                    "PATCH" => self.agent.patch(&url),
348                    _ => self.agent.post(&url),
349                };
350                with_headers(request, &headers)
351                    .header("Content-Type", content_type)
352                    .send(bytes)
353            }
354        };
355        let response = result.map_err(|e| offline(&e))?;
356        let status = response.status().as_u16();
357        let header = |name: &str| {
358            response
359                .headers()
360                .get(name)
361                .and_then(|v| v.to_str().ok())
362                .map(str::to_string)
363        };
364        let peer_protocol = header(HEADER_PROTOCOL);
365        let min_instance = header(HEADER_MIN_ENGINE);
366        let etag = header("etag");
367        let retry_after = header("retry-after");
368        let bytes = response
369            .into_body()
370            .into_with_config()
371            .limit(max_body as u64)
372            .read_to_vec()
373            .map_err(|e| CloudError::Protocol(format!("response body: {e}")))?;
374        let mut value = if bytes.iter().all(u8::is_ascii_whitespace) {
375            Value::Null
376        } else {
377            serde_json::from_slice(&bytes).unwrap_or(Value::Null)
378        };
379        honour_retry_after(status, retry_after.as_deref(), &mut value);
380        if status == 426 {
381            let min = min_instance
382                .or_else(|| value["error"]["min_instance"].as_str().map(str::to_string));
383            return Err(CloudError::UpgradeRequired { min });
384        }
385        // A load balancer or edge proxy answers 413/429/5xx itself, without
386        // (or with a stale) protocol header: the status decides, never a
387        // "no valid protocol version" refusal.
388        if !answered_by_edge(status)
389            && let Some(refused) = peer_protocol.as_deref().and_then(incompatible)
390        {
391            return Err(refused);
392        }
393        if let Some((PROTOCOL_MAJOR, minor)) =
394            peer_protocol.as_deref().and_then(parse_protocol_header)
395        {
396            self.answered_minor
397                .store(minor, std::sync::atomic::Ordering::Relaxed);
398        }
399        Ok((status, etag, bytes, value))
400    }
401}
402
403/// Statuses an edge proxy answers on its own (body too large, rate limit,
404/// upstream down): classified by status, whatever the protocol header says.
405fn answered_by_edge(status: u16) -> bool {
406    matches!(status, 413 | 429 | 500..=599)
407}
408
409/// A 429/503 whose body names no `retry_after_s` takes the `Retry-After`
410/// header's delta-seconds (API §0: 429 sets both; a proxy may set only the
411/// header), so every caller backs off by the same value. A body without an
412/// `error` object (an edge's HTML page) gets one carrying only that value.
413pub(crate) fn honour_retry_after(status: u16, header: Option<&str>, value: &mut Value) {
414    if !matches!(status, 429 | 503) {
415        return;
416    }
417    let Some(seconds) = header.and_then(|h| h.trim().parse::<u64>().ok()) else {
418        return;
419    };
420    if !value.is_object() {
421        *value = Value::Object(serde_json::Map::new());
422    }
423    if let Some(body) = value.as_object_mut()
424        && !body.get("error").is_some_and(Value::is_object)
425    {
426        body.insert("error".into(), Value::Object(serde_json::Map::new()));
427    }
428    if let Some(error) = value.get_mut("error").and_then(Value::as_object_mut)
429        && !error.contains_key("retry_after_s")
430    {
431        error.insert("retry_after_s".into(), seconds.into());
432    }
433}
434
435#[cfg(test)]
436mod retry_after_tests {
437    use super::*;
438
439    #[test]
440    fn the_retry_after_header_fills_a_missing_retry_after_s() {
441        let mut body = serde_json::json!({"error": {"code": "quota_exceeded", "message": "x"}});
442        honour_retry_after(429, Some(" 120 "), &mut body);
443        assert_eq!(body["error"]["retry_after_s"], 120);
444        // The body's own value wins; other statuses and dates are left alone.
445        honour_retry_after(429, Some("5"), &mut body);
446        assert_eq!(body["error"]["retry_after_s"], 120);
447        let mut other = serde_json::json!({"error": {"code": "not_found", "message": "x"}});
448        honour_retry_after(404, Some("5"), &mut other);
449        honour_retry_after(429, Some("Wed, 21 Oct 2026 07:28:00 GMT"), &mut other);
450        assert!(other["error"].get("retry_after_s").is_none());
451    }
452}
453
454fn with_headers<B>(
455    mut request: ureq::RequestBuilder<B>,
456    headers: &[(&str, &str)],
457) -> ureq::RequestBuilder<B> {
458    for (name, value) in headers {
459        request = request.header(*name, *value);
460    }
461    request
462}
463
464fn offline(error: &ureq::Error) -> CloudError {
465    let kind = match error {
466        ureq::Error::Timeout(_) => "timeout".to_string(),
467        ureq::Error::HostNotFound => "host not found".to_string(),
468        ureq::Error::ConnectionFailed => "connection failed".to_string(),
469        ureq::Error::Io(e) => format!("i/o: {}", e.kind()),
470        ureq::Error::Tls(_) | ureq::Error::Rustls(_) => "tls".to_string(),
471        ureq::Error::TooManyRedirects | ureq::Error::RedirectFailed => {
472            return CloudError::Protocol("The Cloud answered with a redirect".into());
473        }
474        other => other.to_string().chars().take(120).collect(),
475    };
476    CloudError::Offline(kind)
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482
483    #[test]
484    fn clients_refuse_plain_http_to_remote_hosts() {
485        assert!(CloudClient::new("http://cloud.example.com").is_err());
486        assert!(CloudClient::new("https://cloud.example.com").is_ok());
487        assert!(CloudClient::new("http://127.0.0.1:9").is_ok());
488    }
489
490    #[test]
491    fn only_a_2x_answer_is_accepted_and_a_refusal_names_the_protocol() {
492        assert!(incompatible("2.0").is_none());
493        assert!(incompatible("2.7").is_none());
494        for peer in ["1.9", "1.8", "1.0", "3.0", "", "two"] {
495            let Some(CloudError::Protocol(message)) = incompatible(peer) else {
496                panic!("{peer:?} must be refused");
497            };
498            assert!(message.contains("Cloud-Protocol 2.x"), "{message}");
499        }
500    }
501
502    /// A Cloud on 127.0.0.1 that answers one request with `raw`.
503    fn answering(raw: String) -> String {
504        use std::io::{BufRead as _, Read as _, Write as _};
505        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
506        let origin = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
507        std::thread::spawn(move || {
508            let Some(Ok(stream)) = listener.incoming().next() else {
509                return;
510            };
511            let mut writer = stream.try_clone().unwrap();
512            let mut reader = std::io::BufReader::new(stream);
513            let mut length = 0usize;
514            loop {
515                let mut line = String::new();
516                if reader.read_line(&mut line).unwrap_or(0) == 0 {
517                    return;
518                }
519                let line = line.trim_end();
520                if line.is_empty() {
521                    break;
522                }
523                if let Some((name, value)) = line.split_once(':')
524                    && name.eq_ignore_ascii_case("content-length")
525                {
526                    length = value.trim().parse().unwrap_or(0);
527                }
528            }
529            let mut body = vec![0; length];
530            let _ = reader.read_exact(&mut body);
531            let _ = writer.write_all(raw.as_bytes());
532        });
533        origin
534    }
535
536    fn edge(status: u16, headers: &str, body: &str) -> String {
537        format!(
538            "HTTP/1.1 {status} X\r\nContent-Type: text/html\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
539            body.len()
540        )
541    }
542
543    /// Review fix: an edge's HTML error (no or a garbled protocol header) is
544    /// classified by status, a bare `Retry-After` is honoured.
545    #[test]
546    fn edge_errors_are_classified_by_status_not_by_protocol_header() {
547        let page = "<html><body>busy</body></html>";
548        let garbled = format!("{HEADER_PROTOCOL}: nginx\r\n");
549        let origin = answering(edge(429, &format!("{garbled}Retry-After: 42\r\n"), page));
550        let limited = CloudClient::new(&origin).unwrap().post("/x", &Value::Null);
551        assert_eq!(
552            limited,
553            Err(CloudError::RateLimited {
554                retry_after: Some(42)
555            })
556        );
557        for status in [502, 503, 504] {
558            let origin = answering(edge(status, &garbled, page));
559            let down = CloudClient::new(&origin).unwrap().get("/keys").unwrap_err();
560            assert!(
561                matches!(down, CloudError::Server { status: s, .. } if s == status),
562                "{status}: {down:?}"
563            );
564            assert!(down.is_transient());
565        }
566        let origin = answering(edge(413, "", page));
567        let too_large = CloudClient::new(&origin).unwrap().post("/x", &Value::Null);
568        assert_eq!(
569            too_large,
570            Err(CloudError::Server {
571                status: 413,
572                code: "payload_too_large".into()
573            })
574        );
575        // A 2xx with a garbled header is still refused.
576        let origin = answering(format!(
577            "HTTP/1.1 200 OK\r\n{garbled}Content-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}"
578        ));
579        assert!(matches!(
580            CloudClient::new(&origin).unwrap().get("/keys"),
581            Err(CloudError::Protocol(_))
582        ));
583    }
584
585    #[test]
586    fn a_bare_retry_after_header_becomes_the_error_body() {
587        let mut body = Value::Null;
588        honour_retry_after(429, Some("17"), &mut body);
589        assert_eq!(body, serde_json::json!({"error": {"retry_after_s": 17}}));
590        let mut other = serde_json::json!({"detail": "x"});
591        honour_retry_after(503, Some("3"), &mut other);
592        assert_eq!(
593            other,
594            serde_json::json!({"detail": "x", "error": {"retry_after_s": 3}})
595        );
596    }
597
598    #[test]
599    fn unreachable_cloud_is_offline() {
600        let client = CloudClient::new("http://127.0.0.1:9").unwrap();
601        assert!(matches!(client.get("/keys"), Err(CloudError::Offline(_))));
602    }
603}