lean-ctx-engine 3.12.7

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use std::path::{Path, PathBuf};

use crate::core::{events, pathjail, roles};

/// Reads a file without following symlinks (TOCTOU protection).
/// Falls back to regular read on non-Unix platforms.
#[cfg(unix)]
pub fn read_file_nofollow(path: &str) -> Result<String, std::io::Error> {
    use std::os::unix::fs::OpenOptionsExt;
    let file = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_NOFOLLOW)
        .open(path);
    match file {
        Ok(mut f) => {
            use std::io::Read;
            let mut buf = Vec::new();
            f.read_to_end(&mut buf)?;
            Ok(crate::core::text_decode::decode(buf))
        }
        Err(e) if e.raw_os_error() == Some(libc::ELOOP) => Err(std::io::Error::other(format!(
            "Symlink detected at {path} — refusing to follow (TOCTOU protection)"
        ))),
        Err(e) => Err(e),
    }
}

/// Windows parity (GL#442): no O_NOFOLLOW exists, so lstat first and refuse
/// symlinks *and* NTFS junctions/reparse points before opening. Small TOCTOU
/// window remains between the check and the open (documented in SECURITY.md).
#[cfg(not(unix))]
pub fn read_file_nofollow(path: &str) -> Result<String, std::io::Error> {
    if let Ok(meta) = std::fs::symlink_metadata(path) {
        if crate::core::pathutil::is_symlink_or_reparse(&meta) {
            return Err(std::io::Error::other(format!(
                "Symlink detected at {path} — refusing to follow (TOCTOU protection)"
            )));
        }
    }
    std::fs::read(path).map(crate::core::text_decode::decode)
}

/// Reads a file as text in any encoding (`text_decode`: UTF-8 with or without
/// BOM, UTF-16 with BOM, Windows-1252), rejecting binary files. The BOM is
/// stripped — leaking it corrupts the first line of every downstream view
/// (limitations doc #11).
/// Uses O_NOFOLLOW on Unix to prevent TOCTOU symlink attacks.
pub fn read_file_lossy(path: &str) -> Result<String, std::io::Error> {
    if crate::core::binary_detect::is_binary_file(path) {
        let msg = crate::core::binary_detect::binary_file_message(path);
        return Err(std::io::Error::other(msg));
    }
    read_file_nofollow(path)
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BoundaryMode {
    Warn,
    Enforce,
}

impl BoundaryMode {
    fn parse(s: &str) -> Self {
        match s.trim().to_lowercase().as_str() {
            "enforce" | "strict" => Self::Enforce,
            _ => Self::Warn,
        }
    }
}

pub fn boundary_mode_effective(role: &roles::Role) -> BoundaryMode {
    if let Ok(v) = std::env::var("LEAN_CTX_IO_BOUNDARY_MODE")
        && !v.trim().is_empty()
    {
        return BoundaryMode::parse(&v);
    }
    BoundaryMode::parse(&role.io.boundary_mode)
}

/// The name of LeanCTX Code's app key file in `<data dir>/agents/`.
pub const APP_KEY_FILE: &str = "app-launch.key";

/// The files only LeanCTX Code may read: its app key and the release ids of
/// offered plan directives (§37.9), a damaged copy set aside (`….damaged`)
/// included. Unlike the other secret-like paths, neither a role that allows
/// secret paths (`admin`) nor the warn boundary mode opens them to an
/// agent's read, search or listing tool.
pub fn app_only_secret(path: &Path) -> Option<&'static str> {
    let lower = path
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("")
        .to_lowercase();
    if lower == APP_KEY_FILE {
        return Some("LeanCTX app key");
    }
    if lower.starts_with(crate::core::agents::RELEASE_IDS_FILE) {
        return Some("LeanCTX release ids");
    }
    None
}

/// Whether a read, search or listing tool leaves `path` out: an app-only
/// secret always ([`app_only_secret`]), any other secret-like path unless
/// the role allows secret paths.
pub fn withheld_secret(path: &Path, allow_secret_paths: bool) -> Option<&'static str> {
    app_only_secret(path).or_else(|| {
        if allow_secret_paths {
            None
        } else {
            is_secret_like(path)
        }
    })
}

pub fn is_secret_like(path: &Path) -> Option<&'static str> {
    let file = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
    let lower = file.to_lowercase();

    // Directory-level sensitive roots
    for comp in path.components() {
        if let std::path::Component::Normal(s) = comp {
            let c = s.to_string_lossy().to_lowercase();
            if c == ".ssh" {
                return Some(".ssh directory");
            }
            if c == ".aws" {
                return Some(".aws directory");
            }
            if c == ".gnupg" {
                return Some(".gnupg directory");
            }
        }
    }

    // Common secret-like files (deny-by-default unless explicitly allowed).
    if lower == ".env" {
        return Some(".env file");
    }
    if lower.starts_with(".env.") {
        let allow_suffixes = [".example", ".sample", ".template", ".dist", ".defaults"];
        if allow_suffixes.iter().any(|s| lower.ends_with(s)) {
            return None;
        }
        return Some(".env.* file");
    }

    if matches!(
        lower.as_str(),
        "id_rsa"
            | "id_ed25519"
            | "id_ecdsa"
            | "id_dsa"
            | "authorized_keys"
            | "known_hosts"
            | ".npmrc"
            | ".netrc"
            | ".pypirc"
            | ".dockerconfigjson"
            | "credentials.json"
            | "secrets.json"
            | "secrets.yaml"
            | "secrets.yml"
            | "keystore.jks"
            | "truststore.jks"
            | ".htpasswd"
            | "shadow"
            | "master.key"
    ) {
        return Some("credential file");
    }

    if let Some(reason) = app_only_secret(path) {
        return Some(reason);
    }

    if lower.starts_with("service-account") {
        let p = std::path::Path::new(&lower);
        if p.extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("json") || ext.eq_ignore_ascii_case("key"))
        {
            return Some("service account key");
        }
    }

    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
    let secret_exts = ["pem", "key", "p12", "pfx", "kdbx"];
    if secret_exts.iter().any(|e| ext.eq_ignore_ascii_case(e)) {
        return Some("secret key material");
    }

    // AWS credentials file (often inside .aws/)
    if lower == "credentials" && path.to_string_lossy().to_lowercase().contains("/.aws/") {
        return Some("aws credentials");
    }

    None
}

/// The project whose Cloud I/O rules apply when the caller names none: the
/// request's bound project, else the configured or detected project of the
/// working directory ([`crate::core::protocol::detect_project_root_or_cwd`]).
fn current_project() -> PathBuf {
    if let Some(project) = crate::core::policy::diagnostics::request_project() {
        return project;
    }
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    PathBuf::from(crate::core::protocol::detect_project_root_or_cwd(
        &cwd.to_string_lossy(),
    ))
}

/// The Cloud I/O rules (`security.readable_roots`, `security.never_send`) in
/// force for `project` (default: `current_project`). `Err` when the
/// installed Cloud policy cannot be applied: callers fail closed.
pub fn cloud_io_rules(
    project: Option<&Path>,
) -> Result<Option<crate::core::policy::cloud_io::IoRules>, String> {
    let project = project.map_or_else(current_project, Path::to_path_buf);
    crate::core::policy::cloud_io::rules_for(&project)
}

/// Refuse reading `path` when the Cloud policy keeps it out of context: outside
/// the readable roots, matching `never_send`, or (fail closed) the installed
/// policy cannot be applied. Always enforced: neither the role nor the warn
/// boundary mode loosens a Cloud rule.
pub fn check_cloud_io_for_tool(
    tool: &str,
    path: &Path,
    project: Option<&Path>,
) -> Result<(), String> {
    let refusal = match cloud_io_rules(project) {
        Ok(None) => return Ok(()),
        Ok(Some(rules)) => match rules.refusal(path) {
            None => return Ok(()),
            Some(refusal) => format!(
                "[I/O BOUNDARY] {} is {}.",
                path.display(),
                refusal.describe()
            ),
        },
        Err(e) => format!(
            "[I/O BOUNDARY] {} refused: {e}; reads stay refused until a valid LeanCTX Cloud policy is installed.",
            path.display()
        ),
    };
    events::emit_policy_violation(&roles::active_role_name(), tool, &refusal);
    Err(format!("ERROR: {refusal}"))
}

/// The Cloud I/O rules ([`check_cloud_io_for_tool`]) and then the role's
/// secret-path rule, for a path read in the current project.
pub fn check_secret_path_for_tool(tool: &str, path: &Path) -> Result<Option<String>, String> {
    check_cloud_io_for_tool(tool, path, None)?;
    secret_path_rule(tool, path)
}

fn secret_path_rule(tool: &str, path: &Path) -> Result<Option<String>, String> {
    let role_name = roles::active_role_name();
    let role = roles::active_role();
    let mode = boundary_mode_effective(&role);

    if let Some(reason) = app_only_secret(path) {
        let msg = format!(
            "[I/O BOUNDARY] {} is the {reason}: only LeanCTX Code reads it, under every role and boundary mode.",
            path.display()
        );
        events::emit_policy_violation(&role_name, tool, &msg);
        return Err(format!("ERROR: {msg}"));
    }

    let Some(reason) = is_secret_like(path) else {
        return Ok(None);
    };

    if role.io.allow_secret_paths {
        return Ok(None);
    }

    let msg = format!(
        "[I/O BOUNDARY] Secret-like path detected ({reason}): {}.\n\
Role: {role_name}. To allow: switch role to 'admin' or set io.allow_secret_paths=true in the active role.",
        path.display()
    );
    events::emit_policy_violation(&role_name, tool, &msg);
    // K12: the secret-path rule refused (enforce) or would have (warn).
    crate::core::cloud_signals::refused(
        &crate::core::cloud_signals::secrets_rule(),
        matches!(mode, BoundaryMode::Enforce),
    );

    match mode {
        BoundaryMode::Enforce => Err(format!("ERROR: {msg}")),
        BoundaryMode::Warn => {
            if crate::core::protocol::meta_visible() {
                Ok(Some(format!("[BOUNDARY WARNING] {msg}")))
            } else {
                Ok(None)
            }
        }
    }
}

pub fn jail_and_check_path(
    tool: &str,
    candidate: &Path,
    jail_root: &Path,
) -> Result<(PathBuf, Option<String>), String> {
    let (jailed, warning) = jail_and_check_with(tool, candidate, jail_root, pathjail::jail_path)?;
    check_cloud_io_for_tool(tool, &jailed, Some(jail_root))?;
    Ok((jailed, warning))
}

/// [`jail_and_check_path`] for a destination that stays contained when the
/// jail is compiled out (`no-jail`) or disabled (`path_jail = false`); see
/// [`pathjail::jail_path_enforced`].
pub fn jail_and_check_export_path(
    tool: &str,
    candidate: &Path,
    jail_root: &Path,
) -> Result<(PathBuf, Option<String>), String> {
    jail_and_check_with(tool, candidate, jail_root, pathjail::jail_path_enforced)
}

fn jail_and_check_with(
    tool: &str,
    candidate: &Path,
    jail_root: &Path,
    jail: fn(&Path, &Path) -> Result<PathBuf, crate::core::error::PathJailError>,
) -> Result<(PathBuf, Option<String>), String> {
    let role_name = roles::active_role_name();
    let jailed = jail(candidate, jail_root).map_err(|e| {
        // Only a real jail escape is a security event. A path that simply doesn't exist
        // (stale graph entry, removed file) is benign — emitting a policy violation for it
        // spams the event feed and mislabels missing files as denials.
        if !matches!(
            e,
            crate::core::error::PathJailError::NoExistingAncestor { .. }
        ) {
            let msg = format!("pathjail denied: {} ({e})", candidate.display());
            events::emit_policy_violation(&role_name, tool, &msg);
        }
        e.to_string()
    })?;
    let warning = secret_path_rule(tool, &jailed)?;
    Ok((jailed, warning))
}

pub fn ensure_ignore_gitignore_allowed(tool: &str) -> Result<(), String> {
    let role_name = roles::active_role_name();
    let role = roles::active_role();
    if role.io.allow_ignore_gitignore {
        return Ok(());
    }
    let msg = format!(
        "[I/O BOUNDARY] ignore_gitignore requires explicit policy.\n\
Role '{role_name}' does not allow scanning .gitignore'd paths. \
An agent cannot escalate to a privileged role at runtime, so configure this where lean-ctx starts:\n\
- set LEAN_CTX_ROLE=admin, or\n\
- add `io.allow_ignore_gitignore = true` to a role file (~/.lean-ctx/roles/<name>.toml), then select it via LEAN_CTX_ROLE.\n\
Docs: https://leanctx.com/docs/security/#ignore-gitignore"
    );
    events::emit_policy_violation(&role_name, tool, &msg);
    Err(format!("ERROR: {msg}"))
}

#[cfg(test)]
pub mod tests {
    use super::*;

    #[cfg(unix)]
    #[test]
    fn nofollow_rejects_symlink() {
        let dir = tempfile::tempdir().unwrap();
        let real = dir.path().join("real.txt");
        std::fs::write(&real, "secret").unwrap();
        let link = dir.path().join("link.txt");
        std::os::unix::fs::symlink(&real, &link).unwrap();
        let result = read_file_nofollow(&link.to_string_lossy());
        assert!(result.is_err());
    }

    #[test]
    fn nofollow_reads_regular_file() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("regular.txt");
        std::fs::write(&file, "hello").unwrap();
        let content = read_file_nofollow(&file.to_string_lossy()).unwrap();
        assert_eq!(content, "hello");
    }

    /// The app key and the release ids stay closed to an agent's read tools
    /// under the admin role and the warn mode, which open every other
    /// secret-like path.
    #[test]
    fn app_only_secrets_stay_refused_for_admin_and_in_warn_mode() {
        let admin = roles::load_role("admin").expect("builtin admin role");
        assert!(admin.io.allow_secret_paths, "admin opens secret paths");
        for mode in ["enforce", "warn"] {
            let _mode = crate::test_env::EnvVarGuard::set("LEAN_CTX_IO_BOUNDARY_MODE", mode);
            roles::with_test_active_role(admin.clone(), || {
                for name in [
                    APP_KEY_FILE,
                    crate::core::agents::RELEASE_IDS_FILE,
                    "directive-release-ids.json.damaged",
                ] {
                    let path = Path::new("/d/agents").join(name);
                    let refused = secret_path_rule("ctx_read", &path)
                        .expect_err("an app-only secret is refused");
                    assert!(refused.contains("only LeanCTX Code"), "{refused}");
                    assert!(withheld_secret(&path, true).is_some(), "{name}");
                }
                // Every other secret-like path stays open to admin.
                let env = Path::new("/p/.env");
                assert_eq!(secret_path_rule("ctx_read", env), Ok(None), "{mode}");
                assert_eq!(withheld_secret(env, true), None);
            });
        }
    }

    #[test]
    fn env_is_secret_like() {
        assert_eq!(is_secret_like(Path::new(".env")), Some(".env file"));
        assert_eq!(is_secret_like(Path::new(".env.local")), Some(".env.* file"));
        assert_eq!(is_secret_like(Path::new(".env.example")), None);
    }

    #[test]
    fn key_is_secret_like() {
        assert_eq!(
            is_secret_like(Path::new("key.pem")),
            Some("secret key material")
        );
        assert_eq!(
            is_secret_like(Path::new("cert.KEY")),
            Some("secret key material")
        );
    }

    #[test]
    fn credentials_json_is_secret_like() {
        assert_eq!(
            is_secret_like(Path::new("credentials.json")),
            Some("credential file")
        );
        assert_eq!(
            is_secret_like(Path::new("secrets.yaml")),
            Some("credential file")
        );
    }

    #[test]
    fn service_account_is_secret_like() {
        assert_eq!(
            is_secret_like(Path::new("service-account.json")),
            Some("service account key")
        );
        assert_eq!(
            is_secret_like(Path::new("service-account-prod.key")),
            Some("service account key")
        );
    }

    #[test]
    fn htpasswd_and_shadow_are_secret_like() {
        assert_eq!(
            is_secret_like(Path::new(".htpasswd")),
            Some("credential file")
        );
        assert_eq!(is_secret_like(Path::new("shadow")), Some("credential file"));
    }

    // The CLI full-read path (`cli_cache::check_and_read`) reads through THIS
    // `read_file_lossy`, not the ctx_read one — both must strip the UTF-8 BOM
    // or the CLI leaks it while the MCP path doesn't (limitations doc #11).
    #[test]
    fn read_file_lossy_strips_utf8_bom() {
        let p = std::env::temp_dir().join("lean_ctx_io_bom_test.txt");
        std::fs::write(&p, b"\xEF\xBB\xBFhello\n").unwrap();
        let s = read_file_lossy(p.to_str().unwrap()).unwrap();
        let _ = std::fs::remove_file(&p);
        assert!(!s.starts_with('\u{feff}'), "BOM must be stripped");
        assert!(s.starts_with("hello"));
    }
}