Skip to content

Commit c033e9e

Browse files
fix(rust-cli): real Lean precondition checks in verification.rs (P0-5) (#215)
ULTRAPLAN **P0-5**. Until now the seven `verify_*` functions in `impl/rust-cli/src/verification.rs` returned `Ok(())`. Each one now checks, against the real filesystem, the Lean precondition its operation is proved under. | Rust | Lean | Checks, in order | |---|---|---| | `verify_mkdir` | `MkdirPrecondition` (`FilesystemModel.lean:119`) | target absent (lstat) → parent exists → parent is dir → parent writable | | `verify_rmdir` | `RmdirPrecondition` (`FilesystemModel.lean:129`) | exists (lstat) → real dir → no entries → not sandbox root → parent writable | | `verify_create_file` | `CreateFilePrecondition` (`FileOperations.lean:11`) | as mkdir | | `verify_delete_file` | `DeleteFilePrecondition` (`FileOperations.lean:20`) | exists (lstat) → not dir → regular file or symlink → parent writable | | `verify_copy_file` | `copyFilePrecondition` | src exists → src not dir → dst absent → dst parent exists → src regular file → dst parent dir → src readable → dst parent writable | | `verify_move` | `movePrecondition` | src exists → dst absent → src ≠ dst → not into itself → dst parent exists → src/dst parents writable | | `verify_symlink` | `SymlinkPrecondition` | link absent (lstat) → parent exists → parent dir → parent writable (the target is deliberately not checked) | **Status, in the plan's taxonomy:** each mapping is **TESTED**, not PROVEN. The Rust checks are written by hand to mirror the Lean `Prop`s, not extracted from them. Correspondence is checked by review plus 41 new positive and negative unit tests. The module doc says so. ## Commits 1. `fix(rust-cli): implement real Lean precondition checks` - Path resolution moves to `state::resolve_under_root`, so the verifiers and `ShellState::resolve_path` use one rule. The body is moved, not changed. - Each verifier first repeats the checks the command already makes, in the same order and with byte-identical messages, then applies the conditions only Lean has. User-visible errors therefore stay the same. 2. `chore(rust-cli): remove broken .cargo/config.toml and no-op build.rs` - The config's only content was rustflags with a literal `$REPOS_DIR` link path, for a `lean-runtime-checks` feature that nothing defines. There is no `extern "C"` and no `#[link]` in `src/`. - `docs/ABI-FFI-BOUNDARY.adoc` is updated to match. 3. `fix(rust-cli): keep rmdir read_dir error text identical to the command` ## Behaviour changes (all from conditions the stub skipped) - **Dangling symlink at a mkdir/touch/cp destination:** now *already exists*. Before, mkdir and touch failed with an OS error, and cp wrote *through* the link. - **`rm` on a FIFO, socket or device:** refused (`Path is not a regular file`). The model has no such node. - New messages, reached only through the Lean-only conditions: `Parent is not a directory (ENOTDIR)`, `… is not writable (EACCES)`, `Source is not readable (EACCES)`, `Cannot remove the sandbox root`. - `mv` follows Lean in not requiring the destination parent to be a directory, so the rename itself reports that case. ## Evidence (rebased on main 3440d69) ``` cargo test suites=23 passed=827 failed=0 ignored=15 cargo clippy --all-targets -D warnings clean cargo fmt --check clean ``` - Before the change, on 4401867: 787 passed / 14 ignored. - This PR adds 41 tests, all in `verification.rs`. - One test moved from passed to ignored because #214 (P0-4) made the oracle test `#[ignore]`. - **Mutant:** putting the `Ok(())` stub back into `verify_mkdir` fails all 5 mkdir negative tests, including the unwritable-parent test. That shows the permission tests really run as uid 1000. - The permission tests skip themselves when run as root. ## ⚠ Finding: `RmdirPrecondition` is unsatisfiable (PROVEN) `isEmptyDir p fs` (`FilesystemModel.lean:69-71`) quantifies over `child.isPrefixOf p`, which ranges over p's **ancestors**, not its children. So it requires p's parent **not** to exist, while `parentWritable` requires the parent to exist. This typechecks against this repo's `FilesystemModel` on Lean v4.34.1: ```lean theorem rmdir_precondition_vacuous (p : Path) (fs : Filesystem) (h : RmdirPrecondition p fs) : False ``` The file was checked with `lake env lean`. As a control, adding `example : (1:Nat) = 2 := by decide` to the same file produces an error, so the file is really checked. **Consequence:** every theorem that takes `hpre : RmdirPrecondition p fs` (in `FilesystemModel`, `FilesystemEquivalence`, `FilesystemComposition`) holds vacuously, including the mkdir/rmdir reversibility results. The Rust here implements the evident *intent* ("the directory has no entries"), and its docstring records the gap. The Lean fix (`p.isPrefixOf child`, i.e. no descendant exists) belongs to the V1 proof phase, not this PR. It has been logged for the owner in `dev-notes/inbox/findings.md`. ## Not in scope - `ffi/rust/src/verification.rs` is a separate copy and is untouched. - The `ShellState::root()` fallback to `/` for a non-UTF-8 root already existed and is unchanged. - The CLAUDE.md test-count table (736) is stale; this PR does not update it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01VxcAoyMQe7CjQwCKL18Mm4 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 3440d69 commit c033e9e

6 files changed

Lines changed: 743 additions & 88 deletions

File tree

‎docs/ABI-FFI-BOUNDARY.adoc‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,8 @@ languages link against. The C-ABI-_provider_ role belongs to
6969
(11 exports, wired to the Idris2 ABI declarations). `+impl/zig/+` is an
7070
experimental fast-path lib plus a Lean-runtime wrapper, gated on the
7171
not-yet-built BEAM daemon. Collapsing the two is future work.
72-
* *The primary Rust CLI (`+impl/rust-cli/+`) does not link the FFI.* Its
73-
`+build.rs+` is intentionally a no-op; `+vsh+` is a self-contained
72+
* *The primary Rust CLI (`+impl/rust-cli/+`) does not link the FFI.* It has
73+
no `+build.rs+` and no link flags; `+vsh+` is a self-contained
7474
pure-Rust shell today. Wiring it to the Zig FFI is future work.
7575

7676
=== Deferred (code-level consolidation — needs owner sign-off)
@@ -80,8 +80,9 @@ the shipping shell:
8080

8181
[arabic]
8282
. Port `+ffi/rust+` to Zig, or fold it behind the Zig FFI.
83-
. Wire `+impl/rust-cli+` to the Zig FFI (replace the no-op
84-
`+build.rs+`).
83+
. Wire `+impl/rust-cli+` to the Zig FFI (would need a `+build.rs+`
84+
and link flags; the former no-op `+build.rs+` and broken
85+
`+.cargo/config.toml+` link path were removed).
8586
. Collapse `+impl/zig+` into `+ffi/zig+`.
8687

8788
Until then, the spine above is the documented contract, and the three

‎impl/rust-cli/.cargo/config.toml‎

Lines changed: 0 additions & 8 deletions
This file was deleted.

‎impl/rust-cli/build.rs‎

Lines changed: 0 additions & 12 deletions
This file was deleted.

‎impl/rust-cli/src/commands.rs‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,7 @@ pub enum CommandError {
7878
pub fn mkdir(state: &mut ShellState, path: &str, verbose: bool) -> Result<()> {
7979
let full_path = state.resolve_path(path);
8080

81-
// Optional Lean 4 verification (compile-time feature flag)
82-
// Provides mathematical guarantee that preconditions are satisfied
81+
// Runtime check of the Lean 4 precondition (see verification.rs)
8382
verification::verify_mkdir(state.root(), path)?;
8483

8584
// Check preconditions (matching Coq)
@@ -146,7 +145,7 @@ pub fn mkdir(state: &mut ShellState, path: &str, verbose: bool) -> Result<()> {
146145
pub fn rmdir(state: &mut ShellState, path: &str, verbose: bool) -> Result<()> {
147146
let full_path = state.resolve_path(path);
148147

149-
// Optional Lean 4 verification
148+
// Runtime check of the Lean 4 precondition (see verification.rs)
150149
verification::verify_rmdir(state.root(), path)?;
151150

152151
// Check preconditions
@@ -210,7 +209,7 @@ pub fn rmdir(state: &mut ShellState, path: &str, verbose: bool) -> Result<()> {
210209
pub fn touch(state: &mut ShellState, path: &str, verbose: bool) -> Result<()> {
211210
let full_path = state.resolve_path(path);
212211

213-
// Optional Lean 4 verification
212+
// Runtime check of the Lean 4 precondition (see verification.rs)
214213
verification::verify_create_file(state.root(), path)?;
215214

216215
if full_path.exists() {
@@ -273,7 +272,7 @@ pub fn touch(state: &mut ShellState, path: &str, verbose: bool) -> Result<()> {
273272
pub fn rm(state: &mut ShellState, path: &str, verbose: bool) -> Result<()> {
274273
let full_path = state.resolve_path(path);
275274

276-
// Optional Lean 4 verification
275+
// Runtime check of the Lean 4 precondition (see verification.rs)
277276
verification::verify_delete_file(state.root(), path)?;
278277

279278
if !full_path.exists() {
@@ -341,7 +340,7 @@ pub fn cp(state: &mut ShellState, src: &str, dst: &str, verbose: bool) -> Result
341340
let src_path = state.resolve_path(src);
342341
let dst_path = state.resolve_path(dst);
343342

344-
// Optional verification
343+
// Runtime check of the Lean 4 precondition (see verification.rs)
345344
verification::verify_copy_file(state.root(), src, dst)?;
346345

347346
// Check preconditions (matching Lean 4 copyFilePrecondition)
@@ -418,7 +417,7 @@ pub fn mv(state: &mut ShellState, src: &str, dst: &str, verbose: bool) -> Result
418417
let src_path = state.resolve_path(src);
419418
let dst_path = state.resolve_path(dst);
420419

421-
// Optional verification
420+
// Runtime check of the Lean 4 precondition (see verification.rs)
422421
verification::verify_move(state.root(), src, dst)?;
423422

424423
// Check preconditions (matching Lean 4 movePrecondition)
@@ -496,7 +495,7 @@ pub fn mv(state: &mut ShellState, src: &str, dst: &str, verbose: bool) -> Result
496495
pub fn symlink(state: &mut ShellState, target: &str, link: &str, verbose: bool) -> Result<()> {
497496
let link_path = state.resolve_path(link);
498497

499-
// Optional verification
498+
// Runtime check of the Lean 4 precondition (see verification.rs)
500499
verification::verify_symlink(state.root(), target, link)?;
501500

502501
// Check preconditions (matching Lean 4 SymlinkPrecondition)

‎impl/rust-cli/src/state.rs‎

Lines changed: 43 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use colored::Colorize;
1111
use serde::{Deserialize, Serialize};
1212
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
1313
use std::fs;
14-
use std::path::PathBuf;
14+
use std::path::{Path, PathBuf};
1515
use uuid::Uuid;
1616

1717
use crate::functions::FunctionTable;
@@ -561,38 +561,7 @@ impl ShellState {
561561
/// Resolve a path relative to sandbox root
562562
/// Prevents path traversal attacks via `..` components
563563
pub fn resolve_path(&self, path: &str) -> PathBuf {
564-
let raw = if let Some(stripped) = path.strip_prefix('/') {
565-
self.root.join(stripped)
566-
} else {
567-
self.root.join(path)
568-
};
569-
570-
// Normalize path components to prevent traversal via ..
571-
let mut normalized = PathBuf::new();
572-
for component in raw.components() {
573-
match component {
574-
std::path::Component::ParentDir => {
575-
// Only pop if we're still within the sandbox root
576-
if normalized.starts_with(&self.root) && normalized != self.root {
577-
normalized.pop();
578-
}
579-
// If popping would escape root, silently clamp to root
580-
}
581-
std::path::Component::CurDir => {
582-
// Skip . components
583-
}
584-
other => {
585-
normalized.push(other);
586-
}
587-
}
588-
}
589-
590-
// Final safety check: ensure result is within sandbox
591-
if !normalized.starts_with(&self.root) {
592-
self.root.clone()
593-
} else {
594-
normalized
595-
}
564+
resolve_under_root(&self.root, path)
596565
}
597566

598567
/// Get root path as string (for Lean FFI)
@@ -949,6 +918,47 @@ struct SerializableState {
949918
previous_dir: Option<PathBuf>,
950919
}
951920

921+
/// Resolve `path` against the sandbox `root`, clamping any `..` traversal so
922+
/// the result never escapes `root`.
923+
///
924+
/// A leading `/` is treated as relative to `root`; `.` components are dropped.
925+
/// This is the single path-resolution rule shared by [`ShellState::resolve_path`]
926+
/// and the precondition checks in [`crate::verification`].
927+
pub fn resolve_under_root(root: &Path, path: &str) -> PathBuf {
928+
let raw = if let Some(stripped) = path.strip_prefix('/') {
929+
root.join(stripped)
930+
} else {
931+
root.join(path)
932+
};
933+
934+
// Normalize path components to prevent traversal via ..
935+
let mut normalized = PathBuf::new();
936+
for component in raw.components() {
937+
match component {
938+
std::path::Component::ParentDir => {
939+
// Only pop if we're still within the sandbox root
940+
if normalized.starts_with(root) && normalized != root {
941+
normalized.pop();
942+
}
943+
// If popping would escape root, silently clamp to root
944+
}
945+
std::path::Component::CurDir => {
946+
// Skip . components
947+
}
948+
other => {
949+
normalized.push(other);
950+
}
951+
}
952+
}
953+
954+
// Final safety check: ensure result is within sandbox
955+
if !normalized.starts_with(root) {
956+
root.to_path_buf()
957+
} else {
958+
normalized
959+
}
960+
}
961+
952962
#[cfg(test)]
953963
mod tests {
954964
use super::*;

0 commit comments

Comments
 (0)