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