Skip to main content

lean_ctx_ext/core/
claim_extractor.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Claim Extraction — decomposes context pipeline outputs into verifiable claims.
3//!
4//! Inspired by VERGE (arXiv:2601.20055): instead of verifying entire outputs
5//! monolithically, we decompose them into atomic, individually verifiable claims
6//! and route each to the appropriate verifier.
7
8use std::path::Path;
9
10use super::context_proof_v2::{
11    Claim, ClaimKind, ClaimStatus, ContextProofV2, VerifierKind, deterministic_claim, policy_claim,
12};
13
14pub struct ClaimExtractor {
15    proof: ContextProofV2,
16}
17
18impl ClaimExtractor {
19    pub fn new(run_id: &str, session_id: Option<&str>) -> Self {
20        Self {
21            proof: ContextProofV2::new(
22                run_id.to_string(),
23                session_id.map(std::string::ToString::to_string),
24            ),
25        }
26    }
27
28    pub fn verify_pathjail(&mut self, path: &str, jail_root: &Path) {
29        let resolved = crate::core::pathjail::jail_path(&std::path::PathBuf::from(path), jail_root);
30        let passed = resolved.is_ok();
31        self.proof.add_claim(policy_claim(
32            &format!("pathjail:{path}"),
33            &format!("Path '{path}' is within jail root"),
34            ClaimKind::PathjailCompliance,
35            passed,
36        ));
37    }
38
39    pub fn verify_no_secrets_in_output(&mut self, output: &str) {
40        let secret_matches = crate::core::secret_detection::detect_secrets(output);
41
42        let passed = secret_matches.is_empty();
43        let text = if passed {
44            "No secret patterns found in output".to_string()
45        } else {
46            let names: Vec<&str> = secret_matches.iter().map(|m| m.pattern_name).collect();
47            let mut unique_names: Vec<&str> = names.clone();
48            unique_names.sort_unstable();
49            unique_names.dedup();
50            format!(
51                "Secret patterns detected ({}): {}",
52                secret_matches.len(),
53                unique_names.join(", ")
54            )
55        };
56
57        self.proof.add_claim(policy_claim(
58            "no_secrets",
59            &text,
60            ClaimKind::SecretPolicy,
61            passed,
62        ));
63    }
64
65    pub fn verify_signatures_preserved(&mut self, original: &[String], compressed: &[String]) {
66        let mut missing = Vec::new();
67        for sig in original {
68            if !compressed.iter().any(|c| c.contains(sig)) {
69                missing.push(sig.clone());
70            }
71        }
72
73        let passed = missing.is_empty();
74        let text = if passed {
75            format!("All {} signatures preserved", original.len())
76        } else {
77            format!(
78                "{} of {} signatures missing: {:?}",
79                missing.len(),
80                original.len(),
81                &missing[..missing.len().min(3)]
82            )
83        };
84
85        self.proof.add_claim(Claim {
86            id: "signatures_preserved".to_string(),
87            text,
88            kind: ClaimKind::CompressionInvariant,
89            verifier: VerifierKind::Ast,
90            status: if passed {
91                ClaimStatus::Passed
92            } else {
93                ClaimStatus::Failed
94            },
95            evidence_ref: None,
96        });
97    }
98
99    pub fn verify_imports_preserved(&mut self, original_imports: &[String], compressed: &str) {
100        let mut missing = Vec::new();
101        for imp in original_imports {
102            if !compressed.contains(imp) {
103                missing.push(imp.clone());
104            }
105        }
106
107        let passed = missing.is_empty();
108        let text = if passed {
109            format!("All {} imports preserved", original_imports.len())
110        } else {
111            format!(
112                "{} of {} imports missing",
113                missing.len(),
114                original_imports.len()
115            )
116        };
117
118        self.proof
119            .add_claim(deterministic_claim("imports_preserved", &text, passed));
120    }
121
122    pub fn add_custom_claim(&mut self, claim: Claim) {
123        self.proof.add_claim(claim);
124    }
125
126    pub fn finalize(self) -> ContextProofV2 {
127        self.proof
128    }
129}
130
131#[cfg(test)]
132pub mod tests {
133    use super::*;
134
135    #[test]
136    fn secret_detection_catches_aws_keys() {
137        let mut ext = ClaimExtractor::new("test_1", None);
138        ext.verify_no_secrets_in_output(concat!("const key = 'AK", "IAIOSFODNN7EXAMPLE'"));
139        let proof = ext.finalize();
140        assert_eq!(proof.summary.failed, 1);
141    }
142
143    #[test]
144    fn clean_output_passes_secret_check() {
145        let mut ext = ClaimExtractor::new("test_2", None);
146        ext.verify_no_secrets_in_output("fn main() { println!(\"hello\"); }");
147        let proof = ext.finalize();
148        assert_eq!(proof.summary.passed, 1);
149        assert_eq!(proof.summary.failed, 0);
150    }
151
152    #[test]
153    fn signatures_preserved_check() {
154        let mut ext = ClaimExtractor::new("test_3", None);
155        let original = vec!["fn main".to_string(), "pub fn process".to_string()];
156        let compressed = vec![
157            "fn main() { ... }".to_string(),
158            "pub fn process(data: &[u8]) -> Result<(), Error>".to_string(),
159        ];
160        ext.verify_signatures_preserved(&original, &compressed);
161        let proof = ext.finalize();
162        assert_eq!(proof.summary.passed, 1);
163    }
164
165    #[test]
166    fn missing_signatures_detected() {
167        let mut ext = ClaimExtractor::new("test_4", None);
168        let original = vec!["fn main()".to_string(), "pub fn gone()".to_string()];
169        let compressed = vec!["fn main() { ... }".to_string()];
170        ext.verify_signatures_preserved(&original, &compressed);
171        let proof = ext.finalize();
172        assert_eq!(proof.summary.failed, 1);
173    }
174
175    #[test]
176    fn pathjail_claim_reports_what_the_build_enforces() {
177        // Hold the env lock with a clean config: parallel pathjail tests set
178        // LEAN_CTX_ALLOW_PATH=/ under that lock, which would admit any path.
179        let _iso = crate::core::data_dir::isolated_data_dir();
180        let root = tempfile::tempdir().unwrap();
181        let outside = tempfile::tempdir().unwrap();
182        let escaped = outside.path().join("secret.txt");
183        std::fs::write(&escaped, "outside the jail").unwrap();
184        let mut ext = ClaimExtractor::new("test_5", None);
185        ext.verify_pathjail(&escaped.to_string_lossy(), root.path());
186        let proof = ext.finalize();
187        // A normal build rejects the escape and must say so. The `no-jail`
188        // build (part of `--all-features`) admits every path, so the claim
189        // must honestly report that the path was allowed.
190        let (failed, passed, level) = if cfg!(feature = "no-jail") {
191            (
192                0,
193                1,
194                super::super::context_proof_v2::QualityLevel::PolicyChecked,
195            )
196        } else {
197            (
198                1,
199                0,
200                super::super::context_proof_v2::QualityLevel::Provenance,
201            )
202        };
203        assert_eq!(proof.summary.failed, failed);
204        assert_eq!(proof.summary.passed, passed);
205        assert_eq!(proof.quality_level, level);
206    }
207
208    #[test]
209    fn combined_extraction_computes_quality() {
210        let _iso = crate::core::data_dir::isolated_data_dir();
211        let root = tempfile::tempdir().unwrap();
212        let inside = root.path().join("src.rs");
213        std::fs::write(&inside, "fn main() {}").unwrap();
214        let mut ext = ClaimExtractor::new("test_6", None);
215        ext.verify_no_secrets_in_output("clean code");
216        ext.verify_pathjail(&inside.to_string_lossy(), root.path());
217        let proof = ext.finalize();
218        assert_eq!(proof.summary.passed, 2);
219        assert_eq!(
220            proof.quality_level,
221            super::super::context_proof_v2::QualityLevel::PolicyChecked
222        );
223    }
224
225    #[test]
226    fn detects_github_pat() {
227        let mut ext = ClaimExtractor::new("test_gh", None);
228        ext.verify_no_secrets_in_output(concat!("token = gh", "p_1234567890abcdef"));
229        let proof = ext.finalize();
230        assert_eq!(proof.summary.failed, 1);
231    }
232
233    #[test]
234    fn detects_gitlab_pat() {
235        let mut ext = ClaimExtractor::new("test_gl", None);
236        ext.verify_no_secrets_in_output("glpat-xxxxxxxxxxxxxxxxxxxx");
237        let proof = ext.finalize();
238        assert_eq!(proof.summary.failed, 1);
239    }
240
241    #[test]
242    fn detects_pem_private_key() {
243        let mut ext = ClaimExtractor::new("test_pem", None);
244        ext.verify_no_secrets_in_output("-----BEGIN RSA PRIVATE KEY-----");
245        let proof = ext.finalize();
246        assert_eq!(proof.summary.failed, 1);
247    }
248
249    #[test]
250    fn empty_signatures_passes() {
251        let mut ext = ClaimExtractor::new("test_empty", None);
252        ext.verify_signatures_preserved(&[], &[]);
253        let proof = ext.finalize();
254        assert_eq!(proof.summary.passed, 1);
255        assert_eq!(proof.summary.failed, 0);
256    }
257
258    #[test]
259    fn empty_imports_passes() {
260        let mut ext = ClaimExtractor::new("test_imp", None);
261        ext.verify_imports_preserved(&[], "some content");
262        let proof = ext.finalize();
263        assert_eq!(proof.summary.passed, 1);
264    }
265
266    #[test]
267    fn finalize_returns_correct_run_id() {
268        let ext = ClaimExtractor::new("my_run_42", Some("sess_7"));
269        let proof = ext.finalize();
270        assert_eq!(proof.run_id, "my_run_42");
271        assert_eq!(proof.session_id, Some("sess_7".to_string()));
272    }
273
274    #[test]
275    fn multiple_secret_patterns_all_detected() {
276        let mut ext = ClaimExtractor::new("test_multi", None);
277        ext.verify_no_secrets_in_output(concat!(
278            "AK",
279            "IAIOSFODNN7EXAMPLE1 and ",
280            "sk",
281            "-abcdefghijklmnopqrstuvwx and password=longvalue1234567890extra",
282        ));
283        let proof = ext.finalize();
284        assert_eq!(proof.summary.failed, 1);
285        assert!(proof.claims[0].text.contains("aws_key"));
286    }
287}