Skip to main content

lean_ctx/core/intelligence_runtime/
code_security.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Optional LeanCTX Cloud hints over a caller-admitted source snapshot. Detection
3//! remains private; the public host validates bounded findings and owns wording.
4
5use super::{InstallError, Result};
6
7pub(crate) const MAX_SOURCE_BYTES: usize = 65_536;
8const MAX_LINES: usize = 2048;
9const MAX_FINDINGS: usize = 8;
10
11#[derive(Debug, Eq, Ord, PartialEq, PartialOrd, serde::Deserialize)]
12#[serde(rename_all = "snake_case")]
13enum Rule {
14    ShellInterpretationEnabled,
15    TlsVerificationDisabled,
16}
17
18#[derive(serde::Deserialize)]
19#[serde(deny_unknown_fields)]
20struct Finding {
21    rule_id: Rule,
22    line: usize,
23}
24
25#[derive(serde::Deserialize)]
26#[serde(deny_unknown_fields)]
27struct Hints {
28    schema_version: u32,
29    strategy: String,
30    source_sha256: String,
31    supported: bool,
32    truncated: bool,
33    findings: Vec<Finding>,
34}
35
36fn language(path: &str) -> Option<&'static str> {
37    match std::path::Path::new(path).extension()?.to_str()? {
38        "py" | "pyi" => Some("python"),
39        "js" | "jsx" | "mjs" | "cjs" => Some("javascript"),
40        "ts" | "tsx" => Some("typescript"),
41        "go" => Some("go"),
42        "rs" => Some("rust"),
43        "cs" => Some("csharp"),
44        "java" => Some("java"),
45        _ => None,
46    }
47}
48
49pub fn enabled_for(path: &str) -> bool {
50    let config = crate::core::config::Config::load_global().intelligence_runtime;
51    language(path).is_some()
52        && config.enabled
53        && config.accept_proprietary
54        && super::bootstrap::permits_config(&config)
55}
56
57/// Never opens a path. The caller supplies the same safe source snapshot used
58/// by the read, before compression, and rechecks source/output authority later.
59/// The note is not a security verdict and must not be stored in source caches.
60pub fn note(path: &str, source: &str) -> Option<String> {
61    let language = language(path)?;
62    let config = crate::core::config::Config::load_global().intelligence_runtime;
63    if !config.enabled || !config.accept_proprietary || !super::bootstrap::permits_config(&config) {
64        return None;
65    }
66    if source.len() > MAX_SOURCE_BYTES
67        || source.lines().count() > MAX_LINES
68        || source.contains('\0')
69    {
70        return Some(
71            "LeanCTX code hints: not analyzed (source exceeds the supported text bounds).".into(),
72        );
73    }
74    Some(match invoke(&config, language, source) {
75        Ok(hints) => render(&hints),
76        Err(error) => unavailable(
77            super::lease::current_lease()
78                .as_ref()
79                .map(super::lease::RuntimeLeaseV1::as_bytes),
80            lean_ctx_time::UtcDateTime::now(),
81            &error,
82        ),
83    })
84}
85
86/// The runtime refuses without saying why, so the note names the likely cause
87/// from the lease the Engine holds. Its claims are read unverified, only to
88/// word this note: admission stays the runtime's own signature check.
89fn unavailable(
90    lease: Option<&[u8]>,
91    now: lean_ctx_time::UtcDateTime,
92    error: &InstallError,
93) -> String {
94    format!(
95        "LeanCTX code hints unavailable ({}); existing read protections are unchanged.",
96        unavailable_cause(lease, now, error)
97    )
98}
99
100fn unavailable_cause(
101    lease: Option<&[u8]>,
102    now: lean_ctx_time::UtcDateTime,
103    error: &InstallError,
104) -> String {
105    use lean_ctx_protocol::cloud::lease::{
106        CloudLeaseEnvelopeV1, CloudPlan, CloudRight, LeaseState,
107    };
108    let Some(bytes) = lease else {
109        return "no LeanCTX lease".into();
110    };
111    let Some(lease) = serde_json::from_slice::<serde_json::Value>(bytes)
112        .ok()
113        .and_then(|mut document| {
114            serde_json::from_value::<CloudLeaseEnvelopeV1>(document["lease"].take()).ok()
115        })
116        .and_then(|envelope| envelope.lease().ok())
117    else {
118        return "the LeanCTX lease is invalid".into();
119    };
120    // The runtime admits until the lease's grace ends, at most 24 h after expiry.
121    let runtime_grace_passed =
122        lean_ctx_time::OffsetDateTime::parse_from_rfc3339(lease.expires_at.as_str())
123            .is_ok_and(|expires| now >= expires + lean_ctx_time::Duration::hours(24));
124    if runtime_grace_passed || matches!(lease.state_at(now.fixed_offset()), Ok(LeaseState::Lapsed))
125    {
126        return "the LeanCTX lease has expired".into();
127    }
128    if matches!(lease.plan, CloudPlan::NoPlan | CloudPlan::Unknown) {
129        return "requires LeanCTX Personal".into();
130    }
131    if !lease.grants(CloudRight::Runtime) {
132        return "the LeanCTX lease does not include the runtime".into();
133    }
134    format!("runtime error: {error}")
135}
136
137fn render(hints: &Hints) -> String {
138    if !hints.supported {
139        return "LeanCTX code hints: no checks available for this language.".into();
140    }
141    if hints.findings.is_empty() {
142        return "LeanCTX code hints: no matching patterns in inspected source (limited static checks)."
143            .into();
144    }
145    let mut text = String::from("LeanCTX code hints (limited static checks; review required):");
146    for finding in &hints.findings {
147        let message = match finding.rule_id {
148            Rule::TlsVerificationDisabled => {
149                "TLS certificate verification is explicitly disabled; review connection trust."
150            }
151            Rule::ShellInterpretationEnabled => {
152                "Shell interpretation is enabled; review command construction and untrusted input."
153            }
154        };
155        // Lines refer to the policy-filtered snapshot, never a guessed original
156        // location after a rule has removed or replaced multiple source lines.
157        text.push_str(&format!(
158            "\n- Inspected source line {}: {message}",
159            finding.line
160        ));
161    }
162    if hints.truncated {
163        text.push_str("\nAdditional matching patterns were omitted at the finding limit.");
164    }
165    text
166}
167
168#[cfg(any(unix, windows, test))]
169fn validate(raw: &str, source: &str) -> Result<Hints> {
170    if raw.len() > 4096 {
171        return Err(InstallError::Exchange);
172    }
173    let hints: Hints = serde_json::from_str(raw).map_err(|_| InstallError::Exchange)?;
174    let lines = source.lines().count();
175    if hints.schema_version != 1
176        || hints.strategy != "bounded_static_v1"
177        || hints.source_sha256 != super::sha256(source.as_bytes())
178        || hints.findings.len() > MAX_FINDINGS
179        || (!hints.supported && (!hints.findings.is_empty() || hints.truncated))
180        || (hints.truncated && hints.findings.len() != MAX_FINDINGS)
181        || hints.findings.iter().any(|f| f.line == 0 || f.line > lines)
182        || hints
183            .findings
184            .windows(2)
185            .any(|pair| (pair[0].line, &pair[0].rule_id) >= (pair[1].line, &pair[1].rule_id))
186    {
187        return Err(InstallError::Exchange);
188    }
189    Ok(hints)
190}
191
192#[cfg(any(unix, windows))]
193fn invoke(
194    config: &crate::core::config::IntelligenceRuntimeConfig,
195    language: &str,
196    source: &str,
197) -> Result<Hints> {
198    use lean_ctx_protocol::runtime_exchange::{RuntimeRequestV1, RuntimeResponseV1};
199    use serde_json::json;
200    use std::{
201        path::Path,
202        time::{SystemTime, UNIX_EPOCH},
203    };
204    let root = Path::new(&config.root);
205    let trust = super::trust_key(&config.trust_key_hex)?;
206    let input =
207        json!({"schema_version":1,"language":language,"source":source,"max_findings":MAX_FINDINGS})
208            .to_string();
209    let binding = super::sha256(input.as_bytes());
210    let input_ref = format!("projection:sha256:{binding}");
211    let (request, executed) = super::session::invoke_built(
212        root,
213        &config.manifest_sha256,
214        &trust,
215        |package| {
216            if !super::health::supports_code_security(package) {
217                return Err(InstallError::Manifest);
218            }
219            let deadline = SystemTime::now()
220                .duration_since(UNIX_EPOCH)
221                .ok()
222                .and_then(|now| u64::try_from(now.as_millis()).ok())
223                .and_then(|now| now.checked_add(2000))
224                .ok_or(InstallError::Exchange)?;
225            let request: RuntimeRequestV1 = serde_json::from_value(json!({
226        "protocol_version":lean_ctx_protocol::runtime_exchange::RUNTIME_EXCHANGE_VERSION,
227        "session_id":format!("code-{binding}"),"request_id":format!("code-{binding}"),
228        "sequence":1,"deadline_unix_ms":deadline,"input":input,
229        "invocation":{"schema_version":1,"invocation_id":format!("code-{binding}"),
230            "engine":{"engine_id":"leanctx-intelligence","engine_version":package.receipt.version},
231            "operation":{"capability_id":"pro.runtime.code_security","capability_version":"1.0.0"},
232            "input_ref":input_ref,"input_digest":format!("sha256:{binding}"),"source_refs":[input_ref],
233            "policy_admission":{"decision":"admitted","policy_ref":format!("policy:code-{binding}")}}
234        })).map_err(|_| InstallError::Exchange)?;
235            Ok(request)
236        },
237    )?;
238    let response: RuntimeResponseV1 =
239        serde_json::from_value(executed["response"].clone()).map_err(|_| InstallError::Exchange)?;
240    response
241        .validate_for(&request)
242        .map_err(|_| InstallError::Exchange)?;
243    if response.observation.status != lean_ctx_protocol::EngineObservationStatusV1::Succeeded
244        || crate::core::config::Config::load_global().intelligence_runtime != *config
245        || super::install::active_manifest(root)? != config.manifest_sha256
246    {
247        return Err(InstallError::Exchange);
248    }
249    validate(
250        response.output.as_deref().ok_or(InstallError::Exchange)?,
251        source,
252    )
253}
254
255#[cfg(not(any(unix, windows)))]
256fn invoke(_: &crate::core::config::IntelligenceRuntimeConfig, _: &str, _: &str) -> Result<Hints> {
257    Err(InstallError::Exchange)
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    fn document(plan: &str, rights: &[&str], issued: lean_ctx_time::UtcDateTime) -> Vec<u8> {
265        use base64::Engine as _;
266        use lean_ctx_protocol::cloud::lease::{CloudLeaseEnvelopeV1, CloudLeaseV1, LEASE_SCHEMA};
267        let at = |offset: lean_ctx_time::Duration| {
268            lean_ctx_protocol::UtcTimestamp::new(
269                (issued + offset).to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
270            )
271            .unwrap()
272        };
273        let lease = CloudLeaseV1 {
274            schema: LEASE_SCHEMA.into(),
275            lease_id: "lease-1".into(),
276            org_id: "org-1".into(),
277            instance_id: "instance-1".into(),
278            plan: serde_json::from_value(serde_json::json!(plan)).unwrap(),
279            seats_limit: 2,
280            rights: serde_json::from_value(serde_json::json!(rights)).unwrap(),
281            issued_at: at(lean_ctx_time::Duration::zero()),
282            expires_at: at(lean_ctx_time::Duration::hours(23)),
283            grace_until: at(lean_ctx_time::Duration::days(7)),
284            server_time: at(lean_ctx_time::Duration::zero()),
285            org_settings: None,
286            trial_ends_at: None,
287        };
288        let signature = base64::engine::general_purpose::STANDARD.encode([0u8; 64]);
289        let envelope = CloudLeaseEnvelopeV1::seal(&lease, "k", signature).unwrap();
290        serde_json::to_vec(
291            &serde_json::json!({"schema": "leanctx.cloud.runtime-lease/v1", "lease": envelope}),
292        )
293        .unwrap()
294    }
295
296    #[test]
297    fn unavailable_hints_name_the_lease_cause() {
298        let now = lean_ctx_time::UtcDateTime::now();
299        let fresh = now - lean_ctx_time::Duration::hours(1);
300        let error = InstallError::Exchange;
301        let cause = |lease: Option<&[u8]>, at| unavailable(lease, at, &error);
302        assert_eq!(
303            cause(None, now),
304            "LeanCTX code hints unavailable (no LeanCTX lease); existing read protections are unchanged."
305        );
306        assert!(
307            cause(Some(b"not a lease".as_slice()), now).contains("(the LeanCTX lease is invalid)")
308        );
309        let personal = document("personal", &["runtime"], fresh);
310        assert!(
311            cause(Some(personal.as_slice()), now).contains(&format!("(runtime error: {error})"))
312        );
313        // Past the runtime's 24 h after expiry, even inside the lease's grace.
314        assert!(
315            cause(
316                Some(personal.as_slice()),
317                fresh + lean_ctx_time::Duration::hours(48)
318            )
319            .contains("(the LeanCTX lease has expired)")
320        );
321        assert!(
322            cause(Some(document("none", &["runtime"], fresh).as_slice()), now)
323                .contains("(requires LeanCTX Personal)")
324        );
325        assert!(
326            cause(
327                Some(document("team", &["knowledge.read"], fresh).as_slice()),
328                now
329            )
330            .contains("(the LeanCTX lease does not include the runtime)")
331        );
332    }
333
334    #[test]
335    fn private_findings_cannot_change_source_or_inject_text() {
336        let source = "first\nsecond\n";
337        let valid = serde_json::json!({"schema_version":1,"strategy":"bounded_static_v1",
338            "source_sha256":super::super::sha256(source.as_bytes()),"supported":true,"truncated":false,
339            "findings":[{"rule_id":"tls_verification_disabled","line":2}]});
340        let rendered = render(&validate(&valid.to_string(), source).unwrap());
341        assert!(rendered.contains("Inspected source line 2"));
342        for (field, replacement) in [
343            ("source_sha256", serde_json::json!("other")),
344            ("supported", serde_json::json!(false)),
345            ("truncated", serde_json::json!(true)),
346            (
347                "findings",
348                serde_json::json!([{"rule_id":"tls_verification_disabled","line":0}]),
349            ),
350            (
351                "findings",
352                serde_json::json!([{"rule_id":"tls_verification_disabled","line":3}]),
353            ),
354            (
355                "findings",
356                serde_json::json!([{"rule_id":"secret text","line":1}]),
357            ),
358            (
359                "findings",
360                serde_json::json!([{"rule_id":"tls_verification_disabled","line":1,"source":"secret"}]),
361            ),
362            (
363                "findings",
364                serde_json::json!([{"rule_id":"tls_verification_disabled","line":2},{"rule_id":"tls_verification_disabled","line":2}]),
365            ),
366        ] {
367            let mut invalid = valid.clone();
368            invalid[field] = replacement;
369            assert!(validate(&invalid.to_string(), source).is_err(), "{field}");
370        }
371    }
372}