Skip to main content

lean_ctx/core/context_package/
verify.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Standalone package verification (spec §8 integrity, §9 signing).
4//!
5//! `lean-ctx pack verify` and the import path share these primitives. All
6//! hashing operates on the *document text* of the content member — never on
7//! re-serialized parsed values, which would be lossy across languages
8//! (a writer's `1.0` re-serializes as `1` in JavaScript and breaks the hash).
9
10use sha2::{Digest, Sha256};
11use std::path::Path;
12
13use super::content::{
14    MAX_CHECKPOINT_ENTRIES, MAX_CHECKPOINT_PACKAGE_PINS, MAX_CHECKPOINT_REFS,
15    MAX_CHECKPOINT_SOURCES, PackageContent,
16};
17use super::manifest::{PackageKind, PackageLayer, PackageManifest};
18
19mod addon;
20mod checkpoint;
21mod text;
22use checkpoint::validate_checkpoint_content;
23pub(crate) use text::compact_json_text;
24
25/// Extract the exact text of one top-level member's value from a JSON object
26/// document, so integrity hashing sees the writer's bytes (spec §8).
27pub(crate) fn extract_top_level_value_text<'a>(doc: &'a str, member: &str) -> Option<&'a str> {
28    crate::core::context_package::integrity::member_text(doc, member)
29}
30
31/// Kind ↔ payload coherence (GH #724/#726): the declared `kind` must match
32/// the content payload it ships, so a mislabeled package can never route
33/// into the wrong trust chain (an "addon" without an addon manifest, or a
34/// context pack smuggling one in).
35pub(crate) fn validate_kind_coherence(
36    manifest: &PackageManifest,
37    content: &PackageContent,
38) -> Result<(), Vec<String>> {
39    let mut errors = Vec::new();
40    match manifest.kind {
41        PackageKind::Addon => {
42            match &content.addon {
43                None => errors.push("kind=addon requires a content.addon payload".into()),
44                Some(addon) => addon::validate_addon(addon, &mut errors),
45            }
46            if content.documents.is_some() {
47                errors.push("content.documents payload requires kind=skills".into());
48            }
49        }
50        PackageKind::Skills => {
51            if content.addon.is_some() {
52                errors.push("content.addon payload requires kind=addon".into());
53            }
54            match &content.documents {
55                None => errors.push("kind=skills requires a content.documents payload".into()),
56                Some(docs) => validate_documents(docs, &mut errors),
57            }
58        }
59        PackageKind::Context | PackageKind::Grammar => {
60            if content.addon.is_some() {
61                errors.push(format!(
62                    "content.addon payload requires kind=addon (manifest declares kind={})",
63                    manifest.kind.as_str()
64                ));
65            }
66            if content.documents.is_some() {
67                errors.push(format!(
68                    "content.documents payload requires kind=skills (manifest declares kind={})",
69                    manifest.kind.as_str()
70                ));
71            }
72        }
73    }
74    let has_checkpoint_layer = manifest.has_layer(PackageLayer::Checkpoint);
75    if has_checkpoint_layer != content.checkpoint.is_some() {
76        errors.push(
77            "manifest checkpoint layer and content.checkpoint must be present together".into(),
78        );
79    }
80    if let Some(checkpoint) = &content.checkpoint {
81        if manifest.schema_version != crate::core::contracts::CONTEXT_PACKAGE_V2_SCHEMA_VERSION
82            || manifest.kind != PackageKind::Context
83        {
84            errors.push("checkpoint content requires schema_version 2 and kind=context".into());
85        }
86        validate_checkpoint_content(checkpoint, &mut errors);
87    }
88    if errors.is_empty() {
89        Ok(())
90    } else {
91        Err(errors)
92    }
93}
94
95fn validate_checkpoint_object(value: &serde_json::Value, errors: &mut Vec<String>) {
96    const KEYS: &[&str] = &[
97        "schema_version",
98        "checkpoint_id",
99        "workspace_id",
100        "state_digest",
101        "state_schema_version",
102        "workspace_state_ref",
103        "logical_state",
104        "source_anchors",
105        "recovery_refs",
106        "package_pins",
107        "package_lock_digest",
108        "policy_digest",
109        "project_context_digest",
110        "lineage",
111        "engine_identity",
112        "sdk_contract",
113        "envelope_digest",
114    ];
115    let Some(object) = value.as_object() else {
116        errors.push("checkpoint envelope must be an object".into());
117        return;
118    };
119    validate_exact_keys(object, KEYS, "checkpoint", errors);
120    if object
121        .get("schema_version")
122        .and_then(serde_json::Value::as_str)
123        != Some("leanctx.context-checkpoint/v2")
124        || object
125            .get("state_schema_version")
126            .and_then(serde_json::Value::as_str)
127            != Some("leanctx.workspace.state/v1")
128        || object
129            .get("sdk_contract")
130            .and_then(serde_json::Value::as_str)
131            != Some("leanctx-product-sdk-research/p6")
132    {
133        errors.push("checkpoint contract identity is unsupported".into());
134    }
135    for name in ["checkpoint_id", "workspace_id"] {
136        let valid = object
137            .get(name)
138            .and_then(serde_json::Value::as_str)
139            .and_then(|raw| uuid::Uuid::parse_str(raw).ok().map(|parsed| (raw, parsed)))
140            .is_some_and(|(raw, parsed)| parsed.hyphenated().to_string() == raw);
141        if !valid {
142            errors.push(format!("checkpoint.{name} must be a canonical UUID"));
143        }
144    }
145    for name in [
146        "state_digest",
147        "policy_digest",
148        "project_context_digest",
149        "envelope_digest",
150    ] {
151        if !object.get(name).is_some_and(valid_prefixed_digest) {
152            errors.push(format!("checkpoint.{name} must be a sha256 digest"));
153        }
154    }
155    if !object.get("workspace_state_ref").is_some_and(|item| {
156        item.as_str().is_some_and(|raw| {
157            raw.starts_with("event:sha256:")
158                && raw.len() == 77
159                && raw[13..]
160                    .bytes()
161                    .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
162        })
163    }) {
164        errors.push("checkpoint.workspace_state_ref must bind an event digest".into());
165    }
166    if !object
167        .get("package_lock_digest")
168        .is_some_and(|item| item.is_null() || valid_prefixed_digest(item))
169    {
170        errors.push("checkpoint.package_lock_digest is invalid".into());
171    }
172
173    let arrays = [
174        ("source_anchors", MAX_CHECKPOINT_SOURCES),
175        ("recovery_refs", MAX_CHECKPOINT_REFS),
176        ("package_pins", MAX_CHECKPOINT_PACKAGE_PINS),
177    ];
178    for (name, cap) in arrays {
179        if object
180            .get(name)
181            .and_then(serde_json::Value::as_array)
182            .is_none_or(|items| items.len() > cap)
183        {
184            errors.push(format!("checkpoint.{name} is missing or exceeds cap {cap}"));
185        }
186    }
187    let Some(logical) = object
188        .get("logical_state")
189        .and_then(serde_json::Value::as_object)
190    else {
191        errors.push("checkpoint.logical_state must be an object".into());
192        return;
193    };
194    const LOGICAL_KEYS: &[&str] = &[
195        "schema_version",
196        "workspace_id",
197        "policy",
198        "sources",
199        "entries",
200        "package_pins",
201        "package_lock_digest",
202    ];
203    validate_exact_keys(logical, LOGICAL_KEYS, "checkpoint.logical_state", errors);
204    if logical
205        .get("schema_version")
206        .and_then(serde_json::Value::as_str)
207        != Some("leanctx.workspace.state/v1")
208    {
209        errors.push("checkpoint logical-state schema is unsupported".into());
210    }
211    validate_workspace_policy(logical.get("policy"), errors);
212    validate_lineage(object.get("lineage"), object.get("workspace_id"), errors);
213    validate_engine_identity(object.get("engine_identity"), errors);
214    if logical.get("workspace_id") != object.get("workspace_id")
215        || logical.get("sources") != object.get("source_anchors")
216        || logical.get("package_pins") != object.get("package_pins")
217        || logical.get("package_lock_digest") != object.get("package_lock_digest")
218    {
219        errors.push("checkpoint cross-field projections disagree".into());
220    }
221    if logical
222        .get("sources")
223        .and_then(serde_json::Value::as_array)
224        .is_none_or(|items| items.len() > MAX_CHECKPOINT_SOURCES)
225        || logical
226            .get("entries")
227            .and_then(serde_json::Value::as_array)
228            .is_none_or(|items| items.len() > MAX_CHECKPOINT_ENTRIES)
229    {
230        errors.push("checkpoint logical-state arrays exceed bounds".into());
231    }
232    let source_ids = logical
233        .get("sources")
234        .and_then(serde_json::Value::as_array)
235        .map(|sources| {
236            sources
237                .iter()
238                .filter_map(|source| source.get("source_id").and_then(serde_json::Value::as_str))
239                .collect::<std::collections::HashSet<_>>()
240        })
241        .unwrap_or_default();
242    if let Some(sources) = logical.get("sources").and_then(serde_json::Value::as_array) {
243        validate_source_anchors(sources, errors);
244    }
245    if let Some(entries) = logical.get("entries").and_then(serde_json::Value::as_array) {
246        validate_context_entries(entries, &source_ids, errors);
247        let mut expected_refs = entries
248            .iter()
249            .filter_map(|entry| {
250                entry
251                    .get("recovery_refs")
252                    .and_then(serde_json::Value::as_array)
253            })
254            .flatten()
255            .cloned()
256            .collect::<Vec<_>>();
257        expected_refs.sort_by(|left, right| left.as_str().cmp(&right.as_str()));
258        expected_refs.dedup();
259        if object
260            .get("recovery_refs")
261            .and_then(serde_json::Value::as_array)
262            != Some(&expected_refs)
263        {
264            errors.push("checkpoint recovery refs disagree with context entries".into());
265        }
266    }
267    if let Some(refs) = object
268        .get("recovery_refs")
269        .and_then(serde_json::Value::as_array)
270    {
271        validate_string_array(
272            refs,
273            MAX_CHECKPOINT_REFS,
274            512,
275            true,
276            "checkpoint recovery refs",
277            errors,
278        );
279    }
280    if let Some(pins) = logical
281        .get("package_pins")
282        .and_then(serde_json::Value::as_array)
283    {
284        validate_package_pins(pins, logical.get("package_lock_digest"), errors);
285    }
286    validate_domain_digest(
287        "leanctx.workspace.state.v1",
288        &serde_json::Value::Object(logical.clone()),
289        object.get("state_digest"),
290        "checkpoint.state_digest",
291        errors,
292    );
293    if let Some(policy) = logical.get("policy") {
294        validate_domain_digest(
295            "leanctx.workspace.policy.v1",
296            policy,
297            object.get("policy_digest"),
298            "checkpoint.policy_digest",
299            errors,
300        );
301    }
302    if let Some(entries) = logical.get("entries") {
303        validate_domain_digest(
304            "leanctx.project-context.state.v1",
305            entries,
306            object.get("project_context_digest"),
307            "checkpoint.project_context_digest",
308            errors,
309        );
310    }
311    let mut unsigned = object.clone();
312    unsigned.remove("envelope_digest");
313    validate_domain_digest(
314        "leanctx.checkpoint.envelope.v2",
315        &serde_json::Value::Object(unsigned),
316        object.get("envelope_digest"),
317        "checkpoint.envelope_digest",
318        errors,
319    );
320}
321
322fn validate_workspace_policy(value: Option<&serde_json::Value>, errors: &mut Vec<String>) {
323    const KEYS: &[&str] = &[
324        "schema_version",
325        "allowed_categories",
326        "max_events",
327        "max_context_entries",
328        "max_entry_bytes",
329        "max_context_bytes",
330        "max_sources",
331        "max_sessions",
332        "allow_external_sources",
333    ];
334    let Some(object) = value.and_then(serde_json::Value::as_object) else {
335        errors.push("checkpoint workspace policy must be an object".into());
336        return;
337    };
338    validate_exact_keys(object, KEYS, "checkpoint workspace policy", errors);
339    let Some(categories) = object
340        .get("allowed_categories")
341        .and_then(serde_json::Value::as_array)
342    else {
343        errors.push("checkpoint workspace policy categories must be an array".into());
344        return;
345    };
346    let category_values = categories
347        .iter()
348        .filter_map(serde_json::Value::as_str)
349        .collect::<Vec<_>>();
350    if object
351        .get("schema_version")
352        .and_then(serde_json::Value::as_str)
353        != Some("leanctx.workspace-policy/v1")
354        || category_values.len() != categories.len()
355        || !category_values.windows(2).all(|pair| pair[0] < pair[1])
356        || category_values.iter().any(|category| {
357            !matches!(
358                *category,
359                "facts" | "decisions" | "constraints" | "unresolved_questions" | "source_refs"
360            )
361        })
362        || [
363            "max_events",
364            "max_context_entries",
365            "max_entry_bytes",
366            "max_context_bytes",
367            "max_sources",
368            "max_sessions",
369        ]
370        .iter()
371        .any(|name| {
372            object
373                .get(*name)
374                .and_then(serde_json::Value::as_u64)
375                .is_none_or(|n| n == 0)
376        })
377        || !object
378            .get("allow_external_sources")
379            .is_some_and(serde_json::Value::is_boolean)
380    {
381        errors.push("checkpoint workspace policy is invalid".into());
382    }
383}
384
385fn validate_lineage(
386    value: Option<&serde_json::Value>,
387    workspace_id: Option<&serde_json::Value>,
388    errors: &mut Vec<String>,
389) {
390    let Some(object) = value.and_then(serde_json::Value::as_object) else {
391        errors.push("checkpoint lineage must be an object".into());
392        return;
393    };
394    validate_exact_keys(
395        object,
396        &["kind", "workspace_id", "state_id"],
397        "checkpoint lineage",
398        errors,
399    );
400    if object.get("kind").and_then(serde_json::Value::as_str) != Some("workspace")
401        || object.get("workspace_id") != workspace_id
402        || !object.get("state_id").is_some_and(valid_prefixed_digest)
403    {
404        errors.push("checkpoint lineage is invalid".into());
405    }
406}
407
408fn validate_engine_identity(value: Option<&serde_json::Value>, errors: &mut Vec<String>) {
409    let Some(object) = value.and_then(serde_json::Value::as_object) else {
410        errors.push("checkpoint engine identity must be an object".into());
411        return;
412    };
413    validate_exact_keys(
414        object,
415        &["interface_version", "schema_version", "transport_version"],
416        "checkpoint engine identity",
417        errors,
418    );
419    if object
420        .get("interface_version")
421        .and_then(serde_json::Value::as_str)
422        != Some("1.0.0")
423        || object
424            .get("schema_version")
425            .and_then(serde_json::Value::as_u64)
426            != Some(1)
427        || object
428            .get("transport_version")
429            .and_then(serde_json::Value::as_u64)
430            != Some(1)
431    {
432        errors.push("checkpoint engine identity is unsupported".into());
433    }
434}
435
436fn validate_source_anchors(sources: &[serde_json::Value], errors: &mut Vec<String>) {
437    const KEYS: &[&str] = &[
438        "schema_version",
439        "source_id",
440        "kind",
441        "canonical_id",
442        "revision",
443        "freshness",
444        "recovery",
445        "trust",
446        "scope",
447        "engine_binding",
448    ];
449    let mut source_ids = Vec::new();
450    for source in sources {
451        let Some(object) = source.as_object() else {
452            errors.push("checkpoint source anchor must be an object".into());
453            continue;
454        };
455        validate_exact_keys(object, KEYS, "checkpoint source anchor", errors);
456        if object
457            .get("schema_version")
458            .and_then(serde_json::Value::as_str)
459            != Some("leanctx.source-anchor/v1")
460        {
461            errors.push("checkpoint source anchor schema is unsupported".into());
462        }
463        let source_id = bounded_string(object.get("source_id"), 128);
464        let kind = object.get("kind").and_then(serde_json::Value::as_str);
465        if source_id.is_none()
466            || !matches!(
467                kind,
468                Some("filesystem" | "git" | "archive" | "api" | "custom")
469            )
470            || bounded_string(object.get("canonical_id"), 2048).is_none()
471        {
472            errors.push("checkpoint source anchor identity is invalid".into());
473        }
474        if let Some(source_id) = source_id {
475            source_ids.push(source_id);
476        }
477        validate_revision(object.get("revision"), kind, errors);
478        validate_freshness(object.get("freshness"), errors);
479        validate_recovery(object.get("recovery"), errors);
480        validate_trust(object.get("trust"), errors);
481        validate_pair_object(
482            object.get("scope"),
483            "checkpoint source scope",
484            64,
485            2048,
486            errors,
487        );
488        validate_engine_binding(object.get("engine_binding"), kind, errors);
489    }
490    if !source_ids.windows(2).all(|pair| pair[0] < pair[1]) {
491        errors.push("checkpoint source ids must be unique and sorted".into());
492    }
493}
494
495fn validate_revision(
496    value: Option<&serde_json::Value>,
497    source_kind: Option<&str>,
498    errors: &mut Vec<String>,
499) {
500    let Some(value) = value else { return };
501    if value.is_null() {
502        return;
503    }
504    let Some(object) = value.as_object() else {
505        errors.push("checkpoint source revision must be null or an object".into());
506        return;
507    };
508    validate_exact_keys(
509        object,
510        &["kind", "value"],
511        "checkpoint source revision",
512        errors,
513    );
514    if bounded_string(object.get("kind"), 64).is_none()
515        || bounded_string(object.get("value"), 2048).is_none()
516        || object.get("kind").and_then(serde_json::Value::as_str) != source_kind
517    {
518        errors.push("checkpoint source revision is invalid".into());
519    }
520}
521
522fn validate_freshness(value: Option<&serde_json::Value>, errors: &mut Vec<String>) {
523    let Some(object) = value.and_then(serde_json::Value::as_object) else {
524        errors.push("checkpoint source freshness must be an object".into());
525        return;
526    };
527    let keys = if object.contains_key("valid_until") {
528        &["observed_at", "status", "valid_until"][..]
529    } else {
530        &["observed_at", "status"][..]
531    };
532    validate_exact_keys(object, keys, "checkpoint source freshness", errors);
533    let observed_raw = object
534        .get("observed_at")
535        .and_then(serde_json::Value::as_str);
536    let observed =
537        observed_raw.and_then(|raw| lean_ctx_time::OffsetDateTime::parse_from_rfc3339(raw).ok());
538    let valid_until_raw = object
539        .get("valid_until")
540        .and_then(serde_json::Value::as_str);
541    let valid_until =
542        valid_until_raw.and_then(|raw| lean_ctx_time::OffsetDateTime::parse_from_rfc3339(raw).ok());
543    if observed_raw.is_none_or(|raw| !canonical_utc_timestamp(raw))
544        || !object
545            .get("status")
546            .is_some_and(|value| matches!(value.as_str(), Some("current" | "stale" | "unknown")))
547        || (object.contains_key("valid_until")
548            && valid_until_raw.is_none_or(|raw| !canonical_utc_timestamp(raw)))
549        || valid_until
550            .zip(observed)
551            .is_some_and(|(valid, observed)| valid < observed)
552    {
553        errors.push("checkpoint source freshness is invalid".into());
554    }
555}
556
557fn validate_recovery(value: Option<&serde_json::Value>, errors: &mut Vec<String>) {
558    let Some(value) = value else { return };
559    if value.is_null() {
560        return;
561    }
562    let Some(object) = value.as_object() else {
563        errors.push("checkpoint source recovery must be null or an object".into());
564        return;
565    };
566    let keys = if object.contains_key("digest") {
567        &["kind", "immutable_ref", "digest"][..]
568    } else {
569        &["kind", "immutable_ref"][..]
570    };
571    validate_exact_keys(object, keys, "checkpoint source recovery", errors);
572    if bounded_string(object.get("kind"), 64).is_none()
573        || !object
574            .get("immutable_ref")
575            .and_then(serde_json::Value::as_str)
576            .is_some_and(|raw| valid_ref(raw, 2048))
577        || object
578            .get("digest")
579            .is_some_and(|value| !valid_prefixed_digest(value))
580    {
581        errors.push("checkpoint source recovery is invalid".into());
582    }
583}
584
585fn validate_trust(value: Option<&serde_json::Value>, errors: &mut Vec<String>) {
586    let Some(object) = value.and_then(serde_json::Value::as_object) else {
587        errors.push("checkpoint source trust must be an object".into());
588        return;
589    };
590    validate_exact_keys(
591        object,
592        &["level", "evidence_refs"],
593        "checkpoint source trust",
594        errors,
595    );
596    let level = object.get("level").and_then(serde_json::Value::as_str);
597    let Some(refs) = object
598        .get("evidence_refs")
599        .and_then(serde_json::Value::as_array)
600    else {
601        errors.push("checkpoint source trust evidence must be an array".into());
602        return;
603    };
604    validate_string_array(
605        refs,
606        32,
607        512,
608        true,
609        "checkpoint source trust evidence",
610        errors,
611    );
612    if !matches!(level, Some("unverified" | "local" | "verified"))
613        || (level == Some("verified")
614            && (refs.is_empty()
615                || refs.iter().any(|value| {
616                    !value.as_str().is_some_and(|raw| {
617                        raw.len() == 79
618                            && raw.starts_with("receipt:sha256:")
619                            && raw[15..]
620                                .bytes()
621                                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
622                    })
623                })))
624    {
625        errors.push("checkpoint source trust is invalid".into());
626    }
627}
628
629fn validate_pair_object(
630    value: Option<&serde_json::Value>,
631    label: &str,
632    first_cap: usize,
633    second_cap: usize,
634    errors: &mut Vec<String>,
635) {
636    let Some(object) = value.and_then(serde_json::Value::as_object) else {
637        errors.push(format!("{label} must be an object"));
638        return;
639    };
640    validate_exact_keys(object, &["kind", "value"], label, errors);
641    if bounded_string(object.get("kind"), first_cap).is_none()
642        || bounded_string(object.get("value"), second_cap).is_none()
643    {
644        errors.push(format!("{label} is invalid"));
645    }
646}
647
648fn validate_engine_binding(
649    value: Option<&serde_json::Value>,
650    source_kind: Option<&str>,
651    errors: &mut Vec<String>,
652) {
653    let Some(value) = value else { return };
654    if value.is_null() {
655        return;
656    }
657    let Some(object) = value.as_object() else {
658        errors.push("checkpoint engine binding must be null or an object".into());
659        return;
660    };
661    if source_kind != Some("filesystem") {
662        errors.push("checkpoint engine binding requires a filesystem source".into());
663    }
664    let required = ["path", "project_root", "media_type"];
665    let allowed = [
666        "path",
667        "project_root",
668        "media_type",
669        "source_ref",
670        "source_digest",
671    ];
672    if object.keys().any(|key| !allowed.contains(&key.as_str()))
673        || required.iter().any(|key| !object.contains_key(*key))
674        || !object
675            .get("path")
676            .and_then(serde_json::Value::as_str)
677            .is_some_and(valid_relative_source_path)
678        || !object
679            .get("project_root")
680            .and_then(serde_json::Value::as_str)
681            .is_some_and(valid_normalized_project_root)
682        || bounded_string(object.get("media_type"), 512).is_none()
683        || object
684            .get("source_ref")
685            .is_some_and(|value| !value.as_str().is_some_and(|raw| valid_ref(raw, 512)))
686        || object
687            .get("source_digest")
688            .is_some_and(|value| !valid_prefixed_digest(value))
689    {
690        errors.push("checkpoint engine binding is invalid".into());
691    }
692}
693
694fn valid_relative_source_path(raw: &str) -> bool {
695    valid_text(raw, 4096)
696        && !is_absolute_path(raw)
697        && !raw.contains('\\')
698        && raw
699            .split('/')
700            .all(|component| !component.is_empty() && !matches!(component, "." | ".."))
701}
702
703fn valid_normalized_project_root(raw: &str) -> bool {
704    if !valid_text(raw, 4096) || !is_absolute_path(raw) {
705        return false;
706    }
707    let tail = if let Some(tail) = raw.strip_prefix("\\\\") {
708        tail
709    } else if let Some(tail) = raw.strip_prefix('/') {
710        tail
711    } else if raw.len() >= 3
712        && raw.as_bytes()[1] == b':'
713        && matches!(raw.as_bytes()[2], b'/' | b'\\')
714    {
715        &raw[3..]
716    } else {
717        return false;
718    };
719    tail.is_empty()
720        || tail
721            .split(['/', '\\'])
722            .all(|component| !component.is_empty() && !matches!(component, "." | ".."))
723}
724
725fn validate_context_entries(
726    entries: &[serde_json::Value],
727    source_ids: &std::collections::HashSet<&str>,
728    errors: &mut Vec<String>,
729) {
730    const KEYS: &[&str] = &[
731        "schema_version",
732        "entry_id",
733        "category",
734        "value",
735        "source_ids",
736        "session_id",
737        "receipt_refs",
738        "recovery_refs",
739    ];
740    let mut entry_ids = Vec::new();
741    for entry in entries {
742        let Some(object) = entry.as_object() else {
743            errors.push("checkpoint context entry must be an object".into());
744            continue;
745        };
746        validate_exact_keys(object, KEYS, "checkpoint context entry", errors);
747        if object
748            .get("schema_version")
749            .and_then(serde_json::Value::as_str)
750            != Some("leanctx.project-context-entry/v1")
751            || !object
752                .get("entry_id")
753                .and_then(serde_json::Value::as_str)
754                .is_some_and(|raw| {
755                    uuid::Uuid::parse_str(raw)
756                        .is_ok_and(|parsed| parsed.hyphenated().to_string() == raw)
757                })
758            || !object.get("category").is_some_and(|value| {
759                matches!(
760                    value.as_str(),
761                    Some(
762                        "facts"
763                            | "decisions"
764                            | "constraints"
765                            | "unresolved_questions"
766                            | "source_refs"
767                    )
768                )
769            })
770            || bounded_string(object.get("value"), 4096).is_none()
771            || object
772                .get("session_id")
773                .is_some_and(|value| !value.is_null() && bounded_string(Some(value), 512).is_none())
774        {
775            errors.push("checkpoint context entry identity/value is invalid".into());
776        }
777        if let Some(entry_id) = object.get("entry_id").and_then(serde_json::Value::as_str) {
778            entry_ids.push(entry_id);
779        }
780        for (field, cap, item_cap, printable) in [
781            ("source_ids", 16, 128, false),
782            ("receipt_refs", 16, 512, true),
783            ("recovery_refs", 16, 512, true),
784        ] {
785            let Some(items) = object.get(field).and_then(serde_json::Value::as_array) else {
786                errors.push(format!("checkpoint context entry {field} must be an array"));
787                continue;
788            };
789            validate_string_array(
790                items,
791                cap,
792                item_cap,
793                printable,
794                "checkpoint context entry refs",
795                errors,
796            );
797            if field == "source_ids"
798                && items
799                    .iter()
800                    .filter_map(serde_json::Value::as_str)
801                    .any(|source_id| !source_ids.contains(source_id))
802            {
803                errors.push("checkpoint context entry references an unknown source".into());
804            }
805        }
806    }
807    if !entry_ids.windows(2).all(|pair| pair[0] < pair[1]) {
808        errors.push("checkpoint context entry ids must be unique and sorted".into());
809    }
810}
811
812fn validate_string_array(
813    values: &[serde_json::Value],
814    cap: usize,
815    item_cap: usize,
816    printable_ascii: bool,
817    label: &str,
818    errors: &mut Vec<String>,
819) {
820    if values.len() > cap
821        || values.iter().any(|value| {
822            bounded_string(Some(value), item_cap).is_none()
823                || (printable_ascii
824                    && !value
825                        .as_str()
826                        .is_some_and(|raw| raw.bytes().all(|byte| (0x20..=0x7e).contains(&byte))))
827        })
828        || !values
829            .windows(2)
830            .all(|pair| pair[0].as_str() < pair[1].as_str())
831    {
832        errors.push(format!("{label} is invalid or exceeds its bound"));
833    }
834}
835
836fn valid_ref(raw: &str, cap: usize) -> bool {
837    !raw.is_empty() && raw.len() <= cap && raw.bytes().all(|byte| (0x20..=0x7e).contains(&byte))
838}
839
840fn canonical_utc_timestamp(raw: &str) -> bool {
841    (raw.len() == 20 || raw.len() == 27)
842        && raw.ends_with('Z')
843        && (raw.len() == 20 || raw.as_bytes().get(19) == Some(&b'.'))
844        && lean_ctx_time::OffsetDateTime::parse_from_rfc3339(raw).is_ok()
845}
846
847fn bounded_string(value: Option<&serde_json::Value>, cap: usize) -> Option<&str> {
848    value
849        .and_then(serde_json::Value::as_str)
850        .filter(|raw| valid_text(raw, cap))
851}
852
853fn valid_text(raw: &str, cap: usize) -> bool {
854    !raw.is_empty() && raw.len() <= cap && !raw.chars().any(char::is_control)
855}
856
857fn validate_package_pins(
858    pins: &[serde_json::Value],
859    lock_digest: Option<&serde_json::Value>,
860    errors: &mut Vec<String>,
861) {
862    const KEYS: &[&str] = &[
863        "schema_version",
864        "name",
865        "version",
866        "artifact_digest",
867        "manifest_digest",
868        "content_hash",
869        "signature_state",
870        "signer_public_key",
871        "trust_state",
872        "policy_decision",
873    ];
874    let mut identities = Vec::new();
875    for pin in pins {
876        let Some(object) = pin.as_object() else {
877            errors.push("checkpoint package pin must be an object".into());
878            continue;
879        };
880        validate_exact_keys(object, KEYS, "checkpoint package pin", errors);
881        if object
882            .get("schema_version")
883            .and_then(serde_json::Value::as_str)
884            != Some("leanctx.package-pin/v1")
885            || object
886                .get("policy_decision")
887                .and_then(serde_json::Value::as_str)
888                != Some("admitted")
889        {
890            errors.push("checkpoint package pin contract is unsupported".into());
891        }
892        for name in ["artifact_digest", "manifest_digest", "content_hash"] {
893            if !object.get(name).is_some_and(valid_prefixed_digest) {
894                errors.push(format!("checkpoint package pin {name} is invalid"));
895            }
896        }
897        let signature = object
898            .get("signature_state")
899            .and_then(serde_json::Value::as_str);
900        let signer = object.get("signer_public_key");
901        if !matches!(signature, Some("signed_valid" | "unsigned"))
902            || (signature == Some("signed_valid")
903                && !signer.is_some_and(|value| {
904                    value.as_str().is_some_and(|raw| {
905                        raw.len() == 64
906                            && raw
907                                .bytes()
908                                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
909                    })
910                }))
911            || (signature == Some("unsigned") && !signer.is_some_and(serde_json::Value::is_null))
912        {
913            errors.push("checkpoint package pin signature identity is invalid".into());
914        }
915        if !object.get("trust_state").is_some_and(|value| {
916            matches!(value.as_str(), Some("trusted" | "untrusted" | "unknown"))
917        }) {
918            errors.push("checkpoint package pin trust state is invalid".into());
919        }
920        let Some(name) = object.get("name").and_then(serde_json::Value::as_str) else {
921            errors.push("checkpoint package pin name is invalid".into());
922            continue;
923        };
924        let Some(version) = object.get("version").and_then(serde_json::Value::as_str) else {
925            errors.push("checkpoint package pin version is invalid".into());
926            continue;
927        };
928        if !valid_text(name, 128) || !valid_text(version, 64) {
929            errors.push("checkpoint package pin name/version exceeds bounds".into());
930        }
931        identities.push((name, version));
932    }
933    if !identities.windows(2).all(|pair| pair[0] < pair[1]) {
934        errors.push("checkpoint package pins must be unique and sorted".into());
935    }
936    if pins.is_empty() {
937        if !lock_digest.is_some_and(serde_json::Value::is_null) {
938            errors.push("empty checkpoint package pins require a null lock digest".into());
939        }
940    } else {
941        validate_domain_digest(
942            "leanctx.package.lock.v1",
943            &serde_json::Value::Array(pins.to_vec()),
944            lock_digest,
945            "checkpoint.package_lock_digest",
946            errors,
947        );
948    }
949}
950
951fn validate_migration_provenance(
952    value: Option<&serde_json::Value>,
953    checkpoint: &serde_json::Value,
954    errors: &mut Vec<String>,
955) {
956    let Some(value) = value else { return };
957    const KEYS: &[&str] = &[
958        "origin",
959        "legacy_snapshot_id",
960        "legacy_snapshot_digest",
961        "migration_contract",
962        "checkpoint_id",
963        "state_digest",
964        "limitations",
965    ];
966    let Some(object) = value.as_object() else {
967        errors.push("migration_provenance must be an object".into());
968        return;
969    };
970    validate_exact_keys(object, KEYS, "migration_provenance", errors);
971    if object.get("origin").and_then(serde_json::Value::as_str) != Some("SnapshotV1")
972        || object
973            .get("migration_contract")
974            .and_then(serde_json::Value::as_str)
975            != Some("leanctx.snapshot-v1-migration/v1")
976    {
977        errors.push("SnapshotV1 migration provenance is unsupported".into());
978    }
979    for name in ["legacy_snapshot_digest", "state_digest"] {
980        if !object.get(name).is_some_and(valid_prefixed_digest) {
981            errors.push(format!("migration_provenance.{name} is invalid"));
982        }
983    }
984    if bounded_string(object.get("legacy_snapshot_id"), 512).is_none()
985        || !object
986            .get("limitations")
987            .and_then(serde_json::Value::as_array)
988            .is_some_and(|items| {
989                items.len() <= 64
990                    && items
991                        .iter()
992                        .all(|item| bounded_string(Some(item), 2048).is_some())
993            })
994    {
995        errors.push("migration_provenance.limitations exceeds its bound".into());
996    }
997    if object.get("checkpoint_id") != checkpoint.get("checkpoint_id")
998        || object.get("state_digest") != checkpoint.get("state_digest")
999    {
1000        errors.push("migration provenance is not bound to the carried checkpoint".into());
1001    }
1002}
1003
1004fn validate_exact_keys(
1005    object: &serde_json::Map<String, serde_json::Value>,
1006    expected: &[&str],
1007    label: &str,
1008    errors: &mut Vec<String>,
1009) {
1010    if object.len() != expected.len()
1011        || object.keys().any(|key| !expected.contains(&key.as_str()))
1012        || expected.iter().any(|key| !object.contains_key(*key))
1013    {
1014        errors.push(format!("{label} fields do not match the open contract"));
1015    }
1016}
1017
1018fn valid_prefixed_digest(value: &serde_json::Value) -> bool {
1019    value.as_str().is_some_and(|raw| {
1020        raw.len() == 71
1021            && raw.starts_with("sha256:")
1022            && raw[7..]
1023                .bytes()
1024                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1025    })
1026}
1027
1028fn validate_domain_digest(
1029    domain: &str,
1030    value: &serde_json::Value,
1031    claimed: Option<&serde_json::Value>,
1032    label: &str,
1033    errors: &mut Vec<String>,
1034) {
1035    let Ok(canonical) = serde_json::to_vec(value) else {
1036        errors.push(format!("{label} input is not canonical JSON"));
1037        return;
1038    };
1039    let mut hasher = Sha256::new();
1040    hasher.update(domain.as_bytes());
1041    hasher.update(b"\n");
1042    hasher.update(canonical);
1043    let expected = format!(
1044        "sha256:{}",
1045        crate::core::agent_identity::hex_encode(&hasher.finalize())
1046    );
1047    if claimed.and_then(serde_json::Value::as_str) != Some(expected.as_str()) {
1048        errors.push(format!("{label} does not match canonical content"));
1049    }
1050}
1051
1052fn collect_non_portable_paths(value: &serde_json::Value, pointer: &str, out: &mut Vec<String>) {
1053    match value {
1054        serde_json::Value::Object(object) => {
1055            for (key, item) in object {
1056                let child = format!("{pointer}.{key}");
1057                if matches!(key.as_str(), "path" | "project_root")
1058                    && item.as_str().is_some_and(is_absolute_path)
1059                {
1060                    out.push(child.clone());
1061                }
1062                if matches!(key.as_str(), "canonical_id" | "immutable_ref")
1063                    && item.as_str().is_some_and(|value| {
1064                        value.starts_with("file:///") || is_absolute_path(value)
1065                    })
1066                {
1067                    out.push(child.clone());
1068                }
1069                collect_non_portable_paths(item, &child, out);
1070            }
1071        }
1072        serde_json::Value::Array(items) => {
1073            for (index, item) in items.iter().enumerate() {
1074                collect_non_portable_paths(item, &format!("{pointer}[{index}]"), out);
1075            }
1076        }
1077        _ => {}
1078    }
1079}
1080
1081fn is_absolute_path(value: &str) -> bool {
1082    value.starts_with('/')
1083        || value.starts_with("\\\\")
1084        || (value.len() > 2
1085            && value.as_bytes()[1] == b':'
1086            && matches!(value.as_bytes()[2], b'/' | b'\\'))
1087}
1088
1089/// Structural + integrity validation of a `kind=skills` payload (GH #727).
1090/// Every blob must decode and match its plaintext hash — a tampered body
1091/// fails verification, so it can never be materialized on disk.
1092fn validate_documents(docs: &super::content::DocumentsContent, errors: &mut Vec<String>) {
1093    use super::content::{MAX_DOCUMENT_FILES, MAX_DOCUMENTS_TOTAL_BYTES};
1094
1095    if docs.files.is_empty() {
1096        errors.push("kind=skills payload has no files".into());
1097        return;
1098    }
1099    if docs.files.len() > MAX_DOCUMENT_FILES {
1100        errors.push(format!(
1101            "skills payload has {} files (cap: {MAX_DOCUMENT_FILES})",
1102            docs.files.len()
1103        ));
1104        return;
1105    }
1106
1107    let mut seen = std::collections::HashSet::new();
1108    let mut total: usize = 0;
1109    for blob in &docs.files {
1110        if let Err(e) = validate_document_path(&blob.path) {
1111            errors.push(e);
1112            continue;
1113        }
1114        if !seen.insert(blob.path.as_str()) {
1115            errors.push(format!("duplicate document path `{}`", blob.path));
1116            continue;
1117        }
1118        if blob.sha256.len() != 64 || !blob.sha256.chars().all(|c| c.is_ascii_hexdigit()) {
1119            errors.push(format!(
1120                "`{}`: sha256 must be a 64-char hex string",
1121                blob.path
1122            ));
1123            continue;
1124        }
1125        match blob.decode_verified() {
1126            Ok(plain) => total += plain.len(),
1127            Err(e) => errors.push(e),
1128        }
1129    }
1130    if total > MAX_DOCUMENTS_TOTAL_BYTES {
1131        errors.push(format!(
1132            "skills payload decodes to {total} bytes (cap: {MAX_DOCUMENTS_TOTAL_BYTES})"
1133        ));
1134    }
1135}
1136
1137/// Path safety for document blobs: relative, `/`-separated, no traversal, no
1138/// absolute/drive/backslash forms — the materializer joins these under the
1139/// pack store and must never be able to escape it.
1140pub(crate) fn validate_document_path(path: &str) -> Result<(), String> {
1141    if path.is_empty() || path.len() > 512 {
1142        return Err(format!(
1143            "invalid document path `{path}` (empty or too long)"
1144        ));
1145    }
1146    if path.starts_with('/') || path.contains('\\') || path.contains(':') {
1147        return Err(format!(
1148            "invalid document path `{path}` (must be relative with `/` separators)"
1149        ));
1150    }
1151    let has_bad_component = path
1152        .split('/')
1153        .any(|c| c.is_empty() || c == "." || c == ".." || c.starts_with(".."));
1154    if has_bad_component || path.chars().any(char::is_control) {
1155        return Err(format!("invalid document path `{path}` (unsafe component)"));
1156    }
1157    Ok(())
1158}
1159
1160/// Outcome of one verification check.
1161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1162pub enum CheckOutcome {
1163    Pass,
1164    Fail,
1165    /// Not applicable — e.g. signature check on an unsigned package.
1166    Skipped,
1167}
1168
1169#[cfg(test)]
1170impl CheckOutcome {
1171    pub(crate) fn as_str(&self) -> &'static str {
1172        match self {
1173            Self::Pass => "pass",
1174            Self::Fail => "fail",
1175            Self::Skipped => "skipped",
1176        }
1177    }
1178}
1179
1180/// Per-check verification report, mirroring the checks every conforming
1181/// reader runs (and the shape of the @ctxpkg/verify reference output).
1182#[derive(Debug)]
1183pub struct VerifyReport {
1184    pub name: Option<String>,
1185    pub version: Option<String>,
1186    pub structure: CheckOutcome,
1187    pub content_hash: CheckOutcome,
1188    pub package_hash: CheckOutcome,
1189    pub signature: CheckOutcome,
1190    /// What a passing signature covers.
1191    pub signature_coverage: Option<super::signing::SignatureCoverage>,
1192    pub errors: Vec<String>,
1193}
1194
1195impl VerifyReport {
1196    pub fn valid(&self) -> bool {
1197        self.errors.is_empty()
1198    }
1199
1200    fn failed(error: String) -> Self {
1201        Self {
1202            name: None,
1203            version: None,
1204            structure: CheckOutcome::Fail,
1205            content_hash: CheckOutcome::Skipped,
1206            package_hash: CheckOutcome::Skipped,
1207            signature: CheckOutcome::Skipped,
1208            signature_coverage: None,
1209            errors: vec![error],
1210        }
1211    }
1212}
1213
1214#[cfg(test)]
1215fn sha256_hex(data: &[u8]) -> String {
1216    let mut h = Sha256::new();
1217    h.update(data);
1218    crate::core::agent_identity::hex_encode(&h.finalize())
1219}
1220
1221/// Verify a `.ctxpkg` document without installing anything.
1222pub(crate) fn verify_package_text(doc: &str) -> VerifyReport {
1223    let value: serde_json::Value = match serde_json::from_str(doc) {
1224        Ok(v) => v,
1225        Err(e) => return VerifyReport::failed(format!("not valid JSON: {e}")),
1226    };
1227
1228    let Some(manifest_value) = value.get("manifest") else {
1229        return VerifyReport::failed("missing required member: manifest".into());
1230    };
1231    if value.get("content").is_none() {
1232        return VerifyReport::failed("missing required member: content".into());
1233    }
1234
1235    let manifest: PackageManifest = match serde_json::from_value(manifest_value.clone()) {
1236        Ok(m) => m,
1237        Err(e) => return VerifyReport::failed(format!("manifest does not parse: {e}")),
1238    };
1239    let mut report = VerifyReport {
1240        name: Some(manifest.name.clone()),
1241        version: Some(manifest.version.clone()),
1242        structure: CheckOutcome::Pass,
1243        content_hash: CheckOutcome::Skipped,
1244        package_hash: CheckOutcome::Skipped,
1245        signature: CheckOutcome::Skipped,
1246        signature_coverage: None,
1247        errors: Vec::new(),
1248    };
1249    if let Err(errs) = manifest.validate() {
1250        report.structure = CheckOutcome::Fail;
1251        report.errors.extend(errs);
1252        return report;
1253    }
1254
1255    // Kind ↔ payload coherence (GH #726) — a structural property: the
1256    // declared kind must match the payload the document actually carries.
1257    let content = match serde_json::from_value::<PackageContent>(
1258        value.get("content").cloned().unwrap_or_default(),
1259    ) {
1260        Ok(content) => content,
1261        Err(error) => {
1262            report.structure = CheckOutcome::Fail;
1263            report
1264                .errors
1265                .push(format!("content does not parse: {error}"));
1266            return report;
1267        }
1268    };
1269    if let Err(errs) = validate_kind_coherence(&manifest, &content) {
1270        report.structure = CheckOutcome::Fail;
1271        report.errors.extend(errs);
1272        return report;
1273    }
1274
1275    // §8 — integrity against the writer's bytes, recomputed exactly as the
1276    // hosted registry recomputes it.
1277    let Some(recomputed) = super::integrity::recompute(doc, &manifest.name, &manifest.version)
1278    else {
1279        report.structure = CheckOutcome::Fail;
1280        report
1281            .errors
1282            .push("could not locate the content member in the document".into());
1283        return report;
1284    };
1285
1286    if recomputed.content_hash == manifest.integrity.content_hash {
1287        report.content_hash = CheckOutcome::Pass;
1288    } else {
1289        report.content_hash = CheckOutcome::Fail;
1290        report.errors.push(format!(
1291            "content_hash mismatch: manifest says {}, content hashes to {}",
1292            manifest.integrity.content_hash, recomputed.content_hash
1293        ));
1294    }
1295    if manifest.integrity.byte_size != recomputed.byte_size {
1296        report.content_hash = CheckOutcome::Fail;
1297        report.errors.push(format!(
1298            "byte_size mismatch: manifest says {}, content is {} bytes",
1299            manifest.integrity.byte_size, recomputed.byte_size
1300        ));
1301    }
1302
1303    if recomputed.sha256 == manifest.integrity.sha256 {
1304        report.package_hash = CheckOutcome::Pass;
1305    } else {
1306        report.package_hash = CheckOutcome::Fail;
1307        report.errors.push(format!(
1308            "package sha256 mismatch: manifest says {}, recomputed {}",
1309            manifest.integrity.sha256, recomputed.sha256
1310        ));
1311    }
1312
1313    // §9 — a present-but-invalid signature is always tampering.
1314    if manifest.signature.is_some() {
1315        match super::signing::signature_coverage_of(manifest_value) {
1316            Ok(Some(coverage)) => {
1317                report.signature = CheckOutcome::Pass;
1318                report.signature_coverage = Some(coverage);
1319            }
1320            Ok(None) => {
1321                report.signature = CheckOutcome::Fail;
1322                report.errors.push(
1323                    "signature verification failed — the package was modified after signing".into(),
1324                );
1325            }
1326            Err(e) => {
1327                report.signature = CheckOutcome::Fail;
1328                report.errors.push(format!("signature check errored: {e}"));
1329            }
1330        }
1331    }
1332
1333    report
1334}
1335
1336/// Read and verify a `.ctxpkg` file (size- and extension-gated like import).
1337pub fn verify_package_file(path: &Path) -> Result<VerifyReport, String> {
1338    Ok(verify_package_text(&read_package_text(path)?))
1339}
1340
1341/// Read once so a caller can verify and decode the same bounded document.
1342pub(crate) fn read_package_text(path: &Path) -> Result<String, String> {
1343    use std::io::Read;
1344
1345    if !crate::core::contracts::is_package_file(path) {
1346        let ext = path
1347            .extension()
1348            .and_then(|e| e.to_str())
1349            .unwrap_or("(none)");
1350        return Err(format!(
1351            "unsupported file extension '.{ext}' — expected .{} or .{}",
1352            crate::core::contracts::PACKAGE_EXTENSION,
1353            crate::core::contracts::LEGACY_PACKAGE_EXTENSION,
1354        ));
1355    }
1356    let meta = std::fs::metadata(path).map_err(|e| format!("stat package file: {e}"))?;
1357    if !meta.is_file() {
1358        return Err("package input must be a regular file".into());
1359    }
1360    if meta.len() > crate::core::contracts::MAX_PACKAGE_FILE_BYTES {
1361        return Err(format!(
1362            "package file too large ({} bytes, max {} bytes)",
1363            meta.len(),
1364            crate::core::contracts::MAX_PACKAGE_FILE_BYTES,
1365        ));
1366    }
1367    let file = std::fs::File::open(path).map_err(|e| format!("open package file: {e}"))?;
1368    let mut doc = String::new();
1369    file.take(crate::core::contracts::MAX_PACKAGE_FILE_BYTES + 1)
1370        .read_to_string(&mut doc)
1371        .map_err(|e| format!("read package file: {e}"))?;
1372    if doc.len() as u64 > crate::core::contracts::MAX_PACKAGE_FILE_BYTES {
1373        return Err("package file exceeded size limit while reading".into());
1374    }
1375    Ok(doc)
1376}
1377
1378#[cfg(test)]
1379mod tests;