Skip to main content

lean_ctx_protocol/cloud/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! LeanCTX | Cloud engine↔service wire contract, protocol major 1.
4//!
5//! The engine connector and the Cloud service build against these types and
6//! the golden fixtures in `tests/fixtures/cloud/`. A contract change is a
7//! fixture change that both sides review.
8//!
9//! Conventions shared by every module:
10//! - Base URL `https://cloud.leanctx.com/v1`; a self-hosted Cloud may use any
11//!   `https` URL (loopback may use `http`).
12//! - Every HTTP body carries `schema` (`leanctx.cloud.<area>/v1`). The one
13//!   exception is the error body `{"error":{...}}`, which proxies may also emit.
14//! - Request types refuse unknown fields (the service rejects them with
15//!   `invalid_request`); response types accept unknown fields, so the service
16//!   can add fields in a minor version without breaking older engines.
17//! - Timestamps are `YYYY-MM-DDTHH:MM:SSZ` ([`UtcTimestamp`](crate::UtcTimestamp)); unix seconds
18//!   appear only where a value is signed as text (`iat`).
19//! - Keys, nonces, signatures and ciphertext are standard base64 with padding.
20//! - `vault_id` is 32 lowercase hex characters: the engine API renders the
21//!   vault UUID in simple form (no dashes) while the web API keeps hyphenated
22//!   UUIDs.
23//! - Signatures are Ed25519 over `domain || canonical_json(value)`, see
24//!   [`canonical_json`]. Signed objects are verified over the raw JSON that
25//!   was received, never over a re-serialized typed value, so additive fields
26//!   stay covered by the signature.
27
28pub mod anchor;
29pub mod app_keys;
30pub mod bus;
31pub mod codegraph;
32pub mod ctxpkg;
33pub mod effective_policy;
34pub mod enroll;
35pub mod error;
36pub mod facts;
37pub mod gate;
38pub mod graph;
39pub mod knowledge;
40pub mod lease;
41pub mod managed;
42pub mod metrics_v2;
43pub mod model_catalog;
44pub mod optin;
45pub mod policy;
46pub mod profiles;
47pub mod receipts_v2;
48pub mod root_cert;
49pub mod status;
50pub mod task_evidence;
51pub mod tasks;
52pub mod telemetry;
53pub mod usage;
54pub mod vault;
55
56pub use error::{CloudErrorBody, CloudErrorCode, CloudErrorDetailV1, CloudUploadKind};
57
58use crate::ValidationError;
59use serde_json::Value;
60use std::collections::BTreeMap;
61
62/// Major protocol version; a different major is incompatible.
63pub const CLOUD_PROTOCOL_MAJOR: u16 = 1;
64/// Minor protocol version; minors only add optional response fields or routes.
65pub const CLOUD_PROTOCOL_MINOR: u16 = 9;
66
67/// Hosted LeanCTX Cloud origin (owner decision 15.11.2026).
68pub const CLOUD_DEFAULT_URL: &str = "https://cloud.leanctx.com";
69/// Hosts of the hosted service.
70pub const HOSTED_HOSTS: &[&str] = &["cloud.leanctx.com"];
71
72/// `origin` lowercased without trailing slashes or surrounding whitespace.
73fn origin_key(origin: &str) -> String {
74    origin.trim().trim_end_matches('/').to_ascii_lowercase()
75}
76
77/// True when `origin` is the hosted service.
78pub fn is_hosted_origin(origin: &str) -> bool {
79    origin_key(origin) == CLOUD_DEFAULT_URL
80}
81
82/// True when `a` and `b` name the same Cloud: equal origins, or both the
83/// hosted service.
84pub fn same_cloud_origin(a: &str, b: &str) -> bool {
85    origin_key(a) == origin_key(b) || (is_hosted_origin(a) && is_hosted_origin(b))
86}
87/// Path prefix of every engine-facing route.
88pub const CLOUD_API_PREFIX: &str = "/v1";
89/// The schema of a `GET /v1/capabilities` answer (C0 `capabilities.response.json`);
90/// an answer of another schema announces no feature.
91pub const CAPABILITIES_SCHEMA: &str = "leanctx.cloud.capabilities/v1";
92/// OAuth-style client id the engine sends in the device flow.
93pub const CLOUD_ENGINE_CLIENT_ID: &str = "lean-ctx-engine";
94
95/// `major.minor` the sender speaks; sent on every request and response.
96pub const HEADER_PROTOCOL: &str = "Cloud-Protocol";
97/// Instance id on authenticated requests.
98pub const HEADER_INSTANCE: &str = "Cloud-Instance";
99/// Lowest engine version the service accepts; sent with `426`.
100pub const HEADER_MIN_ENGINE: &str = "Cloud-Min-Instance";
101/// Client-chosen ULID on every `POST`; replays return the first response.
102pub const HEADER_IDEMPOTENCY_KEY: &str = "Idempotency-Key";
103/// 1.9 VA (until the 3.12 release day): an engine that speaks the vault
104/// names sends [`NAMES_VAULT`] here on every request, the bus WebSocket
105/// upgrade included. Cloud then answers in the vault form (`vault_id`,
106/// `vault:` channels); without it, in the earlier project form. Cloud takes
107/// both forms as input. From the release day only the vault form remains
108/// and the header is ignored.
109pub const HEADER_NAMES: &str = "Cloud-Names";
110/// The [`HEADER_NAMES`] value of the vault form.
111pub const NAMES_VAULT: &str = "vault";
112
113/// Domain of the lease signature (Cloud signing key).
114pub const LEASE_SIGNATURE_DOMAIN: &str = "leanctx.cloud.lease.v1\n";
115/// Domain of the key-set signature (Cloud root key).
116pub const KEYSET_SIGNATURE_DOMAIN: &str = "leanctx.cloud.keyset.v1\n";
117/// Domain of the instance token assertion (instance key).
118pub const TOKEN_ASSERTION_DOMAIN: &str = "leanctx.cloud.token.v1\n";
119/// Domain of a filter-pack statement signature (Cloud signing key).
120pub const FILTER_PACK_SIGNATURE_DOMAIN: &str = "leanctx.filter-pack.v1\n";
121/// Domain of the stable repository identity digest input. The bytes keep
122/// their 1.0 name: a different domain would change every digest and unbind
123/// every linked vault.
124pub const REPO_IDENTITY_DOMAIN: &str = "leanctx.project-identity.v1\n";
125
126/// Largest request or response body either side accepts, except knowledge
127/// documents ([`knowledge::MAX_KNOWLEDGE_BODY_BYTES`]).
128pub const MAX_BODY_BYTES: usize = 1 << 20;
129
130/// `Cloud-Protocol` value this crate speaks.
131pub fn protocol_header_value() -> String {
132    format!("{CLOUD_PROTOCOL_MAJOR}.{CLOUD_PROTOCOL_MINOR}")
133}
134
135/// Parse an `Cloud-Protocol` header into `(major, minor)`.
136pub fn parse_protocol_header(value: &str) -> Option<(u16, u16)> {
137    let (major, minor) = value.trim().split_once('.')?;
138    let digits = |part: &str| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit());
139    if !digits(major) || !digits(minor) {
140        return None;
141    }
142    Some((major.parse().ok()?, minor.parse().ok()?))
143}
144
145/// Whether a peer's `Cloud-Protocol` header is compatible with this crate.
146pub fn protocol_compatible(value: &str) -> bool {
147    parse_protocol_header(value).is_some_and(|(major, _)| major == CLOUD_PROTOCOL_MAJOR)
148}
149
150/// Canonical JSON encoding used under every Cloud signature.
151///
152/// UTF-8, no insignificant whitespace, object keys sorted by their UTF-8
153/// bytes at every depth, strings escaped as `serde_json` does (only `"`, `\`
154/// and control characters are escaped; `\b \f \n \r \t` use the short form,
155/// other control characters `\u00xx` with lowercase hex; non-ASCII stays raw
156/// UTF-8), integers in plain decimal. Non-integer numbers are refused so that
157/// two implementations cannot disagree on float formatting.
158pub fn canonical_json(value: &Value) -> Result<Vec<u8>, ValidationError> {
159    let sorted = canonical_value(value)?;
160    serde_json::to_vec(&sorted)
161        .map_err(|error| ValidationError::new(format!("encode canonical JSON: {error}")))
162}
163
164fn canonical_value(value: &Value) -> Result<Value, ValidationError> {
165    Ok(match value {
166        Value::Object(fields) => {
167            let sorted = fields
168                .iter()
169                .map(|(key, value)| Ok((key.clone(), canonical_value(value)?)))
170                .collect::<Result<BTreeMap<_, _>, ValidationError>>()?;
171            Value::Object(sorted.into_iter().collect())
172        }
173        Value::Array(values) => Value::Array(
174            values
175                .iter()
176                .map(canonical_value)
177                .collect::<Result<_, _>>()?,
178        ),
179        Value::Number(number) if !(number.is_i64() || number.is_u64()) => {
180            return Err(ValidationError::new("canonical JSON carries integers only"));
181        }
182        scalar => scalar.clone(),
183    })
184}
185
186/// `domain || canonical_json(value)`: the exact bytes an Ed25519 key signs.
187pub fn signing_input(domain: &str, value: &Value) -> Result<Vec<u8>, ValidationError> {
188    let mut bytes = domain.as_bytes().to_vec();
189    bytes.extend(canonical_json(value)?);
190    Ok(bytes)
191}
192
193/// Signing input of an object that carries its own `signature` field: the
194/// canonical form of the object without that field.
195pub fn signing_input_without_signature(
196    domain: &str,
197    value: &Value,
198) -> Result<Vec<u8>, ValidationError> {
199    let Value::Object(fields) = value else {
200        return Err(ValidationError::new("signed value must be a JSON object"));
201    };
202    let mut fields = fields.clone();
203    fields.remove("signature");
204    signing_input(domain, &Value::Object(fields))
205}
206
207pub(crate) fn require_schema(actual: &str, expected: &str) -> Result<(), ValidationError> {
208    if actual == expected {
209        Ok(())
210    } else {
211        Err(ValidationError::new(format!(
212            "schema must be {expected}, got {actual:?}"
213        )))
214    }
215}
216
217/// Validate standard padded base64 that decodes to exactly `decoded_len` bytes.
218pub(crate) fn validate_b64_len(
219    value: &str,
220    decoded_len: usize,
221    field: &str,
222) -> Result<(), ValidationError> {
223    let encoded_len = decoded_len.div_ceil(3) * 4;
224    let padding = (3 - decoded_len % 3) % 3;
225    if value.len() == encoded_len && b64_shape_ok(value, padding) {
226        Ok(())
227    } else {
228        Err(ValidationError::new(format!(
229            "{field} must be base64 of exactly {decoded_len} bytes"
230        )))
231    }
232}
233
234/// Validate standard padded base64 of any length up to `max_encoded` chars.
235pub(crate) fn validate_b64_bounded(
236    value: &str,
237    max_encoded: usize,
238    field: &str,
239) -> Result<(), ValidationError> {
240    let padding = value.bytes().rev().take_while(|byte| *byte == b'=').count();
241    if !value.is_empty()
242        && value.len() <= max_encoded
243        && value.len().is_multiple_of(4)
244        && padding <= 2
245        && b64_shape_ok(value, padding)
246    {
247        Ok(())
248    } else {
249        Err(ValidationError::new(format!(
250            "{field} must be non-empty padded base64 of at most {max_encoded} characters"
251        )))
252    }
253}
254
255fn b64_shape_ok(value: &str, padding: usize) -> bool {
256    let (body, pad) = value.split_at(value.len() - padding);
257    pad.bytes().all(|byte| byte == b'=')
258        && body
259            .bytes()
260            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/'))
261}
262
263/// 1.9 R3-3e-1: characters that make a text read differently from what it
264/// is, or hide text a person reviewing it cannot see: bidi marks,
265/// embeddings, overrides and isolates, zero-width space, the invisible
266/// operators, a byte-order mark, tag characters and the variation selector
267/// supplement; and (1.9 erratum) the soft hyphen, the Mongolian vowel
268/// separator, the combining grapheme joiner, the Hangul fillers, the Khmer
269/// inherent vowels and the line and paragraph separators (not controls, so
270/// they would break a one-line text), the whole block U+2060–U+206F (with
271/// the deprecated format controls), the interlinear annotation characters
272/// (they hide annotation text) and the invisible format controls of
273/// Egyptian hieroglyphs, shorthand and musical notation. Every text field
274/// refuses them; engines strip them from foreign content. The joiners
275/// U+200C/U+200D and U+FE00–FE0F stay: emoji and Persian need them; the
276/// visible Arabic and Syriac signs (U+0600–0605, U+06DD, U+070F, U+08E2) too.
277#[must_use]
278pub fn invisible(c: char) -> bool {
279    matches!(
280        c,
281        '\u{00AD}'
282            | '\u{034F}'
283            | '\u{061C}'
284            | '\u{115F}'
285            | '\u{1160}'
286            | '\u{17B4}'
287            | '\u{17B5}'
288            | '\u{180E}'
289            | '\u{200B}'
290            | '\u{200E}'
291            | '\u{200F}'
292            | '\u{2028}'
293            | '\u{2029}'
294            | '\u{202A}'..='\u{202E}'
295            | '\u{2060}'..='\u{206F}'
296            | '\u{3164}'
297            | '\u{FEFF}'
298            | '\u{FFA0}'
299            | '\u{FFF9}'..='\u{FFFB}'
300            | '\u{13430}'..='\u{1343F}'
301            | '\u{1BCA0}'..='\u{1BCA3}'
302            | '\u{1D173}'..='\u{1D17A}'
303            | '\u{E0000}'..='\u{E007F}'
304            | '\u{E0100}'..='\u{E01EF}'
305    )
306}
307
308/// Validate a bounded, printable text field (`max` in characters).
309pub(crate) fn validate_text(
310    value: &str,
311    max: usize,
312    field: &str,
313    allow_newlines: bool,
314) -> Result<(), ValidationError> {
315    let count = value.chars().count();
316    if count == 0 || count > max || value.trim().is_empty() {
317        return Err(ValidationError::new(format!(
318            "{field} must be non-empty text of at most {max} characters"
319        )));
320    }
321    if value
322        .chars()
323        .any(|ch| ch.is_control() && !(allow_newlines && matches!(ch, '\n' | '\t' | '\r')))
324    {
325        return Err(ValidationError::new(format!(
326            "{field} contains control characters"
327        )));
328    }
329    if value.chars().any(invisible) {
330        return Err(ValidationError::new(format!(
331            "{field} contains invisible or direction characters"
332        )));
333    }
334    Ok(())
335}
336
337/// Validate a server- or client-assigned opaque id: 1–128 chars of
338/// `[A-Za-z0-9._:-]`, starting alphanumeric.
339pub(crate) fn validate_id(value: &str, field: &str) -> Result<(), ValidationError> {
340    let bytes = value.as_bytes();
341    if !bytes.is_empty()
342        && bytes.len() <= 128
343        && bytes[0].is_ascii_alphanumeric()
344        && bytes
345            .iter()
346            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-'))
347    {
348        Ok(())
349    } else {
350        Err(ValidationError::new(format!(
351            "{field} must be 1-128 characters of [A-Za-z0-9._:-] starting alphanumeric"
352        )))
353    }
354}
355
356/// Validate a Cloud `vault_id`: 32 lowercase hex characters (128 random
357/// bits), the same form `leanctx.cloud-metrics/v1` requires of `vault.id`.
358/// The engine API renders the vault UUID in simple form (no dashes) while the
359/// web API keeps hyphenated UUIDs.
360pub fn validate_vault_id(value: &str) -> Result<(), ValidationError> {
361    if value.len() == 32
362        && value
363            .bytes()
364            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
365    {
366        Ok(())
367    } else {
368        Err(ValidationError::new(
369            "vault_id must be 32 lowercase hexadecimal characters",
370        ))
371    }
372}
373
374/// Validate an origin: `https://host[:port]`, or `http://` for
375/// localhost/127.0.0.1/`[::1]`; no path, query, credentials or trailing slash.
376pub fn validate_origin(value: &str, field: &str) -> Result<(), ValidationError> {
377    let refuse = || {
378        ValidationError::new(format!(
379            "{field} must be an https origin (http only on loopback)"
380        ))
381    };
382    let (scheme, rest) = value.split_once("://").ok_or_else(refuse)?;
383    if rest.is_empty()
384        || value.len() > 256
385        || rest.contains(['/', '?', '#', '@'])
386        || rest.chars().any(char::is_whitespace)
387    {
388        return Err(refuse());
389    }
390    let host = rest
391        .rsplit_once(':')
392        .filter(|(_, port)| port.bytes().all(|b| b.is_ascii_digit()))
393        .map_or(rest, |(host, _)| host);
394    match scheme {
395        "https" => Ok(()),
396        "http" if matches!(host, "localhost" | "127.0.0.1" | "[::1]") => Ok(()),
397        _ => Err(refuse()),
398    }
399}
400
401/// Validate a lowercase hexadecimal SHA-256 digest without prefix.
402pub(crate) fn validate_hex64(value: &str, field: &str) -> Result<(), ValidationError> {
403    if value.len() == 64
404        && value
405            .bytes()
406            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
407    {
408        Ok(())
409    } else {
410        Err(ValidationError::new(format!(
411            "{field} must be 64 lowercase hexadecimal characters"
412        )))
413    }
414}
415
416pub(crate) fn parse_time(
417    value: &crate::UtcTimestamp,
418) -> Result<lean_ctx_time::OffsetDateTime, ValidationError> {
419    lean_ctx_time::OffsetDateTime::parse_from_rfc3339(value.as_str())
420        .map_err(|_| ValidationError::new(format!("invalid timestamp {:?}", value.as_str())))
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426    use serde_json::json;
427
428    #[test]
429    fn text_refuses_what_a_reviewer_cannot_see() {
430        // Tag characters spell "hi" invisibly after a harmless word.
431        assert!(validate_text("fine\u{E0068}\u{E0069}", 100, "t", false).is_err());
432        assert!(validate_text("a\u{E0100}", 100, "t", false).is_err());
433        assert!(validate_text("safe \u{202E}cod.exe", 100, "t", false).is_err());
434        assert!(validate_text("a\u{200B}b", 100, "t", true).is_err());
435        // Emoji sequences and Persian joiners stay.
436        assert!(
437            validate_text(
438                "dev \u{1F469}\u{200D}\u{1F4BB} \u{2764}\u{FE0F}",
439                100,
440                "t",
441                false
442            )
443            .is_ok()
444        );
445        assert!(
446            validate_text(
447                "\u{0645}\u{06CC}\u{200C}\u{062E}\u{0648}\u{0627}\u{0647}\u{0645}",
448                100,
449                "t",
450                false
451            )
452            .is_ok()
453        );
454    }
455
456    /// 1.9 erratum: every character of the set, one by one, in a one-line
457    /// and a multi-line text and in an anchor path; the joiners stay in
458    /// text only.
459    #[test]
460    fn every_invisible_character_is_refused() {
461        let set = [
462            '\u{00AD}',
463            '\u{034F}',
464            '\u{061C}',
465            '\u{115F}',
466            '\u{1160}',
467            '\u{17B4}',
468            '\u{17B5}',
469            '\u{180E}',
470            '\u{200B}',
471            '\u{200E}',
472            '\u{200F}',
473            '\u{2028}',
474            '\u{2029}',
475            '\u{202A}',
476            '\u{202E}',
477            '\u{2060}',
478            '\u{2064}',
479            '\u{2066}',
480            '\u{2069}',
481            '\u{3164}',
482            '\u{FEFF}',
483            '\u{FFA0}',
484            '\u{E0000}',
485            '\u{E0041}',
486            '\u{E007F}',
487            '\u{E0100}',
488            '\u{E01EF}',
489            '\u{2065}',
490            '\u{206A}',
491            '\u{206F}',
492            '\u{FFF9}',
493            '\u{FFFB}',
494            '\u{13430}',
495            '\u{1343F}',
496            '\u{1BCA0}',
497            '\u{1BCA3}',
498            '\u{1D173}',
499            '\u{1D17A}',
500        ];
501        for c in set {
502            let text = format!("a{c}b");
503            assert!(invisible(c), "{c:?}");
504            assert!(validate_text(&text, 100, "t", false).is_err(), "{c:?}");
505            assert!(validate_text(&text, 100, "t", true).is_err(), "{c:?}");
506            assert!(
507                anchor::validate_anchor_path(&format!("src/{text}.rs")).is_err(),
508                "{c:?}"
509            );
510        }
511        // The joiners, emoji selectors and visible Arabic and Syriac signs stay.
512        for c in [
513            '\u{200C}', '\u{200D}', '\u{FE0F}', '\u{0600}', '\u{06DD}', '\u{070F}', '\u{08E2}',
514            'a', ' ', 'ü',
515        ] {
516            assert!(!invisible(c), "{c:?}");
517        }
518        assert!(anchor::validate_anchor_path("src/a\u{200D}b.rs").is_err());
519    }
520
521    #[test]
522    fn canonical_json_sorts_keys_at_every_depth() {
523        let value = json!({"b": 1, "a": {"z": [ {"y": 2, "x": 1} ], "c": "ü\n"}});
524        assert_eq!(
525            String::from_utf8(canonical_json(&value).unwrap()).unwrap(),
526            r#"{"a":{"c":"ü\n","z":[{"x":1,"y":2}]},"b":1}"#
527        );
528    }
529
530    #[test]
531    fn canonical_json_refuses_floats() {
532        assert!(canonical_json(&json!({"a": 1.5})).is_err());
533        assert!(canonical_json(&json!({"a": -3})).is_ok());
534    }
535
536    #[test]
537    fn signing_input_without_signature_drops_only_the_top_level_field() {
538        let value = json!({"signature": "x", "keys": [{"signature": "kept"}]});
539        let input = signing_input_without_signature("d\n", &value).unwrap();
540        assert_eq!(input, b"d\n{\"keys\":[{\"signature\":\"kept\"}]}".to_vec());
541    }
542
543    #[test]
544    fn protocol_header_parses_and_checks_major() {
545        assert_eq!(parse_protocol_header("1.8"), Some((1, 8)));
546        assert!(protocol_compatible("1.0"));
547        assert!(!protocol_compatible("2.0"));
548        assert!(!protocol_compatible("1"));
549        assert!(!protocol_compatible("1.x"));
550        assert_eq!(protocol_header_value(), "1.9");
551    }
552
553    #[test]
554    fn base64_validation_checks_length_and_padding() {
555        assert!(validate_b64_len(&"A".repeat(44), 32, "k").is_err());
556        assert!(validate_b64_len(&format!("{}=", "A".repeat(43)), 32, "k").is_ok());
557        assert!(validate_b64_len(&format!("{}==", "A".repeat(86)), 64, "s").is_ok());
558        assert!(validate_b64_len(&format!("{}=", "-".repeat(43)), 32, "k").is_err());
559        assert!(validate_b64_bounded("AAAA", 8, "c").is_ok());
560        assert!(validate_b64_bounded("AAA", 8, "c").is_err());
561    }
562
563    #[test]
564    fn the_hosted_origin_is_recognized() {
565        assert_eq!(CLOUD_DEFAULT_URL, "https://cloud.leanctx.com");
566        assert!(is_hosted_origin(CLOUD_DEFAULT_URL));
567        assert!(is_hosted_origin("https://cloud.leanctx.com"));
568        assert!(is_hosted_origin("https://Cloud.LeanCTX.com/"));
569        assert!(!is_hosted_origin("https://cloud.acme.example"));
570        assert!(!is_hosted_origin("http://cloud.leanctx.com"));
571        assert!(same_cloud_origin(
572            "https://cloud.leanctx.com",
573            "https://cloud.leanctx.com/"
574        ));
575        assert!(same_cloud_origin(
576            "https://cloud.acme.example:8443/",
577            "https://cloud.acme.example:8443"
578        ));
579        assert!(!same_cloud_origin(
580            "https://cloud.leanctx.com",
581            "https://cloud.acme.example"
582        ));
583    }
584}