ralon 0.1.5

Filesystem policy for AI coding agents: kernel-enforced write protection driven by an agent.lock file
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! End-to-end tests for the parts of the CLI that work on every platform.

use std::fs;
use std::path::PathBuf;
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};

const BINARY: &str = env!("CARGO_BIN_EXE_ralon");

/// A throwaway project directory, removed on drop.
struct Project {
    root: PathBuf,
}

impl Project {
    fn new(policy: Option<&str>) -> Project {
        static COUNTER: AtomicU32 = AtomicU32::new(0);
        let unique = format!(
            "ralon-test-{}-{}",
            std::process::id(),
            COUNTER.fetch_add(1, Ordering::Relaxed)
        );
        let root = std::env::temp_dir().join(unique);
        fs::create_dir_all(&root).unwrap();

        let project = Project { root };
        if let Some(policy) = policy {
            project.write("agent.lock", policy);
        }
        project
    }

    fn write(&self, relative: &str, contents: &str) -> PathBuf {
        let path = self.root.join(relative);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, contents).unwrap();
        path
    }

    fn run(&self, arguments: &[&str]) -> Output {
        Command::new(BINARY)
            .arg("--dir")
            .arg(&self.root)
            .args(arguments)
            // `run` hands the command the working directory it was given, so a
            // test that leaves this at the harness's cwd is testing the repo,
            // not the project — which is how the first version of the Windows
            // test passed while protecting nothing.
            .current_dir(&self.root)
            .output()
            .expect("failed to run ralon")
    }

    /// A command run *outside* Ralon, the way an agent someone launched from
    /// an IDE is outside it.
    #[cfg(windows)]
    fn shell(&self, command: &str) {
        Command::new("cmd")
            .args(["/c", command])
            .current_dir(&self.root)
            .output()
            .expect("failed to run cmd");
    }
}

impl Drop for Project {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.root);
    }
}

fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

fn stderr(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).into_owned()
}

fn code(output: &Output) -> i32 {
    output.status.code().expect("process was killed")
}

const POLICY: &str = "version: 1\nprotect:\n  - src/index.tsx\n  - .env\n  - config/**\n";

#[test]
fn init_writes_a_usable_policy_and_refuses_to_clobber_it() {
    let project = Project::new(None);

    let created = project.run(&["init"]);
    assert_eq!(code(&created), 0, "{}", stderr(&created));
    assert!(project.root.join("agent.lock").is_file());

    let again = project.run(&["init"]);
    assert_eq!(code(&again), 2);
    assert!(
        stderr(&again).contains("already exists"),
        "{}",
        stderr(&again)
    );

    // The generated file must be valid input for the tool itself.
    let status = project.run(&["status"]);
    assert_eq!(code(&status), 0, "{}", stderr(&status));
}

#[test]
fn check_reports_protected_paths_and_exits_nonzero() {
    let project = Project::new(Some(POLICY));

    let protected = project.run(&["check", "src/index.tsx"]);
    assert_eq!(code(&protected), 1);
    assert!(
        stdout(&protected).contains("locked"),
        "{}",
        stdout(&protected)
    );

    let writable = project.run(&["check", "src/App.tsx"]);
    assert_eq!(code(&writable), 0);
    assert!(stdout(&writable).contains("writable"));
}

#[test]
fn check_protects_the_policy_file_itself() {
    let project = Project::new(Some(POLICY));
    let output = project.run(&["check", "agent.lock"]);
    assert_eq!(code(&output), 1, "{}", stdout(&output));
}

#[test]
fn check_covers_paths_inside_a_protected_directory() {
    let project = Project::new(Some(POLICY));
    let output = project.run(&["check", "config/deep/db.yaml", "src/App.tsx"]);
    assert_eq!(code(&output), 1);
    let text = stdout(&output);
    assert!(text.contains("locked    config/deep/db.yaml"), "{text}");
    assert!(text.contains("writable  src/App.tsx"), "{text}");
}

#[test]
fn check_notices_paths_outside_the_project() {
    let project = Project::new(Some(POLICY));
    let output = project.run(&["check", "../elsewhere.txt"]);
    assert_eq!(code(&output), 0);
    assert!(stdout(&output).contains("outside"), "{}", stdout(&output));
}

#[test]
fn check_without_arguments_lists_what_exists() {
    let project = Project::new(Some(POLICY));
    project.write("src/index.tsx", "locked\n");
    project.write("src/App.tsx", "writable\n");
    project.write("config/db.yaml", "locked\n");

    let output = project.run(&["check"]);
    let text = stdout(&output);
    assert_eq!(code(&output), 0, "{}", stderr(&output));
    assert!(text.contains("agent.lock"), "{text}");
    assert!(text.contains("src/index.tsx"), "{text}");
    // A protected directory is listed once, not expanded entry by entry.
    assert!(text.contains("config/"), "{text}");
    assert!(!text.contains("config/db.yaml"), "{text}");
    assert!(!text.contains("App.tsx"), "{text}");
    // `.env` is declared but absent, so there is nothing to lock.
    assert!(
        stderr(&output).contains("`.env` matches nothing"),
        "{}",
        stderr(&output)
    );
}

#[test]
fn commands_find_the_policy_from_a_subdirectory() {
    let project = Project::new(Some(POLICY));
    project.write("src/deep/nested.txt", "x\n");

    let output = Command::new(BINARY)
        .arg("--dir")
        .arg(project.root.join("src").join("deep"))
        .args(["check", "../index.tsx"])
        .output()
        .unwrap();

    assert_eq!(output.status.code(), Some(1), "{}", stdout(&output));
}

#[test]
fn missing_policy_is_an_error_not_a_silent_pass() {
    let project = Project::new(None);
    let output = project.run(&["check", "anything.txt"]);
    assert_eq!(code(&output), 2);
    assert!(
        stderr(&output).contains("no agent.lock"),
        "{}",
        stderr(&output)
    );
}

#[test]
fn a_broken_policy_stops_everything() {
    let project = Project::new(Some("version: 1\nprotect:\n  - ../escape\n"));
    let output = project.run(&["check", "src/App.tsx"]);
    assert_eq!(code(&output), 2);
    assert!(stderr(&output).contains(".."), "{}", stderr(&output));
}

#[test]
fn dry_run_describes_what_would_be_locked() {
    let project = Project::new(Some(POLICY));
    project.write("src/index.tsx", "locked\n");
    project.write("config/db.yaml", "locked\n");

    let output = project.run(&["run", "--dry-run", "--", "echo", "hello"]);
    let text = stdout(&output);
    assert!(text.contains("read-only  src/index.tsx"), "{text}");
    assert!(text.contains("read-only  config/"), "{text}");
    assert!(text.contains("read-only  agent.lock"), "{text}");
    assert!(text.contains("echo hello"), "{text}");

    // The plan is always shown. Whether it could be enforced depends on the
    // kernel, and the tool must say which instead of pretending either way.
    match code(&output) {
        0 => assert!(!text.contains("would fail"), "{text}"),
        1 => assert!(text.contains("would fail"), "{text}"),
        other => panic!("unexpected exit code {other}\n{text}\n{}", stderr(&output)),
    }
}

#[test]
fn status_lists_backends() {
    let project = Project::new(Some(POLICY));
    let output = project.run(&["status"]);
    let text = stdout(&output);
    assert_eq!(code(&output), 0, "{}", stderr(&output));
    assert!(text.contains("backends"), "{text}");
    assert!(text.contains("mount"), "{text}");
    assert!(text.contains("landlock"), "{text}");
    assert!(text.contains("version    1"), "{text}");
}

/// Windows enforcement, for real: the protected file is held open, so anything
/// that tries to write it gets a sharing violation. This is the counterpart of
/// `tests/enforcement.rs`, which can only run on Linux.
#[test]
#[cfg(windows)]
fn windows_locks_stop_a_write_from_any_process() {
    let project = Project::new(Some(POLICY));
    let secret = project.write(".env", "SECRET=original\n");
    project.write("src/App.tsx", "writable\n");

    // cmd.exe is not an agent and has never heard of a policy — which is the
    // point. The backend blocks processes, not tools that opted in.
    let blocked = project.run(&["run", "--quiet", "--", "cmd", "/c", "echo hacked > .env"]);
    assert_ne!(code(&blocked), 0, "the write should have failed");
    assert_eq!(
        fs::read_to_string(&secret).unwrap(),
        "SECRET=original\n",
        "a protected file was modified"
    );

    // Deleting needs FILE_SHARE_DELETE, which the lock does not grant. `del`
    // reports success even when it failed, so the file on disk is the only
    // thing worth asserting on.
    project.run(&["run", "--quiet", "--", "cmd", "/c", "del /q .env"]);
    assert!(secret.is_file(), "a protected file was deleted");
    assert_eq!(fs::read_to_string(&secret).unwrap(), "SECRET=original\n");

    // Renaming it away is the same operation to Windows, and equally refused.
    project.run(&["run", "--quiet", "--", "cmd", "/c", "ren .env moved.txt"]);
    assert!(secret.is_file(), "a protected file was renamed away");

    // And ordinary work still goes through, or the backend is useless.
    let allowed = project.run(&[
        "run",
        "--quiet",
        "--",
        "cmd",
        "/c",
        "echo edited > src\\App.tsx",
    ]);
    assert_eq!(code(&allowed), 0, "{}", stderr(&allowed));
    assert!(fs::read_to_string(project.root.join("src/App.tsx"))
        .unwrap()
        .contains("edited"));
}

/// The gap a handle cannot reach: creating a *new* entry inside a protected
/// directory opens no existing object, so no share mode is consulted. A deny
/// ACE covers it, and has to come off again afterwards.
#[test]
#[cfg(windows)]
fn windows_refuses_new_files_in_a_protected_directory() {
    let project = Project::new(Some(POLICY));
    project.write("config/db.yaml", "locked\n");

    for attack in [
        "echo hacked > config\\new.yaml",
        "mkdir config\\sneaky",
        "echo hacked > config\\nested\\deep.yaml",
    ] {
        project.run(&["run", "--quiet", "--", "cmd", "/c", attack]);
    }

    assert!(
        !project.root.join("config/new.yaml").exists(),
        "a new file appeared inside a protected directory"
    );
    assert!(!project.root.join("config/sneaky").exists());
    assert!(!project.root.join("config/nested").exists());

    // Renaming an existing entry needs the same right, so it goes too.
    project.run(&[
        "run",
        "--quiet",
        "--",
        "cmd",
        "/c",
        "ren config\\db.yaml x.yaml",
    ]);
    assert!(project.root.join("config/db.yaml").is_file());

    // And the directory is an ordinary directory again once nothing is
    // running. Leaving a permission behind would be worse than the gap.
    fs::write(project.root.join("config/after.yaml"), "fine")
        .expect("the ACL should have been restored when the command finished");
}

/// A file something else is using is the wrong thing to protect — a live
/// database, a log a dev server appends to. Ralon cannot lock it, and finding
/// that out when `run` fails is worse than being told beforehand.
#[test]
#[cfg(windows)]
fn a_file_already_in_use_is_reported_before_it_becomes_a_failure() {
    use std::os::windows::fs::OpenOptionsExt;
    const FILE_SHARE_READ: u32 = 0x0000_0001;

    let project = Project::new(Some("version: 1\nprotect:\n  - app.db\n"));
    let database = project.write("app.db", "rows\n");

    let quiet = stderr(&project.run(&["status"]));
    assert!(!quiet.contains("app.db is held open"), "{quiet}");

    // Opened for writing and shared only for reading: what a running database
    // does, and what makes the lock impossible to take.
    let holder = fs::OpenOptions::new()
        .read(true)
        .write(true)
        .share_mode(FILE_SHARE_READ)
        .open(&database)
        .unwrap();

    let warned = stderr(&project.run(&["status"]));
    assert!(warned.contains("app.db is held open"), "{warned}");

    // And it refuses to run rather than reporting a path as locked when it is
    // not. A failure to enforce is never silent.
    let refused = project.run(&["run", "--quiet", "--", "cmd.exe", "/c", "ver"]);
    assert_eq!(code(&refused), 2, "{}", stderr(&refused));

    drop(holder);
    let quiet_again = stderr(&project.run(&["status"]));
    assert!(
        !quiet_again.contains("app.db is held open"),
        "{quiet_again}"
    );
}

/// The guard: protection with no command to wrap, which is the only way to
/// cover an agent started from an IDE, an extension, or another terminal.
#[test]
#[cfg(windows)]
fn windows_guard_protects_a_process_it_did_not_start() {
    let project = Project::new(Some(POLICY));
    let secret = project.write(".env", "SECRET=original\n");
    project.write("src/App.tsx", "writable\n");

    // Nothing is guarding yet, so this must succeed — otherwise the assertion
    // below proves nothing.
    project.shell("echo unguarded > .env");
    assert!(fs::read_to_string(&secret).unwrap().contains("unguarded"));
    fs::write(&secret, "SECRET=original\n").unwrap();

    let started = project.run(&["guard", "--detach"]);
    assert_eq!(code(&started), 0, "{}", stderr(&started));

    let status = stdout(&project.run(&["status"]));
    assert!(status.contains("guard      running"), "{status}");

    // No `ralon run` anywhere: an ordinary process, started the ordinary way.
    project.shell("echo hacked > .env");
    project.shell("del /q .env");
    project.shell("echo x > config\\new.yaml");
    let held = fs::read_to_string(&secret).unwrap() == "SECRET=original\n"
        && !project.root.join("config/new.yaml").exists();

    // Released before asserting, so a failure does not leave a guard holding
    // the directory this test is about to delete.
    let stopped = project.run(&["guard", "--stop"]);
    assert!(held, "a guarded path was modified by an unwrapped process");
    assert_eq!(code(&stopped), 0, "{}", stderr(&stopped));

    project.shell("echo released > .env");
    assert!(fs::read_to_string(&secret).unwrap().contains("released"));
}

/// A failure to enforce is never silent, and never partial: if the requested
/// backend cannot be applied, the command does not start at all.
///
/// This used to run only where *no* backend existed, which meant it stopped
/// testing anything the moment macOS gained one — and it failed by trying to
/// launch a Windows shell on a Mac. Asking for a backend that cannot exist on
/// this platform tests the same refusal, and every platform has one of those.
#[test]
fn run_refuses_rather_than_running_unprotected_when_the_backend_is_unavailable() {
    let project = Project::new(Some(POLICY));
    project.write("src/index.tsx", "locked\n");

    // `locks` is a Windows idea; `mount` is a Linux one. Neither exists on the
    // other platforms, and `resolve` has to say so rather than panicking on a
    // backend its own table does not list.
    let elsewhere = if cfg!(target_os = "linux") {
        "locks"
    } else {
        "mount"
    };

    let marker = project.root.join("should-not-exist.txt");
    let (shell, flag, script) = if cfg!(windows) {
        ("cmd", "/c", format!("type nul > {}", marker.display()))
    } else {
        ("sh", "-c", format!("touch '{}'", marker.display()))
    };

    let output = project.run(&["run", "--backend", elsewhere, "--", shell, flag, &script]);

    assert_eq!(code(&output), 2, "{}", stdout(&output));
    // The refusal has to say what is missing, or the reader concludes the
    // policy is protecting them when nothing is.
    let explanation = stderr(&output);
    assert!(explanation.contains("unavailable"), "{explanation}");
    assert!(!marker.exists(), "the command must not have run");
}

#[test]
fn hook_install_writes_a_hook_that_refuses_protected_paths() {
    let project = Project::new(Some(POLICY));

    let installed = project.run(&["hook", "install"]);
    assert_eq!(code(&installed), 0, "{}", stderr(&installed));

    let settings = fs::read_to_string(project.root.join(".claude/settings.json")).unwrap();
    assert!(settings.contains("ralon hook check"), "{settings}");
    assert!(settings.contains("PreToolUse"), "{settings}");
    // Bash is deliberately not matched: a hook cannot tell which paths a shell
    // command touches, and claiming otherwise would be worse than the gap.
    assert!(!settings.contains("Bash"), "{settings}");
}

#[test]
fn the_installed_hook_denies_and_allows_the_right_paths() {
    let project = Project::new(Some(POLICY));

    for (relative, expected_deny) in [(".env", true), ("src/App.tsx", false)] {
        let request = format!(
            r#"{{"tool_name":"Write","tool_input":{{"file_path":{}}}}}"#,
            serde_json_string(&project.root.join(relative).to_string_lossy()),
        );

        let mut child = Command::new(BINARY)
            .arg("--dir")
            .arg(&project.root)
            .args(["hook", "check"])
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        use std::io::Write as _;
        child
            .stdin
            .take()
            .unwrap()
            .write_all(request.as_bytes())
            .unwrap();
        let output = child.wait_with_output().unwrap();

        let text = stdout(&output);
        // Exit 2 is what every supported agent reads as "blocked". The JSON
        // carries the reason for the ones that show it to the model, and it
        // carries both spellings — Claude reads one, Cursor the other.
        assert_eq!(
            code(&output),
            if expected_deny { 2 } else { 0 },
            "{relative}: {text}{}",
            stderr(&output)
        );
        assert_eq!(
            text.contains("\"permission\":\"deny\""),
            expected_deny,
            "Cursor's key is missing: {text}"
        );
        assert_eq!(
            text.contains("\"permissionDecision\":\"deny\""),
            expected_deny,
            "{relative} produced: {text}"
        );
    }
}

/// Minimal JSON string escaping, so the test needs no dependency.
fn serde_json_string(value: &str) -> String {
    let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
    format!("\"{escaped}\"")
}

#[test]
fn the_binary_reports_a_version() {
    let output = Command::new(BINARY).arg("--version").output().unwrap();
    assert!(String::from_utf8_lossy(&output.stdout).contains(env!("CARGO_PKG_VERSION")));
}