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