1pub 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
61pub const CLOUD_PROTOCOL_MAJOR: u16 = 1;
63pub const CLOUD_PROTOCOL_MINOR: u16 = 9;
65
66pub const CLOUD_DEFAULT_URL: &str = "https://cloud.leanctx.com";
68pub const HOSTED_HOSTS: &[&str] = &["cloud.leanctx.com"];
70
71fn origin_key(origin: &str) -> String {
73 origin.trim().trim_end_matches('/').to_ascii_lowercase()
74}
75
76pub fn is_hosted_origin(origin: &str) -> bool {
78 origin_key(origin) == CLOUD_DEFAULT_URL
79}
80
81pub 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}
86pub const CLOUD_API_PREFIX: &str = "/v1";
88pub const CLOUD_ENGINE_CLIENT_ID: &str = "lean-ctx-engine";
90
91pub const HEADER_PROTOCOL: &str = "Cloud-Protocol";
93pub const HEADER_INSTANCE: &str = "Cloud-Instance";
95pub const HEADER_MIN_ENGINE: &str = "Cloud-Min-Instance";
97pub const HEADER_IDEMPOTENCY_KEY: &str = "Idempotency-Key";
99pub const HEADER_NAMES: &str = "Cloud-Names";
106pub const NAMES_VAULT: &str = "vault";
108
109pub const LEASE_SIGNATURE_DOMAIN: &str = "leanctx.cloud.lease.v1\n";
111pub const KEYSET_SIGNATURE_DOMAIN: &str = "leanctx.cloud.keyset.v1\n";
113pub const TOKEN_ASSERTION_DOMAIN: &str = "leanctx.cloud.token.v1\n";
115pub const FILTER_PACK_SIGNATURE_DOMAIN: &str = "leanctx.filter-pack.v1\n";
117pub const REPO_IDENTITY_DOMAIN: &str = "leanctx.project-identity.v1\n";
121
122pub const MAX_BODY_BYTES: usize = 1 << 20;
125
126pub fn protocol_header_value() -> String {
128 format!("{CLOUD_PROTOCOL_MAJOR}.{CLOUD_PROTOCOL_MINOR}")
129}
130
131pub 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
141pub fn protocol_compatible(value: &str) -> bool {
143 parse_protocol_header(value).is_some_and(|(major, _)| major == CLOUD_PROTOCOL_MAJOR)
144}
145
146pub 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
182pub 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
189pub 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
213pub(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
230pub(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#[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
304pub(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
333pub(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
352pub 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
370pub 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
397pub(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 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 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 #[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 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}