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