From e1b88f40fbc7730fc2f17fbdd24659f501c8a7a5 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 05:05:45 -0500 Subject: [PATCH 01/32] Add devlayer rename and defaults design and plan --- ...2026-11-13-devlayer-rename-and-defaults.md | 240 +++++++++++++++++ ...-13-devlayer-rename-and-defaults-design.md | 245 ++++++++++++++++++ 2 files changed, 485 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-13-devlayer-rename-and-defaults.md create mode 100644 docs/superpowers/specs/2026-11-13-devlayer-rename-and-defaults-design.md diff --git a/docs/superpowers/plans/2026-11-13-devlayer-rename-and-defaults.md b/docs/superpowers/plans/2026-11-13-devlayer-rename-and-defaults.md new file mode 100644 index 0000000..d1ff67f --- /dev/null +++ b/docs/superpowers/plans/2026-11-13-devlayer-rename-and-defaults.md @@ -0,0 +1,240 @@ +# devlayer Rename and New Defaults Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Rename the project from `sandbox` to `devlayer` (user-facing, then internal), then make the agent-friendly behavior the default: a new layer per run, the cwd bound live, host network, audio, and LLM tool binds; `--join` replaces `--name`; directory-aware `--last`. + +**Architecture:** Two no-behavior-change rename passes, then one task per behavior change. Layer selection moves from "always resolve `name`" to a `LayerSelection` that is chosen from the CLI, env, config and the action. The layer's directory and whether that directory was bound are stored in `settings.json`, and are reused on re-entry and on restart. + +**Tech Stack:** Rust (clap, serde/serde_json, toml, anyhow, rstest), OverlayFS, Linux namespaces, setuid binary; tests run under `sudo` via `make test` / `TEST=name make quick-test`. + +**Spec:** `docs/superpowers/specs/2026-11-13-devlayer-rename-and-defaults-design.md`. Read it before starting any task. + +## Global Constraints + +- Clean switchover: no fallback, alias or migration for any `sandbox` name, path, env var or config file. +- New names: binary `devlayer`; storage `~/.devlayer/`, fallback `/tmp/devlayer-`; env `DEVLAYER_*`; project config `.devlayer.conf` / `.devlayer.toml`; user config `~/.config/devlayer/config.(conf|toml)`; system config `/etc/devlayer.(conf|toml)`. +- Test layer name prefixes: `devlayer-coverage-*`, `devlayer-bind-empty-*`. New test files go in `tests/ai_test_*.rs` (per CLAUDE.md). +- The ephemeral layer name format stays `ephemeral_%Y-%m-%d_%H-%M-%S[.]`. +- Bind layer order (lowest to highest): system defaults + audio → LLM binds → cwd bind → config files → env → CLI. +- Every task ends with `cargo fmt`, `cargo clippy` clean, and the touched tests passing via `TEST= make quick-test`. Tasks 1, 2 and 9 also run the full `make test`. +- Coverage must stay at 100% (`make coverage-check`); any new `#[cfg(feature = "coverage")]` test hooks follow the existing `TEST_*` env-var pattern. + +## Review Focus + +1. **Running `devlayer` from a subdirectory of the directory where a layer was created, with `--last`.** The layer must be entered with its original directory bind, not fail with "bind mounts changed". Test: Task 7, `ai_test_cwd_bind_reenter_from_subdir`. +2. **`devlayer status` in a project dir right after an agent ran.** It must show changes outside the project (whole layer), not an empty list. Test: Task 9, `ai_test_status_default_whole_layer`. +3. **Bare `devlayer accept` / `reject`.** These must refuse with a hint, and must change nothing. Test: Task 9, `ai_test_accept_requires_pattern` (asserts the file is still in the layer afterwards). +4. **Two layers created in the same directory.** `--last` must pick the newer one; a layer created in a deeper directory must not be chosen when you stand in its parent. Test: Task 8, `ai_test_last_nearest_ancestor_and_newest`. +5. **A path in the LLM list that is missing on the host** (most users have only one or two agents). It must be skipped silently, not fail canonicalization. Test: Task 6, unit test `llm_binds_skip_missing_paths`. + +--- + +### Task 1: User-facing rename + +**Files:** +- Modify: `Cargo.toml` (package and `[[bin]]` name → `devlayer`; leave `[lib] name` for Task 2), `Cargo.lock` (regenerated by cargo) +- Modify: `src/config/resolve.rs` (storage dirs, `SANDBOX_*` env reads, `find_config_files` paths, default name text, error strings) +- Modify: `src/config/cli.rs` (`override_usage`, help text), `src/main.rs` and `src/actions/*.rs` (user-visible output strings and errors that say "sandbox") +- Modify: `src/actions/clean.rs:14` (test patterns → `devlayer-coverage-*`, `devlayer-bind-empty-*`), `src/util/mkdir.rs:78,104` (test dir names) +- Modify: `Makefile`, `packaging/*`, `vm-testing/**`, `README.adoc`, `CONTRIBUTING.adoc`, `RELEASE_CHECKLIST.md`, `CLAUDE.md`, `cspell.json`, `tests/README.md` +- Modify: `tests/fixtures/fixture_sandbox.rs` (`target/{debug,coverage}/devlayer`, name prefix `devlayer-coverage-test-`), and every `tests/*.rs` that hard-codes `sandbox-coverage`, `SANDBOX_*`, `.sandbox.toml`, `~/.sandboxes` or binary paths. + +**Interfaces:** +- Produces: binary `target/{debug,coverage}/devlayer`; env vars `DEVLAYER_LOG_LEVEL`, `DEVLAYER_NAME`, `DEVLAYER_STORAGE_DIR`, `DEVLAYER_NET`, `DEVLAYER_IGNORED`, `DEVLAYER_BIND`, `DEVLAYER_MASK`, `DEVLAYER_NO_DEFAULT_BINDS`, `DEVLAYER_AUDIO`, `DEVLAYER_CPUS`, `DEVLAYER_MEMORY` (later tasks rename or remove some of these). + +- [ ] **Step 1: Inventory.** Run `git grep -n -i sandbox -- ':!docs/superpowers'` and sort the hits into: user-visible (this task) or internal identifiers (Task 2). Internal means Rust type, function, module and variable names, plus the `[lib]` crate name and its `use sandbox::` imports. +- [ ] **Step 2: Apply the user-visible rename** using the table in the spec, Part 1. User-facing prose says "layer" where it said "sandbox" as a noun (e.g. "No layer by the name of 'x' found to delete."). The `/run/media/sandbox-coverage-testing` dir in the Makefile and in tests becomes `/run/media/devlayer-coverage-testing`. +- [ ] **Step 3: Build and check for leftovers.** + Run: `cargo build && git grep -n -i sandbox -- ':!docs/superpowers' ':!src' ':!tests'` + Expected: build OK; the grep shows no hits, or only historical text in a changelog if one exists. + Run: `git grep -n -E '"[^"]*[Ss]andbox[^"]*"' src` + Expected: hits only in identifiers or in `#[cfg(test)]` code that Task 2 renames, not in messages. +- [ ] **Step 4: Full test run.** + Run: `make test` + Expected: all non-ignored tests pass. +- [ ] **Step 5: Commit** — `git commit -am "Rename sandbox to devlayer (user-facing)"` + +### Task 2: Internal identifier rename pass + +**Files:** +- Rename: `src/sandbox/` → `src/layer/` (and the `mod sandbox` in `src/lib.rs`), `tests/fixtures/fixture_sandbox.rs` → `tests/fixtures/fixture_layer.rs` +- Modify: `Cargo.toml` `[lib] name = "devlayer"`; every `use sandbox::` → `use devlayer::` +- Modify: all of `src/**` and `tests/**` for the identifier renames below. + +**Interfaces:** +- Produces (later tasks use these names): + - `Sandbox` → `Layer`; `SandboxSettings` → `LayerSettings`; `SandboxLogger` → `DevlayerLogger`; `Lock::sandbox` → `Lock::layer` + - `resolve_sandbox_storage_dir` → `resolve_storage_dir`; `find_last_sandbox` → `find_last_layer`; `get_running_sandbox_pid` → `get_running_layer_pid`; `sandbox_name_completion` → `layer_name_completion`; other `sandbox_*` fns, variables and fields → `layer_*` + - `Config.sandbox_dir` → `Config.layer_dir`, and the `config` action key `sandbox_dir` → `layer_dir` + - Test fixture: `SandboxManager` → `LayerManager`; `#[fixture] fn sandbox()` → `#[fixture] fn layer()`; `get_sandbox_bin` → `get_devlayer_bin`; the field `sandbox_bin` → `devlayer_bin`; test params `mut sandbox: SandboxManager` → `mut layer: LayerManager` + +- [ ] **Step 1: Do the renames** (use `git mv` for files; IDE/LSP rename or careful `sed -i` with word boundaries for identifiers). +- [ ] **Step 2: Verify that no internal name is left.** + Run: `git grep -n -i sandbox -- ':!docs/superpowers'` + Expected: no hits. +- [ ] **Step 3: Build, lint, test.** + Run: `cargo build && cargo clippy && make test` + Expected: clean build, no clippy warnings, all tests pass. +- [ ] **Step 4: Commit** — `git commit -am "Rename internal sandbox identifiers to layer/devlayer"` + +### Task 3: `--join` replaces `--name` + +**Files:** +- Modify: `src/config/cli.rs` (remove `name`; add `join`), `src/config/structs.rs` (`PartialConfig.name` → `join`), `src/config/resolve.rs` (env `DEVLAYER_NAME` → `DEVLAYER_JOIN`, `merge_configs`, the mutual-exclusion check and its message) +- Modify: `tests/fixtures/fixture_layer.rs` (`--name=` → `--join=` in `dir`, `run_with_stdin`, `run_with_env`, `run_in_background`, and the `starts_with("--name")` checks), and every test that passes `--name` or sets `DEVLAYER_NAME` / `name =` in a config +- Modify: `README.adoc` (flag table / examples) +- Test: `tests/ai_test_join.rs` + +**Interfaces:** +- Produces: `Args.join: Option` (`#[arg(long, global = true, add = ArgValueCompleter::new(layer_name_completion), conflicts_with_all = &["new", "last"])]`); `PartialConfig.join: Option`; source key in `Config.sources` stays `"name"`, with the value `"cli --join"` / `"environment"` / ``. + +- [ ] **Step 1: Write failing tests** in `tests/ai_test_join.rs`: + - `ai_test_join_creates_then_reuses`: `--join= touch ` passes; `--join= test -f ` passes (same layer). + - `ai_test_name_flag_removed`: running with `--name=x true` fails (clap unknown argument). + - `ai_test_join_env_and_config`: `DEVLAYER_JOIN=` with `config name` prints ``; a temp config file `join = ""` passed via `--config` gives the same. + - `ai_test_join_conflicts_with_new_last`: `--join=x --new true` and `--join=x --last true` fail; `DEVLAYER_JOIN=x` plus `--new` fails with the message containing `"Cannot use --new or --last"`. +- [ ] **Step 2: Run them; expect failures.** `TEST=ai_test_join make quick-test` → FAIL (unknown `--join`). +- [ ] **Step 3: Implement** the rename in cli/structs/resolve and the fixture. +- [ ] **Step 4: Run.** `TEST=ai_test_join make quick-test` → PASS; then `make test` (the fixture change touches every test) → PASS. +- [ ] **Step 5: Commit** — `git commit -am "Replace --name with --join"` + +### Task 4: Host network by default + +**Files:** +- Modify: `src/config/resolve.rs` (`partial_config.net.unwrap_or(Network::Host)`), `src/config/cli.rs` (help text for `--net`: the default is host, use `--net=none` to disable) +- Modify: tests that assume no network by default (`tests/test_net.rs`, and any `config net` assertions expecting `none`) +- Modify: `README.adoc` +- Test: `tests/ai_test_net_default.rs` + +**Interfaces:** none new. + +- [ ] **Step 1: Write failing tests** in `tests/ai_test_net_default.rs`: `ai_test_net_defaults_to_host` (`--no-config config net` prints `host`, and `sources` shows `default`); `ai_test_net_none_disables` (`--net=none config net` prints `none`). +- [ ] **Step 2: Run** `TEST=ai_test_net_default make quick-test` → FAIL. +- [ ] **Step 3: Implement.** Update existing net tests so that tests which need no network pass `--net=none` explicitly. +- [ ] **Step 4: Run** `TEST=ai_test_net make quick-test` and `TEST=test_net make quick-test` → PASS. +- [ ] **Step 5: Commit** — `git commit -am "Default to host networking"` + +### Task 5: Audio becomes part of the default binds + +**Files:** +- Modify: `src/config/cli.rs` (remove `audio`), `src/config/structs.rs` (remove `audio` from `PartialConfig` and `Config`), `src/config/resolve.rs` (remove `DEVLAYER_AUDIO` env and merge; `get_audio_bind_mounts()` output is appended to the `get_default_bind_mounts` layer, only when `!no_default_binds`), `src/actions/config.rs` (drop the `audio` key), `src/layer/settings.rs` if it references audio +- Modify: `tests/ai_test_audio.rs` (rewrite for the new behavior), `README.adoc` +- Test: `tests/ai_test_audio.rs` + +**Interfaces:** none new. `--audio` and `audio=` no longer exist. + +- [ ] **Step 1: Rewrite tests** in `tests/ai_test_audio.rs`: `ai_test_audio_on_by_default` (with `XDG_RUNTIME_DIR` set to a temp dir containing a `pulse` dir, `config bind_mounts` lists `/pulse`); `ai_test_audio_off_with_no_default_binds` (same setup plus `--no-default-binds` → not listed); `ai_test_audio_flag_removed` (`--audio true` fails). +- [ ] **Step 2: Run** `TEST=ai_test_audio make quick-test` → FAIL. +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run** `TEST=ai_test_audio make quick-test` → PASS. +- [ ] **Step 5: Commit** — `git commit -am "Make audio binds part of the default binds"` + +### Task 6: Default LLM bind layer and `--no-default-llm-binds` + +**Files:** +- Modify: `src/config/resolve.rs`: add `const LLM_BIND_PATHS: &[&str]` and `fn get_llm_bind_mounts(home: &Path) -> Vec`; remove `.claude` / `.aider` / `.cursor` from `get_default_bind_mounts`; insert the LLM layer directly above the default layer, only when `!no_default_llm_binds` +- Modify: `src/config/cli.rs` (`no_default_llm_binds: bool`, help: "Disable default binds of well-known AI tool config (e.g. ~/.claude, ~/.codex)"), `src/config/structs.rs` (`PartialConfig.no_default_llm_binds: Option`, `Config.no_default_llm_binds: bool`), env `DEVLAYER_NO_DEFAULT_LLM_BINDS` (parse like `DEVLAYER_IGNORED`, returning an error on bad values rather than `expect`), `merge_configs`, `src/actions/config.rs` (key `no_default_llm_binds`) +- Modify: `README.adoc` (list the paths) +- Test: unit tests in `src/config/resolve.rs` `mod tests`; `tests/ai_test_llm_binds.rs` + +**Interfaces:** +- Produces: `get_llm_bind_mounts(home: &Path) -> Vec`. It returns absolute path strings, in `LLM_BIND_PATHS` order, for entries that exist under `home`. +- `LLM_BIND_PATHS` (relative to home, exact): `.claude`, `.claude.json`, `.codex`, `.pi`, `.gemini`, `.qwen`, `.aider`, `.cursor`, `.config/opencode`, `.local/share/opencode`, `.config/goose`, `.continue`, `.codeium`, `.config/github-copilot`, `.factory`, `.config/crush`, `.local/share/crush`. + +- [ ] **Step 1: Write failing unit tests:** + - `llm_binds_skip_missing_paths`: create a temp home with only `.codex/` and `.claude.json`; assert `get_llm_bind_mounts(home) == vec![home/.claude.json, home/.codex]`. + - `llm_binds_all_present`: create every entry; assert the length is 17 and the order matches `LLM_BIND_PATHS`. +- [ ] **Step 2: Write failing integration tests** in `tests/ai_test_llm_binds.rs`: `ai_test_llm_binds_default_on` (`config bind_mounts` contains `$HOME/.claude` when it exists; skip if it doesn't, the same way other tests skip on missing host features); `ai_test_no_default_llm_binds_flag`, `ai_test_no_default_llm_binds_env`, `ai_test_no_default_llm_binds_config` (each → not listed); `ai_test_llm_binds_independent_of_no_default_binds` (`--no-default-binds` still lists it). +- [ ] **Step 3: Run** `TEST=llm_binds make quick-test` → FAIL. +- [ ] **Step 4: Implement.** +- [ ] **Step 5: Run** `TEST=llm_binds make quick-test` and `TEST=bind make quick-test` → PASS (existing bind tests that expected `.claude` under the default binds must be updated to the new layer). +- [ ] **Step 6: Commit** — `git commit -am "Add default LLM tool binds and --no-default-llm-binds"` + +### Task 7: cwd bind by default, `--no-bind-cwd`, stored origin + +**Files:** +- Modify: `src/layer/settings.rs`: `LayerSettings` gains `#[serde(default)] created_in: Option` and `#[serde(default)] bind_cwd: Option`, filled from `Config` in `from_config` +- Modify: `src/config/structs.rs`: `Config` gains `created_in: PathBuf` and `bind_cwd: bool`; `PartialConfig.no_bind_cwd: Option` +- Modify: `src/config/cli.rs` (`no_bind_cwd: bool`, help: "Do not bind the current directory into the layer. By default it is bound read-write, so changes there go straight to the host."), env `DEVLAYER_NO_BIND_CWD`, `merge_configs`, `src/actions/config.rs` (keys `created_in`, `bind_cwd`) +- Modify: `src/config/resolve.rs`: after the layer name is known, call `resolve_origin` and push the cwd-bind layer between the LLM layer and the config layers +- Modify: `README.adoc`: document the cwd bind, `--no-bind-cwd`, and the known limitation from the spec (config files are discovered from the current cwd, so joining a layer from another project can load a different `.devlayer.toml`) +- Modify: `tests/fixtures/fixture_layer.rs`: add `pub bind_cwd: bool` (default `false`) and `set_bind_cwd(bool)`. When it is false, every run path (`run_with_env`, `run_with_stdin`, `run_in_background`, `dir`) adds `--no-bind-cwd`, unless `no_default_options` is set. This keeps existing overlay tests meaningful, because tests run from the repo root. +- Test: `tests/ai_test_cwd_bind.rs` + +**Interfaces:** +- Produces: `fn resolve_origin(layer_dir: &Path, cwd: &Path, no_bind_cwd: bool) -> Result<(PathBuf, bool)>`. It returns `(created_in, bind_cwd)`: + - if `layer_dir/settings.json` exists and has both fields → the stored values; + - otherwise → `(canonical cwd, !no_bind_cwd)`, and if `bind_cwd && cwd == "/"`, the error `"Refusing to bind / into the layer; run from a project directory or pass --no-bind-cwd"`. + - When `bind_cwd` is true, the cwd layer is `vec![created_in.display().to_string()]`. +- Task 8 consumes `LayerSettings.created_in`. + +- [ ] **Step 1: Write failing tests** in `tests/ai_test_cwd_bind.rs` (use `set_bind_cwd(true)` and a dir under `generated-test-data//`): + - `ai_test_cwd_bound_by_default`: `cd` into the temp dir, write a file inside the layer, then assert it exists on the host immediately (no accept) and `status /` doesn't list it. + - `ai_test_no_bind_cwd_flag_env_config`: with each of the three forms, the write stays in the layer (not on the host). + - `ai_test_refuse_root`: running from `/` without `--no-bind-cwd` fails with the message above; with `--no-bind-cwd` it passes. + - `ai_test_home_allowed`: running from `$HOME` with the cwd bind passes (`config bind_cwd` → `true`). + - `ai_test_cwd_bind_reenter_from_subdir`: start a background command in dir D (`run_in_background(["sleep","30"])`); from `D/sub`, `--join= config created_in` prints D, and `--join= true` passes (no "bind mounts changed"). + - `ai_test_restart_keeps_origin`: create in D, `stop`, re-run from `D/sub` → `config created_in` is still D. + - `ai_test_no_bind_cwd_persists`: create in D with `--no-bind-cwd`; re-enter without the flag → `config bind_cwd` is `false`. +- [ ] **Step 2: Run** `TEST=ai_test_cwd_bind make quick-test` → FAIL. +- [ ] **Step 3: Implement** settings fields, `resolve_origin`, the bind layer, the flag/env/config, and the fixture default. +- [ ] **Step 4: Run** `TEST=ai_test_cwd_bind make quick-test`, then `make test` (fixture change) → PASS. +- [ ] **Step 5: Commit** — `git commit -am "Bind the current directory by default; add --no-bind-cwd"` + +### Task 8: `--new` by default, directory-aware `--last`, per-action defaults + +**Files:** +- Modify: `src/config/resolve.rs`: replace the `if cli.new … else if cli.last …` block with `select_layer(...)`; rewrite `find_last_layer` to be directory-aware +- Modify: `src/config/cli.rs` (help for `--new`/`--last`/`--join` describing the defaults) +- Modify: `README.adoc` (usage section: a bare `devlayer`, `devlayer --last`, actions default to the last layer for this directory) +- Test: `tests/ai_test_layer_selection.rs`, plus updates to `tests/isolated_test_new_last.rs`, `tests/test_new_last.rs`, `tests/isolated_test_new.rs` + +**Interfaces:** +- Consumes: `LayerSettings::load_from_file`, `LayerSettings.created_in` (Task 7). +- Produces: + - `enum LayerSelection { New, Last, Join(String) }` + - `fn default_selection(action: Option<&Action>) -> LayerSelection` behaves like this: + - `None` → `New`; + - `Status`, `Diff`, `Accept`, `Reject` → `Last`; + - `Stop { all: false, patterns: None }` and `Delete { patterns: None|Some(empty) }` → `Last`; + - `Stop` with `all` or patterns, `Delete` with patterns, `List`, `Sync`, `Clean`, `Config` → `New` *without failing*. + - For `Config`, try `Last` first and fall back to `New` if nothing matches, so `devlayer config name` reports this directory's layer. + - Precedence: `--join`/`--new`/`--last` CLI > `DEVLAYER_JOIN` > config `join` > `default_selection`. + - `fn find_last_layer(storage_dir: &Path, cwd: &Path) -> Result`: for each ancestor `A` of canonical `cwd` (itself first, `/` last), collect the layers whose `settings.json` has `created_in == A`. At the first non-empty set, return the newest by dir creation time (`metadata.created()` falling back to `modified()`, as today). Layers without settings or without `created_in` are ignored. If nothing matches → `"No devlayer found for {cwd} or its parent directories; use --join or `devlayer list`"`. + - The existing `TEST_LAST_IS_EMPTY` coverage hook is kept. + +- [ ] **Step 1: Write failing tests** in `tests/ai_test_layer_selection.rs`. Use a fresh temp storage dir via `--storage-dir`/`DEVLAYER_STORAGE_DIR` so that layers from other tests don't interfere, and `no_default_options` where the fixture's `--join` must be suppressed; clean up created layers. + - `ai_test_bare_run_creates_new_each_time`: two bare `true` runs create two distinct `ephemeral_*` layers. + - `ai_test_last_nearest_ancestor_and_newest`: create L1 in D, L2 in D (later), L3 in `D/sub`. From D, `--last config name` → L2. From `D/sub/deeper` → L3. From the parent of D → error containing `"No devlayer found"`. + - `ai_test_actions_default_to_last`: create a layer in D that writes outside D; from D, `status /` without any selector shows that file, and `config name` equals that layer. + - `ai_test_stop_delete_default_to_last`: from D, bare `stop` stops D's latest layer; `delete -y` deletes it. + - `ai_test_list_clean_sync_no_layer_ok`: from a dir with no layers, `list`, `sync` and `clean -y` all pass and no new layer dir appears in storage. + - `ai_test_explicit_selector_wins`: from D, `--join= status` targets ``; `--new status` passes on an empty new layer. + - `ai_test_last_errors_without_layer`: `status` from a dir with no layers fails with `"No devlayer found"`. +- [ ] **Step 2: Run** `TEST=ai_test_layer_selection make quick-test` → FAIL. +- [ ] **Step 3: Implement** `LayerSelection`, `default_selection` and `find_last_layer`, wired through `resolve_config` (it already receives `cli.action`). +- [ ] **Step 4: Update** the existing `new_last` tests to the directory-aware semantics. Run `TEST=new_last make quick-test` and `TEST=ai_test_layer_selection make quick-test` → PASS. +- [ ] **Step 5: Commit** — `git commit -am "Default to a new layer; make --last directory-aware; actions default to --last"` + +### Task 9: Whole-layer `status`/`diff`; `accept`/`reject` need a pattern + +**Files:** +- Modify: `src/layer/changes/change_entries.rs` (`matching`: empty patterns → all entries; remove the cwd-prefix filter) +- Modify: `src/actions/accept.rs`, `src/actions/reject.rs`: at the start, if `patterns.is_empty()` → `Err("accept requires at least one pattern; use `devlayer accept /` to accept every change in the layer")` (the `reject` version says the same with "reject") +- Modify: `src/config/cli.rs` (help for Status/Diff/Accept/Reject), `README.adoc` +- Modify: existing tests that call bare `accept` (32), `reject` (1), `status` (18) or `diff` (17) and rely on the cwd scope. Change them to pass `.` (which matches the cwd subtree, as the old default did) — do not delete them. +- Test: `tests/ai_test_action_scope.rs` + +**Interfaces:** `ChangeEntries::matching(&self, cwd: &Path, patterns: &[String]) -> ChangeEntries` (unchanged signature). + +- [ ] **Step 1: Write failing tests** in `tests/ai_test_action_scope.rs`: + - `ai_test_status_default_whole_layer`: from `generated-test-data//a`, write a file in a sibling dir `../b/f`; bare `status` lists `b/f`. + - `ai_test_diff_default_whole_layer`: same, with `diff`. + - `ai_test_status_diff_patterns_still_filter`: `status ./nothing-here` lists nothing; `status ../b` lists it. + - `ai_test_accept_requires_pattern`: bare `accept` fails with `"requires at least one pattern"`, and the file still exists only in the layer (`status /` still lists it; the host path is missing). + - `ai_test_reject_requires_pattern`: same, for `reject`. +- [ ] **Step 2: Run** `TEST=ai_test_action_scope make quick-test` → FAIL. +- [ ] **Step 3: Implement** and update the existing bare-action tests. +- [ ] **Step 4: Full run.** `make test && make coverage-report && make coverage-check && make ready-for-commit-tests` → all pass, coverage 100%. +- [ ] **Step 5: Commit** — `git commit -am "Whole-layer status/diff by default; accept/reject require a pattern"` diff --git a/docs/superpowers/specs/2026-11-13-devlayer-rename-and-defaults-design.md b/docs/superpowers/specs/2026-11-13-devlayer-rename-and-defaults-design.md new file mode 100644 index 0000000..314d4ad --- /dev/null +++ b/docs/superpowers/specs/2026-11-13-devlayer-rename-and-defaults-design.md @@ -0,0 +1,245 @@ +# Rename to devlayer and new defaults: design + +## Intent + +The tool is used mainly to run AI coding agents (Claude Code, Codex, pi, ...) +against a project. Today that takes a long config file and several flags: +`--new`, `--bind=.`, `--net=host`, `--audio`, plus a list of agent config +directories. The project is renamed to **devlayer**, and those choices become +the defaults. A bare `devlayer` in a project directory starts a fresh layer. +In that layer the project directory is live on the host, the network and +audio work, and the agent's own config/state is shared with the host. Changes +outside the project directory stay in the layer for review +(`status`/`diff`/`accept`/`reject`). + +## Goals + +1. Clean rename from `sandbox` to `devlayer` everywhere. +2. New defaults: a new layer per run, the current directory bound, host + network, audio on, and well-known LLM tool paths bound. +3. `--join ` replaces `--name`. +4. `--last` becomes directory-aware, and the actions that operate on one + layer default to it. + +## Non-goals + +- No fallback, compatibility or migration for `sandbox` names, paths, env + vars, config files or existing `~/.sandboxes` data. It is a clean + switchover. +- No automatic cleanup of the growing number of `ephemeral_*` layers. That + comes in a later iteration, and `devlayer clean` stays as it is. +- No GitHub repository rename or release work. + +## Anti-goals + +- Never run with `/` bound live by the default directory bind. +- Re-entering an existing layer from a subdirectory must not fail with + "bind mounts changed" just because the current directory differs. + +## Part 1: Rename (clean switchover) + +| Old | New | +|---|---| +| binary / crate / lib name `sandbox` | `devlayer` | +| `~/.sandboxes/`, fallback `/tmp/sandboxes-` | `~/.devlayer/`, fallback `/tmp/devlayer-` | +| `SANDBOX_*` env vars | `DEVLAYER_*` | +| `.sandbox.conf` / `.sandbox.toml` (cwd and parents) | `.devlayer.conf` / `.devlayer.toml` | +| `~/.config/sandbox/config.(conf\|toml)` | `~/.config/devlayer/config.(conf\|toml)` | +| `/etc/sandbox.(conf\|toml)` | `/etc/devlayer.(conf\|toml)` | +| test layer prefixes `sandbox-coverage-*`, `sandbox-bind-empty-*` | `devlayer-coverage-*`, `devlayer-bind-empty-*` | +| README, CONTRIBUTING, CLAUDE.md, RELEASE_CHECKLIST, Makefile, packaging, vm-testing, cspell, completions, user-facing messages | updated to "devlayer" / "layer" | + +User-visible text (help, errors, output, docs) must say devlayer. + +Internal Rust identifiers and modules (`Sandbox`, `SandboxSettings`, +`src/sandbox/`, `SandboxLogger`, `sandbox_*` functions and variables, test +fixture names such as `fixture_sandbox.rs`) are **also renamed** +(Sandbox → Layer / devlayer). This is done as a **separate pass**, in its +own commit(s), apart from the user-facing rename. + +Both rename passes land with no behavior change, before Part 2. + +## Part 2: New behavior + +### Choosing which layer to use + +The flags `--new`, `--last` and `--join ` are mutually exclusive (as +today). + +- **`--join `** works exactly like today's `--name`: it uses that + layer, and creates it if it does not exist. `--name` is removed. + - *(my call)* The config-file key `name` becomes `join`, and the env var + becomes `DEVLAYER_JOIN`. Either one acts like `--join` and overrides the + defaults below. Combining it with `--new`/`--last` is an error, as + today. +- **`--new`** creates a layer with an auto-generated `ephemeral_` + name (naming unchanged, so `clean` keeps working). +- **`--last`** is directory-aware: + - Each layer records the canonical directory it was created in, in its + `settings.json` (new field, e.g. `created_in`). The value is written when + the layer is created and kept unchanged when the layer is restarted. + - Resolution starts at the canonical cwd and walks up through its + ancestors to `/`. At the first directory that is the `created_in` of one + or more layers, it picks the newest of those (by creation time). Note: + `/` counts too, if a layer was created there with `--no-bind-cwd`. + - If no layer matches, it fails with an error that names the directory and + suggests `--join ` or `devlayer list`. + +**Defaults when no selection flag, `join` config or env var is given:** + +| Invocation | Default | +|---|---| +| no action (run a command or a shell) | `--new` | +| `status`, `diff`, `accept`, `reject` | `--last` | +| `stop` / `delete` with no patterns and no `--all` | `--last` | +| `list`, `sync`, `clean`, `config` | need no target. They must not fail or create anything when no layer exists for the cwd. | + +An explicit flag always wins, for example `devlayer --join foo status` or +`devlayer --last bash`. + +### Default scope of `status` / `diff` / `accept` / `reject` + +Today these actions, with no patterns, only consider changes under the cwd +(`ChangeEntries::matching` in `src/sandbox/changes/change_entries.rs`). The +cwd is now bound live, so its changes never reach the layer, and that default +would always be empty. + +- **`status` and `diff` with no patterns cover the whole layer** (the same as + `status /` today). Patterns work as they do today. +- **`accept` and `reject` require at least one pattern.** With no patterns + they fail with an error that suggests `devlayer accept /` (or `reject /`) + for everything. This protects against an accidental system-wide accept. + Pattern behavior is unchanged. + +Implementation note: today the name is resolved inside `resolve_config` +before `main` dispatches the action. The default now depends on the action, +so resolution has to know the action (or be deferred until it is known). + +### Directory bind (`--bind=.` by default) + +- By default the canonical current directory is bind-mounted read-write at + the same path. +- New flag **`--no-bind-cwd`**, with config key `no_bind_cwd` and env var + `DEVLAYER_NO_BIND_CWD`, turns it off. It is independent of + `--no-default-binds`. +- **Refuse to start** a new layer when the directory bind is on and the + canonical cwd is `/`. The error says to use `--no-bind-cwd`. `$HOME` is + allowed. +- **Re-entering an existing layer** (`--join` / `--last`, running or + stopped) *(my call)*: the layer's directory bind is fixed when the layer is + created. `settings.json` records both `created_in` and whether the + directory bind was on (e.g. `bind_cwd: bool`). On re-entry and on restart, + both values come from `settings.json`, and the current cwd and the + `--no-bind-cwd` flag are ignored for this bind. Results: + - Entering from a subdirectory or another directory does not change the + layer's bind set, so it does not trip the "bind mounts changed" check in + `SandboxSettings::validate_against_config`. + - A layer created at `/` with `--no-bind-cwd` never binds `/` later. + - Restarting a stopped layer (which rewrites `settings.json` in + `mount_overlays.rs`) must keep `created_in` and `bind_cwd`. + + Other binds (system, audio, LLM, config/env/CLI) are recomputed and + validated as they are today. +- *(my call, known limitation)* Config files are still found by walking up + from the current cwd, not from `created_in`. So `devlayer --join proj` + run from a different project can load a different `.devlayer.toml` and + fail validation. This is today's behavior with `--name`. Document it in + the README rather than restructure config loading. +- Precedence: the directory bind is a layer above the default and LLM binds + and below config/env/CLI binds. Explicit binds or masks on the same target + therefore override it. + +### Network + +- The default for `net` becomes `host`. `--net=none` (or `net="none"` in + config) disables networking. +- Consequence (intended, noted for the docs): the D-Bus/systemd default + binds that today depend on host networking are now present by default. + +### Audio + +- Audio binds (`/dev/snd`, `$XDG_RUNTIME_DIR/pipewire-0`, + `$XDG_RUNTIME_DIR/pulse`) become part of the default binds, so + `--no-default-binds` disables them. +- *(my call)* The `--audio` flag, the `audio` config key and + `DEVLAYER_AUDIO` are removed. + +### Default LLM binds + +- A new bind layer of well-known AI-tool paths. It is on by default and + disabled with **`--no-default-llm-binds`** (config key + `no_default_llm_binds`, env var `DEVLAYER_NO_DEFAULT_LLM_BINDS`). It is + independent of `--no-default-binds`. +- Each path is bound read-write at the same path, and **only if it exists** + on the host: + - `~/.claude`, `~/.claude.json` + - `~/.codex` + - `~/.pi` + - `~/.gemini` + - `~/.qwen` + - `~/.aider` *(moved here from the system defaults)* + - `~/.cursor` *(moved here from the system defaults)* + - `~/.config/opencode`, `~/.local/share/opencode` + - `~/.config/goose` + - `~/.continue` + - `~/.codeium` + - `~/.config/github-copilot` + - `~/.factory` + - `~/.config/crush`, `~/.local/share/crush` +- Personal binds (ssh keys, gh tokens, docker.sock, herdr) are **not** + defaults. They stay in the user's config. + +### Bind layer order (lowest to highest precedence) + +1. Default system binds (`/dev/fuse`, D-Bus/systemd when net=host) plus + audio. Skipped with `--no-default-binds`. +2. Default LLM binds. Skipped with `--no-default-llm-binds`. +3. Directory bind. Skipped with `--no-bind-cwd`. +4. Config file layers (as today). +5. Environment layer. +6. CLI layer. + +## Approaches considered + +1. **Rename first, then behavior changes, on this branch (chosen).** Each + diff is easy to review. The 116-file rename does not hide the logic + changes. +2. One combined change: less churn in test files, but much harder to + review and to bisect. +3. Keep the `sandbox` name with a `devlayer` alias, or migrate old data: + ruled out, because the user wants a clean switchover. + +For `created_in`: store it in the existing per-layer `settings.json` +(chosen), instead of a separate index file in the storage dir. An index +could get out of sync with layers that are deleted by hand, and +`settings.json` already exists per layer. + +## Testing + +- Follow CLAUDE.md: new tests go in `tests/ai_test_*.rs`. Explicit layer + names use the `devlayer-coverage` prefix. Keep line coverage at the + project's required level (`make coverage-check`). +- Existing tests that rely on the old defaults (no network, default name + `sandbox`, `--name`, `--audio`, `.claude`/`.aider`/`.cursor` in the system + defaults, cwd-scoped `status`/`diff`/`accept`/`reject` with no patterns) + must be updated to the new behavior. Do not delete them. +- New coverage is needed for: directory-aware `--last` (exact dir, ancestor + match, nearest ancestor wins, newest wins within a dir, no match → + error); defaults per action; `--no-bind-cwd`; refusing `/`; re-entering + from a subdirectory keeps the original directory bind; LLM binds only + when the path exists, and disabled by the flag; audio disabled by + `--no-default-binds`; `--join` create-or-use; `join` config/env; + whole-layer `status`/`diff` with no patterns; `accept`/`reject` with no + patterns → error; re-entering or restarting keeps `created_in`/`bind_cwd`. + +## Left to the builder + +- Exact wording of help text and errors. +- How to restructure name resolution so it knows the action. + +## Decided after review + +- Internal identifiers and modules are renamed, in a separate pass (see + Part 1). +- Test helpers (the fixture / layer manager in `tests/fixtures/`) are + updated for `--join` and the new defaults. From 88daf13dc4e624344b26b721b5da4350fb8e3f73 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 05:49:37 -0500 Subject: [PATCH 02/32] Rename sandbox to devlayer (user-facing) --- .github/workflows/coverage.yml | 2 +- .gitignore | 2 +- CLAUDE.md | 22 +- Cargo.lock | 46 ++-- Cargo.toml | 4 +- Makefile | 140 ++++++------ README.adoc | 206 +++++++++--------- RELEASE_CHECKLIST.md | 2 +- cspell.json | 1 + packaging/NOTES.adoc | 12 +- packaging/after-install | 12 +- packaging/common-fpm-options | 4 +- src/actions/accept.rs | 2 +- src/actions/clean.rs | 6 +- src/actions/delete.rs | 18 +- src/actions/diff.rs | 2 +- src/actions/list.rs | 10 +- src/actions/reject.rs | 2 +- src/actions/status.rs | 2 +- src/actions/stop.rs | 9 +- src/config/cli.rs | 58 ++--- src/config/limits.rs | 2 +- src/config/resolve.rs | 72 +++--- src/lib.rs | 2 +- src/main.rs | 4 +- src/sandbox/cgroup.rs | 8 +- src/sandbox/delete.rs | 8 +- src/sandbox/exec.rs | 6 +- src/sandbox/get_or_create.rs | 40 ++-- src/sandbox/mount_overlays.rs | 23 +- src/sandbox/settings.rs | 12 +- src/sandbox/stop.rs | 14 +- src/sandbox/unmount.rs | 2 +- src/util/access.rs | 3 +- src/util/get_running_sandbox_pid.rs | 4 +- src/util/lock_sandbox.rs | 2 +- src/util/mkdir.rs | 4 +- tests/README.md | 2 +- tests/ai_test_audio.rs | 10 +- tests/ai_test_bind_mount_validation.rs | 73 ++++--- tests/ai_test_bind_mounts.rs | 36 +-- tests/ai_test_bind_precedence.rs | 6 +- tests/ai_test_builtin_ignore_patterns.rs | 18 +- tests/ai_test_can_mkdir_coverage.rs | 10 +- tests/ai_test_clean.rs | 12 +- tests/ai_test_config_impls.rs | 6 +- tests/ai_test_config_option.rs | 2 +- tests/ai_test_corrupted_settings.rs | 136 +++++++----- tests/ai_test_delete.rs | 54 ++--- tests/ai_test_error_paths.rs | 3 +- tests/ai_test_ignore_rules.rs | 14 +- tests/ai_test_resource_limits.rs | 30 +-- tests/ai_test_run_media_mount.rs | 10 +- tests/ai_test_sandbox_settings.rs | 152 +++++++------ tests/fixtures/fixture_sandbox.rs | 12 +- ...solated_test_accept_rename_across_mount.rs | 2 +- tests/isolated_test_accept_root.rs | 6 +- tests/isolated_test_clean_running.rs | 4 +- tests/isolated_test_new.rs | 4 +- tests/isolated_test_stop_all.rs | 6 +- tests/isolated_test_stop_all_partial_fail.rs | 4 +- tests/isolated_test_sync.rs | 4 +- tests/test_bind_and_mask.rs | 12 +- tests/test_cli.rs | 54 ++--- tests/test_list.rs | 2 +- tests/test_misc.rs | 13 +- tests/test_mount_unmount_kill.rs | 2 +- tests/test_new_last.rs | 6 +- tests/test_sandbox_failures.rs | 4 +- vm-testing/01-setup-host-for-vm-testing.sh | 4 +- vm-testing/20-prepare-vm-images.sh | 46 ++-- vm-testing/30-build-image-and-start.sh | 12 +- .../42-test-different-relative-paths.sh | 14 +- vm-testing/45-test-different-filesystems.sh | 12 +- vm-testing/51-run-package-testing.sh | 10 +- vm-testing/80-generate-coverage-reports.sh | 12 +- vm-testing/99-cleanup.sh | 2 +- vm-testing/common-functions.sh | 66 +++--- vm-testing/ssh-into-coverage-test-vm.sh | 2 +- 79 files changed, 864 insertions(+), 793 deletions(-) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 5c8e0c2..3803c92 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -39,7 +39,7 @@ jobs: # 96.0 as opposed to 100% because on github and within our full-test # ubuntu vm we seem to be unable to get some profraw data for the # code that writes the llvm profile dump data at the end of setting - # up a sandbox (but the code is definitely run), as well as a + # up a layer (but the code is definitely run), as well as a # pre-kill signal handling bit of code in exec, that is also # definitely run, but the output is not captured. # diff --git a/.gitignore b/.gitignore index af03303..0e6b5fb 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,7 @@ /dist /build -dev_sandbox.sh +dev_devlayer.sh .aider* callgrind.out.* cachegrind.out.* diff --git a/CLAUDE.md b/CLAUDE.md index c297805..c588fb1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,7 +5,7 @@ code in this repository. ## Project Overview -Sandbox is a Linux containerization tool that creates lightweight copy-on-write +devlayer is a Linux containerization tool that creates lightweight copy-on-write views of the system for safely running semi-trusted programs. It uses OverlayFS to track file changes and allows selective acceptance of modifications. @@ -36,15 +36,15 @@ to track file changes and allows selective acceptance of modifications. ### Installation -- `make install` - Install sandbox locally -- `make uninstall` - Remove installed sandbox +- `make install` - Install devlayer locally +- `make uninstall` - Remove installed devlayer ## Architecture ### Core Components - **src/main.rs** - Entry point and CLI handling -- **src/actions/** - Implementation of sandbox actions (accept, reject, status, etc.) +- **src/actions/** - Implementation of layer actions (accept, reject, status, etc.) - **src/config/** - Configuration parsing and management (CLI args, env vars, config files) - **src/container/** - Core containerization logic using Linux namespaces - **src/filesystem/** - OverlayFS management and file operations @@ -52,10 +52,10 @@ to track file changes and allows selective acceptance of modifications. ### Key Concepts -1. **Sandboxes** - Named containers with isolated filesystems +1. **Layers** - Named containers with isolated filesystems 2. **OverlayFS** - Used to create copy-on-write views of the host filesystem 3. **Namespaces** - Linux namespaces for process and network isolation -4. **Storage Directory** - Default ~/.sandboxes/ stores sandbox data +4. **Storage Directory** - Default ~/.devlayer/ stores layer data ### Testing Strategy @@ -68,10 +68,10 @@ to track file changes and allows selective acceptance of modifications. 2. **Config Loading Order** (most to least specific): - CLI arguments - - Environment variables (SANDBOX\_\*) - - .sandbox.conf/.sandbox.toml in current and parent directories - - ~/.config/sandbox/config.(conf|toml) - - /etc/sandbox.(conf|toml) + - Environment variables (DEVLAYER\_\*) + - .devlayer.conf/.devlayer.toml in current and parent directories + - ~/.config/devlayer/config.(conf|toml) + - /etc/devlayer.(conf|toml) 3. **File Operations**: When working with file accept/reject operations, be aware of OverlayFS limitations regarding concurrent modifications to upper/lower filesystems. @@ -79,4 +79,4 @@ to track file changes and allows selective acceptance of modifications. 5. **Cross-Platform**: Supports x86_64 and aarch64 architectures with both GNU and musl libc variants. -6. **New tests**: New tests should be added to the `tests/` directory with a filename prefixed with `ai_test_`. Most tests should use the default name provided by the SandboxManager, if you provide a name, it needs to be prefixed with `sandbox-coverage`. +6. **New tests**: New tests should be added to the `tests/` directory with a filename prefixed with `ai_test_`. Most tests should use the default name provided by the SandboxManager, if you provide a name, it needs to be prefixed with `devlayer-coverage`. diff --git a/Cargo.lock b/Cargo.lock index 85622fd..be745a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -254,6 +254,29 @@ version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a2330da5de22e8a3cb63252ce2abb30116bf5265e89c0e01bc17015ce30a476" +[[package]] +name = "devlayer" +version = "0.4.0-dev" +dependencies = [ + "anyhow", + "chrono", + "clap", + "clap_complete", + "colored", + "data-encoding", + "fast-glob", + "libc", + "log", + "nix", + "rand", + "rstest", + "serde", + "serde_json", + "toml", + "uuid", + "walkdir", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -689,29 +712,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "sandbox" -version = "0.4.0-dev" -dependencies = [ - "anyhow", - "chrono", - "clap", - "clap_complete", - "colored", - "data-encoding", - "fast-glob", - "libc", - "log", - "nix", - "rand", - "rstest", - "serde", - "serde_json", - "toml", - "uuid", - "walkdir", -] - [[package]] name = "semver" version = "1.0.26" diff --git a/Cargo.toml b/Cargo.toml index 9a13529..7226fef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,11 +1,11 @@ [package] -name = "sandbox" +name = "devlayer" version = "0.4.0-dev" edition = "2024" include = ["src/**", "Cargo.toml", "clippy.toml", "*.lock", "tests/**", "Makefile"] [[bin]] -name = "sandbox" +name = "devlayer" path = "src/main.rs" [lib] diff --git a/Makefile b/Makefile index c507c48..0268234 100644 --- a/Makefile +++ b/Makefile @@ -11,16 +11,16 @@ watch: watchexec -w src -w Cargo.toml -- cargo build build-debug-with-setuid: build - sudo cp target/debug/sandbox target/debug/sandbox-setuid - sudo chown root:root target/debug/sandbox-setuid - sudo chmod u+s target/debug/sandbox-setuid + sudo cp target/debug/devlayer target/debug/devlayer-setuid + sudo chown root:root target/debug/devlayer-setuid + sudo chmod u+s target/debug/devlayer-setuid build-coverage-binary: CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage' LLVM_PROFILE_FILE="coverage/profraw/cargo-test-%p-%m.profraw" cargo build --profile coverage --features coverage - rm -f target/coverage/sandbox-setuid - cp target/coverage/sandbox target/coverage/sandbox-setuid - sudo chown root:root target/coverage/sandbox-setuid - sudo chmod u+s target/coverage/sandbox-setuid + rm -f target/coverage/devlayer-setuid + cp target/coverage/devlayer target/coverage/devlayer-setuid + sudo chown root:root target/coverage/devlayer-setuid + sudo chmod u+s target/coverage/devlayer-setuid audit: cargo audit @@ -59,8 +59,8 @@ ready-for-commit-tests: clean-bad-mounts: - sandbox stop --all - mount | grep 'overlay on ' | grep 'sandbox' | awk '{print $$3}' | xargs -I{} sudo umount {} + devlayer stop --all + mount | grep 'overlay on ' | grep 'devlayer' | awk '{print $$3}' | xargs -I{} sudo umount {} @@ -70,9 +70,9 @@ clean: rm -Rf --one-file-system coverage dist build generated-test-data sudo rm -f default*.profraw -clean-coverage-sandboxes: - sandbox stop 'sandbox-coverage-test-*' - sudo rm --one-file-system -Rf ~/.sandboxes/sandbox-coverage-test-* +clean-coverage-layers: + devlayer stop 'devlayer-coverage-test-*' + sudo rm --one-file-system -Rf ~/.devlayer/devlayer-coverage-test-* ### ### Testing @@ -82,7 +82,7 @@ test: build-coverage-binary # Note: This excludes tests marked with #[ignore] (like stop --all tests) sudo rm --one-file-system -Rf coverage mkdir -p coverage/profraw - sudo mkdir -p /run/media/sandbox-coverage-testing + sudo mkdir -p /run/media/devlayer-coverage-testing RUST_BACKTRACE=1 CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage' LLVM_PROFILE_FILE="coverage/profraw/cargo-test-%p-%m.profraw" cargo test --profile coverage --features coverage -- --test-threads=1 coverage coverage-report: test update-coverage-report-and-show-json @@ -91,7 +91,7 @@ update-coverage-report-and-show-json: make update-coverage-report cat coverage/html/coverage.json | jq -# We usually ignore the tests that conflict with external sandboxes, namely `stop --all`. However +# We usually ignore the tests that conflict with external layers, namely `stop --all`. However test-with-stop-all: build-coverage-binary @echo "### Running all tests including --ignored tests" sudo rm --one-file-system -Rf coverage @@ -166,78 +166,78 @@ build-release: cargo build --release --target x86_64-unknown-linux-gnu cargo build --release --target aarch64-unknown-linux-gnu sudo bash -c ' \ - chown root:root target/release/sandbox && \ - chmod u+s target/release/sandbox && \ - chown root:root target/aarch64-unknown-linux-musl/release/sandbox && \ - chmod u+s target/aarch64-unknown-linux-musl/release/sandbox && \ - chown root:root target/x86_64-unknown-linux-musl/release/sandbox && \ - chmod u+s target/x86_64-unknown-linux-musl/release/sandbox && \ - chown root:root target/aarch64-unknown-linux-gnu/release/sandbox && \ - chmod u+s target/aarch64-unknown-linux-gnu/release/sandbox && \ - chown root:root target/x86_64-unknown-linux-gnu/release/sandbox && \ - chmod u+s target/x86_64-unknown-linux-gnu/release/sandbox' + chown root:root target/release/devlayer && \ + chmod u+s target/release/devlayer && \ + chown root:root target/aarch64-unknown-linux-musl/release/devlayer && \ + chmod u+s target/aarch64-unknown-linux-musl/release/devlayer && \ + chown root:root target/x86_64-unknown-linux-musl/release/devlayer && \ + chmod u+s target/x86_64-unknown-linux-musl/release/devlayer && \ + chown root:root target/aarch64-unknown-linux-gnu/release/devlayer && \ + chmod u+s target/aarch64-unknown-linux-gnu/release/devlayer && \ + chown root:root target/x86_64-unknown-linux-gnu/release/devlayer && \ + chmod u+s target/x86_64-unknown-linux-gnu/release/devlayer' build-for-profiling: cargo build --profile profiler # Man page -build/sandbox.1: README.adoc Cargo.toml +build/devlayer.1: README.adoc Cargo.toml mkdir -p build cat README.adoc \ | sed "s/:mansource:.*/:mansource: $(VERSION)/" \ - | asciidoctor -b manpage - -o build/sandbox.1 + | asciidoctor -b manpage - -o build/devlayer.1 -man build/sandbox.1.gz: build/sandbox.1 - gzip -9 < $< > build/sandbox.1.gz +man build/devlayer.1.gz: build/devlayer.1 + gzip -9 < $< > build/devlayer.1.gz # Shell completion scripts completion-scripts: build mkdir -p build - COMPLETE=bash ./target/debug/sandbox | sed 's|/.*/sandbox|sandbox|g' > build/sandbox-bash-completion - COMPLETE=zsh ./target/debug/sandbox | sed 's|/.*/sandbox|sandbox|g' > build/sandbox-zsh-completion - COMPLETE=fish ./target/debug/sandbox | sed 's|/.*/sandbox|sandbox|g' > build/sandbox-fish-completion + COMPLETE=bash ./target/debug/devlayer | sed 's|/.*/devlayer|devlayer|g' > build/devlayer-bash-completion + COMPLETE=zsh ./target/debug/devlayer | sed 's|/.*/devlayer|devlayer|g' > build/devlayer-zsh-completion + COMPLETE=fish ./target/debug/devlayer | sed 's|/.*/devlayer|devlayer|g' > build/devlayer-fish-completion # Packaging COMMON_FPM_FILES=\ - build/sandbox.1.gz=/usr/share/man/man1/sandbox.1.gz \ - build/sandbox-bash-completion=/usr/share/bash-completion/completions/sandbox \ - build/sandbox-fish-completion=/usr/share/fish/vendor_completions.d/sandbox.fish + build/devlayer.1.gz=/usr/share/man/man1/devlayer.1.gz \ + build/devlayer-bash-completion=/usr/share/bash-completion/completions/devlayer \ + build/devlayer-fish-completion=/usr/share/fish/vendor_completions.d/devlayer.fish -package: build/sandbox.1.gz build-release completion-scripts +package: build/devlayer.1.gz build-release completion-scripts rm -Rf dist mkdir -p dist @echo "### Copying raw files to dist" - tar -czvf dist/sandbox-static-$(VERSION)-x86_64.tar.gz target/x86_64-unknown-linux-musl/release/sandbox - tar -czvf dist/sandbox-static-$(VERSION)-arm64.tar.gz target/aarch64-unknown-linux-musl/release/sandbox + tar -czvf dist/devlayer-static-$(VERSION)-x86_64.tar.gz target/x86_64-unknown-linux-musl/release/devlayer + tar -czvf dist/devlayer-static-$(VERSION)-arm64.tar.gz target/aarch64-unknown-linux-musl/release/devlayer @echo "### Building static x86_64 targets" fpm \ -t deb \ --fpm-options-file packaging/common-fpm-options \ --version $(VERSION) \ --architecture x86_64 \ - --package dist/sandbox_$(VERSION)_amd64.deb \ - target/x86_64-unknown-linux-musl/release/sandbox=/usr/bin/sandbox \ - build/sandbox-zsh-completion=/usr/share/zsh/vendor-completions/_sandbox \ + --package dist/devlayer_$(VERSION)_amd64.deb \ + target/x86_64-unknown-linux-musl/release/devlayer=/usr/bin/devlayer \ + build/devlayer-zsh-completion=/usr/share/zsh/vendor-completions/_devlayer \ $(COMMON_FPM_FILES) fpm \ -t rpm \ --fpm-options-file packaging/common-fpm-options \ --version $(VERSION) \ --architecture x86_64 \ - --package dist/sandbox.$(VERSION)-1.x86_64.rpm \ - target/x86_64-unknown-linux-musl/release/sandbox=/usr/bin/sandbox \ - build/sandbox-zsh-completion=/usr/share/zsh/site-functions/_sandbox \ + --package dist/devlayer.$(VERSION)-1.x86_64.rpm \ + target/x86_64-unknown-linux-musl/release/devlayer=/usr/bin/devlayer \ + build/devlayer-zsh-completion=/usr/share/zsh/site-functions/_devlayer \ $(COMMON_FPM_FILES) fpm \ -t pacman \ --fpm-options-file packaging/common-fpm-options \ --version $(VERSION) \ --architecture x86_64 \ - --name sandbox-bin \ - --package dist/sandbox-bin-$(VERSION)-1-x86_64.pkg.tar.zst \ - target/x86_64-unknown-linux-musl/release/sandbox=/usr/bin/sandbox \ - build/sandbox-zsh-completion=/usr/share/zsh/site-functions/_sandbox \ + --name devlayer-bin \ + --package dist/devlayer-bin-$(VERSION)-1-x86_64.pkg.tar.zst \ + target/x86_64-unknown-linux-musl/release/devlayer=/usr/bin/devlayer \ + build/devlayer-zsh-completion=/usr/share/zsh/site-functions/_devlayer \ $(COMMON_FPM_FILES) @echo "### Building static arm64 targets" fpm \ @@ -245,25 +245,25 @@ package: build/sandbox.1.gz build-release completion-scripts --fpm-options-file packaging/common-fpm-options \ --version $(VERSION) \ --architecture arm64 \ - --package dist/sandbox_$(VERSION)_arm64.deb \ - target/aarch64-unknown-linux-musl/release/sandbox=/usr/bin/sandbox \ + --package dist/devlayer_$(VERSION)_arm64.deb \ + target/aarch64-unknown-linux-musl/release/devlayer=/usr/bin/devlayer \ $(COMMON_FPM_FILES) fpm \ -t rpm \ --fpm-options-file packaging/common-fpm-options \ --version $(VERSION) \ --architecture arm64 \ - --package dist/sandbox.$(VERSION)-1.arm64.rpm \ - target/aarch64-unknown-linux-musl/release/sandbox=/usr/bin/sandbox \ + --package dist/devlayer.$(VERSION)-1.arm64.rpm \ + target/aarch64-unknown-linux-musl/release/devlayer=/usr/bin/devlayer \ $(COMMON_FPM_FILES) fpm \ -t pacman \ --fpm-options-file packaging/common-fpm-options \ --version $(VERSION) \ --architecture arm64 \ - --name sandbox-bin \ - --package dist/sandbox-bin-$(VERSION)-1-arm64.pkg.tar.zst \ - target/aarch64-unknown-linux-musl/release/sandbox=/usr/bin/sandbox \ + --name devlayer-bin \ + --package dist/devlayer-bin-$(VERSION)-1-arm64.pkg.tar.zst \ + target/aarch64-unknown-linux-musl/release/devlayer=/usr/bin/devlayer \ $(COMMON_FPM_FILES) @@ -273,7 +273,7 @@ package: build/sandbox.1.gz build-release completion-scripts ### Manual install / uninstall targets ### -install: build/sandbox.1.gz completion-scripts +install: build/devlayer.1.gz completion-scripts cargo build --release # Determine the installation directory based on the PATH @INSTALL_DIR=$$(if echo "$$PATH" | tr ':' '\n' | grep -q "^/usr/bin$$"; then \ @@ -283,28 +283,28 @@ install: build/sandbox.1.gz completion-scripts else \ echo "/usr/bin"; \ fi); \ - echo "Installing to $$INSTALL_DIR/sandbox"; \ - sudo cp target/release/sandbox "$$INSTALL_DIR/sandbox.new"; \ - sudo mv "$$INSTALL_DIR/sandbox.new" "$$INSTALL_DIR/sandbox"; \ - sudo chown root:root "$$INSTALL_DIR/sandbox"; \ - sudo chmod u+s "$$INSTALL_DIR/sandbox" - sudo cp build/sandbox.1.gz /usr/share/man/man1/sandbox.1.gz - sudo cp build/sandbox-bash-completion /usr/share/bash-completion/completions/sandbox - sudo cp build/sandbox-zsh-completion /usr/share/zsh/site-functions/_sandbox - sudo cp build/sandbox-fish-completion /usr/share/fish/vendor_completions.d/sandbox.fish + echo "Installing to $$INSTALL_DIR/devlayer"; \ + sudo cp target/release/devlayer "$$INSTALL_DIR/devlayer.new"; \ + sudo mv "$$INSTALL_DIR/devlayer.new" "$$INSTALL_DIR/devlayer"; \ + sudo chown root:root "$$INSTALL_DIR/devlayer"; \ + sudo chmod u+s "$$INSTALL_DIR/devlayer" + sudo cp build/devlayer.1.gz /usr/share/man/man1/devlayer.1.gz + sudo cp build/devlayer-bash-completion /usr/share/bash-completion/completions/devlayer + sudo cp build/devlayer-zsh-completion /usr/share/zsh/site-functions/_devlayer + sudo cp build/devlayer-fish-completion /usr/share/fish/vendor_completions.d/devlayer.fish uninstall: - sudo rm -f /usr/bin/sandbox \ - /usr/share/man/man1/sandbox.1.gz \ - /usr/share/bash-completion/completions/sandbox \ - /usr/share/zsh/site-functions/_sandbox \ - /usr/share/fish/vendor_completions.d/sandbox.fish + sudo rm -f /usr/bin/devlayer \ + /usr/share/man/man1/devlayer.1.gz \ + /usr/share/bash-completion/completions/devlayer \ + /usr/share/zsh/site-functions/_devlayer \ + /usr/share/fish/vendor_completions.d/devlayer.fish .PHONY: all build watch build-coverage-binary clippy lint clippy-fix \ - install-pre-commit-hooks ready-for-commit-tests clean clean-coverage-sandboxes \ + install-pre-commit-hooks ready-for-commit-tests clean clean-coverage-layers \ test test-ignored quick-test coverage coverage-report update-coverage-report \ full-coverage full-test update-coverage-report-and-show-json \ full-test prepared-coverage-vm install install-cov-tools uninstall \ diff --git a/README.adoc b/README.adoc index 5b230c5..2252437 100644 --- a/README.adoc +++ b/README.adoc @@ -4,27 +4,27 @@ // ifndef::env-github,env-vscode[] -= sandbox(1) += devlayer(1) :doctype: manpage -:man manual: Sandbox Manual +:man manual: devlayer Manual :man source: 0.3.0 :man-linkstyle: pass:[blue R < >] endif::[] ifdef::env-github,env-vscode[] -= Sandbox += devlayer endif::[] ifndef::env-github,env-vscode[] == Name -sandbox - +devlayer - endif::[] A tool for creating lightweight containerized views of your computer for safely running semi-trusted programs and selectively managing their output. == Description -The `sandbox` tool creates lightweight containerized copy-on-write views of your +The `devlayer` tool creates lightweight containerized copy-on-write views of your computer with optional network access. Its primary purpose is to run semi-trusted programs—such as AI agents, app images, or shell installers—in an environment that mirrors your host computer, while preventing them from @@ -33,21 +33,21 @@ doing things like testing migrations or file reorganizations as it lets you run your code, examine the changes, reject the changes and try again rapidly. If you're satisfied with the outcome of your semi-trusted program, you can use the -`sandbox` tool to selectively accept some or all of the changes made to your +`devlayer` tool to selectively accept some or all of the changes made to your files. If you're not satisfied, you can simply reject the changes. -Changes made within sandboxes are easily browsable and persist until you remove -them, allowing you to reuse the same sandbox for as long as needed and by as many -processes as desired. Sandboxes are also very lightweight and quick to create, -making it practical to create new sandboxes for each task you need to perform. +Changes made within layers are easily browsable and persist until you remove +them, allowing you to reuse the same layer for as long as needed and by as many +processes as desired. Layers are also very lightweight and quick to create, +making it practical to create new layers for each task you need to perform. Please note: The use of the term `semi-trusted` is meant to distinguish code that may do things you don't want it to do, but isn't actively malicious in a sophisticated way. While the privilege escalations, data exfiltration, and other -ways of escaping the sandbox would absolutely be considered a bug, it is not -advised to run actively malicious code within a sandbox as there are not many +ways of escaping the layer would absolutely be considered a bug, it is not +advised to run actively malicious code within a layer as there are not many layers to protect your host system from the malicious code, and it is easy for -the code to detect it is running in a sandbox and potentially act accordingly. +the code to detect it is running in a layer and potentially act accordingly. You should be using other more isolated environments for that sort of research. @@ -56,7 +56,7 @@ ifdef::env-github,env-vscode[] To build and install from source simply run `make install`. -Arch Linux users can install the `sandbox-bin` package from the AUR. +Arch Linux users can install the `devlayer-bin` package from the AUR. For most other Linux distributions there are applicable binary packages available from the releases page: https://github.com/anoek/sandbox/releases @@ -72,41 +72,41 @@ endif::[] == Synopsis -*sandbox* [OPTIONS] +*devlayer* [OPTIONS] -*sandbox* [OPTIONS] [ACTION] [ACTION_ARGUMENTS...] +*devlayer* [OPTIONS] [ACTION] [ACTION_ARGUMENTS...] == Quick examples: -Hop into a sandboxed shell +Hop into a shell inside a layer ``` - sandbox + devlayer ``` -Try that trendy web based install script in a sandbox first +Try that trendy web based install script in a layer first ``` - curl -s https://trustmebro.sh | sandbox sh + curl -s https://trustmebro.sh | devlayer sh ``` Let AIs run wild in YOLO mode without too much risk ``` - sandbox --net=host aider + devlayer --net=host aider ``` Check what files were modified ``` - sandbox status + devlayer status ``` Accept changes to all the python files in the current directory, copying -them from the sandbox to the host system. +them from the layer to the host system. ``` - sandbox accept '*.py' + devlayer accept '*.py' ``` -Stop all running processes in the sandbox and unmount the copy on write filesystem overlays. +Stop all running processes in the layer and unmount the copy on write filesystem overlays. ``` - sandbox stop + devlayer stop ``` == Actions: @@ -115,32 +115,32 @@ Stop all running processes in the sandbox and unmount the copy on write filesyst Read and display the configuration. Use in conjunction with `-v` to debug where configuration values are set. `list [PATTERNS]`:: -List running sandboxes matching these patterns (defaults to all) +List running layers matching these patterns (defaults to all) `status [PATTERNS]`:: -Show status of the sandbox matching the patterns in the current directory, or specified -patterns. Use `status /` to show status of all files in the sandbox. +Show status of the layer matching the patterns in the current directory, or specified +patterns. Use `status /` to show status of all files in the layer. `diff`:: -Show changes in the sandbox relative to the current changes +Show changes in the layer relative to the current changes `reject [PATTERNS]`:: -Reject changes in the sandbox. This works relative to your current working directory only, and changes outside of your working directory are ignored. +Reject changes in the layer. This works relative to your current working directory only, and changes outside of your working directory are ignored. `accept [PATTERNS]`:: -Accept changes in the sandbox. This works relative to your current working directory only, and changes outside of your working directory are ignored. +Accept changes in the layer. This works relative to your current working directory only, and changes outside of your working directory are ignored. `sync`:: -Synchronize changes that might have occurred in your host file system so that they are reflected in running sandboxes. Note, this performs a system wide filesystem sync and flushes all caches. +Synchronize changes that might have occurred in your host file system so that they are reflected in running layers. Note, this performs a system wide filesystem sync and flushes all caches. `stop [--all]`:: -Kill all processes in the sandbox and unmount the filesystems. Note this will not reject any changes +Kill all processes in the layer and unmount the filesystems. Note this will not reject any changes `delete [PATTERNS]`:: -Stop and delete all files associated with the sandboxes matching the provided patterns. If no patterns are provided, deletes the default or --name'd sandbox. +Stop and delete all files associated with the layers matching the provided patterns. If no patterns are provided, deletes the default or --name'd layer. `clean`:: -Delete stopped ephemeral sandboxes (created with `--new`) that are more than a week old, and all sandboxes left behind by the test suite. +Delete stopped ephemeral layers (created with `--new`) that are more than a week old, and all layers left behind by the test suite. `help`:: Print this message or the help of the given subcommand(s) @@ -152,19 +152,19 @@ Print this message or the help of the given subcommand(s) Set the log level to one of trace, debug, info, warn, or error. `-v` is shorthand for enabling verbose (trace) logging. `--name=`:: -Name of the sandbox, defaults to "sandbox". Executables run within the same sandbox +Name of the layer, defaults to "devlayer". Executables run within the same layer name will be run in the same container. `--new`:: -Create a new sandbox with an auto-generated timestamp name. This is useful for -creating ephemeral sandboxes for one-off tasks. Cannot be used with --name or --last. +Create a new layer with an auto-generated timestamp name. This is useful for +creating ephemeral layers for one-off tasks. Cannot be used with --name or --last. `--last`:: -Use the most recently created sandbox. This is useful for quickly returning to -the last sandbox you were working in. Cannot be used with --name or --new. +Use the most recently created layer. This is useful for quickly returning to +the last layer you were working in. Cannot be used with --name or --new. `--storage-dir=`:: -Base storage directory for all sandboxes. Defaults to `~/.sandboxes/` +Base storage directory for all layers. Defaults to `~/.devlayer/` `--net[=host|none]`:: Sets network access level. With no parameter this enables host networking. The @@ -172,66 +172,66 @@ default value is `none`, which disables network access. If you want to enable network access by default you can store net="host" in a config file. `--bind[=]`:: -Specify directories or files to bind into the sandbox bypassing the sandbox +Specify directories or files to bind into the layer bypassing the layer OverlayFS system. Examples: - * `--bind=.` bind the current directory into the sandbox so that changes made + * `--bind=.` bind the current directory into the layer so that changes made will be reflected in the host system without having to accept/reject them. The rest of the system will still be mounted in OverlayFS FS layers to protect your system. - * `--bind=data1:/data` to mount the relative `data1` directory into the sandbox as `/data`. + * `--bind=data1:/data` to mount the relative `data1` directory into the layer as `/data`. * `--bind=my/protected/dir::ro` will mount the relative `my/protected/dir` - directory into the sandbox as read only. - * `SANDBOX_BIND="my/protected/dir::ro" sandbox` works as well. - * `SANDBOX_BIND="/dir1,/dir2" sandbox --bind=/dir3:/dir4:ro,/dir5` style combined mix and match bind mounting also works. + directory into the layer as read only. + * `DEVLAYER_BIND="my/protected/dir::ro" devlayer` works as well. + * `DEVLAYER_BIND="/dir1,/dir2" devlayer --bind=/dir3:/dir4:ro,/dir5` style combined mix and match bind mounting also works. `--mask[=]`:: Mask paths by mounting tmpfs (for directories) or /dev/null (for files) to prevent access to sensitive data. This is useful for hiding configuration or -credential directories from sandboxed processes. +credential directories from processes in the layer. Examples: - * `--mask=~/.ssh` hides your SSH keys from the sandboxed process + * `--mask=~/.ssh` hides your SSH keys from processes in the layer * `--mask=/etc/passwd` masks the passwd file with /dev/null * `--mask=~/.aws,~/.config/gcloud` masks multiple paths - * `SANDBOX_MASK="~/.ssh,~/.aws" sandbox` works as well + * `DEVLAYER_MASK="~/.ssh,~/.aws" devlayer` works as well `--no-default-binds`:: Disable default system bind mounts (e.g., /dev/fuse, D-Bus sockets, user directories). -This is useful when you want complete control over what gets mounted into the sandbox. +This is useful when you want complete control over what gets mounted into the layer. `--audio`:: -Allow audio inside the sandbox by binding the PipeWire and PulseAudio sockets +Allow audio inside the layer by binding the PipeWire and PulseAudio sockets from `$XDG_RUNTIME_DIR` and the ALSA devices in `/dev/snd`. Audio is disabled -by default because this also allows sandboxed programs to record from your +by default because this also allows programs in the layer to record from your microphone. Audio works with or without `--net`, and is not affected by `--no-default-binds`. To enable audio by default you can store `audio = true` -in a config file, and `SANDBOX_AUDIO=false` will override that for a single +in a config file, and `DEVLAYER_AUDIO=false` will override that for a single run. `--cpus=`:: -Limit how many CPUs the sandbox can use. Fractional values such as `1.5` are +Limit how many CPUs the layer can use. Fractional values such as `1.5` are allowed. Negative values mean all but that many CPUs, so `--cpus=-2` on a 32 -CPU machine lets the sandbox use 30. This limits the total CPU time the -sandbox gets, it does not pin it to specific CPUs, so tools like `nproc` will +CPU machine lets the layer use 30. This limits the total CPU time the +layer gets, it does not pin it to specific CPUs, so tools like `nproc` will still report every CPU. `--memory=`:: -Limit how much memory the sandbox can use, for example `512M` or `4G`. -Suffixes are binary (`1K` is 1024 bytes). Swap is not available to a sandbox -with a memory limit, and when the sandbox runs out of memory the kernel kills +Limit how much memory the layer can use, for example `512M` or `4G`. +Suffixes are binary (`1K` is 1024 bytes). Swap is not available to a layer +with a memory limit, and when the layer runs out of memory the kernel kills its largest process. + -Resource limits use cgroup v2 and apply to every process in the sandbox. They -are set when the sandbox starts, so you need to stop the sandbox to change +Resource limits use cgroup v2 and apply to every process in the layer. They +are set when the layer starts, so you need to stop the layer to change them. Use `unlimited` to remove a limit set in a config file, for example -`--cpus=unlimited` or `SANDBOX_MEMORY=unlimited`. +`--cpus=unlimited` or `DEVLAYER_MEMORY=unlimited`. + -A sandbox started inside another sandbox can't set up limits of its own. -Instead it warns and shares the limits of the sandbox it's running in. Limits -may not be available at all when `sandbox` is run inside a container. +A layer started inside another layer can't set up limits of its own. +Instead it warns and shares the limits of the layer it's running in. Limits +may not be available at all when `devlayer` is run inside a container. `--json`:: -Formats action output as a JSON blob. Does nothing for sandboxed commands +Formats action output as a JSON blob. Does nothing for layered commands `--no-config`:: Do not load config files. Environment variables will still be used. @@ -248,39 +248,39 @@ Print help `-V, --version`:: Print version -== Sandboxed Commands +== Commands The CLI argument parser will treat anything after the `[OPTIONS]` as either an -action (listed above), or a command to run in the sandbox. Running a command -will implicitly start the sandbox if it isn't running already. +action (listed above), or a command to run in the layer. Running a command +will implicitly start the layer if it isn't running already. -After the `[OPTIONS]`, provided you're not running an action, `sandbox` +After the `[OPTIONS]`, provided you're not running an action, `devlayer` will execute whatever command you provide, along with all subsequent arguments, -in a sandboxed environment. +inside a layer. If you want to run a command that happens to have the same name as an action, you can use the `--` flag to separate the command from the action arguments. For example: ``` - sandbox -- diff + devlayer -- diff ``` == Config Files -When invoked `sandbox` will look for files named `.sandbox.conf` and `.sandbox.toml` in your current directory and every ancestor directory up to you home directory (or / if invoked outside of a user's home directory), as well as in `~/.config/sandbox/config.(conf|toml)`, and finally `/etc/sandbox.(conf|toml)`, with more specific files overriding less specific ones. +When invoked `devlayer` will look for files named `.devlayer.conf` and `.devlayer.toml` in your current directory and every ancestor directory up to you home directory (or / if invoked outside of a user's home directory), as well as in `~/.config/devlayer/config.(conf|toml)`, and finally `/etc/devlayer.(conf|toml)`, with more specific files overriding less specific ones. These config files can set most of the CLI options: ``` - # Name of the sandbox - name="my-sandbox" + # Name of the layer + name="my-layer" - # Path to the directory where the sandbox will store its data - storage_dir="/path/to/sandbox/storage" + # Path to the directory where the layer will store its data + storage_dir="/path/to/devlayer/storage" # "none" or "host" net="none" @@ -288,7 +288,7 @@ These config files can set most of the CLI options: # "trace", "debug", "info", "warn", or "error" log_level="info" - # Bind mounts to apply to the sandbox + # Bind mounts to apply to the layer bind=[ "/dir1", "/dir2::ro", @@ -311,13 +311,13 @@ These config files can set most of the CLI options: You can also set most of the options with environment variables if you wish: ``` - SANDBOX_NAME="my-sandbox" - SANDBOX_STORAGE_DIR="/path/to/sandbox/storage" - SANDBOX_NET="none" - SANDBOX_LOG_LEVEL="info" - SANDBOX_BIND="/my/dir" - SANDBOX_CPUS="-2" - SANDBOX_MEMORY="8G" + DEVLAYER_NAME="my-layer" + DEVLAYER_STORAGE_DIR="/path/to/devlayer/storage" + DEVLAYER_NET="none" + DEVLAYER_LOG_LEVEL="info" + DEVLAYER_BIND="/my/dir" + DEVLAYER_CPUS="-2" + DEVLAYER_MEMORY="8G" ``` @@ -340,43 +340,43 @@ fairly new project so please expect well covered bugs, security issues, and rough edges. Please report any issues you run into to the issue tracker: https://github.com/anoek/sandbox/issues -=== Changing files in both the host system and the sandbox +=== Changing files in both the host system and the layer -`sandbox` uses OverlayFS to manage tracking of file changes and allow -applications to operate within the sandboxed environment seeing those file +`devlayer` uses OverlayFS to manage tracking of file changes and allow +applications to operate within the layered environment seeing those file changes. The safe and supported way to operate with OverlayFS file systems is to avoid making any changes to either to the "lower" file system ( your host filesystem), or to the "upper" file system (the changes that -have been made in the sandbox.) In this regard, the safest way to work -with a sandbox is to start your sandbox, do whatever you want to do within -your sandbox, stop the sandbox, and then accept or reject your changes. +have been made in the layer.) In this regard, the safest way to work +with a layer is to start your layer, do whatever you want to do within +your layer, stop the layer, and then accept or reject your changes. That said it is often convenient to ignore this and make changes to the files on the host system, or to do things like accept or reject changes in -a running sandbox (which makes changes to the "upper" file system). In practice +a running layer (which makes changes to the "upper" file system). In practice this generally works as expected, the primary risk you run -is seeing stale or cached data within the sandbox if you choose to do this. -If you do run into visible problems, you may find running `sandbox sync` +is seeing stale or cached data within the layer if you choose to do this. +If you do run into visible problems, you may find running `devlayer sync` will resolve your issues. If you would like to accept or reject changes from the -sandbox without first stopping the sandbox, `sandbox` will happily oblige the +layer without first stopping the layer, `devlayer` will happily oblige the request, but be aware that technically this is not supported by OverlayFS. These -operations implicitly perform the same actions as `sandbox sync` after their +operations implicitly perform the same actions as `devlayer sync` after their work, so there is no need to call sync again after accepting or rejecting -changes from the sandbox. +changes from the layer. -=== Moving directories out from under a sandbox +=== Moving directories out from under a layer Moving directories around in your host system may be problematic in a running -sandbox, particularly if the sandbox has also moved a moved directory or made +layer, particularly if the layer has also moved a moved directory or made changes within a directory. Although nothing should explode, it's easy to run -into read errors and other file errors within your sandbox if you do this, so +into read errors and other file errors within your layer if you do this, so you should probably avoid doing such things. === Partial accepts that depend on other non-accepted things -In a sandbox, if you move or create a directory, then make a file change in +In a layer, if you move or create a directory, then make a file change in said directory, then try to accept just that file, you will run into an error. Making some rather complicated moves and trying to only accept some of them may result in an accept erroring out in the middle and leaving a mess for you to clean diff --git a/RELEASE_CHECKLIST.md b/RELEASE_CHECKLIST.md index 1ac83a2..e3c7437 100644 --- a/RELEASE_CHECKLIST.md +++ b/RELEASE_CHECKLIST.md @@ -3,4 +3,4 @@ - [ ] `git push origin 0.x.0` - [ ] `make package` - [ ] Release on GitHub, upload files from `dist` -- [ ] Update `sandbox-bin/PKGBUILD` with new versions and sha256sums, `make` to validate, commit and push. +- [ ] Update `devlayer-bin/PKGBUILD` with new versions and sha256sums, `make` to validate, commit and push. diff --git a/cspell.json b/cspell.json index a36ea8e..7a13f2d 100644 --- a/cspell.json +++ b/cspell.json @@ -194,6 +194,7 @@ "rustlib", "rustsec", "rustup", + "devlayer", "sandboxd", "sandboxed", "sandboxing", diff --git a/packaging/NOTES.adoc b/packaging/NOTES.adoc index eebc138..83f1d6d 100644 --- a/packaging/NOTES.adoc +++ b/packaging/NOTES.adoc @@ -7,34 +7,34 @@ == Shell completion -You can enable shell completion for the `sandbox` command by adding the +You can enable shell completion for the `devlayer` command by adding the following snippets to the appropriate shell configuration files, or if you're packaging the shell completion and both will be updated together you can expand the shell scripts to avoid the runtime execution of the -`sandbox` binary to generate the completion scripts. +`devlayer` binary to generate the completion scripts. ### bash ```bash -source <(COMPLETE=bash sandbox) +source <(COMPLETE=bash devlayer) ``` ### zsh ```bash -source <(COMPLETE=zsh sandbox) +source <(COMPLETE=zsh devlayer) ``` ### fish ```sh -source (COMPLETE=fish sandbox | psub) +source (COMPLETE=fish devlayer | psub) ``` ### elvish ```sh -eval (E:COMPLETE=elvish sandbox | slurp) +eval (E:COMPLETE=elvish devlayer | slurp) ``` diff --git a/packaging/after-install b/packaging/after-install index 843a444..d50b2b0 100644 --- a/packaging/after-install +++ b/packaging/after-install @@ -1,11 +1,11 @@ #!/usr/bin/sh -chown root:root /usr/bin/sandbox -chmod u+s /usr/bin/sandbox +chown root:root /usr/bin/devlayer +chmod u+s /usr/bin/devlayer -chmod 644 /usr/share/bash-completion/completions/sandbox -chmod 644 /usr/share/zsh/site-functions/_sandbox -chmod 644 /usr/share/fish/vendor_completions.d/sandbox.fish +chmod 644 /usr/share/bash-completion/completions/devlayer +chmod 644 /usr/share/zsh/site-functions/_devlayer +chmod 644 /usr/share/fish/vendor_completions.d/devlayer.fish -chmod 644 /usr/share/man/man1/sandbox.1.gz +chmod 644 /usr/share/man/man1/devlayer.1.gz diff --git a/packaging/common-fpm-options b/packaging/common-fpm-options index 75dc836..e44bb57 100644 --- a/packaging/common-fpm-options +++ b/packaging/common-fpm-options @@ -1,7 +1,7 @@ -s dir ---name sandbox +--name devlayer --license mit ---description "Run commands in a sandboxed copy-on-write view of your computer" +--description "Run commands in a copy-on-write layer over your computer" --url "https://github.com/anoek/sandbox" --maintainer "Akita Noek " --deb-recommends diffutils diff --git a/src/actions/accept.rs b/src/actions/accept.rs index b77e75b..7fd780f 100644 --- a/src/actions/accept.rs +++ b/src/actions/accept.rs @@ -120,7 +120,7 @@ pub fn accept( sandbox: &Sandbox, patterns: &[String], ) -> Result<()> { - trace!("Accepting changes from sandbox {}", sandbox.name); + trace!("Accepting changes from layer {}", sandbox.name); let cwd = std::env::current_dir()?; let all_changes = sandbox.changes(config)?; diff --git a/src/actions/clean.rs b/src/actions/clean.rs index 5215981..24bcbba 100644 --- a/src/actions/clean.rs +++ b/src/actions/clean.rs @@ -11,7 +11,7 @@ use std::path::Path; /// Sandboxes created by the test suite. These are always cleaned up, /// running or not. const TEST_SANDBOX_PATTERNS: &[&str] = - &["sandbox-coverage-*", "sandbox-bind-empty-*"]; + &["devlayer-coverage-*", "devlayer-bind-empty-*"]; /// Stopped ephemeral sandboxes older than this are cleaned up. const EPHEMERAL_MAX_AGE_DAYS: i64 = 7; @@ -21,7 +21,7 @@ pub fn clean( sandboxes_storage_dir: &Path, force: bool, ) -> Result<()> { - trace!("Finding sandboxes to clean"); + trace!("Finding layers to clean"); let [running_sandboxes, stopped_sandboxes] = get_sandboxes(sandboxes_storage_dir, &[])?; @@ -41,7 +41,7 @@ pub fn clean( .collect(); if running_to_delete.is_empty() && stopped_to_delete.is_empty() { - outln!("No sandboxes to clean."); + outln!("No layers to clean."); return Ok(()); } diff --git a/src/actions/delete.rs b/src/actions/delete.rs index ecabaa1..72ea995 100644 --- a/src/actions/delete.rs +++ b/src/actions/delete.rs @@ -56,7 +56,7 @@ pub fn delete( patterns: &[String], force: bool, ) -> Result<()> { - trace!("Preparing to delete sandboxes"); + trace!("Preparing to delete layers"); let [running_sandboxes, stopped_sandboxes] = if patterns.is_empty() { if Sandbox::from_location( @@ -109,11 +109,11 @@ pub fn delete( if stopped_sandboxes.is_empty() && running_sandboxes.is_empty() { if patterns.is_empty() { outln!( - "No sandbox by the name of '{}' found to delete.", + "No layer by the name of '{}' found to delete.", config.name ); } else { - outln!("No sandboxes found matching the specified patterns."); + outln!("No layers found matching the specified patterns."); } return Ok(()); } @@ -138,7 +138,7 @@ pub fn delete_sandboxes( ) -> Result<()> { // Show sandboxes that will be deleted and ask for confirmation if !force { - outln!("The following sandboxes will be deleted:"); + outln!("The following layers will be deleted:"); for (list, stopped) in [(running_sandboxes, false), (stopped_sandboxes, true)] { @@ -174,7 +174,7 @@ pub fn delete_sandboxes( } // Use eprint! for the prompt since print! is not allowed - eprint!("\nAre you sure you want to delete these sandboxes? [y/N] "); + eprint!("\nAre you sure you want to delete these layers? [y/N] "); let _ = io::stderr().flush(); let mut response = String::new(); @@ -200,22 +200,22 @@ pub fn delete_sandboxes( stopped, )?; - trace!("Deleting sandbox: {}", sandbox_entry.name); + trace!("Deleting layer: {}", sandbox_entry.name); match sandbox_entry.sandbox.delete() { Ok(()) => { - outln!("Deleted sandbox: {}", sandbox_entry.name.green()); + outln!("Deleted layer: {}", sandbox_entry.name.green()); deleted_sandboxes .push(Value::String(sandbox_entry.name.clone())); } Err(e) => { - outln!("Error deleting sandbox: {}", e); + outln!("Error deleting layer: {}", e); errors.push(Value::String(e.to_string())); } } } } - outln!("{} sandboxes deleted", deleted_sandboxes.len()); + outln!("{} layers deleted", deleted_sandboxes.len()); // Set JSON output set_json_output("status", &Value::String("success".to_string())); diff --git a/src/actions/diff.rs b/src/actions/diff.rs index d83986a..b7ae921 100644 --- a/src/actions/diff.rs +++ b/src/actions/diff.rs @@ -18,7 +18,7 @@ pub fn diff( sandbox: &Sandbox, patterns: &[String], ) -> Result<()> { - trace!("Diffing sandbox {}", sandbox.name); + trace!("Diffing layer {}", sandbox.name); if json { return Err(anyhow::anyhow!("JSON mode is not supported for diff")); diff --git a/src/actions/list.rs b/src/actions/list.rs index 983f59c..19d7c01 100644 --- a/src/actions/list.rs +++ b/src/actions/list.rs @@ -12,13 +12,13 @@ use crate::{ }; pub fn list(sandboxes_storage_dir: &Path, patterns: &[String]) -> Result<()> { - trace!("Listing sandboxes"); + trace!("Listing layers"); let [running_sandboxes, stopped_sandboxes] = get_sandboxes(sandboxes_storage_dir, patterns)?; if !running_sandboxes.is_empty() { - outln!("Running sandboxes:"); + outln!("Running layers:"); for sandbox in &running_sandboxes { outln!("{}", sandbox); } @@ -29,20 +29,20 @@ pub fn list(sandboxes_storage_dir: &Path, patterns: &[String]) -> Result<()> { } if !stopped_sandboxes.is_empty() { - outln!("{}", "Stopped sandboxes:".dimmed()); + outln!("{}", "Stopped layers:".dimmed()); for sandbox in &stopped_sandboxes { outln!("{}", sandbox.dimmed()); } } set_json_output( - "running_sandboxes", + "running_layers", &Value::Array( running_sandboxes.into_iter().map(Value::String).collect(), ), ); set_json_output( - "stopped_sandboxes", + "stopped_layers", &Value::Array( stopped_sandboxes.into_iter().map(Value::String).collect(), ), diff --git a/src/actions/reject.rs b/src/actions/reject.rs index d921ec8..792f6a6 100644 --- a/src/actions/reject.rs +++ b/src/actions/reject.rs @@ -12,7 +12,7 @@ pub fn reject( sandbox: &Sandbox, patterns: &[String], ) -> Result<()> { - trace!("Rejecting changes from sandbox {}", sandbox.name); + trace!("Rejecting changes from layer {}", sandbox.name); let cwd = std::env::current_dir()?; let changes = sandbox.changes(config)?; diff --git a/src/actions/status.rs b/src/actions/status.rs index 9dafa71..a1dff96 100644 --- a/src/actions/status.rs +++ b/src/actions/status.rs @@ -19,7 +19,7 @@ pub fn status( sandbox: &Sandbox, patterns: &[String], ) -> Result<()> { - trace!("Status of sandbox {}", sandbox.name); + trace!("Status of layer {}", sandbox.name); let cwd = std::env::current_dir()?; let all_changes = sandbox.changes(config)?; diff --git a/src/actions/stop.rs b/src/actions/stop.rs index 71f5955..52b6ff6 100644 --- a/src/actions/stop.rs +++ b/src/actions/stop.rs @@ -13,7 +13,7 @@ pub fn stop( uid: Uid, gid: Gid, ) -> Result<()> { - trace!("Stopping sandbox {}", sandbox_name); + trace!("Stopping layer {}", sandbox_name); let (sandbox, _lock) = Sandbox::get(sandboxes_storage_dir, sandbox_name, uid, gid, None)?; @@ -39,10 +39,7 @@ pub fn stop_all( gid: Gid, patterns: &[String], ) -> Result<()> { - trace!( - "Stopping all sandboxes in {}", - sandboxes_storage_dir.display() - ); + trace!("Stopping all layers in {}", sandboxes_storage_dir.display()); let sandboxes = sandboxes_storage_dir.read_dir()?; for sandbox in sandboxes { @@ -87,7 +84,7 @@ pub fn stop_all( match stop(sandboxes_storage_dir, &sandbox_name, uid, gid) { Ok(_) => {} Err(e) => { - warn!("Failed to kill sandbox {}: {}", sandbox_name, e); + warn!("Failed to kill layer {}: {}", sandbox_name, e); } } } diff --git a/src/config/cli.rs b/src/config/cli.rs index 602d590..e3f8be7 100644 --- a/src/config/cli.rs +++ b/src/config/cli.rs @@ -6,7 +6,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; #[derive(Parser, Clone, Debug)] #[command(version, about, long_about = None, - override_usage = "\n sandbox [OPTIONS] [ACTION] [ACTION_ARGUMENTS...]\n sandbox [OPTIONS] ")] + override_usage = "\n devlayer [OPTIONS] [ACTION] [ACTION_ARGUMENTS...]\n devlayer [OPTIONS] ")] pub struct Args { /********************/ /* Flags and settings */ @@ -23,19 +23,19 @@ pub struct Args { )] pub log_level: Option, - /// Name of the sandbox, defaults to "sandbox" + /// Name of the layer, defaults to "devlayer" #[arg(long, global = true, value_hint = clap::ValueHint::Other, add = ArgValueCompleter::new(sandbox_name_completion), conflicts_with_all = &["new", "last"])] pub name: Option, - /// Create a new sandbox with an auto-generated timestamp name + /// Create a new layer with an auto-generated timestamp name #[arg(long, global = true, conflicts_with_all = &["name", "last"])] pub new: bool, - /// Use the most recently created sandbox + /// Use the most recently created layer #[arg(long, global = true, conflicts_with_all = &["name", "new"])] pub last: bool, - /// Base storage directory for all sandboxes. Defaults to `~/.sandboxes/` + /// Base storage directory for all layers. Defaults to `~/.devlayer/` #[arg(long, global = true)] pub storage_dir: Option, @@ -51,7 +51,7 @@ pub struct Args { )] pub net: Option, - /// Bind mount directories or files into the sandbox. Can be specified multiple times. + /// Bind mount directories or files into the layer. Can be specified multiple times. /// Format: source:target or just path (mounts to same path). Multiple paths can be /// specified by using --bind multiple times or as a comma-separated list. #[arg( @@ -81,9 +81,9 @@ pub struct Args { #[arg(long, global = true, action = clap::ArgAction::SetTrue)] pub audio: bool, - /// Limit how many CPUs the sandbox can use. Fractional values such as 1.5 + /// Limit how many CPUs the layer can use. Fractional values such as 1.5 /// are allowed. Negative values mean all but that many CPUs, so -2 on a - /// 32 CPU machine allows the sandbox to use 30. Use "unlimited" to remove + /// 32 CPU machine allows the layer to use 30. Use "unlimited" to remove /// a limit set in a config file. Requires cgroup v2. #[arg( long, @@ -93,13 +93,13 @@ pub struct Args { )] pub cpus: Option, - /// Limit how much memory the sandbox can use, for example 512M or 4G. - /// Swap is not available to sandboxes with a memory limit. Use + /// Limit how much memory the layer can use, for example 512M or 4G. + /// Swap is not available to layers with a memory limit. Use /// "unlimited" to remove a limit set in a config file. Requires cgroup v2. #[arg(long, global = true, value_name = "SIZE")] pub memory: Option, - /// Formats action output as a JSON blob. Does nothing for sandboxed commands. + /// Formats action output as a JSON blob. Does nothing for layered commands. #[arg(long, global = true, action = clap::ArgAction::SetTrue)] pub json: bool, @@ -130,14 +130,14 @@ pub struct Args { /*********************/ /* Sandboxed Command */ /*********************/ - /// The command to run in the sandbox. If no command is provided, the current shell will be used. - /// If the sandbox is not running, it will be started with the command. + /// The command to run in the layer. If no command is provided, the current shell will be used. + /// If the layer is not running, it will be started with the command. #[arg( trailing_var_arg = true, allow_hyphen_values = true, num_args = 0.., value_parser = validate_command, - help_heading = "Sandboxed Command", + help_heading = "Command", )] pub sandboxed_command: Option>, } @@ -152,69 +152,69 @@ pub enum Action { keys: Option>, }, - /// List running sandboxes matching these patterns (defaults to all) + /// List running layers matching these patterns (defaults to all) List { - /// Patterns of sandboxes to list + /// Patterns of layers to list #[arg(value_name = "PATTERNS", num_args = 0.., flatten = true)] patterns: Option>, }, - /// Show status of the sandbox matching the patterns in the current directory, or specified - /// patterns. Use `status /` to show status of all files in the sandbox. + /// Show status of the layer matching the patterns in the current directory, or specified + /// patterns. Use `status /` to show status of all files in the layer. Status { /// Patterns of files to show #[arg(value_name = "PATTERNS", num_args = 0..)] patterns: Option>, }, - /// Show changes in the sandbox relative to the current changes + /// Show changes in the layer relative to the current changes Diff { /// Patterns of files to diff #[arg(value_name = "PATTERNS", num_args = 0..)] patterns: Option>, }, - /// Accept changes in the sandbox + /// Accept changes in the layer Accept { #[arg(value_name = "PATTERNS", num_args = 0..)] patterns: Option>, }, - /// Reject changes in the sandbox + /// Reject changes in the layer Reject { #[arg(value_name = "PATTERNS", num_args = 0..)] patterns: Option>, }, /// Synchronize changes that might have occurred in your host - /// file system so that they are reflected in running sandboxes. + /// file system so that they are reflected in running layers. Sync, - /// Kill all processes in the sandbox and unmount the filesystems. + /// Kill all processes in the layer and unmount the filesystems. /// Note this will not reject any changes. Stop { - /// Kill all sandboxes + /// Kill all layers #[arg(long)] all: bool, - /// Patterns of sandboxes to stop + /// Patterns of layers to stop #[arg(value_name = "PATTERNS", num_args = 0.., conflicts_with = "all")] patterns: Option>, }, - /// Delete sandboxes and all associated files + /// Delete layers and all associated files Delete { /// Skip confirmation prompt #[arg(short = 'y', long)] yes: bool, - /// Patterns of sandboxes to delete + /// Patterns of layers to delete #[arg(value_name = "PATTERNS", num_args = 0..)] patterns: Option>, }, - /// Delete stopped ephemeral sandboxes older than a week, and all - /// sandboxes left behind by the test suite + /// Delete stopped ephemeral layers older than a week, and all + /// layers left behind by the test suite Clean { /// Skip confirmation prompt #[arg(short = 'y', long)] diff --git a/src/config/limits.rs b/src/config/limits.rs index 68de8b0..f211e5e 100644 --- a/src/config/limits.rs +++ b/src/config/limits.rs @@ -47,7 +47,7 @@ pub fn parse_cpus(spec: &str, available: usize) -> Result> { if cpus < MIN_CPUS { return Err(anyhow!( - "Invalid cpus value '{}': this leaves {} of the {} available CPUs for the sandbox, the minimum is {}", + "Invalid cpus value '{}': this leaves {} of the {} available CPUs for the layer, the minimum is {}", spec, cpus.max(0.0), available, diff --git a/src/config/resolve.rs b/src/config/resolve.rs index 56f34b4..336106d 100644 --- a/src/config/resolve.rs +++ b/src/config/resolve.rs @@ -69,7 +69,7 @@ pub fn resolve_config(cli: Args) -> Result { // Check for mutually exclusive name options if (cli.new || cli.last) - && (partial_config.name.is_some() || env::var("SANDBOX_NAME").is_ok()) + && (partial_config.name.is_some() || env::var("DEVLAYER_NAME").is_ok()) { // If --new or --last is specified, name must not be provided via env or config return Err(anyhow::anyhow!( @@ -78,7 +78,7 @@ pub fn resolve_config(cli: Args) -> Result { } // Override with environment variables if set - if let Ok(log_level) = env::var("SANDBOX_LOG_LEVEL") { + if let Ok(log_level) = env::var("DEVLAYER_LOG_LEVEL") { if let Ok(log_level) = log::LevelFilter::from_str(&log_level) { partial_config.log_level = Some(log_level); sources.insert("log_level".into(), "environment".into()); @@ -87,21 +87,21 @@ pub fn resolve_config(cli: Args) -> Result { } } if !cli.new && !cli.last { - if let Ok(name) = env::var("SANDBOX_NAME") { + if let Ok(name) = env::var("DEVLAYER_NAME") { if !name.is_empty() { partial_config.name = Some(name); sources.insert("name".into(), "environment".into()); } } } - if let Ok(storage_dir) = env::var("SANDBOX_STORAGE_DIR") { + if let Ok(storage_dir) = env::var("DEVLAYER_STORAGE_DIR") { if !storage_dir.is_empty() { partial_config.storage_dir = Some(storage_dir); sources.insert("storage_dir".into(), "environment".into()); } } - if let Ok(net) = env::var("SANDBOX_NET") { + if let Ok(net) = env::var("DEVLAYER_NET") { if !net.is_empty() { if let Ok(net) = Network::from_str(&net) { partial_config.net = Some(net); @@ -112,13 +112,13 @@ pub fn resolve_config(cli: Args) -> Result { } } - if let Ok(ignored_env) = env::var("SANDBOX_IGNORED") { + if let Ok(ignored_env) = env::var("DEVLAYER_IGNORED") { if let Ok(ignored_val) = bool::from_str(&ignored_env) { partial_config.ignored = Some(ignored_val); sources.insert("ignored".into(), "environment".into()); } else { return Err(anyhow::anyhow!( - "Invalid value for SANDBOX_IGNORED: {}", + "Invalid value for DEVLAYER_IGNORED: {}", ignored_env )); } @@ -126,7 +126,7 @@ pub fn resolve_config(cli: Args) -> Result { // Bind mounts and masks from environment variables form a single layer let mut env_bind_layer = vec![]; - if let Ok(bind_mounts_env) = env::var("SANDBOX_BIND") { + if let Ok(bind_mounts_env) = env::var("DEVLAYER_BIND") { let env_bind_mounts: Vec = bind_mounts_env .split(',') .map(|s| s.trim().to_string()) @@ -139,7 +139,7 @@ pub fn resolve_config(cli: Args) -> Result { } } - if let Ok(mask_paths_env) = env::var("SANDBOX_MASK") { + if let Ok(mask_paths_env) = env::var("DEVLAYER_MASK") { let env_mask_paths: Vec = mask_paths_env .split(',') .map(|s| s.trim()) @@ -154,28 +154,28 @@ pub fn resolve_config(cli: Args) -> Result { } bind_layers.push(env_bind_layer); - if let Ok(no_default_binds_env) = env::var("SANDBOX_NO_DEFAULT_BINDS") { + if let Ok(no_default_binds_env) = env::var("DEVLAYER_NO_DEFAULT_BINDS") { let no_default_binds_val = bool::from_str(&no_default_binds_env) - .expect("Invalid value for SANDBOX_NO_DEFAULT_BINDS"); + .expect("Invalid value for DEVLAYER_NO_DEFAULT_BINDS"); partial_config.no_default_binds = Some(no_default_binds_val); sources.insert("no_default_binds".into(), "environment".into()); } - if let Ok(audio_env) = env::var("SANDBOX_AUDIO") { + if let Ok(audio_env) = env::var("DEVLAYER_AUDIO") { if let Ok(audio_val) = bool::from_str(&audio_env) { partial_config.audio = Some(audio_val); sources.insert("audio".into(), "environment".into()); } else { return Err(anyhow::anyhow!( - "Invalid value for SANDBOX_AUDIO: {}", + "Invalid value for DEVLAYER_AUDIO: {}", audio_env )); } } for (var, key, field) in [ - ("SANDBOX_CPUS", "cpus", &mut partial_config.cpus), - ("SANDBOX_MEMORY", "memory", &mut partial_config.memory), + ("DEVLAYER_CPUS", "cpus", &mut partial_config.cpus), + ("DEVLAYER_MEMORY", "memory", &mut partial_config.memory), ] { if let Some(value) = env::var(var).ok().filter(|v| !v.is_empty()) { *field = Some(value); @@ -261,7 +261,7 @@ pub fn resolve_config(cli: Args) -> Result { bind_layers.push(cli_bind_layer); // If nothing else, fill in with some default values - let name = partial_config.name.unwrap_or("sandbox".to_string()); + let name = partial_config.name.unwrap_or("devlayer".to_string()); if !sources.contains_key("name") { sources.insert("name".into(), "default".into()); } @@ -404,7 +404,7 @@ pub fn resolve_config(cli: Args) -> Result { validate_config(&config)?; trace!("Storage dir: {:?}", config.storage_dir); - trace!("Sandbox: {:?}", config.name); + trace!("Layer: {:?}", config.name); Ok(config) } @@ -518,8 +518,8 @@ pub fn resolve_sandbox_storage_dir( None => { let ugh = resolve_uid_gid_home()?; vec![ - ugh.home.join(".sandboxes"), - PathBuf::from(format!("/tmp/sandboxes-{}", ugh.uid)), + ugh.home.join(".devlayer"), + PathBuf::from(format!("/tmp/devlayer-{}", ugh.uid)), ] } }; @@ -695,20 +695,20 @@ fn find_config_files() -> Result> { // Any project specific files let mut current_dir = std::env::current_dir()?; loop { - paths_to_check.push(current_dir.join(".sandbox.conf")); - paths_to_check.push(current_dir.join(".sandbox.toml")); + paths_to_check.push(current_dir.join(".devlayer.conf")); + paths_to_check.push(current_dir.join(".devlayer.toml")); if current_dir == uid_gid_home.home || !current_dir.pop() { break; } } // ~/.config/sandbox/config.toml - paths_to_check.push(uid_gid_home.home.join(".config/sandbox/config.conf")); - paths_to_check.push(uid_gid_home.home.join(".config/sandbox/config.toml")); + paths_to_check.push(uid_gid_home.home.join(".config/devlayer/config.conf")); + paths_to_check.push(uid_gid_home.home.join(".config/devlayer/config.toml")); // /etc/sandbox.conf - paths_to_check.push(PathBuf::from("/etc/sandbox.conf")); - paths_to_check.push(PathBuf::from("/etc/sandbox.toml")); + paths_to_check.push(PathBuf::from("/etc/devlayer.conf")); + paths_to_check.push(PathBuf::from("/etc/devlayer.toml")); // Finally reverse them so we can process them in order nicely paths_to_check.reverse(); @@ -787,7 +787,7 @@ fn merge_configs( fn validate_config(config: &Config) -> Result<()> { if config.name.contains("/") { - return Err(anyhow::anyhow!("Invalid sandbox name: {}", config.name)); + return Err(anyhow::anyhow!("Invalid layer name: {}", config.name)); } Ok(()) @@ -851,7 +851,7 @@ fn find_last_sandbox( resolve_sandbox_storage_dir(storage_dir.clone(), uid, gid)?; let entries = std::fs::read_dir(&storage_dir).context(format!( - "Failed to read sandbox storage directory: {:?}", + "Failed to read layer storage directory: {:?}", storage_dir ))?; @@ -872,7 +872,7 @@ fn find_last_sandbox( let created = metadata .created() .or_else(|_| metadata.modified()) - .context("Failed to get creation time for sandbox")?; + .context("Failed to get creation time for layer")?; sandboxes.push((name, created)); } } @@ -885,7 +885,7 @@ fn find_last_sandbox( }; if sandboxes.is_empty() { - return Err(anyhow::anyhow!("No sandboxes found")); + return Err(anyhow::anyhow!("No layers found")); } // Sort by creation time (newest first) @@ -959,7 +959,7 @@ mod tests { #[test] fn test_validate_config() { let mut config = Config { - name: "test-sandbox".to_string(), + name: "test-layer".to_string(), storage_dir: PathBuf::from("/tmp/test"), sandbox_dir: PathBuf::from("/tmp/test"), upper_cwd: PathBuf::from("/tmp/test"), @@ -976,13 +976,13 @@ mod tests { config_files: vec![], }; assert!(validate_config(&config).is_ok()); - config.name = "../test-sandbox".to_string(); + config.name = "../test-layer".to_string(); assert!(validate_config(&config).is_err()); - config.name = "test-sandbox/".to_string(); + config.name = "test-layer/".to_string(); assert!(validate_config(&config).is_err()); - config.name = "test-sandbox\\".to_string(); + config.name = "test-layer\\".to_string(); assert!(validate_config(&config).is_ok()); - config.name = "test-sandbox.".to_string(); + config.name = "test-layer.".to_string(); assert!(validate_config(&config).is_ok()); config.name = ".test".to_string(); assert!(validate_config(&config).is_ok()); @@ -1038,7 +1038,7 @@ mod tests { let override_config = PartialConfig { log_level: Some(LevelFilter::Debug), - name: Some("test-sandbox".to_string()), + name: Some("test-layer".to_string()), storage_dir: Some("/tmp/test".to_string()), net: Some(Network::Host), ignored: Some(true), @@ -1070,7 +1070,7 @@ mod tests { // Verify all fields were merged assert_eq!(base.log_level, Some(LevelFilter::Debug)); - assert_eq!(base.name, Some("test-sandbox".to_string())); + assert_eq!(base.name, Some("test-layer".to_string())); assert_eq!(base.storage_dir, Some("/tmp/test".to_string())); assert!(matches!(base.net, Some(Network::Host))); assert_eq!(base.ignored, Some(true)); diff --git a/src/lib.rs b/src/lib.rs index c80c090..fb8e24f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -3,4 +3,4 @@ pub mod config; pub mod logger; pub mod sandbox; pub mod types; -pub mod util; \ No newline at end of file +pub mod util; diff --git a/src/main.rs b/src/main.rs index 39da15e..aaf9f4c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -74,7 +74,7 @@ pub fn main() -> Result<()> { let effective_uid = geteuid(); if !effective_uid.is_root() { return Err(anyhow!( - "Insufficient permissions to create the sandbox, please retry using `sudo` or setuid flags" + "Insufficient permissions to create the layer, please retry using `sudo` or setuid flags" )); } @@ -189,7 +189,7 @@ pub fn main() -> Result<()> { let sandbox = Sandbox::get_or_create(&config, uid_gid_home.uid, uid_gid_home.gid) - .context("Getting or creating sandbox")?; + .context("Getting or creating layer")?; // On success, we never actually return from this call sandbox.exec(&sandboxed_command) diff --git a/src/sandbox/cgroup.rs b/src/sandbox/cgroup.rs index 3907076..a5308e9 100644 --- a/src/sandbox/cgroup.rs +++ b/src/sandbox/cgroup.rs @@ -18,7 +18,7 @@ const CPU_PERIOD_US: u64 = 100_000; /// The cgroup all sandbox cgroups are created in fn cgroup_parent() -> String { - let parent = String::from("sandbox"); + let parent = String::from("devlayer"); // Lets tests start from a parent cgroup that doesn't exist yet #[cfg(feature = "coverage")] @@ -60,7 +60,7 @@ impl Sandbox { debug!("{:#}", error); warn!( - "Resource limits can't be set up inside another sandbox, so this sandbox shares the limits of the sandbox it's running in ({})", + "Resource limits can't be set up inside another layer, so this layer shares the limits of the layer it's running in ({})", describe_limits(outer.cpus, outer.memory) ); Ok(None) @@ -115,7 +115,7 @@ impl Sandbox { // can remove because it's empty. If it's not empty it belongs to // a running sandbox with the same name in another storage dir. std::fs::remove_dir(&path).context(format!( - "Failed to remove existing cgroup {}, is a sandbox with the same name running from a different storage directory?", + "Failed to remove existing cgroup {}, is a layer with the same name running from a different storage directory?", path.display() ))?; } @@ -230,7 +230,7 @@ fn enable_controllers(dir: &Path, controllers: &[&str]) -> Result<()> { for controller in controllers { if !enabled.split_whitespace().any(|c| c == *controller) { let context = format!( - "Failed to enable the {} cgroup controller. Limiting cpus or memory requires permission to manage {}, which may not be available inside containers or other sandboxes", + "Failed to enable the {} cgroup controller. Limiting cpus or memory requires permission to manage {}, which may not be available inside containers or other layers", controller, dir.display() ); diff --git a/src/sandbox/delete.rs b/src/sandbox/delete.rs index 2f8cd1b..eeef6c6 100644 --- a/src/sandbox/delete.rs +++ b/src/sandbox/delete.rs @@ -6,14 +6,14 @@ use log::{debug, trace}; impl Sandbox { pub fn delete(&self) -> Result<()> { - self.stop().context("failed to stop sandbox")?; - self.unmount().context("failed to unmount sandbox")?; + self.stop().context("failed to stop layer")?; + self.unmount().context("failed to unmount layer")?; - trace!("Removing sandbox directory: {}", self.base.display()); + trace!("Removing layer directory: {}", self.base.display()); if self.base.exists() { rmdir_recursive(&self.base)?; } else { - debug!("Sandbox directory does not exist: {}", self.base.display()); + debug!("Layer directory does not exist: {}", self.base.display()); } let lock_file = PathBuf::from(format!("{}.lock", self.base.display())); diff --git a/src/sandbox/exec.rs b/src/sandbox/exec.rs index 688dcde..4a887de 100644 --- a/src/sandbox/exec.rs +++ b/src/sandbox/exec.rs @@ -91,7 +91,7 @@ impl Sandbox { let pid_fd = pidfd_open(self.pid, 0)?; if (unsafe { setns(pid_fd, ns_flags) }) != 0 { return Err(anyhow!( - "Failed to join sandbox namespaces: {}", + "Failed to join layer namespaces: {}", nix::errno::Errno::last() )); } @@ -113,9 +113,9 @@ impl Sandbox { ))?; unsafe { - std::env::set_var("SANDBOX", self.name.clone()); + std::env::set_var("DEVLAYER", self.name.clone()); std::env::set_var( - "SANDBOX_STORAGE_DIR", + "DEVLAYER_STORAGE_DIR", self.data_storage_dir.clone(), ); } diff --git a/src/sandbox/get_or_create.rs b/src/sandbox/get_or_create.rs index 683cba0..b313c61 100644 --- a/src/sandbox/get_or_create.rs +++ b/src/sandbox/get_or_create.rs @@ -79,7 +79,7 @@ impl Sandbox { let lock = match lock { Some(l) => l, None => Lock::sandbox(sandboxes_storage_dir, sandbox_name) - .context(format!("failed to lock sandbox: {}", sandbox_name))?, + .context(format!("failed to lock layer: {}", sandbox_name))?, }; let sandbox_base_dir = sandboxes_storage_dir.join(sandbox_name); @@ -119,7 +119,7 @@ impl Sandbox { /* First lock so we don't have multiple processes trying to get_or_create at the same time */ let lock = Lock::sandbox(storage_dir, sandbox_name) - .context(format!("failed to lock sandbox: {}", sandbox_name))?; + .context(format!("failed to lock layer: {}", sandbox_name))?; /* If we have an existing sandbox, return it */ let (sandbox, _lock) = @@ -154,7 +154,7 @@ impl Sandbox { } Err(e) => { return Err(anyhow!( - "Failed to load existing sandbox settings from {}: {}. The sandbox may be corrupted.", + "Failed to load existing layer settings from {}: {}. The layer may be corrupted.", settings_path.display(), e )); @@ -171,7 +171,7 @@ impl Sandbox { Sandbox::from_location(storage_dir, sandbox_name, uid, gid); trace!( - "Creating new sandbox '{}': {}", + "Creating new layer '{}': {}", sandbox_name, sandbox.base.display() ); @@ -196,10 +196,10 @@ impl Sandbox { * so we fail before mounting anything if limits aren't available. */ let cgroup = sandbox.create_cgroup_or_share_outer(&config)?; - trace!("Mounting sandbox"); + trace!("Mounting layer"); let started = sandbox .mount_overlays(&config) - .context(format!("failed to mount sandbox: {}", sandbox_name)) + .context(format!("failed to mount layer: {}", sandbox_name)) .and_then(|overlay_mounts| { /* Create PID 1 for our sandbox */ sandbox @@ -209,7 +209,7 @@ impl Sandbox { &overlay_mounts, cgroup.as_ref(), ) - .map_err(|e| anyhow!("Failed to start sandbox: {}", e)) + .map_err(|e| anyhow!("Failed to start layer: {}", e)) }); sandbox.pid = match started { @@ -239,7 +239,7 @@ impl Sandbox { // create a pipe between ourselves and the main sandbox process so the main sandbox process can // let us know when it's done setting up the namespaces let (read_fd, write_fd) = - pipe().context("failed to create pipe for sandbox")?; + pipe().context("failed to create pipe for layer")?; let clone_args = Clone3Args { flags: CLONE_NEWNS @@ -270,8 +270,8 @@ impl Sandbox { clone_args }; - let pid = clone3(&clone_args) - .context("clone3 call to start sandbox failed")?; + let pid = + clone3(&clone_args).context("clone3 call to start layer failed")?; if pid.as_raw() > 0 { // We are the parent process @@ -288,10 +288,10 @@ impl Sandbox { // our signal that the namespaces are ready for use. let mut buffer = [0; 1]; nix::unistd::read(read_fd.as_raw_fd(), &mut buffer) - .context("failed to read from sandbox ready pipe")?; + .context("failed to read from layer ready pipe")?; if buffer[0] == 1 { - return Err(anyhow!("Failed to setup sandbox")); + return Err(anyhow!("Failed to setup layer")); } drop(read_fd); @@ -312,13 +312,13 @@ impl Sandbox { overlay_mounts, ) .map_err(|e| { - error!("Failed to setup sandbox: {}", e); + error!("Failed to setup layer: {}", e); e }); // If we're here, an error occurred and we'll exit nix::unistd::write(&write_fd, &[1]) - .context("failed to write to sandbox ready pipe")?; + .context("failed to write to layer ready pipe")?; std::process::exit(1); } @@ -332,7 +332,7 @@ impl Sandbox { write_fd: &OwnedFd, mounts: &Vec, ) -> Result<()> { - trace!("Setting up sandbox root process"); + trace!("Setting up layer root process"); /* Normalize credentials and dumpable state for pidfd-based setns(). * @@ -352,13 +352,13 @@ impl Sandbox { Uid::from_raw(0), Uid::from_raw(0), ) - .context("failed to normalize sandbox PID 1 UIDs to root")?; + .context("failed to normalize layer PID 1 UIDs to root")?; nix::unistd::setresgid( Gid::from_raw(0), Gid::from_raw(0), Gid::from_raw(0), ) - .context("failed to normalize sandbox PID 1 GIDs to root")?; + .context("failed to normalize layer PID 1 GIDs to root")?; unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 1); } @@ -1022,11 +1022,11 @@ impl Sandbox { // send a byte over the pipe to signal that the sandbox is initialized and // ready for use nix::unistd::write(write_fd, &[0]) - .context(format!("failed to write to sandbox ready pipe"))?; + .context(format!("failed to write to layer ready pipe"))?; close(write_fd.as_raw_fd()) - .context(format!("failed to close sandbox ready pipe"))?; + .context(format!("failed to close layer ready pipe"))?; - trace!("Sandbox setup complete"); + trace!("Layer setup complete"); /* Close all file descriptors so our test harness doesn't hang waiting for them to close * before returning a result. */ diff --git a/src/sandbox/mount_overlays.rs b/src/sandbox/mount_overlays.rs index bab6d59..e35b527 100644 --- a/src/sandbox/mount_overlays.rs +++ b/src/sandbox/mount_overlays.rs @@ -27,7 +27,7 @@ impl Sandbox { let mounts = self.determine_mounts(config)?; can_mkdir(&self.base, self.uid, self.gid).context(format!( - "Failed to check if we can create the base directory {:?} for the sandbox failed", + "Failed to check if we can create the base directory {:?} for the layer failed", self.base ))?; mkdir(&self.base, self.uid, self.gid)?; @@ -109,7 +109,7 @@ impl Sandbox { let settings = SandboxSettings::from_config(config, &result_mounts); settings .save_to_file(&self.settings_path()) - .context("Failed to save sandbox settings")?; + .context("Failed to save layer settings")?; Ok(result_mounts) } @@ -120,17 +120,20 @@ impl Sandbox { pub fn determine_mounts(&self, config: &Config) -> Result> { // Check if we have a settings.json file in our storage dir (for nested sandboxes) - let settings_json = Path::new(&config.storage_dir).join("settings.json"); + let settings_json = + Path::new(&config.storage_dir).join("settings.json"); if settings_json.exists() { debug!( - "It looks like we are in a nested sandbox, reading mounts from {}", + "It looks like we are in a nested layer, reading mounts from {}", settings_json.display() ); - let parent_settings = SandboxSettings::load_from_file(&settings_json) - .context(format!( - "Failed to read parent settings.json from {}", - settings_json.display() - ))?; + let parent_settings = SandboxSettings::load_from_file( + &settings_json, + ) + .context(format!( + "Failed to read parent settings.json from {}", + settings_json.display() + ))?; return Ok(parent_settings.mounts); } @@ -198,7 +201,7 @@ impl Sandbox { if mounts.is_empty() { return Err(anyhow!( - "No suitable mounts found for sandbox, something is very wrong" + "No suitable mounts found for layer, something is very wrong" .to_string(), )); } diff --git a/src/sandbox/settings.rs b/src/sandbox/settings.rs index e68b414..436bd46 100644 --- a/src/sandbox/settings.rs +++ b/src/sandbox/settings.rs @@ -44,7 +44,7 @@ impl SandboxSettings { pub fn save_to_file(&self, path: &Path) -> Result<()> { let settings_json = serde_json::to_string_pretty(self) - .context("Failed to serialize sandbox settings to JSON")?; + .context("Failed to serialize layer settings to JSON")?; std::fs::write(path, settings_json).context(format!( "Failed to write settings.json to {}", path.display() @@ -77,7 +77,7 @@ impl SandboxSettings { if self.network != current_settings.network { return Err(anyhow!( - "Network configuration has changed. Existing: {:?}, Current: {:?}. Please stop existing sandbox to change network settings.", + "Network configuration has changed. Existing: {:?}, Current: {:?}. Please stop existing layer to change network settings.", self.network, current_settings.network )); @@ -87,7 +87,7 @@ impl SandboxSettings { || self.memory != current_settings.memory { return Err(anyhow!( - "Resource limits have changed. Existing: {}, Current: {}. Please stop the existing sandbox to change resource limits.", + "Resource limits have changed. Existing: {}, Current: {}. Please stop the existing layer to change resource limits.", describe_limits(self.cpus, self.memory), describe_limits(current_settings.cpus, current_settings.memory), )); @@ -124,7 +124,7 @@ impl SandboxSettings { } error_msg.push_str( - "Please stop the existing sandbox to change mount settings.", + "Please stop the existing layer to change mount settings.", ); return Err(anyhow!(error_msg)); } @@ -161,7 +161,9 @@ impl SandboxSettings { } } - error_msg.push_str("Please stop the existing sandbox to change bind mount settings."); + error_msg.push_str( + "Please stop the existing layer to change bind mount settings.", + ); return Err(anyhow!(error_msg)); } diff --git a/src/sandbox/stop.rs b/src/sandbox/stop.rs index 9e25a40..70a5e09 100644 --- a/src/sandbox/stop.rs +++ b/src/sandbox/stop.rs @@ -9,10 +9,10 @@ impl Sandbox { pub fn stop(&self) -> Result<()> { let pid = self.pid; if pid == Pid::from_raw(-1) { - trace!("Sandbox '{}' doesn't appear to be running", self.name); + trace!("Layer '{}' doesn't appear to be running", self.name); } else { trace!( - "Stopping sandbox '{}' located in {} with pid {}", + "Stopping layer '{}' located in {} with pid {}", self.name, self.base.display(), pid @@ -34,18 +34,18 @@ impl Sandbox { // Get our sandbox namespaces let sandbox_ns_str = format!("/proc/{}/ns/pid_for_children", pid); - trace!("sandbox_ns_str: {}", sandbox_ns_str); + trace!("layer_ns_str: {}", sandbox_ns_str); let sandbox_ns_path = Path::new(&sandbox_ns_str); - trace!("sandbox_ns_path: {}", sandbox_ns_path.display()); + trace!("layer_ns_path: {}", sandbox_ns_path.display()); if !sandbox_ns_path.exists() { - trace!("Sandbox process {} already gone", pid); + trace!("Layer process {} already gone", pid); } else { let ns = readlink(sandbox_ns_path).context(format!( "failed to readlink {}", sandbox_ns_path.display() ))?; - trace!("sandbox_ns: {}", ns.to_string_lossy()); + trace!("layer_ns: {}", ns.to_string_lossy()); // Collect each process that shares a namespace with our sandbox for entry in std::fs::read_dir("/proc") @@ -106,7 +106,7 @@ impl Sandbox { trace!("command: {}", command); trace!( - "[{}] Killing {} in sandbox '{}'", + "[{}] Killing {} in layer '{}'", process_pid, command, self.name ); diff --git a/src/sandbox/unmount.rs b/src/sandbox/unmount.rs index 57e6fb4..a69eaef 100644 --- a/src/sandbox/unmount.rs +++ b/src/sandbox/unmount.rs @@ -15,7 +15,7 @@ impl Sandbox { } if mounts.is_empty() { - debug!("No mounts found for sandbox '{}'", self.name); + debug!("No mounts found for layer '{}'", self.name); } for mount in mounts { diff --git a/src/util/access.rs b/src/util/access.rs index e7b6900..48eaa91 100644 --- a/src/util/access.rs +++ b/src/util/access.rs @@ -20,8 +20,7 @@ pub fn can_access( // Save dumpable flag before EUID toggle. Changing EUID from root to // non-root sets dumpable to SUID_DUMP_ROOT (2) as a side effect, which // breaks pidfd-based setns() on Linux 6.18+ (requires dumpable == 1). - let saved_dumpable = - unsafe { libc::prctl(libc::PR_GET_DUMPABLE) }; + let saved_dumpable = unsafe { libc::prctl(libc::PR_GET_DUMPABLE) }; setegid(gid)?; seteuid(uid)?; diff --git a/src/util/get_running_sandbox_pid.rs b/src/util/get_running_sandbox_pid.rs index 166f4f5..73b6898 100644 --- a/src/util/get_running_sandbox_pid.rs +++ b/src/util/get_running_sandbox_pid.rs @@ -23,7 +23,7 @@ pub fn get_running_sandbox_pid( .filter(|&pid| kill(pid, None).is_ok()) .and_then(|pid| { trace!( - "Existing sandbox '{}' found with PID: {}", + "Existing layer '{}' found with PID: {}", sandbox_name, pid ); @@ -41,7 +41,7 @@ pub fn get_running_sandbox_pid( Some(pid) => return Some(pid), None => { trace!( - "Invalid PID file or sandbox was not in a good state, cleaning up" + "Invalid PID file or layer was not in a good state, cleaning up" ); std::fs::remove_file(&pid_file).ok(); } diff --git a/src/util/lock_sandbox.rs b/src/util/lock_sandbox.rs index 133e823..98bdfb6 100644 --- a/src/util/lock_sandbox.rs +++ b/src/util/lock_sandbox.rs @@ -31,7 +31,7 @@ impl Lock { Ok(file) => file, Err(e) => { return Err(anyhow!( - "Failed to open lock file for sandbox {}: {}", + "Failed to open lock file for layer {}: {}", sandbox_name, e )); diff --git a/src/util/mkdir.rs b/src/util/mkdir.rs index 64903c5..2198fbe 100644 --- a/src/util/mkdir.rs +++ b/src/util/mkdir.rs @@ -75,7 +75,7 @@ mod tests { let uid = getuid(); let gid = getgid(); let path = PathBuf::from(format!( - "/tmp/sandbox-coverage-tests-mkdir-{}", + "/tmp/devlayer-coverage-tests-mkdir-{}", std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() @@ -101,7 +101,7 @@ mod tests { assert!( mkdir( &PathBuf::from(format!( - "/sandbox-coverage-tests-mkdir-{}", + "/devlayer-coverage-tests-mkdir-{}", std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() diff --git a/tests/README.md b/tests/README.md index 3ba1b7f..cf20099 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,6 +1,6 @@ # Integration Tests -This directory contains integration tests for the sandbox. +This directory contains integration tests for devlayer. There are two classes of tests. Tests manually written to stress and cover the codebase, and tests generated by AI to stress and cover the codebase. diff --git a/tests/ai_test_audio.rs b/tests/ai_test_audio.rs index 49dd986..ab7270e 100644 --- a/tests/ai_test_audio.rs +++ b/tests/ai_test_audio.rs @@ -67,27 +67,27 @@ fn ai_test_audio_flag(mut sandbox: SandboxManager) -> Result<()> { fn ai_test_audio_env(mut sandbox: SandboxManager) -> Result<()> { sandbox.run_with_env( &["--no-config", "config", "audio"], - "SANDBOX_AUDIO", + "DEVLAYER_AUDIO", "true", )?; assert_eq!(sandbox.last_stdout.trim(), "true"); sandbox.run_with_env( &["--no-config", "config", "audio"], - "SANDBOX_AUDIO", + "DEVLAYER_AUDIO", "false", )?; assert_eq!(sandbox.last_stdout.trim(), "false"); assert!(sandbox.exfail( &["--no-config", "config", "audio"], - "SANDBOX_AUDIO", + "DEVLAYER_AUDIO", "yes" )); assert!( sandbox .last_stderr - .contains("Invalid value for SANDBOX_AUDIO") + .contains("Invalid value for DEVLAYER_AUDIO") ); Ok(()) @@ -103,7 +103,7 @@ fn ai_test_audio_config_file(mut sandbox: SandboxManager) -> Result<()> { // The environment takes precedence over config files sandbox.run_with_env( &["--config", &config, "config", "audio"], - "SANDBOX_AUDIO", + "DEVLAYER_AUDIO", "false", )?; assert_eq!(sandbox.last_stdout.trim(), "false"); diff --git a/tests/ai_test_bind_mount_validation.rs b/tests/ai_test_bind_mount_validation.rs index e187cc2..babe1c8 100644 --- a/tests/ai_test_bind_mount_validation.rs +++ b/tests/ai_test_bind_mount_validation.rs @@ -6,7 +6,9 @@ use rstest::*; use std::fs; #[rstest] -fn test_bind_mount_validation_failure(mut sandbox: SandboxManager) -> Result<()> { +fn test_bind_mount_validation_failure( + mut sandbox: SandboxManager, +) -> Result<()> { // Create temporary directories using the test filename pattern let bind_source1 = sandbox.test_filename("bind-source-1"); let bind_source2 = sandbox.test_filename("bind-source-2"); @@ -14,65 +16,80 @@ fn test_bind_mount_validation_failure(mut sandbox: SandboxManager) -> Result<()> fs::create_dir_all(&bind_source2)?; fs::write(format!("{}/test.txt", bind_source1), "test content")?; fs::write(format!("{}/test.txt", bind_source2), "different content")?; - + // Create and start sandbox with initial bind mount let initial_bind = format!("{}:{}", bind_source1, "/mnt/test"); - let _output1 = sandbox.run(&["--bind", &initial_bind, "echo", "initial setup"])?; - + let _output1 = + sandbox.run(&["--bind", &initial_bind, "echo", "initial setup"])?; + // Try to run another command with a DIFFERENT bind mount - this should fail let different_bind = format!("{}:{}", bind_source2, "/mnt/test"); - - let result = sandbox.run(&["--bind", &different_bind, "echo", "should fail"]); - + + let result = + sandbox.run(&["--bind", &different_bind, "echo", "should fail"]); + // This should fail because bind mount configuration changed - assert!(result.is_err(), "Expected bind mount validation to fail when bind mounts change"); - + assert!( + result.is_err(), + "Expected bind mount validation to fail when bind mounts change" + ); + // Check that the error message shows detailed changes - let error_output = format!("{}{}", sandbox.last_stderr, sandbox.last_stdout); + let error_output = + format!("{}{}", sandbox.last_stderr, sandbox.last_stdout); assert!( - error_output.contains("Bind mount configuration has changed") && - error_output.contains("Removed bind mounts:") && - error_output.contains("Added bind mounts:"), + error_output.contains("Bind mount configuration has changed") + && error_output.contains("Removed bind mounts:") + && error_output.contains("Added bind mounts:"), "Expected detailed bind mount change information, got: {}", error_output ); - + Ok(()) } -#[rstest] -fn test_bind_mount_validation_success(mut sandbox: SandboxManager) -> Result<()> { +#[rstest] +fn test_bind_mount_validation_success( + mut sandbox: SandboxManager, +) -> Result<()> { // Create temporary directory using the test filename pattern let bind_source = sandbox.test_filename("bind-source-same"); fs::create_dir_all(&bind_source)?; fs::write(format!("{}/test.txt", bind_source), "test content")?; - + // Create and start sandbox with bind mount let bind_mount = format!("{}:{}", bind_source, "/mnt/test"); - let _output1 = sandbox.run(&["--bind", &bind_mount, "echo", "first command"])?; - + let _output1 = + sandbox.run(&["--bind", &bind_mount, "echo", "first command"])?; + // Run another command with the SAME bind mount - this should succeed - let _output2 = sandbox.run(&["--bind", &bind_mount, "echo", "second command"])?; - + let _output2 = + sandbox.run(&["--bind", &bind_mount, "echo", "second command"])?; + Ok(()) } #[rstest] -fn test_bind_mount_options_validation(mut sandbox: SandboxManager) -> Result<()> { +fn test_bind_mount_options_validation( + mut sandbox: SandboxManager, +) -> Result<()> { // Create temporary directory using the test filename pattern let bind_source = sandbox.test_filename("bind-source-options"); fs::create_dir_all(&bind_source)?; - + // Start with read-write bind mount let bind_rw = format!("{}:{}", bind_source, "/mnt/test"); let _output1 = sandbox.run(&["--bind", &bind_rw, "echo", "read-write"])?; - + // Try to change to read-only bind mount - this should fail let bind_ro = format!("{}:{}:ro", bind_source, "/mnt/test"); let result = sandbox.run(&["--bind", &bind_ro, "echo", "read-only"]); - + // This should fail because bind mount options changed - assert!(result.is_err(), "Expected bind mount validation to fail when options change"); - + assert!( + result.is_err(), + "Expected bind mount validation to fail when options change" + ); + Ok(()) -} \ No newline at end of file +} diff --git a/tests/ai_test_bind_mounts.rs b/tests/ai_test_bind_mounts.rs index 542009d..fee6f1f 100644 --- a/tests/ai_test_bind_mounts.rs +++ b/tests/ai_test_bind_mounts.rs @@ -67,7 +67,7 @@ fn test_bind_mount_env(mut sandbox: SandboxManager) -> Result<()> { // Test environment variable using run_with_env sandbox.run_with_env( &["config"], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{},{}", test1, test2), )?; assert!(sandbox.last_stdout.contains(&test1)); @@ -76,7 +76,7 @@ fn test_bind_mount_env(mut sandbox: SandboxManager) -> Result<()> { // Test environment variable with source:target format sandbox.run_with_env( &["config"], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{}:{}", test1, mapped1), )?; assert!( @@ -131,7 +131,7 @@ fn test_no_default_binds_env(mut sandbox: SandboxManager) -> Result<()> { // Test that no default binds works via environment variable sandbox.run_with_env( &["--no-config", "config"], - "SANDBOX_NO_DEFAULT_BINDS", + "DEVLAYER_NO_DEFAULT_BINDS", "true", )?; assert!(sandbox.last_stdout.contains("bind=\n")); @@ -139,7 +139,7 @@ fn test_no_default_binds_env(mut sandbox: SandboxManager) -> Result<()> { // Test that custom binds still work with the env variable sandbox.run_with_env( &["--bind", &test1, "--no-config", "config"], - "SANDBOX_NO_DEFAULT_BINDS", + "DEVLAYER_NO_DEFAULT_BINDS", "true", )?; assert!(sandbox.last_stdout.contains(&test1)); @@ -148,7 +148,7 @@ fn test_no_default_binds_env(mut sandbox: SandboxManager) -> Result<()> { // Test that SANDBOX_NO_DEFAULT_BINDS=false (or any other value) doesn't disable defaults sandbox.run_with_env( &["--no-config", "config"], - "SANDBOX_NO_DEFAULT_BINDS", + "DEVLAYER_NO_DEFAULT_BINDS", "false", )?; assert!(sandbox.last_stdout.contains("/dev/fuse")); @@ -163,7 +163,7 @@ fn test_bind_mount_env_parsing() -> Result<()> { // Test empty env var sandbox.run_with_env( &["--no-default-binds", "--no-config", "config"], - "SANDBOX_BIND", + "DEVLAYER_BIND", "", )?; @@ -180,7 +180,7 @@ fn test_bind_mount_env_parsing() -> Result<()> { sandbox.run_with_env( &["--no-default-binds", "--no-config", "config"], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{},{},", test1, test2), )?; @@ -191,7 +191,7 @@ fn test_bind_mount_env_parsing() -> Result<()> { // Test empty env var combined with CLI bind mount sandbox.run_with_env( &["--bind", &test1, "--no-config", "config"], - "SANDBOX_BIND", + "DEVLAYER_BIND", "", )?; @@ -201,7 +201,7 @@ fn test_bind_mount_env_parsing() -> Result<()> { // Test whitespace-only env var sandbox.run_with_env( &["--no-default-binds", "--no-config", "config"], - "SANDBOX_BIND", + "DEVLAYER_BIND", " ", )?; @@ -227,7 +227,7 @@ fn test_bind_mount_env_with_options(mut sandbox: SandboxManager) -> Result<()> { // Test environment variable with read-only options sandbox.run_with_env( &["--no-default-binds", "config"], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{}::ro,{}::ro", test1, test2), )?; @@ -238,7 +238,7 @@ fn test_bind_mount_env_with_options(mut sandbox: SandboxManager) -> Result<()> { // Test mixed read-only and read-write mounts sandbox.run_with_env( &["--no-default-binds", "config"], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{},{}", test3, test4), )?; @@ -337,7 +337,7 @@ fn test_bind_mount_env_read_only() -> Result<()> { "touch", &format!("{}/new_file.txt", env_ro), ], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{}:{}:ro", test_dir_str, env_ro), ); @@ -365,7 +365,7 @@ fn test_bind_mount_env_read_only() -> Result<()> { sandbox.run_with_env( &["--no-config", "config"], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{},{}:{}:ro,{}::ro", test1, test2, mapped, test_dir_str), )?; @@ -456,7 +456,7 @@ fn test_bind_mount_edge_cases() -> Result<()> { #[rstest] fn test_bind_mount_empty_destination() -> Result<()> { let mut sandbox = SandboxManager::new(); - let test_name = format!("sandbox-bind-empty-dest-{}", sandbox.name); + let test_name = format!("devlayer-bind-empty-dest-{}", sandbox.name); let test_dir = sandbox.test_filename("bind_empty_dest"); fs::create_dir_all(&test_dir)?; let tmp = format!("{}/tmp", test_dir); @@ -482,7 +482,7 @@ fn test_bind_mount_empty_destination() -> Result<()> { #[rstest] fn test_bind_mount_empty_destination_with_sudo() -> Result<()> { // This test verifies empty destination bind mounts work correctly when sudo is involved - let unique_name = format!("sandbox-bind-empty-sudo-{}", rid()); + let unique_name = format!("devlayer-bind-empty-sudo-{}", rid()); let test_dir = format!("generated-test-data/{}", unique_name); fs::create_dir_all(&test_dir)?; let tmp = format!("{}/tmp", test_dir); @@ -491,7 +491,7 @@ fn test_bind_mount_empty_destination_with_sudo() -> Result<()> { // Run directly with sudo to ensure proper handling of bind mount paths let output = std::process::Command::new("sudo") .arg("-E") - .arg(env!("CARGO_BIN_EXE_sandbox")) + .arg(env!("CARGO_BIN_EXE_devlayer")) .arg("--name") .arg(&unique_name) .arg("--bind") @@ -520,7 +520,7 @@ fn test_empty_bind_array_in_config() -> Result<()> { fs::create_dir_all(&work_dir)?; // Write config file in the working directory - let config_file = format!("{}/.sandbox.toml", work_dir); + let config_file = format!("{}/.devlayer.toml", work_dir); fs::write( &config_file, r#" @@ -552,7 +552,7 @@ fn test_all_deserialize_paths(mut sandbox: SandboxManager) -> Result<()> { use std::fs; let test_dir = sandbox.test_filename("test_all_deserialize_paths"); - let config_dir = PathBuf::from(&test_dir).join(".config/sandbox"); + let config_dir = PathBuf::from(&test_dir).join(".config/devlayer"); fs::create_dir_all(&config_dir)?; let config_file = config_dir.join("config.toml"); diff --git a/tests/ai_test_bind_precedence.rs b/tests/ai_test_bind_precedence.rs index 941f3c9..54a6077 100644 --- a/tests/ai_test_bind_precedence.rs +++ b/tests/ai_test_bind_precedence.rs @@ -156,7 +156,7 @@ fn ai_test_bind_env_overrides_config( sandbox.run_with_env( &["--no-default-binds", "--config", &config, "config", "bind"], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{dir}::ro"), )?; assert_eq!(sandbox.last_stdout.trim(), format!("{dir}::ro")); @@ -164,7 +164,7 @@ fn ai_test_bind_env_overrides_config( // Conflicts within the environment layer still fail assert!(sandbox.exfail( &["--no-default-binds", "config"], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{dir},{dir}::ro"), )); @@ -189,7 +189,7 @@ fn ai_test_bind_cli_overrides_config_and_env( "config", "bind", ], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{dir}::ro"), )?; assert_eq!(sandbox.last_stdout.trim(), dir); diff --git a/tests/ai_test_builtin_ignore_patterns.rs b/tests/ai_test_builtin_ignore_patterns.rs index 02f6f77..404e730 100644 --- a/tests/ai_test_builtin_ignore_patterns.rs +++ b/tests/ai_test_builtin_ignore_patterns.rs @@ -18,7 +18,7 @@ fn test_builtin_ignore_patterns_tmp(mut sandbox: SandboxManager) -> Result<()> { ])?; // Create files in /tmp that would normally be tracked - sandbox.run(&["sh", "-c", "mkdir -p /tmp/sandbox-builtin-test && echo 'test' > /tmp/sandbox-builtin-test/should-be-ignored.txt"])?; + sandbox.run(&["sh", "-c", "mkdir -p /tmp/layer-builtin-test && echo 'test' > /tmp/layer-builtin-test/should-be-ignored.txt"])?; // Also create a visible file for comparison let test_dir = sandbox.test_filename("tmp-test"); @@ -41,14 +41,14 @@ fn test_builtin_ignore_patterns_tmp(mut sandbox: SandboxManager) -> Result<()> { // The /tmp file should appear with --ignored but not without assert!( - stdout_ignored.contains("sandbox-builtin-test") + stdout_ignored.contains("layer-builtin-test") || stdout_ignored.contains("should-be-ignored"), "Files in /tmp should show with --ignored flag. Got: {}", stdout_ignored ); assert!( - !stdout.contains("sandbox-builtin-test") + !stdout.contains("layer-builtin-test") && !stdout.contains("should-be-ignored"), "Files in /tmp should be ignored by built-in patterns. Got: {}", stdout @@ -62,7 +62,7 @@ fn test_builtin_ignore_patterns_tmp(mut sandbox: SandboxManager) -> Result<()> { ); // Clean up - sandbox.run(&["sh", "-c", "rm -rf /tmp/sandbox-builtin-test"])?; + sandbox.run(&["sh", "-c", "rm -rf /tmp/layer-builtin-test"])?; Ok(()) } @@ -84,11 +84,11 @@ fn test_builtin_ignore_patterns_home_dotfiles( // The patterns /home/*/.*/** and /home/*/.* ignore hidden files in home dirs // Create hidden files in user's home - sandbox.run(&["sh", "-c", "mkdir -p ~/.sandbox-builtin-test && echo 'hidden' > ~/.sandbox-builtin-test/file.txt"])?; + sandbox.run(&["sh", "-c", "mkdir -p ~/.layer-builtin-test && echo 'hidden' > ~/.layer-builtin-test/file.txt"])?; sandbox.run(&[ "sh", "-c", - "echo 'hidden' > ~/.sandbox-builtin-hidden-file", + "echo 'hidden' > ~/.layer-builtin-hidden-file", ])?; // Create a visible file for comparison in test directory @@ -112,14 +112,14 @@ fn test_builtin_ignore_patterns_home_dotfiles( // Hidden files should show with --ignored but not without assert!( - stdout_ignored.contains(".sandbox-builtin") + stdout_ignored.contains(".layer-builtin") || stdout_ignored.contains("hidden-file"), "Hidden files should show with --ignored flag. Got: {}", stdout_ignored ); assert!( - !stdout.contains(".sandbox-builtin") && !stdout.contains("hidden-file"), + !stdout.contains(".layer-builtin") && !stdout.contains("hidden-file"), "Hidden files in home should be ignored by built-in patterns. Got: {}", stdout ); @@ -135,7 +135,7 @@ fn test_builtin_ignore_patterns_home_dotfiles( sandbox.run(&[ "sh", "-c", - "rm -rf ~/.sandbox-builtin-test ~/.sandbox-builtin-hidden-file", + "rm -rf ~/.layer-builtin-test ~/.layer-builtin-hidden-file", ])?; Ok(()) diff --git a/tests/ai_test_can_mkdir_coverage.rs b/tests/ai_test_can_mkdir_coverage.rs index 11dac51..f8ea059 100644 --- a/tests/ai_test_can_mkdir_coverage.rs +++ b/tests/ai_test_can_mkdir_coverage.rs @@ -49,18 +49,18 @@ fn test_sandbox_creation_nested_storage( ) -> Result<()> { let nested_storage = format!( "/tmp/{}", - sandbox.test_filename("nested/storage/path/for/sandbox") + sandbox.test_filename("nested/storage/path/for/layer") ); - sandbox.epass(&["true"], "SANDBOX_STORAGE_DIR", &nested_storage); + sandbox.epass(&["true"], "DEVLAYER_STORAGE_DIR", &nested_storage); sandbox.epass( &["accept", "**/*.profraw"], - "SANDBOX_STORAGE_DIR", + "DEVLAYER_STORAGE_DIR", &nested_storage, ); - sandbox.epass(&["stop"], "SANDBOX_STORAGE_DIR", &nested_storage); - sandbox.epass(&["delete"], "SANDBOX_STORAGE_DIR", &nested_storage); + sandbox.epass(&["stop"], "DEVLAYER_STORAGE_DIR", &nested_storage); + sandbox.epass(&["delete"], "DEVLAYER_STORAGE_DIR", &nested_storage); Ok(()) } diff --git a/tests/ai_test_clean.rs b/tests/ai_test_clean.rs index 2f9c6d9..445c415 100644 --- a/tests/ai_test_clean.rs +++ b/tests/ai_test_clean.rs @@ -82,10 +82,10 @@ fn test_clean_removes_old_ephemeral_and_test_sandboxes() -> Result<()> { let old = ephemeral_name(TimeDelta::days(8)); let recent = ephemeral_name(TimeDelta::days(6)); let bad_date = format!("ephemeral_not-a-date-{}", id); - let coverage = format!("sandbox-coverage-test-clean-{}", id); - let bind_empty = format!("sandbox-bind-empty-sudo-{}", id); + let coverage = format!("devlayer-coverage-test-clean-{}", id); + let bind_empty = format!("devlayer-bind-empty-sudo-{}", id); let bind_empty_dest = - format!("sandbox-bind-empty-dest-sandbox-coverage-test-{}", id); + format!("devlayer-bind-empty-dest-devlayer-coverage-test-{}", id); let regular = format!("clean-keep-{}", id); for name in [ @@ -101,7 +101,7 @@ fn test_clean_removes_old_ephemeral_and_test_sandboxes() -> Result<()> { } env.run(&["clean", "-y"])?; - assert!(env.sandbox.last_stdout.contains("4 sandboxes deleted")); + assert!(env.sandbox.last_stdout.contains("4 layers deleted")); for name in [&old, &coverage, &bind_empty, &bind_empty_dest] { assert!(!env.exists(name), "{} should have been cleaned", name); @@ -125,7 +125,7 @@ fn test_clean_prompts_for_confirmation() -> Result<()> { assert!( env.sandbox .last_stdout - .contains("The following sandboxes will be deleted") + .contains("The following layers will be deleted") ); assert!(env.sandbox.last_stdout.contains(&old_stopped)); assert!( @@ -144,7 +144,7 @@ fn test_clean_nothing_to_clean() -> Result<()> { env.create_stopped(&ephemeral_name(TimeDelta::zero()))?; env.run(&["clean", "-y"])?; - assert!(env.sandbox.last_stdout.contains("No sandboxes to clean.")); + assert!(env.sandbox.last_stdout.contains("No layers to clean.")); Ok(()) } diff --git a/tests/ai_test_config_impls.rs b/tests/ai_test_config_impls.rs index e98f861..39ce6da 100644 --- a/tests/ai_test_config_impls.rs +++ b/tests/ai_test_config_impls.rs @@ -40,7 +40,7 @@ fn test_valid_config_formats() -> Result<()> { // Create a local config file in test directory let test_dir = format!("generated-test-data/{}", sandbox.name); fs::create_dir_all(&test_dir)?; - let config_file = format!("{}/.sandbox.toml", test_dir); + let config_file = format!("{}/.devlayer.toml", test_dir); // Test valid configs - just verify they don't cause parse errors let bind_single = format!("{}/single", test_dir); @@ -96,7 +96,7 @@ fn test_config_file_locations() -> Result<()> { // 1. .sandbox.toml in current directory let test_dir = format!("generated-test-data/{}", sandbox.name); fs::create_dir_all(&test_dir)?; - let local_config = format!("{}/.sandbox.toml", test_dir); + let local_config = format!("{}/.devlayer.toml", test_dir); fs::write(&local_config, r#"log_level = "TRACE""#)?; // Change to test directory and run config @@ -106,7 +106,7 @@ fn test_config_file_locations() -> Result<()> { if sandbox.pass(&["config"]) { assert!( sandbox.last_stdout.contains("TRACE"), - "Should pick up local .sandbox.toml config" + "Should pick up local .devlayer.toml config" ); } diff --git a/tests/ai_test_config_option.rs b/tests/ai_test_config_option.rs index a704e18..577366a 100644 --- a/tests/ai_test_config_option.rs +++ b/tests/ai_test_config_option.rs @@ -12,7 +12,7 @@ fn ai_test_config_option() -> Result<()> { // This tests the CLI parsing functionality directly // Create test config files - let test_dir = std::env::temp_dir().join("sandbox_config_test"); + let test_dir = std::env::temp_dir().join("layer_config_test"); std::fs::create_dir_all(&test_dir)?; let config_file = test_dir.join("test.toml"); diff --git a/tests/ai_test_corrupted_settings.rs b/tests/ai_test_corrupted_settings.rs index 95142a1..687f419 100644 --- a/tests/ai_test_corrupted_settings.rs +++ b/tests/ai_test_corrupted_settings.rs @@ -9,135 +9,169 @@ use rstest::*; use std::fs; #[rstest] -fn test_get_or_create_with_corrupted_settings(mut sandbox: SandboxManager) -> Result<()> { +fn test_get_or_create_with_corrupted_settings( + mut sandbox: SandboxManager, +) -> Result<()> { // First, create a working sandbox let _output = sandbox.run(&["echo", "initial setup"])?; - + // Get the sandbox directory from the sandbox tool itself let sandbox_dir = sandbox.dir()?; let data_dir = sandbox_dir.join("data"); let settings_file = data_dir.join("settings.json"); - + // Verify the sandbox was created and settings file exists - assert!(settings_file.exists(), "Settings file should exist after initial sandbox creation at {}", settings_file.display()); - + assert!( + settings_file.exists(), + "Settings file should exist after initial layer creation at {}", + settings_file.display() + ); + // Corrupt the settings file by writing invalid JSON using sudo let corrupt_json = "{ invalid json content that cannot be parsed }"; let write_cmd = std::process::Command::new("sudo") - .args(&["sh", "-c", &format!("echo '{}' > '{}'", corrupt_json, settings_file.display())]) + .args(&[ + "sh", + "-c", + &format!("echo '{}' > '{}'", corrupt_json, settings_file.display()), + ]) .output()?; - + if !write_cmd.status.success() { - return Err(anyhow::anyhow!("Failed to corrupt settings file with sudo: {}", - String::from_utf8_lossy(&write_cmd.stderr))); + return Err(anyhow::anyhow!( + "Failed to corrupt settings file with sudo: {}", + String::from_utf8_lossy(&write_cmd.stderr) + )); } - + // Now try to run another command - this should trigger the error path in get_or_create // because the existing sandbox has corrupted settings let success = sandbox.pass(&["echo", "second command"]); - + // The command should fail due to corrupted settings - assert!(!success, "Command should fail due to corrupted settings file"); - + assert!( + !success, + "Command should fail due to corrupted settings file" + ); + // Check that the error message contains the expected text let error_output = sandbox.last_stderr.clone(); - + assert!( - error_output.contains("Failed to load existing sandbox settings") || - error_output.contains("The sandbox may be corrupted") || - error_output.contains("Failed to parse"), + error_output.contains("Failed to load existing layer settings") + || error_output.contains("The layer may be corrupted") + || error_output.contains("Failed to parse"), "Expected error message about corrupted settings, got: {}", error_output ); - + Ok(()) } #[rstest] -fn test_get_or_create_with_unreadable_settings(mut sandbox: SandboxManager) -> Result<()> { +fn test_get_or_create_with_unreadable_settings( + mut sandbox: SandboxManager, +) -> Result<()> { // First, create a working sandbox let _output = sandbox.run(&["echo", "initial setup"])?; - + // Get the sandbox directory from the sandbox tool itself let sandbox_dir = sandbox.dir()?; let data_dir = sandbox_dir.join("data"); let settings_file = data_dir.join("settings.json"); - + // Verify the sandbox was created and settings file exists - assert!(settings_file.exists(), "Settings file should exist after initial sandbox creation"); - + assert!( + settings_file.exists(), + "Settings file should exist after initial layer creation" + ); + // Make the file unreadable by changing permissions (if we have permission to do so) #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let mut perms = fs::metadata(&settings_file)?.permissions(); perms.set_mode(0o000); // No read permissions - + // Only test this if we can actually change permissions (i.e., we're not root) if fs::set_permissions(&settings_file, perms).is_ok() { // Try to run another command - this should trigger the error path let success = sandbox.pass(&["echo", "second command"]); - + // The command should fail due to permission error - assert!(!success, "Command should fail due to unreadable settings file"); - + assert!( + !success, + "Command should fail due to unreadable settings file" + ); + // Check that the error message contains the expected text let error_output = sandbox.last_stderr.clone(); - + assert!( - error_output.contains("Failed to load existing sandbox settings") || - error_output.contains("The sandbox may be corrupted") || - error_output.contains("Permission denied"), + error_output.contains("Failed to load existing layer settings") + || error_output.contains("The layer may be corrupted") + || error_output.contains("Permission denied"), "Expected error message about unreadable settings, got: {}", error_output ); - + // Restore permissions for cleanup let mut perms = fs::metadata(&settings_file)?.permissions(); perms.set_mode(0o644); let _ = fs::set_permissions(&settings_file, perms); } } - + Ok(()) } #[rstest] -fn test_get_or_create_with_directory_as_settings_file(mut sandbox: SandboxManager) -> Result<()> { +fn test_get_or_create_with_directory_as_settings_file( + mut sandbox: SandboxManager, +) -> Result<()> { // First, create a working sandbox let _output = sandbox.run(&["echo", "initial setup"])?; - - // Get the sandbox directory from the sandbox tool itself + + // Get the sandbox directory from the sandbox tool itself let sandbox_dir = sandbox.dir()?; let data_dir = sandbox_dir.join("data"); let settings_file = data_dir.join("settings.json"); - + // Verify the sandbox was created and settings file exists - assert!(settings_file.exists(), "Settings file should exist after initial sandbox creation"); - + assert!( + settings_file.exists(), + "Settings file should exist after initial layer creation" + ); + // Remove the settings file and replace it with a directory fs::remove_file(&settings_file)?; fs::create_dir(&settings_file)?; - + // Verify the path now exists as a directory - assert!(settings_file.is_dir(), "Settings path should now be a directory"); - + assert!( + settings_file.is_dir(), + "Settings path should now be a directory" + ); + // Try to run another command - this should trigger the error path let success = sandbox.pass(&["echo", "second command"]); - + // The command should fail - assert!(!success, "Command should fail when settings.json is a directory"); - + assert!( + !success, + "Command should fail when settings.json is a directory" + ); + // Check that the error message contains the expected text let error_output = sandbox.last_stderr.clone(); - + assert!( - error_output.contains("Failed to load existing sandbox settings") || - error_output.contains("The sandbox may be corrupted") || - error_output.contains("Is a directory"), + error_output.contains("Failed to load existing layer settings") + || error_output.contains("The layer may be corrupted") + || error_output.contains("Is a directory"), "Expected error message about directory as settings file, got: {}", error_output ); - + Ok(()) -} \ No newline at end of file +} diff --git a/tests/ai_test_delete.rs b/tests/ai_test_delete.rs index 32a79ec..b21d813 100644 --- a/tests/ai_test_delete.rs +++ b/tests/ai_test_delete.rs @@ -20,7 +20,7 @@ fn test_delete_single_sandbox() -> Result<()> { // Delete with confirmation (use -y flag) sandbox.run(&["delete", "-y", &name])?; assert!(sandbox.last_stdout.contains(&name)); - assert!(sandbox.last_stdout.contains("1 sandboxes deleted")); + assert!(sandbox.last_stdout.contains("1 layers deleted")); // Verify sandbox no longer exists sandbox.run(&["list"])?; @@ -39,13 +39,13 @@ fn test_delete_current_sandbox_without_y() -> Result<()> { // Delete without patterns and without -y should prompt for current sandbox // TODO: Once the bug is fixed, this should show the current sandbox - // For now it will show "No default sandbox found" + // For now it will show "No default layer found" sandbox.run_with_stdin(&["delete"], "n\n")?; assert!( sandbox .last_stdout - .contains("The following sandboxes will be deleted") + .contains("The following layers will be deleted") ); assert!(sandbox.last_stdout.contains(&sandbox.name)); @@ -62,12 +62,12 @@ fn test_delete_current_sandbox_no_pattern() -> Result<()> { // Delete without pattern should delete current sandbox // NOTE: There's a bug in the current implementation where patterns.is_empty() - // is checked twice with contradictory logic, so it currently shows "No default sandbox" + // is checked twice with contradictory logic, so it currently shows "No default layer" sandbox.run(&["delete", "-y"])?; // TODO: Once the bug is fixed, this should delete the current sandbox // For now, we test what it actually does - assert!(sandbox.last_stdout.contains("1 sandboxes deleted")); + assert!(sandbox.last_stdout.contains("1 layers deleted")); Ok(()) } @@ -78,7 +78,7 @@ fn test_delete_current_non_existent_sandbox() -> Result<()> { let _name = sandbox.name.clone(); sandbox.run_with_stdin(&["delete"], "y\n")?; - assert!(sandbox.last_stdout.contains("No sandbox by the name")); + assert!(sandbox.last_stdout.contains("No layer by the name")); Ok(()) } @@ -89,7 +89,7 @@ fn test_delete_shows_sandbox_status() -> Result<()> { let mut sandbox2 = sandbox(); // Give them unique but similar names - let base_name = format!("sandbox-coverage-test-del-status-{}", rid()); + let base_name = format!("devlayer-coverage-test-del-status-{}", rid()); sandbox1.name = format!("{}-1", base_name); sandbox2.name = format!("{}-2", base_name); let name1 = sandbox1.name.clone(); @@ -109,7 +109,7 @@ fn test_delete_shows_sandbox_status() -> Result<()> { assert!(sandbox1.last_stdout.contains(&name1)); assert!(sandbox1.last_stdout.contains(&name2)); // The actual output format shows "running" or "stopped" before the sandbox name - assert!(sandbox1.last_stdout.contains("2 sandboxes deleted")); + assert!(sandbox1.last_stdout.contains("2 layers deleted")); Ok(()) } @@ -121,9 +121,9 @@ fn test_delete_multiple_sandboxes_with_pattern() -> Result<()> { let mut sandbox3 = sandbox(); // Give them related names - sandbox1.name = format!("sandbox-coverage-test-delete-{}", rid()); - sandbox2.name = format!("sandbox-coverage-test-delete-{}", rid()); - sandbox3.name = format!("sandbox-coverage-test-other-{}", rid()); + sandbox1.name = format!("devlayer-coverage-test-delete-{}", rid()); + sandbox2.name = format!("devlayer-coverage-test-delete-{}", rid()); + sandbox3.name = format!("devlayer-coverage-test-other-{}", rid()); // Create sandboxes sandbox1.run(&["true"])?; @@ -131,7 +131,7 @@ fn test_delete_multiple_sandboxes_with_pattern() -> Result<()> { sandbox3.run(&["true"])?; // Delete sandboxes matching pattern - sandbox1.run(&["delete", "-y", "sandbox-coverage-test-delete*"])?; + sandbox1.run(&["delete", "-y", "devlayer-coverage-test-delete*"])?; // Should show the sandboxes being deleted assert!(sandbox1.last_stdout.contains(&sandbox1.name)); @@ -142,7 +142,7 @@ fn test_delete_multiple_sandboxes_with_pattern() -> Result<()> { let deleted_count = sandbox1 .last_stdout .lines() - .filter(|line| line.contains("Deleted sandbox:")) + .filter(|line| line.contains("Deleted layer:")) .count(); assert!(deleted_count >= 2); @@ -160,8 +160,8 @@ fn test_delete_no_matching_sandboxes() -> Result<()> { let mut sandbox = sandbox(); // Try to delete non-existent sandbox - sandbox.run(&["delete", "-y", "non-existent-sandbox"])?; - assert!(sandbox.last_stdout.contains("No sandboxes found matching")); + sandbox.run(&["delete", "-y", "non-existent-layer"])?; + assert!(sandbox.last_stdout.contains("No layers found matching")); Ok(()) } @@ -184,7 +184,7 @@ fn test_delete_stopped_sandbox() -> Result<()> { assert!(sandbox.last_stdout.contains("0 entries")); assert!(sandbox.last_stdout.contains("stopped")); assert!(sandbox.last_stdout.contains(&name)); - assert!(sandbox.last_stdout.contains("1 sandboxes deleted")); + assert!(sandbox.last_stdout.contains("1 layers deleted")); Ok(()) } @@ -247,7 +247,7 @@ fn test_delete_stopped_sandbox_by_name() -> Result<()> { assert!(sandbox.last_stdout.contains("0 entries")); assert!(sandbox.last_stdout.contains("stopped")); assert!(sandbox.last_stdout.contains(&name)); - assert!(sandbox.last_stdout.contains("1 sandboxes deleted")); + assert!(sandbox.last_stdout.contains("1 layers deleted")); Ok(()) } @@ -256,7 +256,7 @@ fn test_delete_stopped_sandbox_by_name() -> Result<()> { fn test_delete_failure(mut sandbox: SandboxManager) -> Result<()> { sandbox.run(&["true"])?; assert!(sandbox.epass(&["delete", "-y"], "TEST_DELETE_FAILURE", "1")); - assert!(sandbox.last_stdout.contains("Error deleting sandbox")); + assert!(sandbox.last_stdout.contains("Error deleting layer")); Ok(()) } @@ -275,7 +275,7 @@ fn test_delete_running_sandbox_by_name() -> Result<()> { sandbox.run_with_stdin(&["delete", &name], "y\n")?; assert!(sandbox.last_stdout.contains("running")); assert!(sandbox.last_stdout.contains(&name)); - assert!(sandbox.last_stdout.contains("1 sandboxes deleted")); + assert!(sandbox.last_stdout.contains("1 layers deleted")); Ok(()) } @@ -291,7 +291,7 @@ fn test_delete_running_sandbox_no_modifications_no_confirm() -> Result<()> { // Delete should work even though there are no modifications sandbox.run(&["delete", "-y", &name])?; assert!(sandbox.last_stdout.contains(&name)); - assert!(sandbox.last_stdout.contains("1 sandboxes deleted")); + assert!(sandbox.last_stdout.contains("1 layers deleted")); // Verify sandbox no longer exists sandbox.run(&["list"])?; @@ -307,7 +307,7 @@ fn test_delete_multiple_stopped_sandboxes() -> Result<()> { let mut sandbox3 = sandbox(); // Give them related names - let base_name = format!("sandbox-coverage-test-del-stopped-{}", rid()); + let base_name = format!("devlayer-coverage-test-del-stopped-{}", rid()); sandbox1.name = format!("{}-1", base_name); sandbox2.name = format!("{}-2", base_name); sandbox3.name = format!("{}-3", base_name); @@ -332,7 +332,7 @@ fn test_delete_multiple_stopped_sandboxes() -> Result<()> { assert!(sandbox1.last_stdout.contains(&name1)); assert!(sandbox1.last_stdout.contains(&name2)); assert!(sandbox1.last_stdout.contains(&name3)); - assert!(sandbox1.last_stdout.contains("3 sandboxes deleted")); + assert!(sandbox1.last_stdout.contains("3 layers deleted")); Ok(()) } @@ -344,7 +344,7 @@ fn test_delete_mixed_running_and_stopped_sandboxes() -> Result<()> { let mut sandbox3 = sandbox(); // Give them related names - let base_name = format!("sandbox-coverage-test-del-mixed-{}", rid()); + let base_name = format!("devlayer-coverage-test-del-mixed-{}", rid()); sandbox1.name = format!("{}-running", base_name); sandbox2.name = format!("{}-stopped", base_name); sandbox3.name = format!("{}-also-running", base_name); @@ -367,7 +367,7 @@ fn test_delete_mixed_running_and_stopped_sandboxes() -> Result<()> { assert!(sandbox1.last_stdout.contains(&name1)); assert!(sandbox1.last_stdout.contains(&name2)); assert!(sandbox1.last_stdout.contains(&name3)); - assert!(sandbox1.last_stdout.contains("3 sandboxes deleted")); + assert!(sandbox1.last_stdout.contains("3 layers deleted")); // Verify all are deleted sandbox1.run(&["list"])?; @@ -413,7 +413,7 @@ fn test_delete_confirmation_yes() -> Result<()> { // Test confirming with 'y' sandbox.run_with_stdin(&["delete", &name], "y\n")?; - assert!(sandbox.last_stdout.contains("1 sandboxes deleted")); + assert!(sandbox.last_stdout.contains("1 layers deleted")); assert!(sandbox.last_stdout.contains(&name)); Ok(()) @@ -519,7 +519,7 @@ fn test_delete_with_modifications() -> Result<()> { // Delete with -y flag just shows success messages sandbox.run(&["delete", "-y", &name])?; assert!(sandbox.last_stdout.contains(&name)); - assert!(sandbox.last_stdout.contains("1 sandboxes deleted")); + assert!(sandbox.last_stdout.contains("1 layers deleted")); Ok(()) } @@ -553,6 +553,6 @@ fn test_delete_ignore_invalid_upper_dirs( //sandbox.run(&["true"])?; // Now delete should process these directories and skip them sandbox.run_with_stdin(&["delete"], "y\n")?; - assert!(sandbox.last_stdout.contains("1 sandboxes deleted")); + assert!(sandbox.last_stdout.contains("1 layers deleted")); Ok(()) } diff --git a/tests/ai_test_error_paths.rs b/tests/ai_test_error_paths.rs index 1b3ddd6..dbe4155 100644 --- a/tests/ai_test_error_paths.rs +++ b/tests/ai_test_error_paths.rs @@ -48,7 +48,8 @@ fn ai_test_new_with_unusable_storage_dir( // when the storage directory can't be used. --new conflicts with the // --name the fixture normally adds. sandbox.no_default_options = true; - let storage_dir = format!("--storage-dir=/proc/sandbox-coverage-{}", rid()); + let storage_dir = + format!("--storage-dir=/proc/devlayer-coverage-{}", rid()); assert!(sandbox.xfail(&["--new", &storage_dir, "config", "name"])); assert!( sandbox diff --git a/tests/ai_test_ignore_rules.rs b/tests/ai_test_ignore_rules.rs index 3453fbb..6ba5c6a 100644 --- a/tests/ai_test_ignore_rules.rs +++ b/tests/ai_test_ignore_rules.rs @@ -690,7 +690,7 @@ fn test_env_flag_includes_ignored(mut sandbox: SandboxManager) -> Result<()> { // Call `status` WITHOUT the flag but WITH env var set to true sandbox.set_ignored(false); // Disable automatic --ignored - sandbox.run_with_env(&["status", &test_dir], "SANDBOX_IGNORED", "true")?; + sandbox.run_with_env(&["status", &test_dir], "DEVLAYER_IGNORED", "true")?; let stdout = sandbox.last_stdout.clone(); sandbox.set_ignored(true); // Reset back @@ -701,16 +701,20 @@ fn test_env_flag_includes_ignored(mut sandbox: SandboxManager) -> Result<()> { // Invalid value for SANDBOX_IGNORED sandbox.set_ignored(false); // Disable automatic --ignored let result = - sandbox.run_with_env(&["status", &test_dir], "SANDBOX_IGNORED", "cow"); + sandbox.run_with_env(&["status", &test_dir], "DEVLAYER_IGNORED", "cow"); sandbox.set_ignored(true); // Reset back assert!( result.is_err(), - "Expected error for invalid SANDBOX_IGNORED value" + "Expected error for invalid DEVLAYER_IGNORED value" ); // False value for SANDBOX_IGNORED sandbox.set_ignored(false); // Disable automatic --ignored - sandbox.run_with_env(&["status", &test_dir], "SANDBOX_IGNORED", "false")?; + sandbox.run_with_env( + &["status", &test_dir], + "DEVLAYER_IGNORED", + "false", + )?; let stdout = sandbox.last_stdout.clone(); sandbox.set_ignored(true); // Reset back assert!(!stdout.contains(ignored_file.to_str().unwrap())); @@ -721,7 +725,7 @@ fn test_env_flag_includes_ignored(mut sandbox: SandboxManager) -> Result<()> { // and test that it overrides the env var sandbox.set_ignored(false); // Disable automatic --ignored let output = Command::new("sudo") - .env("SANDBOX_IGNORED", "false") + .env("DEVLAYER_IGNORED", "false") .args(["-E", &sandbox.sandbox_bin]) .args([ "-v", diff --git a/tests/ai_test_resource_limits.rs b/tests/ai_test_resource_limits.rs index 4a38b75..0f87614 100644 --- a/tests/ai_test_resource_limits.rs +++ b/tests/ai_test_resource_limits.rs @@ -41,7 +41,7 @@ fn limits_available(sandbox: &mut SandboxManager) -> bool { /// Finds our sandbox's cgroup on the host, if it has one fn host_cgroup(sandbox: &SandboxManager) -> Option { let suffix = format!("-{}", sandbox.name); - fs::read_dir("/sys/fs/cgroup/sandbox") + fs::read_dir("/sys/fs/cgroup/layer") .ok()? .filter_map(|entry| entry.ok()) .map(|entry| entry.path()) @@ -98,14 +98,14 @@ fn ai_test_limits_env(mut sandbox: SandboxManager) -> Result<()> { let args = ["--no-config", "config"]; sandbox.run_with_env( &[&args[..], &["cpus"]].concat(), - "SANDBOX_CPUS", + "DEVLAYER_CPUS", "3", )?; assert_eq!(sandbox.last_stdout.trim(), "3"); sandbox.run_with_env( &[&args[..], &["memory"]].concat(), - "SANDBOX_MEMORY", + "DEVLAYER_MEMORY", "2G", )?; assert_eq!(sandbox.last_stdout.trim(), (2u64 << 30).to_string()); @@ -113,7 +113,7 @@ fn ai_test_limits_env(mut sandbox: SandboxManager) -> Result<()> { // Empty values are ignored sandbox.run_with_env( &[&args[..], &["cpus"]].concat(), - "SANDBOX_CPUS", + "DEVLAYER_CPUS", "", )?; assert_eq!(sandbox.last_stdout.trim(), "unlimited"); @@ -121,7 +121,7 @@ fn ai_test_limits_env(mut sandbox: SandboxManager) -> Result<()> { // The CLI takes precedence over the environment sandbox.run_with_env( &["--no-config", "--cpus=1", "config", "cpus"], - "SANDBOX_CPUS", + "DEVLAYER_CPUS", "3", )?; assert_eq!(sandbox.last_stdout.trim(), "1"); @@ -157,7 +157,7 @@ fn ai_test_limits_config_file(mut sandbox: SandboxManager) -> Result<()> { // The environment takes precedence over config files sandbox.run_with_env( &["--config", &config, "config", "cpus"], - "SANDBOX_CPUS", + "DEVLAYER_CPUS", "2", )?; assert_eq!(sandbox.last_stdout.trim(), "2"); @@ -220,7 +220,7 @@ fn ai_test_limits_applied(mut sandbox: SandboxManager) -> Result<()> { assert_eq!(run(&mut sandbox, &["cat", "/proc/self/cgroup"])?, "0::/"); // Processes that join the running sandbox are in its cgroup too - let cgroup = host_cgroup(&sandbox).expect("sandbox cgroup should exist"); + let cgroup = host_cgroup(&sandbox).expect("layer cgroup should exist"); let mut child = sandbox.run_in_background(&[args[0], args[1], "sleep", "30"])?; let mut joined = false; @@ -232,7 +232,7 @@ fn ai_test_limits_applied(mut sandbox: SandboxManager) -> Result<()> { } std::thread::sleep(std::time::Duration::from_millis(50)); } - assert!(joined, "sleep should have joined the sandbox cgroup"); + assert!(joined, "sleep should have joined the layer cgroup"); // Stopping the sandbox removes its cgroup sandbox.run(&["stop"])?; @@ -330,7 +330,7 @@ fn ai_test_limits_stale_cgroup(mut sandbox: SandboxManager) -> Result<()> { } // Kill the sandbox without cleaning up, leaving an empty cgroup behind - let cgroup = host_cgroup(&sandbox).expect("sandbox cgroup should exist"); + let cgroup = host_cgroup(&sandbox).expect("layer cgroup should exist"); sandbox.run(&["config", "sandbox_dir"])?; let pid_file = format!("{}.pid", sandbox.last_stdout.trim()); let pid = fs::read_to_string(&pid_file)?; @@ -404,7 +404,7 @@ fn ai_test_limits_setup_failures(mut sandbox: SandboxManager) -> Result<()> { "TEST_START_SANDBOX_FAILURE", "1" )); - assert!(sandbox.last_stderr.contains("Failed to start sandbox")); + assert!(sandbox.last_stderr.contains("Failed to start layer")); assert!(host_cgroup(&sandbox).is_none()); Ok(()) } @@ -505,7 +505,7 @@ fn ai_test_limits_stop_cgroup_busy(mut sandbox: SandboxManager) -> Result<()> { // A child cgroup keeps the sandbox's cgroup from being removed, so stop // retries for a while and then gives up without failing - let cgroup = host_cgroup(&sandbox).expect("sandbox cgroup should exist"); + let cgroup = host_cgroup(&sandbox).expect("layer cgroup should exist"); let child = cgroup.join("busy"); let sudo = |args: &[&str]| std::process::Command::new("sudo").args(args).status(); @@ -543,7 +543,7 @@ fn ai_test_limits_unlimited_override( sandbox.run_with_env( &["--config", &config, "config", "cpus"], - "SANDBOX_CPUS", + "DEVLAYER_CPUS", "unlimited", )?; assert_eq!(sandbox.last_stdout.trim(), "unlimited"); @@ -590,7 +590,7 @@ fn ai_test_limits_nested(mut sandbox: SandboxManager) -> Result<()> { assert_eq!(sandbox.last_stdout.trim(), "200000 100000"); assert!( sandbox.last_stderr.contains( - "shares the limits of the sandbox it's running in (cpus=2 memory=unlimited)" + "shares the limits of the layer it's running in (cpus=2 memory=unlimited)" ), "{}", sandbox.last_stderr @@ -601,7 +601,7 @@ fn ai_test_limits_nested(mut sandbox: SandboxManager) -> Result<()> { sandbox.run(&["--no-config", &inner, "--no-config", "--cpus=1", "true"])?; assert!( sandbox.last_stderr.contains( - "shares the limits of the sandbox it's running in (cpus=unlimited memory=unlimited)" + "shares the limits of the layer it's running in (cpus=unlimited memory=unlimited)" ), "{}", sandbox.last_stderr @@ -619,7 +619,7 @@ fn ai_test_limits_delete_removes_cgroup( // delete stops sandboxes without knowing which user started them, so // it has to find the cgroup from the running sandbox - let cgroup = host_cgroup(&sandbox).expect("sandbox cgroup should exist"); + let cgroup = host_cgroup(&sandbox).expect("layer cgroup should exist"); let name = sandbox.name.clone(); sandbox.run(&["delete", "-y", &name])?; assert!(!cgroup.exists()); diff --git a/tests/ai_test_run_media_mount.rs b/tests/ai_test_run_media_mount.rs index 0705ad5..c4da550 100644 --- a/tests/ai_test_run_media_mount.rs +++ b/tests/ai_test_run_media_mount.rs @@ -14,23 +14,23 @@ fn test_bind_mount_under_run_media(mut sandbox: SandboxManager) -> Result<()> { let test_file = format!("{}/test.txt", test_dir); std::fs::write(&test_file, "test content")?; - if !std::path::Path::new("/run/media/sandbox-coverage-testing").exists() { - std::fs::create_dir_all("/run/media/sandbox-coverage-testing")?; + if !std::path::Path::new("/run/media/devlayer-coverage-testing").exists() { + std::fs::create_dir_all("/run/media/devlayer-coverage-testing")?; } // Try to bind mount the temp directory to /run/media/test // This should work with our fix, as we now create parent directories let success = sandbox.pass(&[ "--bind", - &format!("{}:/run/media/sandbox-coverage-testing", test_dir), + &format!("{}:/run/media/devlayer-coverage-testing", test_dir), "ls", - "/run/media/sandbox-coverage-testing/test.txt", + "/run/media/devlayer-coverage-testing/test.txt", ]); // The command should succeed and show the test file assert!( success, - "Failed to bind mount to /run/media/sandbox-coverage-testing: {}", + "Failed to bind mount to /run/media/devlayer-coverage-testing: {}", sandbox.last_stderr ); assert!( diff --git a/tests/ai_test_sandbox_settings.rs b/tests/ai_test_sandbox_settings.rs index 005f948..2b8be4f 100644 --- a/tests/ai_test_sandbox_settings.rs +++ b/tests/ai_test_sandbox_settings.rs @@ -17,9 +17,9 @@ use std::collections::HashMap; fn create_test_config() -> ::sandbox::config::Config { ::sandbox::config::Config { log_level: log::LevelFilter::Info, - name: "test_sandbox".to_string(), + name: "test_layer".to_string(), storage_dir: PathBuf::from("/tmp/test_storage"), - sandbox_dir: PathBuf::from("/tmp/test_sandbox"), + sandbox_dir: PathBuf::from("/tmp/test_layer"), upper_cwd: PathBuf::from("/tmp/test_upper"), overlay_cwd: PathBuf::from("/tmp/test_overlay"), net: Network::None, @@ -38,7 +38,7 @@ fn create_test_config() -> ::sandbox::config::Config { fn test_from_config() -> Result<()> { let mut config = create_test_config(); config.net = Network::Host; - + let bind_mount = BindMount { source: PathBuf::from("/source"), target: PathBuf::from("/target"), @@ -65,36 +65,36 @@ fn test_from_config() -> Result<()> { #[rstest] fn test_user_bind_mounts_filtering_through_validation() -> Result<()> { let mut config = create_test_config(); - + let user_bind = BindMount { source: PathBuf::from("/user/source"), target: PathBuf::from("/user/target"), options: BindMountOptions::ReadWrite, argument: "user_bind".to_string(), }; - + let data_bind = BindMount { source: PathBuf::from("/data/source"), target: PathBuf::from("/data/target"), options: BindMountOptions::ReadOnly, argument: "data".to_string(), }; - + config.bind_mounts = vec![user_bind.clone(), data_bind.clone()]; let settings = SandboxSettings::from_config(&config, &[]); - + // Test that "data" bind mount is filtered out by trying validation with only data bind let mut config_with_data_only = create_test_config(); config_with_data_only.bind_mounts = vec![data_bind]; - + let result = settings.validate_against_config(&config_with_data_only, &[]); - + // Should fail because user_bind was removed, proving "data" bind is ignored assert!(result.is_err()); let error_msg = result.unwrap_err().to_string(); assert!(error_msg.contains("Bind mount configuration has changed")); assert!(error_msg.contains("user_bind")); - + Ok(()) } @@ -107,7 +107,7 @@ fn test_save_and_load_from_file() -> Result<()> { let mut config = create_test_config(); config.net = Network::None; - + let bind_mount = BindMount { source: PathBuf::from("/test/source"), target: PathBuf::from("/test/target"), @@ -131,7 +131,7 @@ fn test_save_and_load_from_file() -> Result<()> { // Test save_to_file original_settings.save_to_file(&settings_path)?; - + // Verify file was created and contains valid JSON assert!(settings_path.exists()); let file_content = fs::read_to_string(&settings_path)?; @@ -139,7 +139,7 @@ fn test_save_and_load_from_file() -> Result<()> { // Test load_from_file let loaded_settings = SandboxSettings::load_from_file(&settings_path)?; - + assert_eq!(loaded_settings, original_settings); assert_eq!(loaded_settings.network, Network::None); assert_eq!(loaded_settings.mounts.len(), 2); @@ -152,13 +152,13 @@ fn test_save_and_load_from_file() -> Result<()> { #[rstest] fn test_load_from_nonexistent_file() -> Result<()> { let nonexistent_path = PathBuf::from("/nonexistent/path/settings.json"); - + let result = SandboxSettings::load_from_file(&nonexistent_path); - + assert!(result.is_err()); let error_msg = result.unwrap_err().to_string(); assert!(error_msg.contains("Settings file does not exist")); - + Ok(()) } @@ -171,13 +171,13 @@ fn test_load_from_invalid_json_file() -> Result<()> { // Write invalid JSON fs::write(&settings_path, "{ invalid json }")?; - + let result = SandboxSettings::load_from_file(&settings_path); - + assert!(result.is_err()); let error_msg = result.unwrap_err().to_string(); assert!(error_msg.contains("Failed to parse settings.json")); - + Ok(()) } @@ -185,15 +185,15 @@ fn test_load_from_invalid_json_file() -> Result<()> { fn test_save_to_invalid_path() -> Result<()> { let config = create_test_config(); let settings = SandboxSettings::from_config(&config, &[]); - + let invalid_path = PathBuf::from("/nonexistent/directory/settings.json"); - + let result = settings.save_to_file(&invalid_path); - + assert!(result.is_err()); let error_msg = result.unwrap_err().to_string(); assert!(error_msg.contains("Failed to write settings.json")); - + Ok(()) } @@ -201,7 +201,7 @@ fn test_save_to_invalid_path() -> Result<()> { fn test_validate_against_config_identical() -> Result<()> { let mut config = create_test_config(); config.net = Network::Host; - + let bind_mount = BindMount { source: PathBuf::from("/source"), target: PathBuf::from("/target"), @@ -216,7 +216,7 @@ fn test_validate_against_config_identical() -> Result<()> { }]; let settings = SandboxSettings::from_config(&config, &mounts); - + // Validation against the same config should succeed let result = settings.validate_against_config(&config, &mounts); assert!(result.is_ok()); @@ -228,26 +228,29 @@ fn test_validate_against_config_identical() -> Result<()> { fn test_validate_against_config_network_change() -> Result<()> { let mut original_config = create_test_config(); original_config.net = Network::Host; - + let mounts = vec![MountHash { hash: "test_hash".to_string(), dir: "/test/dir".to_string(), }]; let settings = SandboxSettings::from_config(&original_config, &mounts); - + // Change network configuration let mut new_config = original_config.clone(); new_config.net = Network::None; - + let result = settings.validate_against_config(&new_config, &mounts); - + assert!(result.is_err()); let error_msg = result.unwrap_err().to_string(); assert!(error_msg.contains("Network configuration has changed")); assert!(error_msg.contains("Host")); assert!(error_msg.contains("None")); - assert!(error_msg.contains("Please stop existing sandbox to change network settings")); + assert!( + error_msg + .contains("Please stop existing layer to change network settings") + ); Ok(()) } @@ -255,7 +258,7 @@ fn test_validate_against_config_network_change() -> Result<()> { #[rstest] fn test_validate_against_config_mounts_removed() -> Result<()> { let config = create_test_config(); - + let original_mounts = vec![ MountHash { hash: "hash1".to_string(), @@ -268,21 +271,25 @@ fn test_validate_against_config_mounts_removed() -> Result<()> { ]; let settings = SandboxSettings::from_config(&config, &original_mounts); - + // Remove one mount let new_mounts = vec![MountHash { hash: "hash1".to_string(), dir: "/dir1".to_string(), }]; - + let result = settings.validate_against_config(&config, &new_mounts); - + assert!(result.is_err()); let error_msg = result.unwrap_err().to_string(); assert!(error_msg.contains("Mount configuration has changed")); assert!(error_msg.contains("Removed mounts")); assert!(error_msg.contains("/dir2")); - assert!(error_msg.contains("Please stop the existing sandbox to change mount settings")); + assert!( + error_msg.contains( + "Please stop the existing layer to change mount settings" + ) + ); Ok(()) } @@ -290,14 +297,14 @@ fn test_validate_against_config_mounts_removed() -> Result<()> { #[rstest] fn test_validate_against_config_mounts_added() -> Result<()> { let config = create_test_config(); - + let original_mounts = vec![MountHash { hash: "hash1".to_string(), dir: "/dir1".to_string(), }]; let settings = SandboxSettings::from_config(&config, &original_mounts); - + // Add another mount let new_mounts = vec![ MountHash { @@ -309,9 +316,9 @@ fn test_validate_against_config_mounts_added() -> Result<()> { dir: "/dir2".to_string(), }, ]; - + let result = settings.validate_against_config(&config, &new_mounts); - + assert!(result.is_err()); let error_msg = result.unwrap_err().to_string(); assert!(error_msg.contains("Mount configuration has changed")); @@ -324,37 +331,39 @@ fn test_validate_against_config_mounts_added() -> Result<()> { #[rstest] fn test_validate_against_config_bind_mounts_removed() -> Result<()> { let mut original_config = create_test_config(); - + let bind1 = BindMount { source: PathBuf::from("/source1"), target: PathBuf::from("/target1"), options: BindMountOptions::ReadOnly, argument: "bind1".to_string(), }; - + let bind2 = BindMount { source: PathBuf::from("/source2"), target: PathBuf::from("/target2"), options: BindMountOptions::ReadWrite, argument: "bind2".to_string(), }; - + original_config.bind_mounts = vec![bind1.clone(), bind2]; - + let settings = SandboxSettings::from_config(&original_config, &[]); - + // Remove one bind mount let mut new_config = original_config.clone(); new_config.bind_mounts = vec![bind1]; - + let result = settings.validate_against_config(&new_config, &[]); - + assert!(result.is_err()); let error_msg = result.unwrap_err().to_string(); assert!(error_msg.contains("Bind mount configuration has changed")); assert!(error_msg.contains("Removed bind mounts")); assert!(error_msg.contains("bind2")); - assert!(error_msg.contains("Please stop the existing sandbox to change bind mount settings")); + assert!(error_msg.contains( + "Please stop the existing layer to change bind mount settings" + )); Ok(()) } @@ -362,18 +371,18 @@ fn test_validate_against_config_bind_mounts_removed() -> Result<()> { #[rstest] fn test_validate_against_config_bind_mounts_added() -> Result<()> { let mut original_config = create_test_config(); - + let bind1 = BindMount { source: PathBuf::from("/source1"), target: PathBuf::from("/target1"), options: BindMountOptions::ReadOnly, argument: "bind1".to_string(), }; - + original_config.bind_mounts = vec![bind1.clone()]; - + let settings = SandboxSettings::from_config(&original_config, &[]); - + // Add another bind mount let bind2 = BindMount { source: PathBuf::from("/source2"), @@ -381,12 +390,12 @@ fn test_validate_against_config_bind_mounts_added() -> Result<()> { options: BindMountOptions::Mask, argument: "bind2".to_string(), }; - + let mut new_config = original_config.clone(); new_config.bind_mounts = vec![bind1, bind2]; - + let result = settings.validate_against_config(&new_config, &[]); - + assert!(result.is_err()); let error_msg = result.unwrap_err().to_string(); assert!(error_msg.contains("Bind mount configuration has changed")); @@ -399,31 +408,31 @@ fn test_validate_against_config_bind_mounts_added() -> Result<()> { #[rstest] fn test_validate_against_config_data_bind_mount_ignored() -> Result<()> { let mut original_config = create_test_config(); - + let user_bind = BindMount { source: PathBuf::from("/user/source"), target: PathBuf::from("/user/target"), options: BindMountOptions::ReadOnly, argument: "user_bind".to_string(), }; - + let data_bind = BindMount { source: PathBuf::from("/data/source"), target: PathBuf::from("/data/target"), options: BindMountOptions::ReadWrite, argument: "data".to_string(), }; - + original_config.bind_mounts = vec![user_bind.clone(), data_bind.clone()]; - + let settings = SandboxSettings::from_config(&original_config, &[]); - + // New config has only the data bind mount (user bind removed) let mut new_config = original_config.clone(); new_config.bind_mounts = vec![data_bind]; - + let result = settings.validate_against_config(&new_config, &[]); - + // Should fail because user_bind was removed, even though data bind is ignored assert!(result.is_err()); let error_msg = result.unwrap_err().to_string(); @@ -437,42 +446,43 @@ fn test_validate_against_config_data_bind_mount_ignored() -> Result<()> { #[rstest] fn test_validate_against_config_multiple_changes() -> Result<()> { let mut original_config = create_test_config(); - + let mount1 = MountHash { hash: "hash1".to_string(), dir: "/dir1".to_string(), }; - + let mount2 = MountHash { hash: "hash2".to_string(), dir: "/dir2".to_string(), }; - + let bind1 = BindMount { source: PathBuf::from("/bind1"), target: PathBuf::from("/target1"), options: BindMountOptions::ReadOnly, argument: "bind1".to_string(), }; - + original_config.bind_mounts = vec![bind1.clone()]; original_config.net = Network::Host; - + let original_mounts = vec![mount1, mount2]; - let settings = SandboxSettings::from_config(&original_config, &original_mounts); - + let settings = + SandboxSettings::from_config(&original_config, &original_mounts); + // Change everything let mut new_config = original_config.clone(); new_config.net = Network::None; // This should be the first error new_config.bind_mounts = vec![]; // Remove bind mount let new_mounts = vec![]; // Remove all mounts - + let result = settings.validate_against_config(&new_config, &new_mounts); - + assert!(result.is_err()); let error_msg = result.unwrap_err().to_string(); // Should fail on network change first assert!(error_msg.contains("Network configuration has changed")); Ok(()) -} \ No newline at end of file +} diff --git a/tests/fixtures/fixture_sandbox.rs b/tests/fixtures/fixture_sandbox.rs index ca9bd74..6632969 100644 --- a/tests/fixtures/fixture_sandbox.rs +++ b/tests/fixtures/fixture_sandbox.rs @@ -40,13 +40,13 @@ pub fn get_sandbox_bin() -> String { let bin = if let Ok(current_exe) = std::env::current_exe() { if current_exe.to_string_lossy().contains("/coverage/") { - "target/coverage/sandbox" + "target/coverage/devlayer" } else { - "target/debug/sandbox" + "target/debug/devlayer" } } else { // Fallback if we can't determine the path - "target/debug/sandbox" + "target/debug/devlayer" }; let path = project_root.join(bin); @@ -72,7 +72,7 @@ pub struct SandboxManager { impl SandboxManager { pub fn new() -> Self { - let name = format!("sandbox-coverage-test-{}", rid()); + let name = format!("devlayer-coverage-test-{}", rid()); #[allow(clippy::panic)] match std::fs::create_dir_all( @@ -401,7 +401,7 @@ impl Drop for SandboxManager { self.ignored = true; if let Err(e) = self.run(&["stop"]) { - error!("Failed to kill sandbox: {}", e); + error!("Failed to kill layer: {}", e); error!("last_stderr: {}", self.last_stderr); error!("last_stdout: {}", self.last_stdout); return; @@ -425,7 +425,7 @@ impl Drop for SandboxManager { match self.run(&["delete", "-y", sandbox_name.as_str()]) { Ok(_) => (), Err(e) => { - warn!("Failed to delete sandbox: {}", e); + warn!("Failed to delete layer: {}", e); warn!("last_stderr: {}", self.last_stderr); warn!("last_stdout: {}", self.last_stdout); } diff --git a/tests/isolated_test_accept_rename_across_mount.rs b/tests/isolated_test_accept_rename_across_mount.rs index b5e0621..dbe84df 100644 --- a/tests/isolated_test_accept_rename_across_mount.rs +++ b/tests/isolated_test_accept_rename_across_mount.rs @@ -18,7 +18,7 @@ use std::{path::Path, process::Command}; #[rstest] fn test_accept_rename_across_mount(mut sandbox: SandboxManager) -> Result<()> { - let dest_host_dir = "/delete-me-this-is-a-sandbox-coverage-test-dir-for-rename-across-mount"; + let dest_host_dir = "/delete-me-this-is-a-devlayer-coverage-test-dir-for-rename-across-mount"; let dir_to_move = sandbox.test_filename("dir_to_move"); Command::new("sudo") .arg("mkdir") diff --git a/tests/isolated_test_accept_root.rs b/tests/isolated_test_accept_root.rs index ec98ce6..352fefe 100644 --- a/tests/isolated_test_accept_root.rs +++ b/tests/isolated_test_accept_root.rs @@ -10,9 +10,9 @@ use std::{path::Path, process::Command}; #[rstest] fn test_accept_root_file(mut sandbox: SandboxManager) -> Result<()> { - let dirname = "/delete-me-this-is-a-sandbox-coverage-test-dir"; - let filename = - dirname.to_string() + "/delete-me-this-is-a-sandbox-coverage-test-file"; + let dirname = "/delete-me-this-is-a-devlayer-coverage-test-dir"; + let filename = dirname.to_string() + + "/delete-me-this-is-a-devlayer-coverage-test-file"; Command::new("sudo").arg("mkdir").arg(dirname).output()?; Command::new("sudo").arg("touch").arg(&filename).output()?; Command::new("sudo") diff --git a/tests/isolated_test_clean_running.rs b/tests/isolated_test_clean_running.rs index a49e5f6..4b1e490 100644 --- a/tests/isolated_test_clean_running.rs +++ b/tests/isolated_test_clean_running.rs @@ -8,14 +8,14 @@ use rstest::*; * also delete any real stopped ephemeral sandboxes older than a week. */ #[rstest] -#[ignore = "Ignoring as this will delete old non test ephemeral sandboxes"] +#[ignore = "Ignoring as this will delete old non test ephemeral layers"] fn test_clean_deletes_running_test_sandboxes() -> Result<()> { let mut sandbox = sandbox(); let name = sandbox.name.clone(); sandbox.run(&["true"])?; sandbox.run(&["list"])?; - assert!(sandbox.last_stdout.contains("Running sandboxes:")); + assert!(sandbox.last_stdout.contains("Running layers:")); assert!(sandbox.last_stdout.contains(&name)); sandbox.run(&["clean", "-y"])?; diff --git a/tests/isolated_test_new.rs b/tests/isolated_test_new.rs index 39c65e7..5aaa851 100644 --- a/tests/isolated_test_new.rs +++ b/tests/isolated_test_new.rs @@ -22,12 +22,12 @@ fn test_new_last_name_with_ms() -> Result<()> { assert!(sandbox.epass( &["--new", "-v", "true"], "TEST_NAME_WITH_MS", - "sandbox-coverage-new-with-ms" + "devlayer-coverage-new-with-ms" )); sandbox.run(&["--last", "config", "name"])?; sandbox.name = sandbox.last_stdout.trim().to_string(); - println!("sandbox.name: {}", sandbox.name); + println!("layer.name: {}", sandbox.name); } Ok(()) diff --git a/tests/isolated_test_stop_all.rs b/tests/isolated_test_stop_all.rs index a08cff7..dd2557f 100644 --- a/tests/isolated_test_stop_all.rs +++ b/tests/isolated_test_stop_all.rs @@ -10,7 +10,7 @@ use std::{io::Write, process::Command, thread::sleep, time::Duration}; * tests that were running in parallel. */ #[rstest] -#[ignore = "Ignoring as this will stop non test sandboxes"] +#[ignore = "Ignoring as this will stop non test layers"] fn test_stop_all() -> Result<()> { let mut sandbox1 = sandbox(); let mut sandbox2 = sandbox(); @@ -37,9 +37,7 @@ fn test_stop_all() -> Result<()> { } if !ok { - return Err(anyhow::anyhow!( - "Sandboxes did not start within 10 seconds" - )); + return Err(anyhow::anyhow!("Layers did not start within 10 seconds")); } // ensure they're actually there diff --git a/tests/isolated_test_stop_all_partial_fail.rs b/tests/isolated_test_stop_all_partial_fail.rs index 54d42b0..4944805 100644 --- a/tests/isolated_test_stop_all_partial_fail.rs +++ b/tests/isolated_test_stop_all_partial_fail.rs @@ -10,7 +10,7 @@ use std::{process::Command, thread::sleep, time::Duration}; * tests that were running in parallel. */ #[rstest] -#[ignore = "Problematic on dev machines with running sandboxes"] +#[ignore = "Problematic on dev machines with running layers"] fn test_stop_all_partial_fail() -> Result<()> { let mut bad_sandbox = sandbox(); bad_sandbox.run(&["true"])?; @@ -26,7 +26,7 @@ fn test_stop_all_partial_fail() -> Result<()> { assert!(bad_sandbox.xfail(&["true"])); assert!(bad_sandbox.all_stderr.contains("Failed to open lock")); - /* Despite bad state that the above "sandbox" is in, the following is expected to work. */ + /* Despite bad state that the above "devlayer" is in, the following is expected to work. */ let mut sandbox1 = sandbox(); let mut sandbox2 = sandbox(); let mut c1 = sandbox1.run_in_background(&["sleep", "9897135"])?; diff --git a/tests/isolated_test_sync.rs b/tests/isolated_test_sync.rs index 69da3a6..84869d1 100644 --- a/tests/isolated_test_sync.rs +++ b/tests/isolated_test_sync.rs @@ -18,14 +18,14 @@ fn test_sync(mut sandbox: SandboxManager) -> Result<()> { sandbox.run(&[ "bash", "-c", - format!("echo -n 'from sandbox echo' > {}", t.as_str()).as_str(), + format!("echo -n 'from layer echo' > {}", t.as_str()).as_str(), ])?; std::fs::write(&t, "goodbye")?; sandbox.run(&["cat", t.clone().as_str()])?; let stdout = sandbox.last_stdout.trim(); - assert_eq!(stdout, "from sandbox echo"); + assert_eq!(stdout, "from layer echo"); // remove the file from the upper directory std::fs::remove_file(upper_dir.join(&t)).context(format!( diff --git a/tests/test_bind_and_mask.rs b/tests/test_bind_and_mask.rs index 1ff0a0b..da5531e 100644 --- a/tests/test_bind_and_mask.rs +++ b/tests/test_bind_and_mask.rs @@ -92,7 +92,7 @@ fn test_mask_env(mut sandbox: SandboxManager) -> Result<()> { std::fs::write(&test_file, "test")?; sandbox.run_with_env( &["--no-config", "ls", "-l", &test_dir], - "SANDBOX_MASK", + "DEVLAYER_MASK", &test_dir, )?; println!("{}", sandbox.last_stdout); @@ -108,7 +108,7 @@ fn test_mask_empty_env(mut sandbox: SandboxManager) -> Result<()> { std::fs::write(&test_file, "test")?; sandbox.run_with_env( &["--no-config", "ls", "-l", &test_dir], - "SANDBOX_MASK", + "DEVLAYER_MASK", "", )?; println!("{}", sandbox.last_stdout); @@ -124,7 +124,7 @@ fn test_mask_bind_mask(mut sandbox: SandboxManager) -> Result<()> { std::fs::write(&test_file, "test")?; sandbox.run_with_env( &["ls", "-l", &test_dir], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{}:{}:mask", test_dir, test_dir), )?; println!("{}", sandbox.last_stdout); @@ -140,7 +140,7 @@ fn test_mask_file(mut sandbox: SandboxManager) -> Result<()> { std::fs::write(&test_file, "test")?; sandbox.run_with_env( &["cat", &test_file], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{}:{}:mask", test_file, test_file), )?; // file exists but is masked so won't contain the test we wrote @@ -148,7 +148,7 @@ fn test_mask_file(mut sandbox: SandboxManager) -> Result<()> { sandbox.run_with_env( &["ls", &test_file], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{}:{}:mask", test_file, test_file), )?; println!("{}", sandbox.last_stdout); @@ -162,7 +162,7 @@ fn test_mask_file(mut sandbox: SandboxManager) -> Result<()> { fn test_mask_combined(mut sandbox: SandboxManager) -> Result<()> { sandbox.run_with_env( &["--mask", "/tmp", "config"], - "SANDBOX_MASK", + "DEVLAYER_MASK", "/run", )?; assert!(sandbox.last_stdout.contains("/tmp")); diff --git a/tests/test_cli.rs b/tests/test_cli.rs index 1bc01e2..d976953 100644 --- a/tests/test_cli.rs +++ b/tests/test_cli.rs @@ -23,16 +23,16 @@ fn test_cli(mut sandbox: SandboxManager) -> Result<()> { assert!(sandbox.pass(&["--name=test-cli", "config"])); assert!(sandbox.last_stdout.contains("name=test-cli")); - assert!(sandbox.pass(&["--storage-dir=/tmp/sandbox", "config"])); - assert!(sandbox.last_stdout.contains("storage_dir=/tmp/sandbox")); + assert!(sandbox.pass(&["--storage-dir=/tmp/layer", "config"])); + assert!(sandbox.last_stdout.contains("storage_dir=/tmp/layer")); - assert!(sandbox.pass(&["--storage-dir=/tmp/sandbox", "config"])); - assert!(sandbox.last_stdout.contains("storage_dir=/tmp/sandbox")); + assert!(sandbox.pass(&["--storage-dir=/tmp/layer", "config"])); + assert!(sandbox.last_stdout.contains("storage_dir=/tmp/layer")); // default values check sandbox.no_default_options = true; assert!(sandbox.pass(&["--no-config", "config"])); - assert!(sandbox.last_stdout.contains("name=sandbox")); + assert!(sandbox.last_stdout.contains("name=layer")); assert!(sandbox.last_stdout.contains("net=none")); // Test config_files display @@ -48,66 +48,66 @@ fn test_cli_with_config(mut sandbox: SandboxManager) -> Result<()> { net = "none" name = "parent" log_level = "trace" - storage_dir = "/tmp/sandbox1" + storage_dir = "/tmp/layer1" bind = [".cargo"] "#; let config = r#" net = "host" name = "test-cli-with-config" log_level = "info" - storage_dir = "/tmp/sandbox2" + storage_dir = "/tmp/layer2" bind = [".cargo"] "#; - let _ = std::fs::remove_file(".sandbox.toml"); - let _ = std::fs::remove_file("../.sandbox.conf"); + let _ = std::fs::remove_file(".devlayer.toml"); + let _ = std::fs::remove_file("../.devlayer.conf"); - std::fs::write("../.sandbox.conf", parent_config)?; + std::fs::write("../.devlayer.conf", parent_config)?; sandbox.no_default_options = true; - assert!(sandbox.epass(&["config"], "SANDBOX_BIND", ".cargo")); + assert!(sandbox.epass(&["config"], "DEVLAYER_BIND", ".cargo")); assert!(sandbox.last_stdout.contains("name=parent")); assert!(sandbox.last_stdout.contains("net=none")); assert!(sandbox.last_stdout.contains("log_level=TRACE")); - assert!(sandbox.last_stdout.contains("storage_dir=/tmp/sandbox1")); + assert!(sandbox.last_stdout.contains("storage_dir=/tmp/layer1")); assert!(sandbox.last_stdout.contains(".cargo")); - std::fs::write(".sandbox.toml", config)?; + std::fs::write(".devlayer.toml", config)?; sandbox.no_default_options = true; assert!(sandbox.pass(&["config", "--bind=.cargo"])); assert!(sandbox.last_stdout.contains("name=test-cli-with-config")); assert!(sandbox.last_stdout.contains("net=host")); println!("{}", sandbox.last_stdout); assert!(sandbox.last_stdout.contains("log_level=INFO")); - assert!(sandbox.last_stdout.contains("storage_dir=/tmp/sandbox2")); + assert!(sandbox.last_stdout.contains("storage_dir=/tmp/layer2")); - std::fs::remove_file(".sandbox.toml")?; - std::fs::remove_file("../.sandbox.conf")?; + std::fs::remove_file(".devlayer.toml")?; + std::fs::remove_file("../.devlayer.conf")?; Ok(()) } #[rstest] fn test_cli_with_env(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.epass(&["config"], "SANDBOX_NET", "")); - assert!(sandbox.epass(&["config"], "SANDBOX_NET", "host")); + assert!(sandbox.epass(&["config"], "DEVLAYER_NET", "")); + assert!(sandbox.epass(&["config"], "DEVLAYER_NET", "host")); assert!(sandbox.last_stdout.contains("net=host")); - assert!(sandbox.epass(&["config"], "SANDBOX_NET", "none")); + assert!(sandbox.epass(&["config"], "DEVLAYER_NET", "none")); assert!(sandbox.last_stdout.contains("net=none")); - assert!(sandbox.exfail(&["config"], "SANDBOX_NET", "foobar")); + assert!(sandbox.exfail(&["config"], "DEVLAYER_NET", "foobar")); assert!(sandbox.last_stderr.contains("Invalid network type: foobar")); - assert!(sandbox.epass(&["config"], "SANDBOX_LOG_LEVEL", "trace")); + assert!(sandbox.epass(&["config"], "DEVLAYER_LOG_LEVEL", "trace")); assert!(sandbox.last_stdout.contains("log_level=TRACE")); - assert!(sandbox.exfail(&["config"], "SANDBOX_LOG_LEVEL", "foobar")); + assert!(sandbox.exfail(&["config"], "DEVLAYER_LOG_LEVEL", "foobar")); assert!(sandbox.last_stderr.contains("Invalid log level: foobar")); - assert!(sandbox.epass(&["config"], "SANDBOX_NAME", "")); - assert!(sandbox.epass(&["config"], "SANDBOX_NAME", "test-cli-with-env")); + assert!(sandbox.epass(&["config"], "DEVLAYER_NAME", "")); + assert!(sandbox.epass(&["config"], "DEVLAYER_NAME", "test-cli-with-env")); - assert!(sandbox.epass(&["config"], "SANDBOX_STORAGE_DIR", "")); - assert!(sandbox.epass(&["config"], "SANDBOX_STORAGE_DIR", "/tmp/sandbox")); - assert!(sandbox.last_stdout.contains("storage_dir=/tmp/sandbox")); + assert!(sandbox.epass(&["config"], "DEVLAYER_STORAGE_DIR", "")); + assert!(sandbox.epass(&["config"], "DEVLAYER_STORAGE_DIR", "/tmp/layer")); + assert!(sandbox.last_stdout.contains("storage_dir=/tmp/layer")); Ok(()) } diff --git a/tests/test_list.rs b/tests/test_list.rs index 665520d..f1eb932 100644 --- a/tests/test_list.rs +++ b/tests/test_list.rs @@ -50,7 +50,7 @@ fn test_list_ignore_bad_pid_file(mut sandbox: SandboxManager) -> Result<()> { println!("t: {}", t.display()); let bad_sandbox_base = format!("{}/{}", t.to_string_lossy(), "coverage_test_bad_pid_file"); - println!("bad_sandbox_base: {}", bad_sandbox_base); + println!("bad_layer_base: {}", bad_sandbox_base); let pid_file_name = format!("{}.pid", bad_sandbox_base); let lock_file_name = format!("{}.lock", bad_sandbox_base); diff --git a/tests/test_misc.rs b/tests/test_misc.rs index 3548f8e..c24ec15 100644 --- a/tests/test_misc.rs +++ b/tests/test_misc.rs @@ -91,8 +91,11 @@ fn test_weird_sudo_env_variables(sandbox: SandboxManager) -> Result<()> { let mut cmd = Command::new("sudo"); cmd.args([ "-E", - format!("SANDBOX_STORAGE_DIR={}", absolute_dir_with_spaces.display()) - .as_str(), + format!( + "DEVLAYER_STORAGE_DIR={}", + absolute_dir_with_spaces.display() + ) + .as_str(), &sandbox_bin, ]); cmd.args([format!("--name={}", &sandbox.name)]); @@ -143,8 +146,10 @@ fn test_sandbox_no_print_to_stdout_by_default( } #[rstest] -fn test_sandbox_env_variable_is_set(mut sandbox: SandboxManager) -> Result<()> { - let output = sandbox.run(&["sh", "-c", "echo -n $SANDBOX"])?; +fn test_devlayer_env_variable_is_set( + mut sandbox: SandboxManager, +) -> Result<()> { + let output = sandbox.run(&["sh", "-c", "echo -n $DEVLAYER"])?; assert_eq!(String::from_utf8_lossy(&output.stdout), sandbox.name); Ok(()) } diff --git a/tests/test_mount_unmount_kill.rs b/tests/test_mount_unmount_kill.rs index 069f3ca..6d4c0d0 100644 --- a/tests/test_mount_unmount_kill.rs +++ b/tests/test_mount_unmount_kill.rs @@ -20,7 +20,7 @@ fn test_no_mounts_found(mut sandbox: SandboxManager) -> Result<()> { assert!(sandbox.exfail(&["env"], "TEST_NO_MOUNTS_FOUND", "1")); assert!(sandbox.pass(&["true"])); assert!(sandbox.epass(&["stop"], "TEST_NO_MOUNTS_FOUND", "1")); - assert!(sandbox.last_stderr.contains("No mounts found for sandbox")); + assert!(sandbox.last_stderr.contains("No mounts found for layer")); Ok(()) } diff --git a/tests/test_new_last.rs b/tests/test_new_last.rs index 4243b42..ac83c40 100644 --- a/tests/test_new_last.rs +++ b/tests/test_new_last.rs @@ -12,8 +12,8 @@ fn test_new_last_mutual_exclusivity(mut sandbox: SandboxManager) -> Result<()> { assert!(sandbox.xfail(&["--name=foo", "--last", "ls"])); assert!(sandbox.xfail(&["--name=foo", "--new", "ls"])); assert!(sandbox.xfail(&["--name=foo", "--new", "--last", "ls"])); - assert!(sandbox.exfail(&["--new", "ls"], "SANDBOX_NAME", "foo")); - assert!(sandbox.exfail(&["--last", "ls"], "SANDBOX_NAME", "foo")); + assert!(sandbox.exfail(&["--new", "ls"], "DEVLAYER_NAME", "foo")); + assert!(sandbox.exfail(&["--last", "ls"], "DEVLAYER_NAME", "foo")); Ok(()) } @@ -27,7 +27,7 @@ fn test_last_is_empty(mut sandbox: SandboxManager) -> Result<()> { "TEST_LAST_IS_EMPTY", "1" )); - assert!(sandbox.last_stderr.contains("No sandboxes found")); + assert!(sandbox.last_stderr.contains("No layers found")); Ok(()) } diff --git a/tests/test_sandbox_failures.rs b/tests/test_sandbox_failures.rs index 77e6d17..ff446ae 100644 --- a/tests/test_sandbox_failures.rs +++ b/tests/test_sandbox_failures.rs @@ -10,7 +10,7 @@ use std::{ #[rstest] fn test_fail_to_start_sandbox(mut sandbox: SandboxManager) -> Result<()> { assert!(sandbox.exfail(&["env"], "TEST_START_SANDBOX_FAILURE", "1")); - assert!(sandbox.all_stderr.contains("Failed to start sandbox")); + assert!(sandbox.all_stderr.contains("Failed to start layer")); Ok(()) } @@ -75,7 +75,7 @@ fn test_unable_to_join_sandbox(mut sandbox: SandboxManager) -> Result<()> { assert!( sandbox .last_stderr - .contains("Failed to join sandbox namespaces") + .contains("Failed to join layer namespaces") ); Ok(()) diff --git a/vm-testing/01-setup-host-for-vm-testing.sh b/vm-testing/01-setup-host-for-vm-testing.sh index 1243bc3..da640b2 100755 --- a/vm-testing/01-setup-host-for-vm-testing.sh +++ b/vm-testing/01-setup-host-for-vm-testing.sh @@ -45,9 +45,9 @@ fi sudo virsh net-list --all # Ensure we have a ssh key -if [ ! -f "generated/id_sandbox_test_vm_key" ]; then +if [ ! -f "generated/id_devlayer_test_vm_key" ]; then echo "Generating ssh key" - ssh-keygen -t ed25519 -C "SSH key copied into the virtual machines to test the sandbox binary" -f "generated/id_sandbox_test_vm_key" -N "" + ssh-keygen -t ed25519 -C "SSH key copied into the virtual machines to test the devlayer binary" -f "generated/id_devlayer_test_vm_key" -N "" fi echo "Done!" diff --git a/vm-testing/20-prepare-vm-images.sh b/vm-testing/20-prepare-vm-images.sh index f8eb2a1..6b6ff9f 100755 --- a/vm-testing/20-prepare-vm-images.sh +++ b/vm-testing/20-prepare-vm-images.sh @@ -40,9 +40,9 @@ fi mkdir -p generated # Ensure we have a ssh key -if [ ! -f "generated/id_sandbox_test_vm_key" ]; then +if [ ! -f "generated/id_devlayer_test_vm_key" ]; then echo "Generating ssh key" - ssh-keygen -t ed25519 -C "SSH key copied into the virtual machines to test the sandbox binary" -f "generated/id_sandbox_test_vm_key" -N "" + ssh-keygen -t ed25519 -C "SSH key copied into the virtual machines to test the devlayer binary" -f "generated/id_devlayer_test_vm_key" -N "" fi echo "Generating 50-dhcp-coverage.yaml" @@ -62,28 +62,28 @@ network: EOF cat < generated/exports -/home/sandbox/nfs_sandboxes *(rw,sync,no_subtree_check,no_root_squash) -/home/sandbox/nfs_source *(rw,sync,no_subtree_check,no_root_squash) +/home/devlayer/nfs_layers *(rw,sync,no_subtree_check,no_root_squash) +/home/devlayer/nfs_source *(rw,sync,no_subtree_check,no_root_squash) EOF -# Create sudoers file for sandbox user -echo "sandbox ALL=(ALL) NOPASSWD:ALL" > generated/sandbox-sudoers +# Create sudoers file for devlayer user +echo "devlayer ALL=(ALL) NOPASSWD:ALL" > generated/devlayer-sudoers echo "Customizing coverage testing image" cp images/ubuntu24lts-base.img images/coverage-prepared.qcow2 qemu-img resize images/coverage-prepared.qcow2 +10G -# The sandbox user password is blank, the -e flag denotes that the password +# The devlayer user password is blank, the -e flag denotes that the password # is already encrypted and U6aMy0wojraho is the empty string, so just hit # enter for the password to login if you need to drop into the virsh console sudo virt-customize -a images/coverage-prepared.qcow2 \ --network \ --hostname coverage-test \ - --run-command "adduser sandbox -q" \ - --run-command "adduser sandbox sudo" \ - --run-command "echo 'sandbox:U6aMy0wojraho' | chpasswd -e" \ + --run-command "adduser devlayer -q" \ + --run-command "adduser devlayer sudo" \ + --run-command "echo 'devlayer:U6aMy0wojraho' | chpasswd -e" \ --run-command "apt update" \ --run-command "apt -y install cloud-guest-utils" \ --run-command "growpart /dev/sda 1" \ @@ -92,18 +92,18 @@ sudo virt-customize -a images/coverage-prepared.qcow2 \ --run-command "systemctl enable nfs-kernel-server.service" \ --copy-in generated/exports:/etc \ --run-command "chmod 644 /etc/exports" \ - --run-command "chmod 755 /home/sandbox" \ - --run-command "mkdir -p /home/sandbox/nfs_sandboxes" \ - --run-command "mkdir -p /home/sandbox/nfs_source" \ - --run-command "chmod 755 /home/sandbox/nfs_sandboxes" \ - --run-command "chmod 755 /home/sandbox/nfs_source" \ - --run-command "echo 'tmpfs /home/sandbox/nfs_sandboxes tmpfs defaults,size=512M 0 0' >> /etc/fstab" \ - --run-command "echo 'tmpfs /home/sandbox/nfs_source tmpfs defaults,size=4G 0 0' >> /etc/fstab" \ + --run-command "chmod 755 /home/devlayer" \ + --run-command "mkdir -p /home/devlayer/nfs_layers" \ + --run-command "mkdir -p /home/devlayer/nfs_source" \ + --run-command "chmod 755 /home/devlayer/nfs_layers" \ + --run-command "chmod 755 /home/devlayer/nfs_source" \ + --run-command "echo 'tmpfs /home/devlayer/nfs_layers tmpfs defaults,size=512M 0 0' >> /etc/fstab" \ + --run-command "echo 'tmpfs /home/devlayer/nfs_source tmpfs defaults,size=4G 0 0' >> /etc/fstab" \ --copy-in generated/50-dhcp-coverage.yaml:/etc/netplan \ - --copy-in generated/sandbox-sudoers:/etc/sudoers.d/ \ - --run-command "chown 0:0 /etc/sudoers.d/sandbox-sudoers" \ - --run-command "chmod 440 /etc/sudoers.d/sandbox-sudoers" \ - --run-command "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sudo -u sandbox sh -s -- -y --default-toolchain stable --profile minimal" \ - --run-command "sudo -u sandbox bash -c 'source /home/sandbox/.cargo/env && rustup component add rustfmt clippy llvm-tools && cargo install grcov'" \ - --ssh-inject sandbox:file:generated/id_sandbox_test_vm_key.pub \ + --copy-in generated/devlayer-sudoers:/etc/sudoers.d/ \ + --run-command "chown 0:0 /etc/sudoers.d/devlayer-sudoers" \ + --run-command "chmod 440 /etc/sudoers.d/devlayer-sudoers" \ + --run-command "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sudo -u devlayer sh -s -- -y --default-toolchain stable --profile minimal" \ + --run-command "sudo -u devlayer bash -c 'source /home/devlayer/.cargo/env && rustup component add rustfmt clippy llvm-tools && cargo install grcov'" \ + --ssh-inject devlayer:file:generated/id_devlayer_test_vm_key.pub \ --firstboot-command 'ssh-keygen -A && systemctl restart sshd' diff --git a/vm-testing/30-build-image-and-start.sh b/vm-testing/30-build-image-and-start.sh index d182119..a73d26f 100755 --- a/vm-testing/30-build-image-and-start.sh +++ b/vm-testing/30-build-image-and-start.sh @@ -8,7 +8,7 @@ VCPUS=$(nproc) sudo virsh destroy coverage-test || true sudo virsh undefine coverage-test || true -rm -f sandbox-*.crate +rm -f devlayer-*.crate if [ ! -f vendor.tar.gz ]; then cd .. @@ -19,10 +19,10 @@ fi cd .. cargo package --allow-dirty --no-verify -cp target/package/sandbox-*.crate vm-testing/ +cp target/package/devlayer-*.crate vm-testing/ cd vm-testing -CRATE=$(ls sandbox-*.crate) +CRATE=$(ls devlayer-*.crate) sudo cp images/coverage-prepared.qcow2 images/coverage-test.qcow2 @@ -37,9 +37,9 @@ EOF sudo virt-customize -a images/coverage-test.qcow2 \ - --copy-in vendor.tar.gz:/home/sandbox/ \ - --copy-in $CRATE:/home/sandbox/ \ - --copy-in generated/cargo_config.toml:/home/sandbox/ + --copy-in vendor.tar.gz:/home/devlayer/ \ + --copy-in $CRATE:/home/devlayer/ \ + --copy-in generated/cargo_config.toml:/home/devlayer/ sudo virt-install --name coverage-test \ --memory $MEM \ diff --git a/vm-testing/42-test-different-relative-paths.sh b/vm-testing/42-test-different-relative-paths.sh index 5a42c16..0069171 100755 --- a/vm-testing/42-test-different-relative-paths.sh +++ b/vm-testing/42-test-different-relative-paths.sh @@ -6,24 +6,24 @@ set -e common_init reinitialize_fs mkfs.ext4 -do_test /home/sandbox/source/utf8/こんにちは +do_test /home/devlayer/source/utf8/こんにちは reinitialize_fs mkfs.ext4 -do_test /home/sandbox/source/utf8/😀 +do_test /home/devlayer/source/utf8/😀 reinitialize_fs mkfs.ext4 -do_test /home/sandbox/source/one_dir_deep +do_test /home/devlayer/source/one_dir_deep -# We test /home/sandbox/source in the filesystem test a lot, no need to test it here +# We test /home/devlayer/source in the filesystem test a lot, no need to test it here ### At this point coverage tests should be at 100% so lets bail early if they aren't -# ssh -o "StrictHostKeyChecking no" -i generated/id_sandbox_test_vm_key sandbox@$COVERAGE_IP 'bash -s' < Date: Fri, 13 Nov 2026 05:54:04 -0500 Subject: [PATCH 03/32] Rename internal sandbox identifiers to layer/devlayer --- CLAUDE.md | 2 +- Cargo.toml | 2 +- cspell.json | 4 - src/actions/accept.rs | 18 +- src/actions/clean.rs | 29 +- src/actions/config.rs | 9 +- src/actions/delete.rs | 136 ++-- src/actions/diff.rs | 14 +- src/actions/list.rs | 64 +- src/actions/reject.rs | 8 +- src/actions/status.rs | 12 +- src/actions/stop.rs | 61 +- src/config/cli.rs | 12 +- src/config/resolve.rs | 54 +- src/config/structs.rs | 6 +- src/{sandbox => layer}/cgroup.rs | 44 +- .../changes/change_entries.rs | 2 +- src/{sandbox => layer}/changes/changes.rs | 6 +- .../changes/file_details.rs | 2 +- src/{sandbox => layer}/changes/mod.rs | 0 src/{sandbox => layer}/delete.rs | 4 +- src/{sandbox => layer}/exec.rs | 28 +- src/{sandbox => layer}/exists.rs | 4 +- src/{sandbox => layer}/get_or_create.rs | 148 +++-- .../layer_struct.rs} | 4 +- src/{sandbox => layer}/mod.rs | 4 +- src/{sandbox => layer}/mount_overlays.rs | 24 +- src/{sandbox => layer}/settings.rs | 10 +- src/{sandbox => layer}/stop.rs | 30 +- src/{sandbox => layer}/unmount.rs | 4 +- src/lib.rs | 2 +- src/logger.rs | 12 +- src/main.rs | 64 +- ...andbox_pid.rs => get_running_layer_pid.rs} | 24 +- src/util/{lock_sandbox.rs => lock_layer.rs} | 13 +- src/util/mod.rs | 8 +- tests/ai_cli_flags.rs | 162 ++--- tests/ai_test_accept.rs | 122 ++-- tests/ai_test_audio.rs | 90 ++- tests/ai_test_bind_mount_validation.rs | 40 +- tests/ai_test_bind_mounts.rs | 226 ++++--- tests/ai_test_bind_parent_dirs.rs | 16 +- tests/ai_test_bind_precedence.rs | 110 ++-- tests/ai_test_builtin_ignore_patterns.rs | 90 ++- tests/ai_test_can_mkdir_coverage.rs | 24 +- tests/ai_test_clean.rs | 42 +- tests/ai_test_config_impls.rs | 42 +- tests/ai_test_config_option.rs | 10 +- tests/ai_test_corrupted_settings.rs | 60 +- tests/ai_test_delete.rs | 580 +++++++++--------- tests/ai_test_diff_coverage.rs | 170 +++-- tests/ai_test_error_paths.rs | 44 +- tests/ai_test_gitignore_anchored_pattern.rs | 32 +- tests/ai_test_ignore_rules.rs | 262 ++++---- tests/ai_test_ignore_rules_coverage.rs | 107 ++-- tests/ai_test_ignore_rules_overlay.rs | 62 +- ..._settings.rs => ai_test_layer_settings.rs} | 50 +- tests/ai_test_resource_limits.rs | 404 ++++++------ tests/ai_test_run_media_mount.rs | 10 +- tests/ai_test_sigterm.rs | 16 +- .../{fixture_sandbox.rs => fixture_layer.rs} | 42 +- tests/fixtures/mod.rs | 4 +- ...solated_test_accept_rename_across_mount.rs | 8 +- tests/isolated_test_accept_root.rs | 6 +- tests/isolated_test_clean_running.rs | 24 +- ..._test_create_old_root_host_path_failure.rs | 6 +- tests/isolated_test_new.rs | 18 +- tests/isolated_test_new_last.rs | 62 +- tests/isolated_test_pivot_root_failure.rs | 6 +- tests/isolated_test_special_files.rs | 16 +- tests/isolated_test_special_files_remove.rs | 12 +- tests/isolated_test_stop_all.rs | 16 +- tests/isolated_test_stop_all_partial_fail.rs | 32 +- tests/isolated_test_stop_pattern.rs | 16 +- tests/isolated_test_stop_stops_children.rs | 8 +- tests/isolated_test_sync.rs | 24 +- tests/isolated_test_twisted.rs | 38 +- tests/test_accept.rs | 298 +++++---- tests/test_accept_deep_reshuffle.rs | 20 +- tests/test_bind_and_mask.rs | 119 ++-- tests/test_cli.rs | 134 ++-- tests/test_diff.rs | 66 +- tests/test_fuse.rs | 4 +- tests/test_json.rs | 16 +- tests/test_layer_failures.rs | 143 +++++ ...x_inception.rs => test_layer_inception.rs} | 20 +- tests/test_list.rs | 72 +-- tests/test_misc.rs | 114 ++-- tests/test_mount_unmount_kill.rs | 60 +- tests/test_net.rs | 16 +- tests/test_new_last.rs | 28 +- tests/test_partial_move_failures.rs | 16 +- tests/test_reject.rs | 68 +- tests/test_sandbox_failures.rs | 145 ----- tests/test_status.rs | 214 ++++--- 95 files changed, 2686 insertions(+), 2844 deletions(-) rename src/{sandbox => layer}/cgroup.rs (84%) rename src/{sandbox => layer}/changes/change_entries.rs (99%) rename src/{sandbox => layer}/changes/changes.rs (99%) rename src/{sandbox => layer}/changes/file_details.rs (99%) rename src/{sandbox => layer}/changes/mod.rs (100%) rename src/{sandbox => layer}/delete.rs (93%) rename src/{sandbox => layer}/exec.rs (92%) rename src/{sandbox => layer}/exists.rs (87%) rename src/{sandbox => layer}/get_or_create.rs (90%) rename src/{sandbox/sandbox_struct.rs => layer/layer_struct.rs} (78%) rename src/{sandbox => layer}/mod.rs (78%) rename src/{sandbox => layer}/mount_overlays.rs (93%) rename src/{sandbox => layer}/settings.rs (96%) rename src/{sandbox => layer}/stop.rs (86%) rename src/{sandbox => layer}/unmount.rs (96%) rename src/util/{get_running_sandbox_pid.rs => get_running_layer_pid.rs} (71%) rename src/util/{lock_sandbox.rs => lock_layer.rs} (80%) rename tests/{ai_test_sandbox_settings.rs => ai_test_layer_settings.rs} (89%) rename tests/fixtures/{fixture_sandbox.rs => fixture_layer.rs} (92%) create mode 100644 tests/test_layer_failures.rs rename tests/{test_sandbox_inception.rs => test_layer_inception.rs} (71%) delete mode 100644 tests/test_sandbox_failures.rs diff --git a/CLAUDE.md b/CLAUDE.md index c588fb1..30e7796 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -79,4 +79,4 @@ to track file changes and allows selective acceptance of modifications. 5. **Cross-Platform**: Supports x86_64 and aarch64 architectures with both GNU and musl libc variants. -6. **New tests**: New tests should be added to the `tests/` directory with a filename prefixed with `ai_test_`. Most tests should use the default name provided by the SandboxManager, if you provide a name, it needs to be prefixed with `devlayer-coverage`. +6. **New tests**: New tests should be added to the `tests/` directory with a filename prefixed with `ai_test_`. Most tests should use the default name provided by the LayerManager, if you provide a name, it needs to be prefixed with `devlayer-coverage`. diff --git a/Cargo.toml b/Cargo.toml index 7226fef..13dd8d8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ name = "devlayer" path = "src/main.rs" [lib] -name = "sandbox" +name = "devlayer" path = "src/lib.rs" [lints.rust] diff --git a/cspell.json b/cspell.json index 7a13f2d..a0e6fab 100644 --- a/cspell.json +++ b/cspell.json @@ -195,10 +195,6 @@ "rustsec", "rustup", "devlayer", - "sandboxd", - "sandboxed", - "sandboxing", - "sandboxnet", "sched", "serde", "setegid", diff --git a/src/actions/accept.rs b/src/actions/accept.rs index 7fd780f..0251d0d 100644 --- a/src/actions/accept.rs +++ b/src/actions/accept.rs @@ -1,5 +1,5 @@ /* -= Sandbox Acceptance Algorithm += Layer Acceptance Algorithm == Notes on OverlayFS @@ -37,7 +37,7 @@ - We have separate OverlayFS mounts that correspond to each normal mount on the system. For example, if we have three partitions, one for `/`, one for `/home`, and one for `/var`, we have three OverlayFS mounts, one for each. Wherever - we store our sandbox changes we will have three directories, `upper`, `work`, + we store our layer changes we will have three directories, `upper`, `work`, and `overlay`, each will have a corresponding base32 encoded directory of the mount point name, so `F4` for `/`, `F5UG63LF` for `/home`, and so forth. @@ -100,11 +100,11 @@ Once we have a change set we can apply it. to its final destination. */ +use crate::layer::changes::changes::{by_destination, by_reverse_source}; +use crate::layer::changes::{ChangeEntries, EntryOperation, FileDetails}; use crate::outln; -use crate::sandbox::changes::changes::{by_destination, by_reverse_source}; -use crate::sandbox::changes::{ChangeEntries, EntryOperation, FileDetails}; use crate::util::{find_mount_point, sync_and_drop_caches}; -use crate::{config::Config, sandbox::Sandbox}; +use crate::{config::Config, layer::Layer}; use anyhow::{Context, Result}; use colored::*; use log::{debug, error, trace}; @@ -114,16 +114,16 @@ use nix::unistd::{Gid, Uid, fchownat}; use std::fs; use std::path::{Path, PathBuf}; -/* The accept function will accept the changes from the sandbox into the real filesystem. */ +/* The accept function will accept the changes from the layer into the real filesystem. */ pub fn accept( config: &Config, - sandbox: &Sandbox, + layer: &Layer, patterns: &[String], ) -> Result<()> { - trace!("Accepting changes from layer {}", sandbox.name); + trace!("Accepting changes from layer {}", layer.name); let cwd = std::env::current_dir()?; - let all_changes = sandbox.changes(config)?; + let all_changes = layer.changes(config)?; let mut changes = all_changes.matching(&cwd, patterns); let non_matching_count = diff --git a/src/actions/clean.rs b/src/actions/clean.rs index 24bcbba..e912acf 100644 --- a/src/actions/clean.rs +++ b/src/actions/clean.rs @@ -1,5 +1,5 @@ -use crate::actions::delete::delete_sandboxes; -use crate::actions::list::get_sandboxes; +use crate::actions::delete::delete_layers; +use crate::actions::list::get_layers; use crate::config::Config; use crate::outln; use anyhow::Result; @@ -8,32 +8,29 @@ use fast_glob::glob_match; use log::trace; use std::path::Path; -/// Sandboxes created by the test suite. These are always cleaned up, +/// Layers created by the test suite. These are always cleaned up, /// running or not. -const TEST_SANDBOX_PATTERNS: &[&str] = +const TEST_LAYER_PATTERNS: &[&str] = &["devlayer-coverage-*", "devlayer-bind-empty-*"]; -/// Stopped ephemeral sandboxes older than this are cleaned up. +/// Stopped ephemeral layers older than this are cleaned up. const EPHEMERAL_MAX_AGE_DAYS: i64 = 7; pub fn clean( config: &Config, - sandboxes_storage_dir: &Path, + layers_storage_dir: &Path, force: bool, ) -> Result<()> { trace!("Finding layers to clean"); - let [running_sandboxes, stopped_sandboxes] = - get_sandboxes(sandboxes_storage_dir, &[])?; + let [running_layers, stopped_layers] = get_layers(layers_storage_dir, &[])?; let cutoff = Local::now().naive_local() - TimeDelta::days(EPHEMERAL_MAX_AGE_DAYS); - let running_to_delete: Vec = running_sandboxes - .into_iter() - .filter(|n| is_test(n)) - .collect(); - let stopped_to_delete: Vec = stopped_sandboxes + let running_to_delete: Vec = + running_layers.into_iter().filter(|n| is_test(n)).collect(); + let stopped_to_delete: Vec = stopped_layers .into_iter() .filter(|n| { is_test(n) || ephemeral_created_at(n).is_some_and(|t| t < cutoff) @@ -45,9 +42,9 @@ pub fn clean( return Ok(()); } - delete_sandboxes( + delete_layers( config, - sandboxes_storage_dir, + layers_storage_dir, &running_to_delete, &stopped_to_delete, force, @@ -55,7 +52,7 @@ pub fn clean( } fn is_test(name: &str) -> bool { - TEST_SANDBOX_PATTERNS + TEST_LAYER_PATTERNS .iter() .any(|pattern| glob_match(pattern, name)) } diff --git a/src/actions/config.rs b/src/actions/config.rs index 615c080..6d391f8 100644 --- a/src/actions/config.rs +++ b/src/actions/config.rs @@ -20,7 +20,7 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { "cpus", "memory", "storage_dir", - "sandbox_dir", + "layer_dir", "upper_cwd", "overlay_cwd", "ignored", @@ -68,10 +68,9 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { "storage_dir", config.storage_dir.to_str().unwrap_or(""), ), - "sandbox_dir" | "sandbox-dir" => ( - "sandbox_dir", - config.sandbox_dir.to_str().unwrap_or(""), - ), + "layer_dir" | "layer-dir" => { + ("layer_dir", config.layer_dir.to_str().unwrap_or("")) + } "upper_cwd" | "upper-cwd" => { ("upper_cwd", config.upper_cwd.to_str().unwrap_or("")) } diff --git a/src/actions/delete.rs b/src/actions/delete.rs index 72ea995..94b2cb1 100644 --- a/src/actions/delete.rs +++ b/src/actions/delete.rs @@ -1,6 +1,6 @@ -use crate::actions::list::get_sandboxes; +use crate::actions::list::get_layers; use crate::config::Config; -use crate::sandbox::Sandbox; +use crate::layer::Layer; use crate::util::Lock; use crate::{outln, util::set_json_output}; use anyhow::Result; @@ -10,41 +10,41 @@ use serde_json::Value; use std::io::{self, Write}; use std::path::Path; -struct SandboxEntry { +struct LayerEntry { name: String, stopped: bool, - sandbox: Sandbox, + layer: Layer, _lock: Box, } -impl SandboxEntry { +impl LayerEntry { pub fn new( - sandboxes_storage_dir: &Path, - sandbox_name: &str, + layers_storage_dir: &Path, + layer_name: &str, stopped: bool, ) -> Result { - let (sandbox, lock) = Sandbox::get( - sandboxes_storage_dir, - sandbox_name, + let (layer, lock) = Layer::get( + layers_storage_dir, + layer_name, nix::unistd::Uid::from_raw(0), nix::unistd::Gid::from_raw(0), None, )?; - let sandbox = match sandbox { - Some(sandbox) => sandbox, - None => Sandbox::from_location( - sandboxes_storage_dir, - sandbox_name, + let layer = match layer { + Some(layer) => layer, + None => Layer::from_location( + layers_storage_dir, + layer_name, nix::unistd::Uid::from_raw(0), nix::unistd::Gid::from_raw(0), ), }; Ok(Self { - name: sandbox_name.to_string(), + name: layer_name.to_string(), stopped, - sandbox, + layer, _lock: lock, }) } @@ -52,24 +52,24 @@ impl SandboxEntry { pub fn delete( config: &Config, - sandboxes_storage_dir: &Path, + layers_storage_dir: &Path, patterns: &[String], force: bool, ) -> Result<()> { trace!("Preparing to delete layers"); - let [running_sandboxes, stopped_sandboxes] = if patterns.is_empty() { - if Sandbox::from_location( - sandboxes_storage_dir, + let [running_layers, stopped_layers] = if patterns.is_empty() { + if Layer::from_location( + layers_storage_dir, &config.name, nix::unistd::Uid::from_raw(0), nix::unistd::Gid::from_raw(0), ) .exists() { - // serves as a check to see if the sandbox is running or not - if Sandbox::get( - sandboxes_storage_dir, + // serves as a check to see if the layer is running or not + if Layer::get( + layers_storage_dir, &config.name, nix::unistd::Uid::from_raw(0), nix::unistd::Gid::from_raw(0), @@ -86,27 +86,27 @@ pub fn delete( [vec![], vec![]] } } else { - get_sandboxes(sandboxes_storage_dir, patterns)? + get_layers(layers_storage_dir, patterns)? }; /* - let mut sandbox_entries = Vec::new(); - for sandbox_name in running_sandboxes { - sandbox_entries.push(SandboxEntry::new( - sandboxes_storage_dir, - sandbox_name.as_str(), + let mut layer_entries = Vec::new(); + for layer_name in running_layers { + layer_entries.push(LayerEntry::new( + layers_storage_dir, + layer_name.as_str(), false, )?); } - for sandbox_name in stopped_sandboxes { - sandbox_entries.push(SandboxEntry::new( - sandboxes_storage_dir, - sandbox_name.as_str(), + for layer_name in stopped_layers { + layer_entries.push(LayerEntry::new( + layers_storage_dir, + layer_name.as_str(), true, )?); } */ - if stopped_sandboxes.is_empty() && running_sandboxes.is_empty() { + if stopped_layers.is_empty() && running_layers.is_empty() { if patterns.is_empty() { outln!( "No layer by the name of '{}' found to delete.", @@ -118,42 +118,41 @@ pub fn delete( return Ok(()); } - delete_sandboxes( + delete_layers( config, - sandboxes_storage_dir, - &running_sandboxes, - &stopped_sandboxes, + layers_storage_dir, + &running_layers, + &stopped_layers, force, ) } -/// Lists the given sandboxes, asks for confirmation unless `force` is set, +/// Lists the given layers, asks for confirmation unless `force` is set, /// then deletes them. -pub fn delete_sandboxes( +pub fn delete_layers( config: &Config, - sandboxes_storage_dir: &Path, - running_sandboxes: &[String], - stopped_sandboxes: &[String], + layers_storage_dir: &Path, + running_layers: &[String], + stopped_layers: &[String], force: bool, ) -> Result<()> { - // Show sandboxes that will be deleted and ask for confirmation + // Show layers that will be deleted and ask for confirmation if !force { outln!("The following layers will be deleted:"); - for (list, stopped) in - [(running_sandboxes, false), (stopped_sandboxes, true)] + for (list, stopped) in [(running_layers, false), (stopped_layers, true)] { for name in list { - let sandbox_entry = SandboxEntry::new( - sandboxes_storage_dir, + let layer_entry = LayerEntry::new( + layers_storage_dir, name.as_str(), stopped, )?; let modifications = - sandbox_entry.sandbox.count_upper_entries(config)?; + layer_entry.layer.count_upper_entries(config)?; let color = if modifications.not_ignored > 0 { Color::Red - } else if !sandbox_entry.stopped { + } else if !layer_entry.stopped { Color::Green } else { Color::White @@ -161,12 +160,12 @@ pub fn delete_sandboxes( outln!( " {} {} ({} entries, {} ignored)", - if sandbox_entry.stopped { + if layer_entry.stopped { "stopped" } else { "running" }, - sandbox_entry.name.color(color), + layer_entry.name.color(color), modifications.not_ignored, modifications.ignored ); @@ -186,26 +185,21 @@ pub fn delete_sandboxes( } } - // Delete each sandbox - let mut deleted_sandboxes = Vec::new(); + // Delete each layer + let mut deleted_layers = Vec::new(); let mut errors = Vec::new(); - for (list, stopped) in - [(running_sandboxes, false), (stopped_sandboxes, true)] - { + for (list, stopped) in [(running_layers, false), (stopped_layers, true)] { for name in list { - let sandbox_entry = SandboxEntry::new( - sandboxes_storage_dir, - name.as_str(), - stopped, - )?; - - trace!("Deleting layer: {}", sandbox_entry.name); - match sandbox_entry.sandbox.delete() { + let layer_entry = + LayerEntry::new(layers_storage_dir, name.as_str(), stopped)?; + + trace!("Deleting layer: {}", layer_entry.name); + match layer_entry.layer.delete() { Ok(()) => { - outln!("Deleted layer: {}", sandbox_entry.name.green()); - deleted_sandboxes - .push(Value::String(sandbox_entry.name.clone())); + outln!("Deleted layer: {}", layer_entry.name.green()); + deleted_layers + .push(Value::String(layer_entry.name.clone())); } Err(e) => { outln!("Error deleting layer: {}", e); @@ -215,11 +209,11 @@ pub fn delete_sandboxes( } } - outln!("{} layers deleted", deleted_sandboxes.len()); + outln!("{} layers deleted", deleted_layers.len()); // Set JSON output set_json_output("status", &Value::String("success".to_string())); - set_json_output("deleted", &Value::Array(deleted_sandboxes)); + set_json_output("deleted", &Value::Array(deleted_layers)); set_json_output("errors", &Value::Array(errors)); Ok(()) diff --git a/src/actions/diff.rs b/src/actions/diff.rs index b7ae921..28457b6 100644 --- a/src/actions/diff.rs +++ b/src/actions/diff.rs @@ -9,23 +9,23 @@ use std::process::Command; use crate::{ config::Config, - sandbox::{Sandbox, changes::EntryOperation}, + layer::{Layer, changes::EntryOperation}, }; pub fn diff( config: &Config, json: bool, - sandbox: &Sandbox, + layer: &Layer, patterns: &[String], ) -> Result<()> { - trace!("Diffing layer {}", sandbox.name); + trace!("Diffing layer {}", layer.name); if json { return Err(anyhow::anyhow!("JSON mode is not supported for diff")); } let cwd = std::env::current_dir()?; - let all_changes = sandbox.changes(config)?; + let all_changes = layer.changes(config)?; let changes = all_changes.matching(&cwd, patterns); // Exercise `EntryOperation::Error` handling during coverage builds. @@ -33,9 +33,9 @@ pub fn diff( let mut changes = changes.clone(); #[cfg(feature = "coverage")] { - use crate::sandbox::changes::ChangeError; + use crate::layer::changes::ChangeError; - changes.0.push(crate::sandbox::changes::ChangeEntry { + changes.0.push(crate::layer::changes::ChangeEntry { operation: EntryOperation::Error(ChangeError::UnsupportedFileType), source: None, destination: PathBuf::from("/dev/null"), @@ -46,7 +46,7 @@ pub fn diff( let should_colorize = SHOULD_COLORIZE.should_colorize(); let upper_cwd_str = config.upper_cwd.to_string_lossy(); - let replacement = format!("<{}>", sandbox.name).cyan().to_string(); + let replacement = format!("<{}>", layer.name).cyan().to_string(); #[cfg(feature = "coverage")] let should_colorize = if std::env::var_os("TEST_FORCE_DIFF_COLOR").is_some() diff --git a/src/actions/list.rs b/src/actions/list.rs index 19d7c01..3dcced9 100644 --- a/src/actions/list.rs +++ b/src/actions/list.rs @@ -8,59 +8,55 @@ use std::path::Path; use crate::{ outln, - util::{get_sandbox_pid_path, set_json_output}, + util::{get_layer_pid_path, set_json_output}, }; -pub fn list(sandboxes_storage_dir: &Path, patterns: &[String]) -> Result<()> { +pub fn list(layers_storage_dir: &Path, patterns: &[String]) -> Result<()> { trace!("Listing layers"); - let [running_sandboxes, stopped_sandboxes] = - get_sandboxes(sandboxes_storage_dir, patterns)?; + let [running_layers, stopped_layers] = + get_layers(layers_storage_dir, patterns)?; - if !running_sandboxes.is_empty() { + if !running_layers.is_empty() { outln!("Running layers:"); - for sandbox in &running_sandboxes { - outln!("{}", sandbox); + for layer in &running_layers { + outln!("{}", layer); } } - if !running_sandboxes.is_empty() && !stopped_sandboxes.is_empty() { + if !running_layers.is_empty() && !stopped_layers.is_empty() { outln!(""); } - if !stopped_sandboxes.is_empty() { + if !stopped_layers.is_empty() { outln!("{}", "Stopped layers:".dimmed()); - for sandbox in &stopped_sandboxes { - outln!("{}", sandbox.dimmed()); + for layer in &stopped_layers { + outln!("{}", layer.dimmed()); } } set_json_output( "running_layers", - &Value::Array( - running_sandboxes.into_iter().map(Value::String).collect(), - ), + &Value::Array(running_layers.into_iter().map(Value::String).collect()), ); set_json_output( "stopped_layers", - &Value::Array( - stopped_sandboxes.into_iter().map(Value::String).collect(), - ), + &Value::Array(stopped_layers.into_iter().map(Value::String).collect()), ); Ok(()) } -pub fn get_sandboxes( - sandboxes_storage_dir: &Path, +pub fn get_layers( + layers_storage_dir: &Path, patterns: &[String], ) -> Result<[Vec; 2]> { - let mut running_sandboxes: Vec = Vec::new(); - let mut stopped_sandboxes: Vec = Vec::new(); + let mut running_layers: Vec = Vec::new(); + let mut stopped_layers: Vec = Vec::new(); - let sandboxes = sandboxes_storage_dir.read_dir()?; - for sandbox in sandboxes { - let entry = sandbox?; + let layers = layers_storage_dir.read_dir()?; + for layer in layers { + let entry = layer?; let path = entry.path(); let filename = path .components() @@ -68,16 +64,16 @@ pub fn get_sandboxes( .expect("Failed to get filename") .as_os_str(); if filename.to_string_lossy().ends_with(".lock") { - let sandbox_name = + let layer_name = filename.to_string_lossy()[..filename.len() - 5].to_string(); if patterns.is_empty() || patterns .iter() - .any(|pattern| glob_match(pattern, &sandbox_name)) + .any(|pattern| glob_match(pattern, &layer_name)) { let pid_file = - get_sandbox_pid_path(sandboxes_storage_dir, &sandbox_name); + get_layer_pid_path(layers_storage_dir, &layer_name); if pid_file.exists() { let pid = std::fs::read_to_string(pid_file)?; @@ -85,24 +81,24 @@ pub fn get_sandboxes( Ok(pid) => { let pid = Pid::from_raw(pid); if kill(pid, None).is_ok() { - running_sandboxes.push(sandbox_name); + running_layers.push(layer_name); } else { - stopped_sandboxes.push(sandbox_name); + stopped_layers.push(layer_name); } } Err(_) => { - stopped_sandboxes.push(sandbox_name); + stopped_layers.push(layer_name); } } } else { - stopped_sandboxes.push(sandbox_name); + stopped_layers.push(layer_name); } } } } - running_sandboxes.sort(); - stopped_sandboxes.sort(); + running_layers.sort(); + stopped_layers.sort(); - Ok([running_sandboxes, stopped_sandboxes]) + Ok([running_layers, stopped_layers]) } diff --git a/src/actions/reject.rs b/src/actions/reject.rs index 792f6a6..46d3db8 100644 --- a/src/actions/reject.rs +++ b/src/actions/reject.rs @@ -1,7 +1,7 @@ use crate::{ config::Config, + layer::{Layer, changes::changes::by_staged_descending}, outln, - sandbox::{Sandbox, changes::changes::by_staged_descending}, util::sync_and_drop_caches, }; use anyhow::{Context, Result}; @@ -9,13 +9,13 @@ use log::{debug, trace}; pub fn reject( config: &Config, - sandbox: &Sandbox, + layer: &Layer, patterns: &[String], ) -> Result<()> { - trace!("Rejecting changes from layer {}", sandbox.name); + trace!("Rejecting changes from layer {}", layer.name); let cwd = std::env::current_dir()?; - let changes = sandbox.changes(config)?; + let changes = layer.changes(config)?; let mut changes = changes.matching(&cwd, patterns); changes.sort_by(by_staged_descending); diff --git a/src/actions/status.rs b/src/actions/status.rs index a1dff96..084a67f 100644 --- a/src/actions/status.rs +++ b/src/actions/status.rs @@ -1,13 +1,13 @@ use crate::{ config::Config, - outln, - sandbox::{ - Sandbox, + layer::{ + Layer, changes::{ ChangeEntries, EntryOperation, changes::{by_destination, by_reverse_source}, }, }, + outln, util::set_json_output, }; use anyhow::Result; @@ -16,13 +16,13 @@ use serde_json::{Value, json}; pub fn status( config: &Config, - sandbox: &Sandbox, + layer: &Layer, patterns: &[String], ) -> Result<()> { - trace!("Status of layer {}", sandbox.name); + trace!("Status of layer {}", layer.name); let cwd = std::env::current_dir()?; - let all_changes = sandbox.changes(config)?; + let all_changes = layer.changes(config)?; let mut changes = all_changes.matching(&cwd, patterns); let non_matching_count = ChangeEntries::calculate_non_matching_count(&all_changes, &changes); diff --git a/src/actions/stop.rs b/src/actions/stop.rs index 52b6ff6..9610a37 100644 --- a/src/actions/stop.rs +++ b/src/actions/stop.rs @@ -4,46 +4,41 @@ use fast_glob::glob_match; use log::{trace, warn}; use nix::unistd::{Gid, Uid}; -use crate::sandbox::Sandbox; +use crate::layer::Layer; use anyhow::Result; pub fn stop( - sandboxes_storage_dir: &Path, - sandbox_name: &str, + layers_storage_dir: &Path, + layer_name: &str, uid: Uid, gid: Gid, ) -> Result<()> { - trace!("Stopping layer {}", sandbox_name); - let (sandbox, _lock) = - Sandbox::get(sandboxes_storage_dir, sandbox_name, uid, gid, None)?; + trace!("Stopping layer {}", layer_name); + let (layer, _lock) = + Layer::get(layers_storage_dir, layer_name, uid, gid, None)?; - let sandbox = match sandbox { - Some(sandbox) => sandbox, - None => Sandbox::from_location( - sandboxes_storage_dir, - sandbox_name, - uid, - gid, - ), + let layer = match layer { + Some(layer) => layer, + None => Layer::from_location(layers_storage_dir, layer_name, uid, gid), }; - sandbox.stop()?; - sandbox.unmount()?; + layer.stop()?; + layer.unmount()?; Ok(()) } pub fn stop_all( - sandboxes_storage_dir: &Path, + layers_storage_dir: &Path, uid: Uid, gid: Gid, patterns: &[String], ) -> Result<()> { - trace!("Stopping all layers in {}", sandboxes_storage_dir.display()); + trace!("Stopping all layers in {}", layers_storage_dir.display()); - let sandboxes = sandboxes_storage_dir.read_dir()?; - for sandbox in sandboxes { - let entry = sandbox?; + let layers = layers_storage_dir.read_dir()?; + for layer in layers { + let entry = layer?; let path = entry.path(); let filename = path .components() @@ -51,21 +46,15 @@ pub fn stop_all( .expect("Failed to get filename") .as_os_str(); if filename.to_string_lossy().ends_with(".lock") { - let sandbox_name = + let layer_name = filename.to_string_lossy()[..filename.len() - 5].to_string(); - let lock_file = format!( - "{}/{}.lock", - sandboxes_storage_dir.display(), - sandbox_name - ); - let pid_file = format!( - "{}/{}.pid", - sandboxes_storage_dir.display(), - sandbox_name - ); + let lock_file = + format!("{}/{}.lock", layers_storage_dir.display(), layer_name); + let pid_file = + format!("{}/{}.pid", layers_storage_dir.display(), layer_name); let storage_dir = - format!("{}/{}", sandboxes_storage_dir.display(), sandbox_name); + format!("{}/{}", layers_storage_dir.display(), layer_name); if !Path::new(&lock_file).exists() || !Path::new(&pid_file).exists() @@ -78,13 +67,13 @@ pub fn stop_all( || patterns.iter().any(|pattern| { let mut pattern = pattern.clone(); pattern = format!("*{pattern}*"); - glob_match(&pattern, &sandbox_name) + glob_match(&pattern, &layer_name) }) { - match stop(sandboxes_storage_dir, &sandbox_name, uid, gid) { + match stop(layers_storage_dir, &layer_name, uid, gid) { Ok(_) => {} Err(e) => { - warn!("Failed to kill layer {}: {}", sandbox_name, e); + warn!("Failed to kill layer {}: {}", layer_name, e); } } } diff --git a/src/config/cli.rs b/src/config/cli.rs index e3f8be7..91804ee 100644 --- a/src/config/cli.rs +++ b/src/config/cli.rs @@ -24,7 +24,7 @@ pub struct Args { pub log_level: Option, /// Name of the layer, defaults to "devlayer" - #[arg(long, global = true, value_hint = clap::ValueHint::Other, add = ArgValueCompleter::new(sandbox_name_completion), conflicts_with_all = &["new", "last"])] + #[arg(long, global = true, value_hint = clap::ValueHint::Other, add = ArgValueCompleter::new(layer_name_completion), conflicts_with_all = &["new", "last"])] pub name: Option, /// Create a new layer with an auto-generated timestamp name @@ -128,7 +128,7 @@ pub struct Args { pub action: Option, /*********************/ - /* Sandboxed Command */ + /* Layered Command */ /*********************/ /// The command to run in the layer. If no command is provided, the current shell will be used. /// If the layer is not running, it will be started with the command. @@ -139,7 +139,7 @@ pub struct Args { value_parser = validate_command, help_heading = "Command", )] - pub sandboxed_command: Option>, + pub layered_command: Option>, } #[derive(clap::Subcommand, Clone, Debug)] @@ -222,7 +222,7 @@ pub enum Action { }, } -pub fn sandbox_name_completion( +pub fn layer_name_completion( current: &std::ffi::OsStr, ) -> Vec { let ugh = resolve_uid_gid_home(); @@ -245,9 +245,9 @@ pub fn sandbox_name_completion( Err(_) => return completions, }; - let sandboxes_storage_dir = config.storage_dir; + let layers_storage_dir = config.storage_dir; - let entries = match std::fs::read_dir(sandboxes_storage_dir) { + let entries = match std::fs::read_dir(layers_storage_dir) { Ok(entries) => entries, Err(_) => return completions, }; diff --git a/src/config/resolve.rs b/src/config/resolve.rs index 336106d..615b530 100644 --- a/src/config/resolve.rs +++ b/src/config/resolve.rs @@ -206,8 +206,8 @@ pub fn resolve_config(cli: Args) -> Result { partial_config.name = Some(name); sources.insert("name".into(), "cli --new".into()); } else if cli.last { - // Find the most recently created sandbox - let name = find_last_sandbox( + // Find the most recently created layer + let name = find_last_layer( &partial_config.storage_dir, uid_gid_home.uid, uid_gid_home.gid, @@ -304,7 +304,7 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("memory".into(), "default".into()); } - let storage_dir = resolve_sandbox_storage_dir( + let storage_dir = resolve_storage_dir( partial_config.storage_dir, uid_gid_home.uid, uid_gid_home.gid, @@ -313,9 +313,9 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("storage_dir".into(), "default".into()); } - let sandbox_dir = storage_dir.join(name.clone()); - if !sources.contains_key("sandbox_dir") { - sources.insert("sandbox_dir".into(), "derived from storage_dir".into()); + let layer_dir = storage_dir.join(name.clone()); + if !sources.contains_key("layer_dir") { + sources.insert("layer_dir".into(), "derived from storage_dir".into()); } let cwd = std::env::current_dir()?; @@ -387,7 +387,7 @@ pub fn resolve_config(cli: Args) -> Result { name, net, storage_dir, - sandbox_dir, + layer_dir, upper_cwd, overlay_cwd, log_level: partial_config.log_level.unwrap_or(log::LevelFilter::Info), @@ -495,7 +495,7 @@ fn get_audio_bind_mounts() -> Vec { audio_binds } -pub fn resolve_sandbox_storage_dir( +pub fn resolve_storage_dir( storage_dir: Option, uid: Uid, gid: Gid, @@ -702,11 +702,11 @@ fn find_config_files() -> Result> { } } - // ~/.config/sandbox/config.toml + // ~/.config/layer/config.toml paths_to_check.push(uid_gid_home.home.join(".config/devlayer/config.conf")); paths_to_check.push(uid_gid_home.home.join(".config/devlayer/config.toml")); - // /etc/sandbox.conf + // /etc/layer.conf paths_to_check.push(PathBuf::from("/etc/devlayer.conf")); paths_to_check.push(PathBuf::from("/etc/devlayer.toml")); @@ -798,8 +798,7 @@ fn generate_timestamp_name( uid: Uid, gid: Gid, ) -> Result { - let storage_dir = - resolve_sandbox_storage_dir(storage_dir.clone(), uid, gid)?; + let storage_dir = resolve_storage_dir(storage_dir.clone(), uid, gid)?; #[cfg(feature = "coverage")] let mut iter = 0; @@ -810,8 +809,8 @@ fn generate_timestamp_name( format!("ephemeral_{}", now.format("%Y-%m-%d_%H-%M-%S")); // Check if this name already exists - let sandbox_path = storage_dir.join(&base_name); - if !sandbox_path.exists() { + let layer_path = storage_dir.join(&base_name); + if !layer_path.exists() { return Ok(base_name); } @@ -827,8 +826,8 @@ fn generate_timestamp_name( name_with_ms }; - let sandbox_path_ms = storage_dir.join(&name_with_ms); - if !sandbox_path_ms.exists() { + let layer_path_ms = storage_dir.join(&name_with_ms); + if !layer_path_ms.exists() { return Ok(name_with_ms); } @@ -842,26 +841,25 @@ fn generate_timestamp_name( } } -fn find_last_sandbox( +fn find_last_layer( storage_dir: &Option, uid: Uid, gid: Gid, ) -> Result { - let storage_dir = - resolve_sandbox_storage_dir(storage_dir.clone(), uid, gid)?; + let storage_dir = resolve_storage_dir(storage_dir.clone(), uid, gid)?; let entries = std::fs::read_dir(&storage_dir).context(format!( "Failed to read layer storage directory: {:?}", storage_dir ))?; - let mut sandboxes: Vec<(String, SystemTime)> = Vec::new(); + let mut layers: Vec<(String, SystemTime)> = Vec::new(); for entry in entries { let entry = entry?; let path = entry.path(); - // Check if this is a valid sandbox directory + // Check if this is a valid layer directory if path.is_dir() && path.join("upper").is_dir() && path.join("work").is_dir() @@ -873,25 +871,25 @@ fn find_last_sandbox( .created() .or_else(|_| metadata.modified()) .context("Failed to get creation time for layer")?; - sandboxes.push((name, created)); + layers.push((name, created)); } } #[cfg(feature = "coverage")] - let mut sandboxes = if std::env::var_os("TEST_LAST_IS_EMPTY").is_some() { + let mut layers = if std::env::var_os("TEST_LAST_IS_EMPTY").is_some() { vec![] } else { - sandboxes + layers }; - if sandboxes.is_empty() { + if layers.is_empty() { return Err(anyhow::anyhow!("No layers found")); } // Sort by creation time (newest first) - sandboxes.sort_by(|a, b| b.1.cmp(&a.1)); + layers.sort_by(|a, b| b.1.cmp(&a.1)); - Ok(sandboxes[0].0.clone()) + Ok(layers[0].0.clone()) } #[cfg(test)] @@ -961,7 +959,7 @@ mod tests { let mut config = Config { name: "test-layer".to_string(), storage_dir: PathBuf::from("/tmp/test"), - sandbox_dir: PathBuf::from("/tmp/test"), + layer_dir: PathBuf::from("/tmp/test"), upper_cwd: PathBuf::from("/tmp/test"), overlay_cwd: PathBuf::from("/tmp/test"), net: Network::Host, diff --git a/src/config/structs.rs b/src/config/structs.rs index 94b2223..d9a70b6 100644 --- a/src/config/structs.rs +++ b/src/config/structs.rs @@ -72,7 +72,7 @@ pub struct Config { pub log_level: log::LevelFilter, pub name: String, pub storage_dir: PathBuf, - pub sandbox_dir: PathBuf, + pub layer_dir: PathBuf, pub upper_cwd: PathBuf, pub overlay_cwd: PathBuf, pub net: Network, @@ -81,9 +81,9 @@ pub struct Config { pub bind_mounts: Vec, pub no_default_binds: bool, pub audio: bool, - /// Number of CPUs the sandbox may use, None for unlimited + /// Number of CPUs the layer may use, None for unlimited pub cpus: Option, - /// Bytes of memory the sandbox may use, None for unlimited + /// Bytes of memory the layer may use, None for unlimited pub memory: Option, pub config_files: Vec, } diff --git a/src/sandbox/cgroup.rs b/src/layer/cgroup.rs similarity index 84% rename from src/sandbox/cgroup.rs rename to src/layer/cgroup.rs index a5308e9..f195fa2 100644 --- a/src/sandbox/cgroup.rs +++ b/src/layer/cgroup.rs @@ -1,12 +1,12 @@ -//! cgroup v2 support for limiting the CPU and memory available to a sandbox. +//! cgroup v2 support for limiting the CPU and memory available to a layer. //! -//! Sandboxes with resource limits get a cgroup at -//! /sys/fs/cgroup/sandbox/-. The sandbox's PID 1 is started in that -//! cgroup, which also makes it the root of the sandbox's cgroup namespace, and -//! every process that later joins the sandbox is moved into it. +//! Layers with resource limits get a cgroup at +//! /sys/fs/cgroup/layer/-. The layer's PID 1 is started in that +//! cgroup, which also makes it the root of the layer's cgroup namespace, and +//! every process that later joins the layer is moved into it. use crate::config::Config; -use crate::sandbox::{Sandbox, SandboxSettings, describe_limits}; +use crate::layer::{Layer, LayerSettings, describe_limits}; use anyhow::{Context, Result, anyhow}; use log::{debug, trace, warn}; use std::os::fd::OwnedFd; @@ -16,7 +16,7 @@ use std::time::{Duration, Instant}; const CGROUP_ROOT: &str = "/sys/fs/cgroup"; const CPU_PERIOD_US: u64 = 100_000; -/// The cgroup all sandbox cgroups are created in +/// The cgroup all layer cgroups are created in fn cgroup_parent() -> String { let parent = String::from("devlayer"); @@ -27,7 +27,7 @@ fn cgroup_parent() -> String { parent } -impl Sandbox { +impl Layer { fn cgroup_name(&self) -> String { format!("{}-{}", self.uid, self.name) } @@ -39,8 +39,8 @@ impl Sandbox { } /// Sets up our cgroup like create_cgroup, except that inside another - /// sandbox, where cgroups can't be managed, we warn and run without a - /// cgroup of our own. We're still in the outer sandbox's cgroup, so its + /// layer, where cgroups can't be managed, we warn and run without a + /// cgroup of our own. We're still in the outer layer's cgroup, so its /// limits continue to apply. pub(crate) fn create_cgroup_or_share_outer( &self, @@ -51,10 +51,10 @@ impl Sandbox { Err(e) => e.context("Failed to set up resource limits"), }; - // A nested sandbox's storage directory is the outer sandbox's data - // directory, which holds the outer sandbox's settings + // A nested layer's storage directory is the outer layer's data + // directory, which holds the outer layer's settings let outer_settings = config.storage_dir.join("settings.json"); - let Ok(outer) = SandboxSettings::load_from_file(&outer_settings) else { + let Ok(outer) = LayerSettings::load_from_file(&outer_settings) else { return Err(error); }; @@ -111,9 +111,9 @@ impl Sandbox { let path = self.cgroup_path(); if path.exists() { - // Left behind by a sandbox that wasn't stopped cleanly, which we + // Left behind by a layer that wasn't stopped cleanly, which we // can remove because it's empty. If it's not empty it belongs to - // a running sandbox with the same name in another storage dir. + // a running layer with the same name in another storage dir. std::fs::remove_dir(&path).context(format!( "Failed to remove existing cgroup {}, is a layer with the same name running from a different storage directory?", path.display() @@ -145,7 +145,7 @@ impl Sandbox { } if let Some(memory) = config.memory { write_cgroup_file(path, "memory.max", &memory.to_string())?; - // Swap would let the sandbox use more memory than its limit, but + // Swap would let the layer use more memory than its limit, but // the file only exists when swap accounting is enabled. let swap_accounting = path.join("memory.swap.max").exists(); @@ -160,10 +160,10 @@ impl Sandbox { Ok(()) } - /// Returns the path to our cgroup if our sandbox is running in one. We + /// Returns the path to our cgroup if our layer is running in one. We /// go by the cgroup our PID 1 is in rather than the name we'd give a new /// cgroup, because the uid in the name is that of the user who started - /// the sandbox, which isn't always ours (e.g. `delete` doesn't know it). + /// the layer, which isn't always ours (e.g. `delete` doesn't know it). pub(crate) fn running_cgroup(&self) -> Option { let cgroups = std::fs::read_to_string(format!("/proc/{}/cgroup", self.pid)) @@ -178,8 +178,8 @@ impl Sandbox { .then(|| Path::new(CGROUP_ROOT).join(relative)) } - /// Moves the current process into our sandbox's cgroup, if it has one, - /// so processes we launch in the sandbox are subject to its limits. + /// Moves the current process into our layer's cgroup, if it has one, + /// so processes we launch in the layer are subject to its limits. pub(crate) fn join_cgroup(&self) -> Result<()> { if let Some(path) = self.running_cgroup() { trace!("Joining cgroup {}", path.display()); @@ -191,8 +191,8 @@ impl Sandbox { } /// Removes a cgroup once the processes in it have exited, waiting a little -/// while for that. Sandbox processes have already been killed by this point. -/// The only other processes in the cgroup are the `sandbox` commands waiting +/// while for that. Layer processes have already been killed by this point. +/// The only other processes in the cgroup are the `layer` commands waiting /// on them, which exit by themselves once their child is gone, so they get to /// report its exit status instead of being killed too. pub(crate) fn remove_cgroup(path: &Path) { diff --git a/src/sandbox/changes/change_entries.rs b/src/layer/changes/change_entries.rs similarity index 99% rename from src/sandbox/changes/change_entries.rs rename to src/layer/changes/change_entries.rs index 966f5ed..5b82ad5 100644 --- a/src/sandbox/changes/change_entries.rs +++ b/src/layer/changes/change_entries.rs @@ -25,7 +25,7 @@ pub enum EntryOperation { Error(ChangeError), } -/// A ChangeEntry is a single change that has been detected in the sandbox. +/// A ChangeEntry is a single change that has been detected in the layer. #[derive(Debug, Clone)] pub struct ChangeEntry { /// The destination path of the change. This may or may not exist yet. diff --git a/src/sandbox/changes/changes.rs b/src/layer/changes/changes.rs similarity index 99% rename from src/sandbox/changes/changes.rs rename to src/layer/changes/changes.rs index cdde85b..0670f98 100644 --- a/src/sandbox/changes/changes.rs +++ b/src/layer/changes/changes.rs @@ -1,6 +1,6 @@ use crate::config::Config; -use crate::sandbox::Sandbox; -use crate::sandbox::changes::*; +use crate::layer::Layer; +use crate::layer::changes::*; use crate::util::find_mount_point; use anyhow::Context; use anyhow::Result; @@ -44,7 +44,7 @@ const BUILT_IN_IGNORE_PATTERNS: &[&str] = &[ "**/.git", ]; -impl Sandbox { +impl Layer { /** * This function will walk the upper directory and create a list of changes that have been * made. It will return a vector of ChangeEntry structs that can be used to apply the changes. diff --git a/src/sandbox/changes/file_details.rs b/src/layer/changes/file_details.rs similarity index 99% rename from src/sandbox/changes/file_details.rs rename to src/layer/changes/file_details.rs index 24e8752..9cd646f 100644 --- a/src/sandbox/changes/file_details.rs +++ b/src/layer/changes/file_details.rs @@ -54,7 +54,7 @@ impl FileDetails { } /* An opaque directory means that we have created the directory - * within the sandbox, possibly removing a previous directory by + * within the layer, possibly removing a previous directory by * the same name along with all its contents. */ pub fn is_opaque(&self) -> bool { let mut buffer = vec![0; 1]; diff --git a/src/sandbox/changes/mod.rs b/src/layer/changes/mod.rs similarity index 100% rename from src/sandbox/changes/mod.rs rename to src/layer/changes/mod.rs diff --git a/src/sandbox/delete.rs b/src/layer/delete.rs similarity index 93% rename from src/sandbox/delete.rs rename to src/layer/delete.rs index eeef6c6..2b77a9b 100644 --- a/src/sandbox/delete.rs +++ b/src/layer/delete.rs @@ -1,10 +1,10 @@ use std::path::PathBuf; -use crate::{actions::rmdir_recursive, sandbox::Sandbox}; +use crate::{actions::rmdir_recursive, layer::Layer}; use anyhow::{Context, Result}; use log::{debug, trace}; -impl Sandbox { +impl Layer { pub fn delete(&self) -> Result<()> { self.stop().context("failed to stop layer")?; self.unmount().context("failed to unmount layer")?; diff --git a/src/sandbox/exec.rs b/src/layer/exec.rs similarity index 92% rename from src/sandbox/exec.rs rename to src/layer/exec.rs index 4a887de..cb9cf8e 100644 --- a/src/sandbox/exec.rs +++ b/src/layer/exec.rs @@ -1,5 +1,5 @@ #![allow(static_mut_refs)] -use crate::sandbox::Sandbox; +use crate::layer::Layer; use crate::util::drop_privileges; use anyhow::{Context, Result, anyhow}; use libc::syscall; @@ -17,9 +17,9 @@ unsafe extern "C" { fn __llvm_profile_set_filename(filename: *const i8); } -impl Sandbox { +impl Layer { /** - * Exec within the provided sandbox. This function never returns on + * Exec within the provided layer. This function never returns on * success. */ pub fn exec(&self, command: &[String]) -> Result<()> { @@ -34,16 +34,16 @@ impl Sandbox { | libc::CLONE_NEWUTS; #[cfg(feature = "coverage")] - let ns_flags = if std::env::var_os("TEST_UNABLE_TO_JOIN_SANDBOX") + let ns_flags = if std::env::var_os("TEST_UNABLE_TO_JOIN_LAYER") .is_some() { - // in this test case we are failing to enter a sandbox so our - // .profraw file will be outside of the sandbox, so we'll place + // in this test case we are failing to enter a layer so our + // .profraw file will be outside of the layer, so we'll place // it directly where we want it for coverage analysis unsafe { __llvm_profile_set_filename( CString::new( - format!("coverage/profraw/join-sandbox-failure-{}-{}-%m.profraw", + format!("coverage/profraw/join-layer-failure-{}-{}-%m.profraw", self.pid, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) .context("Failed to get current time")? @@ -82,12 +82,12 @@ impl Sandbox { libc::prctl(libc::PR_SET_DUMPABLE, 1); }; - /* Join the sandbox's cgroup so we're subject to its resource limits. - * This needs to happen before we enter the sandbox's mount namespace, + /* Join the layer's cgroup so we're subject to its resource limits. + * This needs to happen before we enter the layer's mount namespace, * where the cgroup filesystem is read-only. */ self.join_cgroup()?; - /* Join the sandbox namespaces */ + /* Join the layer namespaces */ let pid_fd = pidfd_open(self.pid, 0)?; if (unsafe { setns(pid_fd, ns_flags) }) != 0 { return Err(anyhow!( @@ -96,11 +96,11 @@ impl Sandbox { )); } - // Enter the sandbox mount namespace - chdir("/").context(format!("failed to chdir to /"))?; // This will be the sandbox root - chroot(".").context(format!("failed to chroot to ."))?; // Now we fully enter the sandbox namespace + // Enter the layer mount namespace + chdir("/").context(format!("failed to chdir to /"))?; // This will be the layer root + chroot(".").context(format!("failed to chroot to ."))?; // Now we fully enter the layer namespace - /* Restore our CWD to be within our sandbox */ + /* Restore our CWD to be within our layer */ trace!("Setting CWD to {}", cwd.display()); std::env::set_current_dir(&cwd) .context(format!("failed to set CWD to {}", cwd.display()))?; diff --git a/src/sandbox/exists.rs b/src/layer/exists.rs similarity index 87% rename from src/sandbox/exists.rs rename to src/layer/exists.rs index b96bad7..cc05fe5 100644 --- a/src/sandbox/exists.rs +++ b/src/layer/exists.rs @@ -1,8 +1,8 @@ use std::path::PathBuf; -use crate::sandbox::Sandbox; +use crate::layer::Layer; -impl Sandbox { +impl Layer { pub fn exists(&self) -> bool { let pid_file = PathBuf::from(format!("{}.pid", self.base.display())); let lock_file = PathBuf::from(format!("{}.lock", self.base.display())); diff --git a/src/sandbox/get_or_create.rs b/src/layer/get_or_create.rs similarity index 90% rename from src/sandbox/get_or_create.rs rename to src/layer/get_or_create.rs index b313c61..d2aa8f3 100644 --- a/src/sandbox/get_or_create.rs +++ b/src/layer/get_or_create.rs @@ -1,12 +1,12 @@ use super::cgroup::remove_cgroup; use super::mount_overlays::MountHash; use crate::config::{BindMount, BindMountOptions, Config, Network}; -use crate::sandbox::Sandbox; +use crate::layer::Layer; #[cfg(feature = "coverage")] use crate::util::CLONE_FS; use crate::util::Lock; -use crate::util::get_running_sandbox_pid; -use crate::util::get_sandbox_pid_path; +use crate::util::get_layer_pid_path; +use crate::util::get_running_layer_pid; use crate::util::{ CLONE_INTO_CGROUP, CLONE_NEWCGROUP, CLONE_NEWIPC, CLONE_NEWNET, CLONE_NEWNS, CLONE_NEWPID, CLONE_NEWUTS, Clone3Args, @@ -40,23 +40,23 @@ unsafe extern "C" { const TMPFS_SIZE: i32 = 64 * 1024 * 1024; // 64MB, because that's what docker does -impl Sandbox { +impl Layer { pub fn from_location( - sandboxes_storage_dir: &Path, - sandbox_name: &str, + layers_storage_dir: &Path, + layer_name: &str, uid: Uid, gid: Gid, - ) -> Sandbox { + ) -> Layer { let root_suffix = data_encoding::BASE32_NOPAD.encode(b"/"); - let sandbox_base_dir = sandboxes_storage_dir.join(sandbox_name); - let work_base = sandbox_base_dir.join("work"); - let upper_base = sandbox_base_dir.join("upper"); - let overlay_base = sandbox_base_dir.join("overlay"); - let data_base = sandbox_base_dir.join("data"); - - Sandbox { - name: sandbox_name.to_string(), - base: sandbox_base_dir.clone(), + let layer_base_dir = layers_storage_dir.join(layer_name); + let work_base = layer_base_dir.join("work"); + let upper_base = layer_base_dir.join("upper"); + let overlay_base = layer_base_dir.join("overlay"); + let data_base = layer_base_dir.join("data"); + + Layer { + name: layer_name.to_string(), + base: layer_base_dir.clone(), work_base: work_base.clone(), upper_base: upper_base.clone(), overlay_base: overlay_base.clone(), @@ -69,48 +69,39 @@ impl Sandbox { } pub fn get( - sandboxes_storage_dir: &Path, - sandbox_name: &str, + layers_storage_dir: &Path, + layer_name: &str, uid: Uid, gid: Gid, lock: Option>, - ) -> Result<(Option, Box)> { + ) -> Result<(Option, Box)> { /* Lock so we don't have multiple processes trying to get at the same time */ let lock = match lock { Some(l) => l, - None => Lock::sandbox(sandboxes_storage_dir, sandbox_name) - .context(format!("failed to lock layer: {}", sandbox_name))?, + None => Lock::layer(layers_storage_dir, layer_name) + .context(format!("failed to lock layer: {}", layer_name))?, }; - let sandbox_base_dir = sandboxes_storage_dir.join(sandbox_name); - if !sandbox_base_dir.exists() { + let layer_base_dir = layers_storage_dir.join(layer_name); + if !layer_base_dir.exists() { return Ok((None, lock)); } - /* If we have an existing sandbox, return it */ - if let Some(pid) = - get_running_sandbox_pid(sandboxes_storage_dir, sandbox_name) + /* If we have an existing layer, return it */ + if let Some(pid) = get_running_layer_pid(layers_storage_dir, layer_name) { - let mut sandbox = Sandbox::from_location( - sandboxes_storage_dir, - sandbox_name, - uid, - gid, - ); - sandbox.pid = pid; - return Ok((Some(sandbox), lock)); + let mut layer = + Layer::from_location(layers_storage_dir, layer_name, uid, gid); + layer.pid = pid; + return Ok((Some(layer), lock)); } Ok((None, lock)) } - pub fn get_or_create( - config: &Config, - uid: Uid, - gid: Gid, - ) -> Result { + pub fn get_or_create(config: &Config, uid: Uid, gid: Gid) -> Result { let storage_dir = &config.storage_dir; - let sandbox_name = &config.name; + let layer_name = &config.name; /* Ensure that the storage directory exists */ mkdir(storage_dir, uid, gid).context(format!( "failed to create storage directory: {}", @@ -118,31 +109,31 @@ impl Sandbox { ))?; /* First lock so we don't have multiple processes trying to get_or_create at the same time */ - let lock = Lock::sandbox(storage_dir, sandbox_name) - .context(format!("failed to lock layer: {}", sandbox_name))?; + let lock = Lock::layer(storage_dir, layer_name) + .context(format!("failed to lock layer: {}", layer_name))?; - /* If we have an existing sandbox, return it */ - let (sandbox, _lock) = - Sandbox::get(storage_dir, sandbox_name, uid, gid, Some(lock))?; + /* If we have an existing layer, return it */ + let (layer, _lock) = + Layer::get(storage_dir, layer_name, uid, gid, Some(lock))?; - if let Some(sandbox) = sandbox { - // Validate that the existing sandbox settings are compatible with current config - let settings_path = sandbox.settings_path(); + if let Some(layer) = layer { + // Validate that the existing layer settings are compatible with current config + let settings_path = layer.settings_path(); if settings_path.exists() { - match crate::sandbox::SandboxSettings::load_from_file( + match crate::layer::LayerSettings::load_from_file( &settings_path, ) { Ok(existing_settings) => { // Determine what the current mounts should be - let expected_mounts = sandbox.determine_mounts(config) + let expected_mounts = layer.determine_mounts(config) .context("Failed to determine expected mounts for validation")?; // Create a config that includes the implicit data bind mount for validation let mut validation_config = config.clone(); validation_config.bind_mounts.push(BindMount { argument: "data".to_string(), - source: sandbox.data_storage_dir.clone(), - target: sandbox.data_storage_dir.clone(), + source: layer.data_storage_dir.clone(), + target: layer.data_storage_dir.clone(), options: BindMountOptions::ReadWrite, }); @@ -161,19 +152,18 @@ impl Sandbox { } } } - return Ok(sandbox); + return Ok(layer); } /* - * Otherwise, create a new sandbox + * Otherwise, create a new layer */ - let mut sandbox = - Sandbox::from_location(storage_dir, sandbox_name, uid, gid); + let mut layer = Layer::from_location(storage_dir, layer_name, uid, gid); trace!( "Creating new layer '{}': {}", - sandbox_name, - sandbox.base.display() + layer_name, + layer.base.display() ); /* Sanity check our storage path*/ @@ -187,56 +177,56 @@ impl Sandbox { let mut config = config.clone(); config.bind_mounts.push(BindMount { argument: "data".to_string(), - source: sandbox.data_storage_dir.clone(), - target: sandbox.data_storage_dir.clone(), + source: layer.data_storage_dir.clone(), + target: layer.data_storage_dir.clone(), options: BindMountOptions::ReadWrite, }); /* Create a cgroup to enforce any resource limits. We do this first * so we fail before mounting anything if limits aren't available. */ - let cgroup = sandbox.create_cgroup_or_share_outer(&config)?; + let cgroup = layer.create_cgroup_or_share_outer(&config)?; trace!("Mounting layer"); - let started = sandbox + let started = layer .mount_overlays(&config) - .context(format!("failed to mount layer: {}", sandbox_name)) + .context(format!("failed to mount layer: {}", layer_name)) .and_then(|overlay_mounts| { - /* Create PID 1 for our sandbox */ - sandbox - .start_sandbox( + /* Create PID 1 for our layer */ + layer + .start_layer( &config, - &get_sandbox_pid_path(storage_dir, sandbox_name), + &get_layer_pid_path(storage_dir, layer_name), &overlay_mounts, cgroup.as_ref(), ) .map_err(|e| anyhow!("Failed to start layer: {}", e)) }); - sandbox.pid = match started { + layer.pid = match started { Ok(pid) => pid, Err(e) => { if cgroup.is_some() { - remove_cgroup(&sandbox.cgroup_path()); + remove_cgroup(&layer.cgroup_path()); } return Err(e); } }; - Ok(sandbox) + Ok(layer) } /** * This launches a new process with new namespaces. The process will go to sleep * but stick around to allow future processes to be launched in the same namespaces. */ - fn start_sandbox( + fn start_layer( &self, config: &Config, pid_file: &PathBuf, overlay_mounts: &Vec, cgroup: Option<&OwnedFd>, ) -> Result { - // create a pipe between ourselves and the main sandbox process so the main sandbox process can + // create a pipe between ourselves and the main layer process so the main layer process can // let us know when it's done setting up the namespaces let (read_fd, write_fd) = pipe().context("failed to create pipe for layer")?; @@ -262,7 +252,7 @@ impl Sandbox { #[cfg(feature = "coverage")] let clone_args = - if std::env::var_os("TEST_START_SANDBOX_FAILURE").is_some() { + if std::env::var_os("TEST_START_LAYER_FAILURE").is_some() { let mut new_args = clone_args.clone(); new_args.flags |= CLONE_FS; // invalid flag combination with NEWNS new_args @@ -306,7 +296,7 @@ impl Sandbox { // Normal operation is that this doesn't return. let _ = self - .setup_sandbox_and_sleep_forever( + .setup_layer_and_sleep_forever( config, &write_fd, overlay_mounts, @@ -324,9 +314,9 @@ impl Sandbox { } } - /* After forking via clone3, this is function gets called to finish setting up the sandbox. + /* After forking via clone3, this is function gets called to finish setting up the layer. * namespaces. It should never return, if it does it's an error. */ - fn setup_sandbox_and_sleep_forever( + fn setup_layer_and_sleep_forever( &self, config: &Config, write_fd: &OwnedFd, @@ -810,7 +800,7 @@ impl Sandbox { )?; } - /* Mask out certain things from /proc and /sys to help isolate the sandbox. + /* Mask out certain things from /proc and /sys to help isolate the layer. * These are based off of the things that docker masks out by default, see * * https://github.com/moby/moby/blob/master/oci/defaults.go @@ -1019,7 +1009,7 @@ impl Sandbox { nix::unistd::sethostname(self.name.as_str()) .context(format!("failed to set hostname: {}", self.name))?; - // send a byte over the pipe to signal that the sandbox is initialized and + // send a byte over the pipe to signal that the layer is initialized and // ready for use nix::unistd::write(write_fd, &[0]) .context(format!("failed to write to layer ready pipe"))?; @@ -1061,7 +1051,7 @@ impl Sandbox { unsafe { __llvm_profile_set_filename( - CString::new(format!("coverage/profraw/setup_sandbox-{}-{}-%m.profraw", self.pid, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs()).as_str(),) + CString::new(format!("coverage/profraw/setup_layer-{}-{}-%m.profraw", self.pid, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs()).as_str(),) .unwrap() .as_ptr(), ); diff --git a/src/sandbox/sandbox_struct.rs b/src/layer/layer_struct.rs similarity index 78% rename from src/sandbox/sandbox_struct.rs rename to src/layer/layer_struct.rs index 3350cec..a43ed14 100644 --- a/src/sandbox/sandbox_struct.rs +++ b/src/layer/layer_struct.rs @@ -3,13 +3,13 @@ use nix::unistd::Pid; use nix::unistd::Uid; use std::path::PathBuf; -pub struct Sandbox { +pub struct Layer { pub name: String, pub base: PathBuf, pub work_base: PathBuf, pub upper_base: PathBuf, pub overlay_base: PathBuf, - pub data_storage_dir: PathBuf, // storage dir for sandbox data and nested sandboxes + pub data_storage_dir: PathBuf, // storage dir for layer data and nested layers //pub root_suffix: String, //pub root_work: PathBuf, //pub root_upper: PathBuf, diff --git a/src/sandbox/mod.rs b/src/layer/mod.rs similarity index 78% rename from src/sandbox/mod.rs rename to src/layer/mod.rs index 3f7a76e..77f7df0 100644 --- a/src/sandbox/mod.rs +++ b/src/layer/mod.rs @@ -4,11 +4,11 @@ mod delete; mod exec; mod exists; mod get_or_create; +mod layer_struct; pub mod mount_overlays; -mod sandbox_struct; mod settings; mod stop; mod unmount; -pub use sandbox_struct::*; +pub use layer_struct::*; pub use settings::*; diff --git a/src/sandbox/mount_overlays.rs b/src/layer/mount_overlays.rs similarity index 93% rename from src/sandbox/mount_overlays.rs rename to src/layer/mount_overlays.rs index e35b527..8d2e5fd 100644 --- a/src/sandbox/mount_overlays.rs +++ b/src/layer/mount_overlays.rs @@ -1,5 +1,5 @@ use crate::config::Config; -use crate::sandbox::{Sandbox, SandboxSettings}; +use crate::layer::{Layer, LayerSettings}; use crate::util::{can_mkdir, mkdir}; use anyhow::{Context, Result, anyhow}; use log::debug; @@ -22,7 +22,7 @@ pub struct MountHash { pub dir: String, } -impl Sandbox { +impl Layer { pub fn mount_overlays(&self, config: &Config) -> Result> { let mounts = self.determine_mounts(config)?; @@ -105,8 +105,8 @@ impl Sandbox { result_mounts.sort_by(|a, b| a.dir.cmp(&b.dir)); - // Save sandbox settings to settings.json in sandbox base directory - let settings = SandboxSettings::from_config(config, &result_mounts); + // Save layer settings to settings.json in layer base directory + let settings = LayerSettings::from_config(config, &result_mounts); settings .save_to_file(&self.settings_path()) .context("Failed to save layer settings")?; @@ -119,7 +119,7 @@ impl Sandbox { } pub fn determine_mounts(&self, config: &Config) -> Result> { - // Check if we have a settings.json file in our storage dir (for nested sandboxes) + // Check if we have a settings.json file in our storage dir (for nested layers) let settings_json = Path::new(&config.storage_dir).join("settings.json"); if settings_json.exists() { @@ -127,13 +127,11 @@ impl Sandbox { "It looks like we are in a nested layer, reading mounts from {}", settings_json.display() ); - let parent_settings = SandboxSettings::load_from_file( - &settings_json, - ) - .context(format!( - "Failed to read parent settings.json from {}", - settings_json.display() - ))?; + let parent_settings = LayerSettings::load_from_file(&settings_json) + .context(format!( + "Failed to read parent settings.json from {}", + settings_json.display() + ))?; return Ok(parent_settings.mounts); } @@ -172,7 +170,7 @@ impl Sandbox { CStr::from_ptr((*mnt).mnt_type).to_string_lossy() }); - /* Mount / regardless of type, in docker or another sandbox it is expected + /* Mount / regardless of type, in docker or another layer it is expected * to be an overlayfs. For all other file systems though, skip them if * they don't seem to be real file systems. */ if mnt_dir != "/" diff --git a/src/sandbox/settings.rs b/src/layer/settings.rs similarity index 96% rename from src/sandbox/settings.rs rename to src/layer/settings.rs index 436bd46..7d1d8f5 100644 --- a/src/sandbox/settings.rs +++ b/src/layer/settings.rs @@ -1,23 +1,23 @@ use crate::config::{BindMount, Config}; -use crate::sandbox::mount_overlays::MountHash; +use crate::layer::mount_overlays::MountHash; use anyhow::{Context, Result, anyhow}; use serde::{Deserialize, Serialize}; use std::path::Path; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct SandboxSettings { +pub struct LayerSettings { pub version: String, pub mounts: Vec, pub network: crate::config::Network, pub bind_mounts: Vec, - // Defaulted so settings from sandboxes started by older versions load + // Defaulted so settings from layers started by older versions load #[serde(default)] pub cpus: Option, #[serde(default)] pub memory: Option, } -impl SandboxSettings { +impl LayerSettings { pub fn from_config(config: &Config, mounts: &[MountHash]) -> Self { Self { version: env!("CARGO_PKG_VERSION").to_string(), @@ -63,7 +63,7 @@ impl SandboxSettings { "Failed to read settings.json from {}", path.display() ))?; - let settings: SandboxSettings = serde_json::from_str(&settings_json) + let settings: LayerSettings = serde_json::from_str(&settings_json) .context("Failed to parse settings.json")?; Ok(settings) } diff --git a/src/sandbox/stop.rs b/src/layer/stop.rs similarity index 86% rename from src/sandbox/stop.rs rename to src/layer/stop.rs index 70a5e09..9166568 100644 --- a/src/sandbox/stop.rs +++ b/src/layer/stop.rs @@ -1,11 +1,11 @@ -use crate::sandbox::Sandbox; -use crate::sandbox::cgroup::remove_cgroup; +use crate::layer::Layer; +use crate::layer::cgroup::remove_cgroup; use anyhow::{Context, Result}; use log::trace; use nix::{fcntl::readlink, unistd::Pid}; use std::path::{Path, PathBuf}; -impl Sandbox { +impl Layer { pub fn stop(&self) -> Result<()> { let pid = self.pid; if pid == Pid::from_raw(-1) { @@ -23,7 +23,7 @@ impl Sandbox { #[cfg(feature = "coverage")] if std::env::var_os("TEST_STOP_RACE").is_some() { - // pre-kill the sandbox process to simulate a race or otherwise + // pre-kill the layer process to simulate a race or otherwise // inability to read the pid namespace file nix::sys::signal::kill(pid, nix::sys::signal::Signal::SIGKILL)?; // wait for the process to be killed @@ -32,22 +32,22 @@ impl Sandbox { } } - // Get our sandbox namespaces - let sandbox_ns_str = format!("/proc/{}/ns/pid_for_children", pid); - trace!("layer_ns_str: {}", sandbox_ns_str); - let sandbox_ns_path = Path::new(&sandbox_ns_str); - trace!("layer_ns_path: {}", sandbox_ns_path.display()); + // Get our layer namespaces + let layer_ns_str = format!("/proc/{}/ns/pid_for_children", pid); + trace!("layer_ns_str: {}", layer_ns_str); + let layer_ns_path = Path::new(&layer_ns_str); + trace!("layer_ns_path: {}", layer_ns_path.display()); - if !sandbox_ns_path.exists() { + if !layer_ns_path.exists() { trace!("Layer process {} already gone", pid); } else { - let ns = readlink(sandbox_ns_path).context(format!( + let ns = readlink(layer_ns_path).context(format!( "failed to readlink {}", - sandbox_ns_path.display() + layer_ns_path.display() ))?; trace!("layer_ns: {}", ns.to_string_lossy()); - // Collect each process that shares a namespace with our sandbox + // Collect each process that shares a namespace with our layer for entry in std::fs::read_dir("/proc") .context(format!("failed to read /proc"))? .filter_map(Result::ok) @@ -66,7 +66,7 @@ impl Sandbox { let process_pid = Pid::from_raw(pid_str.parse::()?); - // Check if this process belongs to our sandbox namespace + // Check if this process belongs to our layer namespace let proc_ns_str = format!("/proc/{}/ns/pid", pid_str); #[cfg(feature = "coverage")] @@ -112,7 +112,7 @@ impl Sandbox { #[cfg(feature = "coverage")] if std::env::var_os("TEST_STOP_RACE2").is_some() { - // pre-kill the sandbox process to simulate a race or otherwise + // pre-kill the layer process to simulate a race or otherwise // inability to read the pid namespace file nix::sys::signal::kill( pid, diff --git a/src/sandbox/unmount.rs b/src/layer/unmount.rs similarity index 96% rename from src/sandbox/unmount.rs rename to src/layer/unmount.rs index a69eaef..20c1a53 100644 --- a/src/sandbox/unmount.rs +++ b/src/layer/unmount.rs @@ -1,10 +1,10 @@ -use crate::sandbox::Sandbox; +use crate::layer::Layer; use crate::util::get_mounts; use anyhow::Result; use log::{debug, error}; use std::ffi::CString; -impl Sandbox { +impl Layer { pub fn unmount(&self) -> Result<()> { let mut mounts = get_mounts(&self.base)?; mounts.sort_by(|a, b| b.cmp(a)); diff --git a/src/lib.rs b/src/lib.rs index fb8e24f..c040c5c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,6 @@ pub mod actions; pub mod config; +pub mod layer; pub mod logger; -pub mod sandbox; pub mod types; pub mod util; diff --git a/src/logger.rs b/src/logger.rs index dfa9759..272e69a 100644 --- a/src/logger.rs +++ b/src/logger.rs @@ -3,14 +3,14 @@ use log::{Level, LevelFilter, Log, Metadata, Record}; use std::io::{self, Write}; use std::sync::Mutex; -pub struct SandboxLogger { +pub struct DevlayerLogger { level: Mutex, output: Mutex>, deferred: Mutex>, defer_output: Mutex, } -impl SandboxLogger { +impl DevlayerLogger { pub fn new(level: LevelFilter) -> &'static Self { Box::leak(Box::new(Self { level: Mutex::new(level), @@ -54,7 +54,7 @@ impl SandboxLogger { } } -impl Log for SandboxLogger { +impl Log for DevlayerLogger { fn enabled(&self, metadata: &Metadata) -> bool { metadata.level() <= *self.level.lock().expect("Failed to lock level") } @@ -127,8 +127,8 @@ mod tests { } } - fn logger(level: LevelFilter, captured: &Captured) -> SandboxLogger { - SandboxLogger { + fn logger(level: LevelFilter, captured: &Captured) -> DevlayerLogger { + DevlayerLogger { level: Mutex::new(level), output: Mutex::new(Box::new(captured.clone())), deferred: Mutex::new(Vec::new()), @@ -136,7 +136,7 @@ mod tests { } } - fn log(logger: &SandboxLogger, level: Level, message: &str) { + fn log(logger: &DevlayerLogger, level: Level, message: &str) { logger.log( &Record::builder() .level(level) diff --git a/src/main.rs b/src/main.rs index aaf9f4c..0c3f63b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,8 +18,8 @@ pub mod actions; pub mod config; +pub mod layer; pub mod logger; -pub mod sandbox; pub mod types; pub mod util; @@ -28,9 +28,9 @@ use clap::CommandFactory; use clap_complete::CompleteEnv; use config::{cli, resolve_config}; +use layer::Layer; use log::Log; use nix::unistd::geteuid; -use sandbox::Sandbox; use serde_json::Value; use util::{ drop_privileges, print_json_output, resolve_uid_gid_home, set_json_output, @@ -39,7 +39,7 @@ use util::{ use clap::Parser; pub fn main() -> Result<()> { - let logger = logger::SandboxLogger::new(log::LevelFilter::Trace) + let logger = logger::DevlayerLogger::new(log::LevelFilter::Trace) .init() .map_err(|e| anyhow!("Failed to initialize logger: {}", e))?; let cli: cli::Args = cli::Args::parse(); @@ -55,7 +55,7 @@ pub fn main() -> Result<()> { resolve_uid_gid_home().context("Resolving uid/gid/home")?; // This is tab completion stuff. We put it after loading configs and parsing command line stuff - // so that we can use the potential storage directory specified to complete the sandbox names. + // so that we can use the potential storage directory specified to complete the layer names. // This function will not return if there is tab completion requested. if std::env::var("COMPLETE").is_ok() { drop_privileges(uid_gid_home.uid, uid_gid_home.gid)?; @@ -79,10 +79,10 @@ pub fn main() -> Result<()> { } // Figure out who we really are - let sandboxes_storage_dir = config.storage_dir.clone(); + let layers_storage_dir = config.storage_dir.clone(); - let sandbox = Sandbox::from_location( - &sandboxes_storage_dir, + let layer = Layer::from_location( + &layers_storage_dir, &config.name, uid_gid_home.uid, uid_gid_home.gid, @@ -94,62 +94,56 @@ pub fn main() -> Result<()> { cli::Action::Config { keys } => actions::config(&config, keys), cli::Action::Sync => actions::sync(), cli::Action::List { patterns } => actions::list( - &sandboxes_storage_dir, + &layers_storage_dir, &patterns.unwrap_or_default(), ), cli::Action::Stop { all, patterns } => { if all { actions::stop_all( - &sandboxes_storage_dir, + &layers_storage_dir, uid_gid_home.uid, uid_gid_home.gid, &["*".to_string()], ) } else if let Some(patterns) = patterns { actions::stop_all( - &sandboxes_storage_dir, + &layers_storage_dir, uid_gid_home.uid, uid_gid_home.gid, &patterns, ) } else { actions::stop( - &sandboxes_storage_dir, + &layers_storage_dir, &config.name, uid_gid_home.uid, uid_gid_home.gid, ) } } - cli::Action::Status { patterns } => actions::status( - &config, - &sandbox, - &patterns.unwrap_or_default(), - ), + cli::Action::Status { patterns } => { + actions::status(&config, &layer, &patterns.unwrap_or_default()) + } cli::Action::Diff { patterns } => actions::diff( &config, cli.json, - &sandbox, - &patterns.unwrap_or_default(), - ), - cli::Action::Reject { patterns } => actions::reject( - &config, - &sandbox, - &patterns.unwrap_or_default(), - ), - cli::Action::Accept { patterns } => actions::accept( - &config, - &sandbox, + &layer, &patterns.unwrap_or_default(), ), + cli::Action::Reject { patterns } => { + actions::reject(&config, &layer, &patterns.unwrap_or_default()) + } + cli::Action::Accept { patterns } => { + actions::accept(&config, &layer, &patterns.unwrap_or_default()) + } cli::Action::Delete { yes, patterns } => actions::delete( &config, - &sandboxes_storage_dir, + &layers_storage_dir, &patterns.unwrap_or_default(), yes, ), cli::Action::Clean { yes } => { - actions::clean(&config, &sandboxes_storage_dir, yes) + actions::clean(&config, &layers_storage_dir, yes) } }; if cli.json { @@ -180,17 +174,17 @@ pub fn main() -> Result<()> { } // - // If no subcommand was specified, we're running a command in the sandbox + // If no subcommand was specified, we're running a command in the layer // - let sandboxed_command = match cli.sandboxed_command { - Some(sandboxed_command) => sandboxed_command, + let layered_command = match cli.layered_command { + Some(layered_command) => layered_command, None => vec![std::env::var("SHELL").unwrap_or("sh".to_string())], }; - let sandbox = - Sandbox::get_or_create(&config, uid_gid_home.uid, uid_gid_home.gid) + let layer = + Layer::get_or_create(&config, uid_gid_home.uid, uid_gid_home.gid) .context("Getting or creating layer")?; // On success, we never actually return from this call - sandbox.exec(&sandboxed_command) + layer.exec(&layered_command) } diff --git a/src/util/get_running_sandbox_pid.rs b/src/util/get_running_layer_pid.rs similarity index 71% rename from src/util/get_running_sandbox_pid.rs rename to src/util/get_running_layer_pid.rs index 73b6898..fa38785 100644 --- a/src/util/get_running_sandbox_pid.rs +++ b/src/util/get_running_layer_pid.rs @@ -5,16 +5,16 @@ use std::path::PathBuf; use log::trace; /** - * Get the PID of a running sandbox. + * Get the PID of a running layer. * - * Returns None if the sandbox is not running. + * Returns None if the layer is not running. */ -pub fn get_running_sandbox_pid( - sandboxes_storage_dir: &Path, - sandbox_name: &str, +pub fn get_running_layer_pid( + layers_storage_dir: &Path, + layer_name: &str, ) -> Option { - let sandboxes_storage_dir = &PathBuf::from(sandboxes_storage_dir); - let pid_file = get_sandbox_pid_path(sandboxes_storage_dir, sandbox_name); + let layers_storage_dir = &PathBuf::from(layers_storage_dir); + let pid_file = get_layer_pid_path(layers_storage_dir, layer_name); if pid_file.exists() { match std::fs::read_to_string(&pid_file) .ok() @@ -24,7 +24,7 @@ pub fn get_running_sandbox_pid( .and_then(|pid| { trace!( "Existing layer '{}' found with PID: {}", - sandbox_name, pid + layer_name, pid ); std::fs::read_to_string(format!("/proc/{}/stat", pid.as_raw())) @@ -51,9 +51,9 @@ pub fn get_running_sandbox_pid( None } -pub fn get_sandbox_pid_path( - sandboxes_storage_dir: &Path, - sandbox_name: &str, +pub fn get_layer_pid_path( + layers_storage_dir: &Path, + layer_name: &str, ) -> PathBuf { - sandboxes_storage_dir.join(format!("{}.pid", sandbox_name)) + layers_storage_dir.join(format!("{}.pid", layer_name)) } diff --git a/src/util/lock_sandbox.rs b/src/util/lock_layer.rs similarity index 80% rename from src/util/lock_sandbox.rs rename to src/util/lock_layer.rs index 98bdfb6..416e69e 100644 --- a/src/util/lock_sandbox.rs +++ b/src/util/lock_layer.rs @@ -13,13 +13,12 @@ pub struct Lock { } impl Lock { - /** Acquire a lock on the sandbox storage directory. */ - pub fn sandbox( - sandboxes_storage_dir: &Path, - sandbox_name: &str, + /** Acquire a lock on the layer storage directory. */ + pub fn layer( + layers_storage_dir: &Path, + layer_name: &str, ) -> Result> { - let lock_file = - sandboxes_storage_dir.join(format!("{}.lock", sandbox_name)); + let lock_file = layers_storage_dir.join(format!("{}.lock", layer_name)); trace!("Acquiring lock {}", lock_file.display()); let file = match OpenOptions::new() .create(true) @@ -32,7 +31,7 @@ impl Lock { Err(e) => { return Err(anyhow!( "Failed to open lock file for layer {}: {}", - sandbox_name, + layer_name, e )); } diff --git a/src/util/mod.rs b/src/util/mod.rs index 2a34c57..0adeb47 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -3,8 +3,8 @@ mod clone3; mod drop_privileges; mod expand_tilde; mod find_mount_point; -mod get_running_sandbox_pid; -mod lock_sandbox; +mod get_running_layer_pid; +mod lock_layer; mod mkdir; mod mount; mod mounts; @@ -17,8 +17,8 @@ pub use clone3::*; pub use drop_privileges::*; pub use expand_tilde::*; pub use find_mount_point::*; -pub use get_running_sandbox_pid::*; -pub use lock_sandbox::*; +pub use get_running_layer_pid::*; +pub use lock_layer::*; pub use mkdir::*; pub use mount::*; pub use mounts::*; diff --git a/tests/ai_cli_flags.rs b/tests/ai_cli_flags.rs index b92bd13..d57b64a 100644 --- a/tests/ai_cli_flags.rs +++ b/tests/ai_cli_flags.rs @@ -5,84 +5,84 @@ use fixtures::*; use rstest::*; #[rstest] -fn test_flags_before_action(mut sandbox: SandboxManager) -> Result<()> { +fn test_flags_before_action(mut layer: LayerManager) -> Result<()> { // Disable default -v flag to avoid conflicts - sandbox.no_default_options = true; - let name = sandbox.name.clone(); + layer.no_default_options = true; + let name = layer.name.clone(); // Test flags before action - traditional style - assert!(sandbox.pass(&["--name", &name, "config"])); + assert!(layer.pass(&["--name", &name, "config"])); assert!( - sandbox + layer .last_stdout .contains(format!("name={}", name).as_str()) ); - assert!(sandbox.pass(&["--name", &name, "--net=host", "config"])); - assert!(sandbox.last_stdout.contains("net=host")); + assert!(layer.pass(&["--name", &name, "--net=host", "config"])); + assert!(layer.last_stdout.contains("net=host")); - assert!(sandbox.pass(&["--name", &name, "-v", "config"])); - assert!(sandbox.last_stdout.contains("log_level=TRACE")); + assert!(layer.pass(&["--name", &name, "-v", "config"])); + assert!(layer.last_stdout.contains("log_level=TRACE")); - assert!(sandbox.pass(&["--name", &name, "--log-level=debug", "config"])); - assert!(sandbox.last_stdout.contains("log_level=DEBUG")); + assert!(layer.pass(&["--name", &name, "--log-level=debug", "config"])); + assert!(layer.last_stdout.contains("log_level=DEBUG")); - assert!(sandbox.pass(&["--name", &name, "--json", "config"])); + assert!(layer.pass(&["--name", &name, "--json", "config"])); // JSON output should be valid JSON assert!( - serde_json::from_str::(&sandbox.last_stdout).is_ok() + serde_json::from_str::(&layer.last_stdout).is_ok() ); // Test a simple action without extra flags - assert!(sandbox.pass(&["--name", &name, "status"])); + assert!(layer.pass(&["--name", &name, "status"])); Ok(()) } #[rstest] -fn test_flags_after_action(mut sandbox: SandboxManager) -> Result<()> { +fn test_flags_after_action(mut layer: LayerManager) -> Result<()> { // Disable default -v flag to avoid conflicts - sandbox.no_default_options = true; - let name = sandbox.name.clone(); + layer.no_default_options = true; + let name = layer.name.clone(); // Test flags after action - new flexible style - assert!(sandbox.pass(&["config", "--name", "test-after"])); - assert!(sandbox.last_stdout.contains("name=test-after")); + assert!(layer.pass(&["config", "--name", "test-after"])); + assert!(layer.last_stdout.contains("name=test-after")); - assert!(sandbox.pass(&["--name", &name, "config", "--net=host"])); - assert!(sandbox.last_stdout.contains("net=host")); + assert!(layer.pass(&["--name", &name, "config", "--net=host"])); + assert!(layer.last_stdout.contains("net=host")); - assert!(sandbox.pass(&["--name", &name, "config", "-v"])); - assert!(sandbox.last_stdout.contains("log_level=TRACE")); + assert!(layer.pass(&["--name", &name, "config", "-v"])); + assert!(layer.last_stdout.contains("log_level=TRACE")); - assert!(sandbox.pass(&["--name", &name, "config", "--log-level=debug"])); - assert!(sandbox.last_stdout.contains("log_level=DEBUG")); + assert!(layer.pass(&["--name", &name, "config", "--log-level=debug"])); + assert!(layer.last_stdout.contains("log_level=DEBUG")); - assert!(sandbox.pass(&["--name", &name, "config", "--json"])); + assert!(layer.pass(&["--name", &name, "config", "--json"])); // JSON output should be valid JSON assert!( - serde_json::from_str::(&sandbox.last_stdout).is_ok() + serde_json::from_str::(&layer.last_stdout).is_ok() ); // Test a simple action without extra flags - assert!(sandbox.pass(&["--name", &name, "status"])); + assert!(layer.pass(&["--name", &name, "status"])); Ok(()) } #[rstest] -fn test_flags_mixed_position(mut sandbox: SandboxManager) -> Result<()> { +fn test_flags_mixed_position(mut layer: LayerManager) -> Result<()> { // Test mixing flags before and after action - assert!(sandbox.pass(&["--name", "test-mixed", "config", "--net=host"])); - assert!(sandbox.last_stdout.contains("name=test-mixed")); - assert!(sandbox.last_stdout.contains("net=host")); + assert!(layer.pass(&["--name", "test-mixed", "config", "--net=host"])); + assert!(layer.last_stdout.contains("name=test-mixed")); + assert!(layer.last_stdout.contains("net=host")); - assert!(sandbox.pass(&["-v", "config", "--net=none"])); - assert!(sandbox.last_stdout.contains("log_level=TRACE")); - assert!(sandbox.last_stdout.contains("net=none")); + assert!(layer.pass(&["-v", "config", "--net=none"])); + assert!(layer.last_stdout.contains("log_level=TRACE")); + assert!(layer.last_stdout.contains("net=none")); - assert!(sandbox.pass(&["--json", "config", "--name=json-test", "-v"])); - let json: serde_json::Value = serde_json::from_str(&sandbox.last_stdout)?; + assert!(layer.pass(&["--json", "config", "--name=json-test", "-v"])); + let json: serde_json::Value = serde_json::from_str(&layer.last_stdout)?; assert_eq!(json["name"], "json-test"); assert_eq!(json["log_level"], "TRACE"); @@ -90,30 +90,30 @@ fn test_flags_mixed_position(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_flags_with_complex_actions(mut sandbox: SandboxManager) -> Result<()> { +fn test_flags_with_complex_actions(mut layer: LayerManager) -> Result<()> { // Create a test file to test actions - sandbox.run(&["sh", "-c", "echo test > testfile.txt"])?; + layer.run(&["sh", "-c", "echo test > testfile.txt"])?; // Test flags with various actions that take arguments - assert!(sandbox.pass(&["status", "testfile.txt", "--json"])); + assert!(layer.pass(&["status", "testfile.txt", "--json"])); assert!( - serde_json::from_str::(&sandbox.last_stdout).is_ok() + serde_json::from_str::(&layer.last_stdout).is_ok() ); - assert!(sandbox.pass(&["--json", "status", "testfile.txt"])); + assert!(layer.pass(&["--json", "status", "testfile.txt"])); assert!( - serde_json::from_str::(&sandbox.last_stdout).is_ok() + serde_json::from_str::(&layer.last_stdout).is_ok() ); // Test with list action instead of diff (diff doesn't support JSON) - assert!(sandbox.pass(&["list", "--json"])); + assert!(layer.pass(&["list", "--json"])); assert!( - serde_json::from_str::(&sandbox.last_stdout).is_ok() + serde_json::from_str::(&layer.last_stdout).is_ok() ); - assert!(sandbox.pass(&["--json", "list"])); + assert!(layer.pass(&["--json", "list"])); assert!( - serde_json::from_str::(&sandbox.last_stdout).is_ok() + serde_json::from_str::(&layer.last_stdout).is_ok() ); Ok(()) @@ -121,77 +121,77 @@ fn test_flags_with_complex_actions(mut sandbox: SandboxManager) -> Result<()> { #[rstest] fn test_flag_errors_in_different_positions( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { // Test invalid flag values in different positions - assert!(sandbox.xfail(&["--net=invalid", "config"])); - assert!(sandbox.xfail(&["config", "--net=invalid"])); - assert!(sandbox.xfail(&["--bind-fuse=invalid", "config"])); - assert!(sandbox.xfail(&["config", "--bind-fuse=invalid"])); + assert!(layer.xfail(&["--net=invalid", "config"])); + assert!(layer.xfail(&["config", "--net=invalid"])); + assert!(layer.xfail(&["--bind-fuse=invalid", "config"])); + assert!(layer.xfail(&["config", "--bind-fuse=invalid"])); // Test unknown flags in different positions - assert!(sandbox.xfail(&["--unknown-flag", "config"])); - assert!(sandbox.xfail(&["config", "--unknown-flag"])); + assert!(layer.xfail(&["--unknown-flag", "config"])); + assert!(layer.xfail(&["config", "--unknown-flag"])); Ok(()) } #[rstest] -fn test_boolean_flags_positioning(mut sandbox: SandboxManager) -> Result<()> { +fn test_boolean_flags_positioning(mut layer: LayerManager) -> Result<()> { // Disable default ignored flag to avoid conflicts - sandbox.set_ignored(false); + layer.set_ignored(false); // Test boolean flags without values in different positions - assert!(sandbox.pass(&["--ignored", "config"])); - assert!(sandbox.last_stdout.contains("ignored=true")); + assert!(layer.pass(&["--ignored", "config"])); + assert!(layer.last_stdout.contains("ignored=true")); - sandbox.set_ignored(false); - assert!(sandbox.pass(&["config", "--ignored"])); - assert!(sandbox.last_stdout.contains("ignored=true")); + layer.set_ignored(false); + assert!(layer.pass(&["config", "--ignored"])); + assert!(layer.last_stdout.contains("ignored=true")); - sandbox.set_ignored(false); - assert!(sandbox.pass(&["--json", "config", "--ignored"])); - let json: serde_json::Value = serde_json::from_str(&sandbox.last_stdout)?; + layer.set_ignored(false); + assert!(layer.pass(&["--json", "config", "--ignored"])); + let json: serde_json::Value = serde_json::from_str(&layer.last_stdout)?; assert_eq!(json["ignored"], "true"); Ok(()) } #[rstest] -fn test_short_flags_positioning(mut sandbox: SandboxManager) -> Result<()> { +fn test_short_flags_positioning(mut layer: LayerManager) -> Result<()> { // Test short flags in different positions - assert!(sandbox.pass(&["-v", "config"])); - assert!(sandbox.last_stdout.contains("log_level=TRACE")); + assert!(layer.pass(&["-v", "config"])); + assert!(layer.last_stdout.contains("log_level=TRACE")); - assert!(sandbox.pass(&["config", "-v"])); - assert!(sandbox.last_stdout.contains("log_level=TRACE")); + assert!(layer.pass(&["config", "-v"])); + assert!(layer.last_stdout.contains("log_level=TRACE")); // Test combining with other flags - assert!(sandbox.pass(&["-v", "config", "--json"])); - let json: serde_json::Value = serde_json::from_str(&sandbox.last_stdout)?; + assert!(layer.pass(&["-v", "config", "--json"])); + let json: serde_json::Value = serde_json::from_str(&layer.last_stdout)?; assert_eq!(json["log_level"], "TRACE"); Ok(()) } #[rstest] -fn test_no_config_flag_positioning(mut sandbox: SandboxManager) -> Result<()> { - sandbox.no_default_options = true; +fn test_no_config_flag_positioning(mut layer: LayerManager) -> Result<()> { + layer.no_default_options = true; // Test --no-config flag in different positions - assert!(sandbox.pass(&["--no-config", "config"])); + assert!(layer.pass(&["--no-config", "config"])); // Should show defaults when no config is loaded - assert!(sandbox.last_stdout.contains("net=none")); + assert!(layer.last_stdout.contains("net=none")); - assert!(sandbox.pass(&["config", "--no-config"])); - assert!(sandbox.last_stdout.contains("net=none")); + assert!(layer.pass(&["config", "--no-config"])); + assert!(layer.last_stdout.contains("net=none")); // Test with other flags - assert!(sandbox.pass(&["--no-config", "--net=host", "config"])); - assert!(sandbox.last_stdout.contains("net=host")); + assert!(layer.pass(&["--no-config", "--net=host", "config"])); + assert!(layer.last_stdout.contains("net=host")); - assert!(sandbox.pass(&["config", "--no-config", "--net=host"])); - assert!(sandbox.last_stdout.contains("net=host")); + assert!(layer.pass(&["config", "--no-config", "--net=host"])); + assert!(layer.last_stdout.contains("net=host")); Ok(()) } diff --git a/tests/ai_test_accept.rs b/tests/ai_test_accept.rs index 68fd16a..3579ab1 100644 --- a/tests/ai_test_accept.rs +++ b/tests/ai_test_accept.rs @@ -7,28 +7,28 @@ use std::path::Path; #[rstest] fn test_accept_directory_removal_counting( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { // Create a directory with multiple files inside - let dirname = sandbox.test_filename("dir-with-files"); + let dirname = layer.test_filename("dir-with-files"); let file1 = format!("{}/file1.txt", dirname); let file2 = format!("{}/file2.txt", dirname); let subdir = format!("{}/subdir", dirname); let file3 = format!("{}/file3.txt", subdir); - // Create the structure outside the sandbox first + // Create the structure outside the layer first std::fs::create_dir(&dirname)?; std::fs::write(&file1, "content1")?; std::fs::write(&file2, "content2")?; std::fs::create_dir(&subdir)?; std::fs::write(&file3, "content3")?; - // Now remove the entire directory inside the sandbox - sandbox.run(&["rm", "-rf", &dirname])?; + // Now remove the entire directory inside the layer + layer.run(&["rm", "-rf", &dirname])?; // First check the status to see what changes are detected - sandbox.run(&["status"])?; - let status_output = sandbox.last_stdout.clone(); + layer.run(&["status"])?; + let status_output = layer.last_stdout.clone(); println!("Full status output:\n{}", status_output); // Count only the removals in our test directory from the status output @@ -39,15 +39,15 @@ fn test_accept_directory_removal_counting( let removal_count = status_lines.len(); // Accept all changes - we'll filter by the dirname in our counting - sandbox.run(&["accept"])?; + layer.run(&["accept"])?; // The output should show the actual count of changes // This will help us verify if there's double counting - println!("Accept output: {}", sandbox.last_stdout); + println!("Accept output: {}", layer.last_stdout); // With the fix, we now count only the parent directories and avoid counting // files that are removed as part of their parent directory removal - let output = &sandbox.last_stdout; + let output = &layer.last_stdout; println!("Number of removals in test directory: {}", removal_count); // Check for the "external or non-matching" message @@ -103,34 +103,34 @@ fn test_accept_directory_removal_counting( #[rstest] fn test_accept_pretend_count_mixed_operations( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { // Test that pretend count matches actual count for various operations // Create files to modify - let file1 = sandbox.test_filename("modify-file.txt"); - let file2 = sandbox.test_filename("delete-file.txt"); - let file3 = sandbox.test_filename("rename-source.txt"); - let file4 = sandbox.test_filename("rename-dest.txt"); + let file1 = layer.test_filename("modify-file.txt"); + let file2 = layer.test_filename("delete-file.txt"); + let file3 = layer.test_filename("rename-source.txt"); + let file4 = layer.test_filename("rename-dest.txt"); - // Create initial files outside sandbox + // Create initial files outside layer std::fs::write(&file1, "original")?; std::fs::write(&file2, "to delete")?; std::fs::write(&file3, "to rename")?; - // Perform operations inside sandbox - sandbox.run(&["sh", "-c", &format!("echo modified > {}", file1)])?; // Modify - sandbox.run(&["rm", &file2])?; // Remove - sandbox.run(&["mv", &file3, &file4])?; // Rename - sandbox.run(&["touch", sandbox.test_filename("new-file.txt").as_str()])?; // Create + // Perform operations inside layer + layer.run(&["sh", "-c", &format!("echo modified > {}", file1)])?; // Modify + layer.run(&["rm", &file2])?; // Remove + layer.run(&["mv", &file3, &file4])?; // Rename + layer.run(&["touch", layer.test_filename("new-file.txt").as_str()])?; // Create // Check status first to see what changes exist - sandbox.run(&["status"])?; - println!("Status output:\n{}", sandbox.last_stdout); + layer.run(&["status"])?; + println!("Status output:\n{}", layer.last_stdout); // Accept changes and verify counts - sandbox.run(&["accept"])?; - let output = sandbox.last_stdout.clone(); + layer.run(&["accept"])?; + let output = layer.last_stdout.clone(); println!("Accept output:\n{}", output); // Extract counts @@ -167,19 +167,19 @@ fn test_accept_pretend_count_mixed_operations( #[rstest] fn test_accept_file_in_new_directory_counts_once( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { // Test that creating a file in a new directory only counts as 1 change - let dirname = sandbox.test_filename("new-dir"); + let dirname = layer.test_filename("new-dir"); let filename = format!("{}/new-file.txt", dirname); - // Create file in new directory inside sandbox (this will create the directory too) - sandbox.run(&["mkdir", "-p", &dirname])?; - sandbox.run(&["sh", "-c", &format!("echo content > {}", filename)])?; + // Create file in new directory inside layer (this will create the directory too) + layer.run(&["mkdir", "-p", &dirname])?; + layer.run(&["sh", "-c", &format!("echo content > {}", filename)])?; // Check status to see what changes are detected - sandbox.run(&["status"])?; - let status_output = sandbox.last_stdout.clone(); + layer.run(&["status"])?; + let status_output = layer.last_stdout.clone(); println!("Status output:\n{}", status_output); // Count our specific changes from status @@ -194,8 +194,8 @@ fn test_accept_file_in_new_directory_counts_once( } // Accept changes - sandbox.run(&["accept"])?; - let output = sandbox.last_stdout.clone(); + layer.run(&["accept"])?; + let output = layer.last_stdout.clone(); println!("Accept output:\n{}", output); // Extract count @@ -227,20 +227,20 @@ fn test_accept_file_in_new_directory_counts_once( #[rstest] fn test_accept_file_in_depth_2_directory( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { // Test that creating a file in depth 2 directory only counts as 1 change - let dir1 = sandbox.test_filename("dir1"); + let dir1 = layer.test_filename("dir1"); let dir2 = format!("{}/dir2", dir1); let filename = format!("{}/file.txt", dir2); - // Create file in depth 2 directory inside sandbox - sandbox.run(&["mkdir", "-p", &dir2])?; - sandbox.run(&["touch", &filename])?; + // Create file in depth 2 directory inside layer + layer.run(&["mkdir", "-p", &dir2])?; + layer.run(&["touch", &filename])?; // Check status to see what changes are detected - sandbox.run(&["status"])?; - let status_output = sandbox.last_stdout.clone(); + layer.run(&["status"])?; + let status_output = layer.last_stdout.clone(); println!("Status output:\n{}", status_output); // Count our specific changes from status @@ -255,8 +255,8 @@ fn test_accept_file_in_depth_2_directory( } // Accept all changes (not just our directory) - sandbox.run(&["accept"])?; - let output = sandbox.last_stdout.clone(); + layer.run(&["accept"])?; + let output = layer.last_stdout.clone(); println!("Accept output:\n{}", output); // Extract count @@ -300,25 +300,25 @@ fn test_accept_file_in_depth_2_directory( #[rstest] fn test_accept_directory_removal_counts_all_components( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { // Test that removing a directory structure counts each component // Create a/b/c structure - let dir_a = sandbox.test_filename("a"); + let dir_a = layer.test_filename("a"); let dir_b = format!("{}/b", dir_a); let dir_c = format!("{}/c", dir_b); - // Create the structure outside sandbox + // Create the structure outside layer std::fs::create_dir(&dir_a)?; std::fs::create_dir(&dir_b)?; std::fs::create_dir(&dir_c)?; - // Remove the entire structure inside sandbox - sandbox.run(&["rm", "-rf", &dir_a])?; + // Remove the entire structure inside layer + layer.run(&["rm", "-rf", &dir_a])?; // Check status - sandbox.run(&["status"])?; - let status_output = sandbox.last_stdout.clone(); + layer.run(&["status"])?; + let status_output = layer.last_stdout.clone(); println!("Status output:\n{}", status_output); // Count removals @@ -329,8 +329,8 @@ fn test_accept_directory_removal_counts_all_components( println!("Removal count: {}", removal_count); // Accept all changes (not filtered by pattern to avoid issues) - sandbox.run(&["accept"])?; - let output = sandbox.last_stdout.clone(); + layer.run(&["accept"])?; + let output = layer.last_stdout.clone(); println!("Accept output:\n{}", output); // Extract count @@ -366,12 +366,12 @@ fn test_accept_directory_removal_counts_all_components( #[rstest] fn test_accept_non_matching_count_message( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { // Test that the non-matching count message appears correctly // Create files in different directories - let file_in_test_dir = sandbox.test_filename("test-file.txt"); + let file_in_test_dir = layer.test_filename("test-file.txt"); let other_dir = "some-other-dir"; let file_in_other_dir = format!("{}/other-file.txt", other_dir); @@ -379,22 +379,22 @@ fn test_accept_non_matching_count_message( std::fs::create_dir_all(other_dir)?; std::fs::write(&file_in_other_dir, "other content")?; - // Inside sandbox: modify both files - sandbox.run(&["sh", "-c", &format!("echo test > {}", file_in_test_dir)])?; - sandbox.run(&[ + // Inside layer: modify both files + layer.run(&["sh", "-c", &format!("echo test > {}", file_in_test_dir)])?; + layer.run(&[ "sh", "-c", &format!("echo modified > {}", file_in_other_dir), ])?; // Check status to see all changes - sandbox.run(&["status"])?; - let status_output = sandbox.last_stdout.clone(); + layer.run(&["status"])?; + let status_output = layer.last_stdout.clone(); println!("Status output:\n{}", status_output); // Accept only changes in our test directory (using pattern) - sandbox.run(&["accept", &format!("{}*", sandbox.test_filename(""))])?; - let output = sandbox.last_stdout.clone(); + layer.run(&["accept", &format!("{}*", layer.test_filename(""))])?; + let output = layer.last_stdout.clone(); println!("Accept output:\n{}", output); // Check for the non-matching message diff --git a/tests/ai_test_audio.rs b/tests/ai_test_audio.rs index ab7270e..11b4bb4 100644 --- a/tests/ai_test_audio.rs +++ b/tests/ai_test_audio.rs @@ -6,7 +6,7 @@ use rstest::*; use std::fs; use std::path::Path; -/// Host paths that --audio should bind into the sandbox, limited to the ones +/// Host paths that --audio should bind into the layer, limited to the ones /// that exist on this machine fn host_audio_paths() -> Vec { let mut paths = vec![]; @@ -26,66 +26,64 @@ fn host_audio_paths() -> Vec { /// Writes a config file with the given contents and returns its path fn write_config( - sandbox: &SandboxManager, + layer: &LayerManager, prefix: &str, contents: &str, ) -> Result { - let path = format!("{}.toml", sandbox.test_filename(prefix)); + let path = format!("{}.toml", layer.test_filename(prefix)); fs::write(&path, contents)?; Ok(path) } #[rstest] -fn ai_test_audio_disabled_by_default( - mut sandbox: SandboxManager, -) -> Result<()> { - sandbox.run(&["--no-config", "config", "audio"])?; - assert_eq!(sandbox.last_stdout.trim(), "false"); +fn ai_test_audio_disabled_by_default(mut layer: LayerManager) -> Result<()> { + layer.run(&["--no-config", "config", "audio"])?; + assert_eq!(layer.last_stdout.trim(), "false"); - sandbox.run(&["--no-config", "config", "bind"])?; + layer.run(&["--no-config", "config", "bind"])?; for path in host_audio_paths() { - assert!(!sandbox.last_stdout.contains(&path)); + assert!(!layer.last_stdout.contains(&path)); } Ok(()) } #[rstest] -fn ai_test_audio_flag(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run(&["--no-config", "--audio", "config", "audio"])?; - assert_eq!(sandbox.last_stdout.trim(), "true"); +fn ai_test_audio_flag(mut layer: LayerManager) -> Result<()> { + layer.run(&["--no-config", "--audio", "config", "audio"])?; + assert_eq!(layer.last_stdout.trim(), "true"); - sandbox.run(&["--no-config", "--audio", "config", "bind"])?; + layer.run(&["--no-config", "--audio", "config", "bind"])?; for path in host_audio_paths() { - assert!(sandbox.last_stdout.contains(&path)); + assert!(layer.last_stdout.contains(&path)); } Ok(()) } #[rstest] -fn ai_test_audio_env(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run_with_env( +fn ai_test_audio_env(mut layer: LayerManager) -> Result<()> { + layer.run_with_env( &["--no-config", "config", "audio"], "DEVLAYER_AUDIO", "true", )?; - assert_eq!(sandbox.last_stdout.trim(), "true"); + assert_eq!(layer.last_stdout.trim(), "true"); - sandbox.run_with_env( + layer.run_with_env( &["--no-config", "config", "audio"], "DEVLAYER_AUDIO", "false", )?; - assert_eq!(sandbox.last_stdout.trim(), "false"); + assert_eq!(layer.last_stdout.trim(), "false"); - assert!(sandbox.exfail( + assert!(layer.exfail( &["--no-config", "config", "audio"], "DEVLAYER_AUDIO", "yes" )); assert!( - sandbox + layer .last_stderr .contains("Invalid value for DEVLAYER_AUDIO") ); @@ -94,44 +92,42 @@ fn ai_test_audio_env(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn ai_test_audio_config_file(mut sandbox: SandboxManager) -> Result<()> { - let config = write_config(&sandbox, "audio", "audio = true")?; +fn ai_test_audio_config_file(mut layer: LayerManager) -> Result<()> { + let config = write_config(&layer, "audio", "audio = true")?; - sandbox.run(&["--config", &config, "config", "audio"])?; - assert_eq!(sandbox.last_stdout.trim(), "true"); + layer.run(&["--config", &config, "config", "audio"])?; + assert_eq!(layer.last_stdout.trim(), "true"); // The environment takes precedence over config files - sandbox.run_with_env( + layer.run_with_env( &["--config", &config, "config", "audio"], "DEVLAYER_AUDIO", "false", )?; - assert_eq!(sandbox.last_stdout.trim(), "false"); + assert_eq!(layer.last_stdout.trim(), "false"); Ok(()) } #[rstest] -fn ai_test_audio_with_no_default_binds( - mut sandbox: SandboxManager, -) -> Result<()> { - sandbox.run(&[ +fn ai_test_audio_with_no_default_binds(mut layer: LayerManager) -> Result<()> { + layer.run(&[ "--no-config", "--no-default-binds", "--audio", "config", "bind", ])?; - assert!(!sandbox.last_stdout.contains("/dev/fuse")); + assert!(!layer.last_stdout.contains("/dev/fuse")); for path in host_audio_paths() { - assert!(sandbox.last_stdout.contains(&path)); + assert!(layer.last_stdout.contains(&path)); } Ok(()) } #[rstest] -fn ai_test_audio_mounted_in_sandbox(mut sandbox: SandboxManager) -> Result<()> { +fn ai_test_audio_mounted_in_layer(mut layer: LayerManager) -> Result<()> { let paths = host_audio_paths(); // Without audio devices or sockets, e.g. on CI runners, --audio has @@ -142,22 +138,22 @@ fn ai_test_audio_mounted_in_sandbox(mut sandbox: SandboxManager) -> Result<()> { } for path in &paths { - assert!(sandbox.xfail(&["--no-config", "test", "-e", path])); + assert!(layer.xfail(&["--no-config", "test", "-e", path])); } - // Changing audio for a running sandbox requires a restart - assert!(sandbox.xfail(&["--no-config", "--audio", "true"])); - sandbox.run(&["stop"])?; + // Changing audio for a running layer requires a restart + assert!(layer.xfail(&["--no-config", "--audio", "true"])); + layer.run(&["stop"])?; for path in &paths { - assert!(sandbox.pass(&["--no-config", "--audio", "test", "-e", path])); + assert!(layer.pass(&["--no-config", "--audio", "test", "-e", path])); } // Parent directories created for the sockets mirror the host's ownership // so that clients like pactl will trust XDG_RUNTIME_DIR if let Ok(xdg_runtime_dir) = std::env::var("XDG_RUNTIME_DIR") { if Path::new(&xdg_runtime_dir).join("pulse").exists() { - sandbox.run(&[ + layer.run(&[ "--no-config", "--audio", "stat", @@ -168,7 +164,7 @@ fn ai_test_audio_mounted_in_sandbox(mut sandbox: SandboxManager) -> Result<()> { let host = fs::metadata(&xdg_runtime_dir)?; use std::os::unix::fs::MetadataExt; assert_eq!( - sandbox.last_stdout.trim(), + layer.last_stdout.trim(), format!("{} {:o}", host.uid(), host.mode() & 0o7777) ); } @@ -179,19 +175,19 @@ fn ai_test_audio_mounted_in_sandbox(mut sandbox: SandboxManager) -> Result<()> { #[rstest] fn ai_test_audio_without_xdg_runtime_dir( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { // Without XDG_RUNTIME_DIR we can't find the sockets, but /dev/snd is // still bound if it exists - sandbox.run_with_env( + layer.run_with_env( &["--no-config", "--audio", "config", "bind"], "XDG_RUNTIME_DIR", "", )?; - assert!(!sandbox.last_stdout.contains("pipewire-0")); - assert!(!sandbox.last_stdout.contains("/pulse")); + assert!(!layer.last_stdout.contains("pipewire-0")); + assert!(!layer.last_stdout.contains("/pulse")); assert_eq!( - sandbox.last_stdout.contains("/dev/snd"), + layer.last_stdout.contains("/dev/snd"), Path::new("/dev/snd").exists() ); diff --git a/tests/ai_test_bind_mount_validation.rs b/tests/ai_test_bind_mount_validation.rs index babe1c8..c017552 100644 --- a/tests/ai_test_bind_mount_validation.rs +++ b/tests/ai_test_bind_mount_validation.rs @@ -6,27 +6,24 @@ use rstest::*; use std::fs; #[rstest] -fn test_bind_mount_validation_failure( - mut sandbox: SandboxManager, -) -> Result<()> { +fn test_bind_mount_validation_failure(mut layer: LayerManager) -> Result<()> { // Create temporary directories using the test filename pattern - let bind_source1 = sandbox.test_filename("bind-source-1"); - let bind_source2 = sandbox.test_filename("bind-source-2"); + let bind_source1 = layer.test_filename("bind-source-1"); + let bind_source2 = layer.test_filename("bind-source-2"); fs::create_dir_all(&bind_source1)?; fs::create_dir_all(&bind_source2)?; fs::write(format!("{}/test.txt", bind_source1), "test content")?; fs::write(format!("{}/test.txt", bind_source2), "different content")?; - // Create and start sandbox with initial bind mount + // Create and start layer with initial bind mount let initial_bind = format!("{}:{}", bind_source1, "/mnt/test"); let _output1 = - sandbox.run(&["--bind", &initial_bind, "echo", "initial setup"])?; + layer.run(&["--bind", &initial_bind, "echo", "initial setup"])?; // Try to run another command with a DIFFERENT bind mount - this should fail let different_bind = format!("{}:{}", bind_source2, "/mnt/test"); - let result = - sandbox.run(&["--bind", &different_bind, "echo", "should fail"]); + let result = layer.run(&["--bind", &different_bind, "echo", "should fail"]); // This should fail because bind mount configuration changed assert!( @@ -35,8 +32,7 @@ fn test_bind_mount_validation_failure( ); // Check that the error message shows detailed changes - let error_output = - format!("{}{}", sandbox.last_stderr, sandbox.last_stdout); + let error_output = format!("{}{}", layer.last_stderr, layer.last_stdout); assert!( error_output.contains("Bind mount configuration has changed") && error_output.contains("Removed bind mounts:") @@ -49,41 +45,37 @@ fn test_bind_mount_validation_failure( } #[rstest] -fn test_bind_mount_validation_success( - mut sandbox: SandboxManager, -) -> Result<()> { +fn test_bind_mount_validation_success(mut layer: LayerManager) -> Result<()> { // Create temporary directory using the test filename pattern - let bind_source = sandbox.test_filename("bind-source-same"); + let bind_source = layer.test_filename("bind-source-same"); fs::create_dir_all(&bind_source)?; fs::write(format!("{}/test.txt", bind_source), "test content")?; - // Create and start sandbox with bind mount + // Create and start layer with bind mount let bind_mount = format!("{}:{}", bind_source, "/mnt/test"); let _output1 = - sandbox.run(&["--bind", &bind_mount, "echo", "first command"])?; + layer.run(&["--bind", &bind_mount, "echo", "first command"])?; // Run another command with the SAME bind mount - this should succeed let _output2 = - sandbox.run(&["--bind", &bind_mount, "echo", "second command"])?; + layer.run(&["--bind", &bind_mount, "echo", "second command"])?; Ok(()) } #[rstest] -fn test_bind_mount_options_validation( - mut sandbox: SandboxManager, -) -> Result<()> { +fn test_bind_mount_options_validation(mut layer: LayerManager) -> Result<()> { // Create temporary directory using the test filename pattern - let bind_source = sandbox.test_filename("bind-source-options"); + let bind_source = layer.test_filename("bind-source-options"); fs::create_dir_all(&bind_source)?; // Start with read-write bind mount let bind_rw = format!("{}:{}", bind_source, "/mnt/test"); - let _output1 = sandbox.run(&["--bind", &bind_rw, "echo", "read-write"])?; + let _output1 = layer.run(&["--bind", &bind_rw, "echo", "read-write"])?; // Try to change to read-only bind mount - this should fail let bind_ro = format!("{}:{}:ro", bind_source, "/mnt/test"); - let result = sandbox.run(&["--bind", &bind_ro, "echo", "read-only"]); + let result = layer.run(&["--bind", &bind_ro, "echo", "read-only"]); // This should fail because bind mount options changed assert!( diff --git a/tests/ai_test_bind_mounts.rs b/tests/ai_test_bind_mounts.rs index fee6f1f..9bd6402 100644 --- a/tests/ai_test_bind_mounts.rs +++ b/tests/ai_test_bind_mounts.rs @@ -6,9 +6,9 @@ use rstest::*; use std::{fs, path::PathBuf}; #[rstest] -fn test_bind_mount_cli(mut sandbox: SandboxManager) -> Result<()> { +fn test_bind_mount_cli(mut layer: LayerManager) -> Result<()> { // Create test directory and bind mount directories - let test_dir = sandbox.test_filename("bind_cli"); + let test_dir = layer.test_filename("bind_cli"); fs::create_dir_all(&test_dir)?; let test1 = format!("{}/test1", test_dir); let test2 = format!("{}/test2", test_dir); @@ -18,33 +18,29 @@ fn test_bind_mount_cli(mut sandbox: SandboxManager) -> Result<()> { fs::create_dir_all(&mapped1)?; // Test single bind mount - assert!(sandbox.pass(&["--bind", &test1, "config"])); + assert!(layer.pass(&["--bind", &test1, "config"])); // The output will include default bind mounts too, so just check that our bind mount is included - assert!(sandbox.last_stdout.contains("bind=")); - assert!(sandbox.last_stdout.contains(&test1)); + assert!(layer.last_stdout.contains("bind=")); + assert!(layer.last_stdout.contains(&test1)); // Test multiple bind mounts with separate flags - assert!(sandbox.pass(&["--bind", &test1, "--bind", &test2, "config"])); - assert!(sandbox.last_stdout.contains(&test1)); - assert!(sandbox.last_stdout.contains(&test2)); + assert!(layer.pass(&["--bind", &test1, "--bind", &test2, "config"])); + assert!(layer.last_stdout.contains(&test1)); + assert!(layer.last_stdout.contains(&test2)); // Test comma-separated bind mounts - assert!(sandbox.pass(&[ - "--bind", - &format!("{},{}", test1, test2), - "config" - ])); - assert!(sandbox.last_stdout.contains(&test1)); - assert!(sandbox.last_stdout.contains(&test2)); + assert!(layer.pass(&["--bind", &format!("{},{}", test1, test2), "config"])); + assert!(layer.last_stdout.contains(&test1)); + assert!(layer.last_stdout.contains(&test2)); // Test bind mount with source:target format - assert!(sandbox.pass(&[ + assert!(layer.pass(&[ "--bind", &format!("{}:{}", test1, mapped1), "config" ])); assert!( - sandbox + layer .last_stdout .contains(&format!("{}:{}", test1, mapped1)) ); @@ -53,9 +49,9 @@ fn test_bind_mount_cli(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_bind_mount_env(mut sandbox: SandboxManager) -> Result<()> { +fn test_bind_mount_env(mut layer: LayerManager) -> Result<()> { // Create test directory and bind mount directories - let test_dir = sandbox.test_filename("bind_env"); + let test_dir = layer.test_filename("bind_env"); fs::create_dir_all(&test_dir)?; let test1 = format!("{}/test1", test_dir); let test2 = format!("{}/test2", test_dir); @@ -65,22 +61,22 @@ fn test_bind_mount_env(mut sandbox: SandboxManager) -> Result<()> { fs::create_dir_all(&mapped1)?; // Test environment variable using run_with_env - sandbox.run_with_env( + layer.run_with_env( &["config"], "DEVLAYER_BIND", &format!("{},{}", test1, test2), )?; - assert!(sandbox.last_stdout.contains(&test1)); - assert!(sandbox.last_stdout.contains(&test2)); + assert!(layer.last_stdout.contains(&test1)); + assert!(layer.last_stdout.contains(&test2)); // Test environment variable with source:target format - sandbox.run_with_env( + layer.run_with_env( &["config"], "DEVLAYER_BIND", &format!("{}:{}", test1, mapped1), )?; assert!( - sandbox + layer .last_stdout .contains(&format!("{}:{}", test1, mapped1)) ); @@ -91,129 +87,129 @@ fn test_bind_mount_env(mut sandbox: SandboxManager) -> Result<()> { // NOTE: test_bind_mount_additive moved to ai_isolated_bind_mount_additive.rs #[rstest] -fn test_default_bind_mounts(mut sandbox: SandboxManager) -> Result<()> { +fn test_default_bind_mounts(mut layer: LayerManager) -> Result<()> { // Test that default bind mounts are included - assert!(sandbox.pass(&["config"])); + assert!(layer.pass(&["config"])); // Default bind mounts should include some system directories // The exact list might vary by system, but /dev/fuse is commonly included: - assert!(sandbox.last_stdout.contains("/dev/fuse")); + assert!(layer.last_stdout.contains("/dev/fuse")); Ok(()) } #[rstest] -fn test_no_default_binds_flag(mut sandbox: SandboxManager) -> Result<()> { +fn test_no_default_binds_flag(mut layer: LayerManager) -> Result<()> { // Create test directory and bind mount directories - let test_dir = sandbox.test_filename("no_default_binds"); + let test_dir = layer.test_filename("no_default_binds"); fs::create_dir_all(&test_dir)?; let test1 = format!("{}/test1", test_dir); fs::create_dir_all(&test1)?; // Test that custom binds work with --no-default-binds - assert!(sandbox.pass(&["--no-default-binds", "--bind", &test1, "config"])); + assert!(layer.pass(&["--no-default-binds", "--bind", &test1, "config"])); // Should only contain the custom bind mount - assert!(sandbox.last_stdout.contains(&test1)); - assert!(!sandbox.last_stdout.contains("/dev/fuse")); + assert!(layer.last_stdout.contains(&test1)); + assert!(!layer.last_stdout.contains("/dev/fuse")); Ok(()) } #[rstest] -fn test_no_default_binds_env(mut sandbox: SandboxManager) -> Result<()> { +fn test_no_default_binds_env(mut layer: LayerManager) -> Result<()> { // Create test directory and bind mount directories - let test_dir = sandbox.test_filename("no_default_binds_env"); + let test_dir = layer.test_filename("no_default_binds_env"); fs::create_dir_all(&test_dir)?; let test1 = format!("{}/test1", test_dir); fs::create_dir_all(&test1)?; // Test that no default binds works via environment variable - sandbox.run_with_env( + layer.run_with_env( &["--no-config", "config"], "DEVLAYER_NO_DEFAULT_BINDS", "true", )?; - assert!(sandbox.last_stdout.contains("bind=\n")); + assert!(layer.last_stdout.contains("bind=\n")); // Test that custom binds still work with the env variable - sandbox.run_with_env( + layer.run_with_env( &["--bind", &test1, "--no-config", "config"], "DEVLAYER_NO_DEFAULT_BINDS", "true", )?; - assert!(sandbox.last_stdout.contains(&test1)); - assert!(!sandbox.last_stdout.contains("/dev/fuse")); + assert!(layer.last_stdout.contains(&test1)); + assert!(!layer.last_stdout.contains("/dev/fuse")); - // Test that SANDBOX_NO_DEFAULT_BINDS=false (or any other value) doesn't disable defaults - sandbox.run_with_env( + // Test that LAYER_NO_DEFAULT_BINDS=false (or any other value) doesn't disable defaults + layer.run_with_env( &["--no-config", "config"], "DEVLAYER_NO_DEFAULT_BINDS", "false", )?; - assert!(sandbox.last_stdout.contains("/dev/fuse")); + assert!(layer.last_stdout.contains("/dev/fuse")); Ok(()) } #[rstest] fn test_bind_mount_env_parsing() -> Result<()> { - let mut sandbox = SandboxManager::new(); + let mut layer = LayerManager::new(); // Test empty env var - sandbox.run_with_env( + layer.run_with_env( &["--no-default-binds", "--no-config", "config"], "DEVLAYER_BIND", "", )?; // Should have no bind mounts - assert!(sandbox.last_stdout.contains("bind=\n")); + assert!(layer.last_stdout.contains("bind=\n")); // Test env var with trailing comma - let test_dir = sandbox.test_filename("bind_env_parsing"); + let test_dir = layer.test_filename("bind_env_parsing"); fs::create_dir_all(&test_dir)?; let test1 = format!("{}/test1", test_dir); let test2 = format!("{}/test2", test_dir); fs::create_dir_all(&test1)?; fs::create_dir_all(&test2)?; - sandbox.run_with_env( + layer.run_with_env( &["--no-default-binds", "--no-config", "config"], "DEVLAYER_BIND", &format!("{},{},", test1, test2), )?; // Should have the two bind mounts (trailing comma is ignored) - assert!(sandbox.last_stdout.contains(&test1)); - assert!(sandbox.last_stdout.contains(&test2)); + assert!(layer.last_stdout.contains(&test1)); + assert!(layer.last_stdout.contains(&test2)); // Test empty env var combined with CLI bind mount - sandbox.run_with_env( + layer.run_with_env( &["--bind", &test1, "--no-config", "config"], "DEVLAYER_BIND", "", )?; // Should have the CLI bind mount - assert!(sandbox.last_stdout.contains(&test1)); + assert!(layer.last_stdout.contains(&test1)); // Test whitespace-only env var - sandbox.run_with_env( + layer.run_with_env( &["--no-default-binds", "--no-config", "config"], "DEVLAYER_BIND", " ", )?; // Should have no bind mounts - assert!(sandbox.last_stdout.contains("bind=\n")); + assert!(layer.last_stdout.contains("bind=\n")); Ok(()) } #[rstest] -fn test_bind_mount_env_with_options(mut sandbox: SandboxManager) -> Result<()> { - let test_dir = sandbox.test_filename("bind_env_options"); +fn test_bind_mount_env_with_options(mut layer: LayerManager) -> Result<()> { + let test_dir = layer.test_filename("bind_env_options"); fs::create_dir_all(&test_dir)?; let test1 = format!("{}/test1", test_dir); let test2 = format!("{}/test2", test_dir); @@ -225,36 +221,36 @@ fn test_bind_mount_env_with_options(mut sandbox: SandboxManager) -> Result<()> { fs::create_dir_all(&test4)?; // Test environment variable with read-only options - sandbox.run_with_env( + layer.run_with_env( &["--no-default-binds", "config"], "DEVLAYER_BIND", &format!("{}::ro,{}::ro", test1, test2), )?; // Should include both bind mounts with their options - assert!(sandbox.last_stdout.contains(&format!("{}::ro", test1))); - assert!(sandbox.last_stdout.contains(&format!("{}::ro", test2))); + assert!(layer.last_stdout.contains(&format!("{}::ro", test1))); + assert!(layer.last_stdout.contains(&format!("{}::ro", test2))); // Test mixed read-only and read-write mounts - sandbox.run_with_env( + layer.run_with_env( &["--no-default-binds", "config"], "DEVLAYER_BIND", &format!("{},{}", test3, test4), )?; - assert!(sandbox.last_stdout.contains(&test3)); - assert!(sandbox.last_stdout.contains(&test4)); + assert!(layer.last_stdout.contains(&test3)); + assert!(layer.last_stdout.contains(&test4)); Ok(()) } #[rstest] fn test_bind_mount_path_validation() -> Result<()> { - let mut sandbox = SandboxManager::new(); + let mut layer = LayerManager::new(); // Test handling of bind mounts with special characters // These should be accepted without issue - let test_dir = sandbox.test_filename("bind_special_chars"); + let test_dir = layer.test_filename("bind_special_chars"); fs::create_dir_all(&test_dir)?; let path_with_spaces = format!("{}/path with spaces", test_dir); let path_with_dashes = format!("{}/path-with-dashes", test_dir); @@ -263,7 +259,7 @@ fn test_bind_mount_path_validation() -> Result<()> { fs::create_dir_all(&path_with_dashes)?; fs::create_dir_all(&path_with_underscores)?; - assert!(sandbox.pass(&[ + assert!(layer.pass(&[ "--bind", &path_with_spaces, "--bind", @@ -273,19 +269,19 @@ fn test_bind_mount_path_validation() -> Result<()> { "config" ])); - assert!(sandbox.last_stdout.contains(&path_with_spaces)); - assert!(sandbox.last_stdout.contains(&path_with_dashes)); - assert!(sandbox.last_stdout.contains(&path_with_underscores)); + assert!(layer.last_stdout.contains(&path_with_spaces)); + assert!(layer.last_stdout.contains(&path_with_dashes)); + assert!(layer.last_stdout.contains(&path_with_underscores)); Ok(()) } #[rstest] fn test_bind_mount_read_only_behavior() -> Result<()> { - let mut sandbox = SandboxManager::new(); + let mut layer = LayerManager::new(); // Create a test directory with a file - let test_dir = sandbox.test_filename("bind_ro_test"); + let test_dir = layer.test_filename("bind_ro_test"); fs::create_dir_all(&test_dir)?; let existing_file = format!("{}/existing.txt", test_dir); fs::write(&existing_file, "existing content")?; @@ -295,7 +291,7 @@ fn test_bind_mount_read_only_behavior() -> Result<()> { // For this test, we'll simulate the read-only behavior by checking // that the bind mount is set up correctly - assert!(sandbox.pass(&[ + assert!(layer.pass(&[ "--bind", &test_dir, "--", @@ -304,17 +300,17 @@ fn test_bind_mount_read_only_behavior() -> Result<()> { ])); // Should be able to read the existing file - assert_eq!(sandbox.last_stdout.trim(), "existing content"); + assert_eq!(layer.last_stdout.trim(), "existing content"); Ok(()) } #[rstest] fn test_bind_mount_env_read_only() -> Result<()> { - let mut sandbox = SandboxManager::new(); + let mut layer = LayerManager::new(); // Create test directory with a file - let test_dir = sandbox.test_filename("bind_env_ro"); + let test_dir = layer.test_filename("bind_env_ro"); fs::create_dir_all(&test_dir)?; let test_file = format!("{}/test.txt", test_dir); fs::write(&test_file, "test content")?; @@ -322,7 +318,7 @@ fn test_bind_mount_env_read_only() -> Result<()> { let test_dir_str = std::fs::canonicalize(&test_dir)? .to_string_lossy() .to_string(); - let env_ro = sandbox.test_filename("env_ro"); + let env_ro = layer.test_filename("env_ro"); fs::create_dir_all(&env_ro)?; let env_ro = std::fs::canonicalize(&env_ro)? .to_string_lossy() @@ -330,7 +326,7 @@ fn test_bind_mount_env_read_only() -> Result<()> { // Test read-only bind mounts via environment variable // We expect this to fail with a non-zero exit code - let result = sandbox.run_with_env( + let result = layer.run_with_env( &[ "--no-config", "--", @@ -349,38 +345,34 @@ fn test_bind_mount_env_read_only() -> Result<()> { // Check for read-only filesystem error assert!( - sandbox.last_stderr.contains("Read-only file system") - || sandbox.last_stderr.contains("read-only file system"), + layer.last_stderr.contains("Read-only file system") + || layer.last_stderr.contains("read-only file system"), "Expected read-only filesystem error, got: {}", - sandbox.last_stderr + layer.last_stderr ); // Test comma-separated bind mounts with mixed options - let test1 = sandbox.test_filename("test1"); - let test2 = sandbox.test_filename("test2"); - let mapped = sandbox.test_filename("mapped"); + let test1 = layer.test_filename("test1"); + let test2 = layer.test_filename("test2"); + let mapped = layer.test_filename("mapped"); fs::create_dir_all(&test1)?; fs::create_dir_all(&test2)?; fs::create_dir_all(&mapped)?; - sandbox.run_with_env( + layer.run_with_env( &["--no-config", "config"], "DEVLAYER_BIND", &format!("{},{}:{}:ro,{}::ro", test1, test2, mapped, test_dir_str), )?; // Should contain all bind mounts - assert!(sandbox.last_stdout.contains(&test1)); + assert!(layer.last_stdout.contains(&test1)); assert!( - sandbox + layer .last_stdout .contains(&format!("{}:{}:ro", test2, mapped)) ); - assert!( - sandbox - .last_stdout - .contains(&format!("{}::ro", test_dir_str)) - ); + assert!(layer.last_stdout.contains(&format!("{}::ro", test_dir_str))); // Cleanup fs::remove_dir_all(test_dir)?; @@ -390,8 +382,8 @@ fn test_bind_mount_env_read_only() -> Result<()> { #[rstest] fn test_bind_mount_edge_cases() -> Result<()> { - let mut sandbox = SandboxManager::new(); - let test_dir = sandbox.test_filename("bind_edge_cases"); + let mut layer = LayerManager::new(); + let test_dir = layer.test_filename("bind_edge_cases"); fs::create_dir_all(&test_dir)?; let tmp = format!("{}/tmp", test_dir); let var = format!("{}/var", test_dir); @@ -399,46 +391,46 @@ fn test_bind_mount_edge_cases() -> Result<()> { fs::create_dir_all(&var)?; // Test case 1: /tmp: (source with empty destination) - assert!(sandbox.pass(&[ + assert!(layer.pass(&[ "--no-config", "--bind", &format!("{}:", tmp), "config" ])); // Should mount /tmp to /tmp (empty destination means same as source) - assert!(sandbox.last_stdout.contains(&format!("{}:", tmp))); + assert!(layer.last_stdout.contains(&format!("{}:", tmp))); // Test case 2: /tmp:: (source with empty destination and empty options) - let mut sandbox2 = SandboxManager::new(); - assert!(sandbox2.pass(&[ + let mut layer2 = LayerManager::new(); + assert!(layer2.pass(&[ "--no-config", "--bind", &format!("{}::", tmp), "config" ])); // Should mount /tmp to /tmp with no options - assert!(sandbox2.last_stdout.contains(&format!("{}::", tmp))); + assert!(layer2.last_stdout.contains(&format!("{}::", tmp))); // Test case 3: Empty destination with actual execution (from ai_test_bind_mount_empty_destination.rs) - let mut sandbox3 = SandboxManager::new(); - assert!(sandbox3.pass(&[ + let mut layer3 = LayerManager::new(); + assert!(layer3.pass(&[ "--bind", &format!("{}:", tmp), "bash", "-c", "echo 'testing empty destination'", ])); - assert!(sandbox3.last_stdout.contains("testing empty destination")); + assert!(layer3.last_stdout.contains("testing empty destination")); // Verify exit code is successful assert_eq!( - sandbox3.last_stdout.lines().last(), + layer3.last_stdout.lines().last(), Some("testing empty destination") ); // Test case 4: Multiple bind mounts with empty destinations - let mut sandbox4 = SandboxManager::new(); - assert!(sandbox4.pass(&[ + let mut layer4 = LayerManager::new(); + assert!(layer4.pass(&[ "--bind", &format!("{}:", tmp), "--bind", @@ -447,7 +439,7 @@ fn test_bind_mount_edge_cases() -> Result<()> { "-c", "echo 'multiple empty destinations'", ])); - assert!(sandbox4.last_stdout.contains("multiple empty destinations")); + assert!(layer4.last_stdout.contains("multiple empty destinations")); Ok(()) } @@ -455,15 +447,15 @@ fn test_bind_mount_edge_cases() -> Result<()> { // From ai_test_bind_mount_empty_destination.rs #[rstest] fn test_bind_mount_empty_destination() -> Result<()> { - let mut sandbox = SandboxManager::new(); - let test_name = format!("devlayer-bind-empty-dest-{}", sandbox.name); - let test_dir = sandbox.test_filename("bind_empty_dest"); + let mut layer = LayerManager::new(); + let test_name = format!("devlayer-bind-empty-dest-{}", layer.name); + let test_dir = layer.test_filename("bind_empty_dest"); fs::create_dir_all(&test_dir)?; let tmp = format!("{}/tmp", test_dir); fs::create_dir_all(&tmp)?; - // Run a command that will definitely create a new sandbox and process bind mounts - assert!(sandbox.pass(&[ + // Run a command that will definitely create a new layer and process bind mounts + assert!(layer.pass(&[ "--name", &test_name, "--bind", @@ -474,7 +466,7 @@ fn test_bind_mount_empty_destination() -> Result<()> { "echo 'empty dest bind mount test'" ])); - assert!(sandbox.last_stdout.contains("empty dest bind mount test")); + assert!(layer.last_stdout.contains("empty dest bind mount test")); Ok(()) } @@ -513,10 +505,10 @@ fn test_bind_mount_empty_destination_with_sudo() -> Result<()> { #[rstest] fn test_empty_bind_array_in_config() -> Result<()> { // Test empty bind array in config - let mut sandbox = SandboxManager::new(); + let mut layer = LayerManager::new(); // Create a temporary working directory for the config file - let work_dir = sandbox.test_filename("workdir"); + let work_dir = layer.test_filename("workdir"); fs::create_dir_all(&work_dir)?; // Write config file in the working directory @@ -529,12 +521,12 @@ bind = [] )?; // Should work but only have default binds - let result = sandbox.run(&["config"]); + let result = layer.run(&["config"]); assert!(result.is_ok()); // Should have default binds but no custom ones - let bind_mounts_line = sandbox + let bind_mounts_line = layer .last_stdout .lines() .find(|line| line.starts_with("bind=")) @@ -547,11 +539,11 @@ bind = [] } #[rstest] -fn test_all_deserialize_paths(mut sandbox: SandboxManager) -> Result<()> { +fn test_all_deserialize_paths(mut layer: LayerManager) -> Result<()> { // Comprehensive test covering all deserialization paths use std::fs; - let test_dir = sandbox.test_filename("test_all_deserialize_paths"); + let test_dir = layer.test_filename("test_all_deserialize_paths"); let config_dir = PathBuf::from(&test_dir).join(".config/devlayer"); fs::create_dir_all(&config_dir)?; let config_file = config_dir.join("config.toml"); @@ -574,13 +566,13 @@ fn test_all_deserialize_paths(mut sandbox: SandboxManager) -> Result<()> { fs::write(&config_file, config)?; // Set HOME to the test directory to use our config - let result = sandbox.run_with_env(&["--version"], "HOME", &test_dir)?; + let result = layer.run_with_env(&["--version"], "HOME", &test_dir)?; assert!( result.status.success(), "Should handle {} correctly, got stderr: {}", desc, - sandbox.last_stderr + layer.last_stderr ); } diff --git a/tests/ai_test_bind_parent_dirs.rs b/tests/ai_test_bind_parent_dirs.rs index 92d43d0..941f716 100644 --- a/tests/ai_test_bind_parent_dirs.rs +++ b/tests/ai_test_bind_parent_dirs.rs @@ -6,21 +6,21 @@ use rstest::*; #[rstest] fn ai_test_bind_parent_dir_missing_on_host( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - let test_dir = sandbox.test_filename("bind_parent"); + let test_dir = layer.test_filename("bind_parent"); std::fs::create_dir_all(&test_dir)?; std::fs::write(format!("{}/test.txt", test_dir), "test content")?; // Neither the target nor its parent exist on the host, so the parent is - // created inside the sandbox without any host ownership to mirror - let parent = format!("/run/{}", sandbox.name); + // created inside the layer without any host ownership to mirror + let parent = format!("/run/{}", layer.name); assert!(!std::path::Path::new(&parent).exists()); let target = format!("{}/mnt", parent); let bind = format!("{}:{}", test_dir, target); - sandbox.run(&[ + layer.run(&[ "--no-config", "--bind", &bind, @@ -29,16 +29,16 @@ fn ai_test_bind_parent_dir_missing_on_host( "%u", &parent, ])?; - assert_eq!(sandbox.last_stdout.trim(), "0"); + assert_eq!(layer.last_stdout.trim(), "0"); - sandbox.run(&[ + layer.run(&[ "--no-config", "--bind", &bind, "cat", &format!("{}/test.txt", target), ])?; - assert_eq!(sandbox.last_stdout.trim(), "test content"); + assert_eq!(layer.last_stdout.trim(), "test content"); Ok(()) } diff --git a/tests/ai_test_bind_precedence.rs b/tests/ai_test_bind_precedence.rs index 54a6077..2a1f110 100644 --- a/tests/ai_test_bind_precedence.rs +++ b/tests/ai_test_bind_precedence.rs @@ -6,34 +6,34 @@ use rstest::*; use std::fs; /// Creates a directory to bind and returns its path -fn make_dir(sandbox: &SandboxManager, prefix: &str) -> Result { - let dir = sandbox.test_filename(prefix); +fn make_dir(layer: &LayerManager, prefix: &str) -> Result { + let dir = layer.test_filename(prefix); fs::create_dir_all(&dir)?; Ok(dir) } /// Writes a config file with the given contents and returns its path fn write_config( - sandbox: &SandboxManager, + layer: &LayerManager, prefix: &str, contents: &str, ) -> Result { - let path = format!("{}.toml", sandbox.test_filename(prefix)); + let path = format!("{}.toml", layer.test_filename(prefix)); fs::write(&path, contents)?; Ok(path) } #[rstest] fn ai_test_bind_higher_precedence_config_overrides( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - let dir = make_dir(&sandbox, "bind_dir")?; - let low = write_config(&sandbox, "low", &format!("bind = [\"{dir}\"]"))?; + let dir = make_dir(&layer, "bind_dir")?; + let low = write_config(&layer, "low", &format!("bind = [\"{dir}\"]"))?; let high = - write_config(&sandbox, "high", &format!("bind = [\"{dir}::ro\"]"))?; + write_config(&layer, "high", &format!("bind = [\"{dir}::ro\"]"))?; // Later --config files take precedence over earlier ones - sandbox.run(&[ + layer.run(&[ "--no-default-binds", "--config", &low, @@ -42,9 +42,9 @@ fn ai_test_bind_higher_precedence_config_overrides( "config", "bind", ])?; - assert_eq!(sandbox.last_stdout.trim(), format!("{dir}::ro")); + assert_eq!(layer.last_stdout.trim(), format!("{dir}::ro")); - sandbox.run(&[ + layer.run(&[ "--no-default-binds", "--config", &high, @@ -53,29 +53,29 @@ fn ai_test_bind_higher_precedence_config_overrides( "config", "bind", ])?; - assert_eq!(sandbox.last_stdout.trim(), dir); + assert_eq!(layer.last_stdout.trim(), dir); Ok(()) } #[rstest] fn ai_test_bind_conflict_within_config_fails( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - let dir = make_dir(&sandbox, "bind_dir")?; + let dir = make_dir(&layer, "bind_dir")?; let conflicting = write_config( - &sandbox, + &layer, "conflicting", &format!("bind = [\"{dir}\", \"{dir}::ro\"]"), )?; let overriding = - write_config(&sandbox, "overriding", &format!("bind = [\"{dir}\"]"))?; + write_config(&layer, "overriding", &format!("bind = [\"{dir}\"]"))?; - assert!(sandbox.xfail(&["--config", &conflicting, "config"])); - assert!(sandbox.last_stderr.contains("Conflicting bind mount")); + assert!(layer.xfail(&["--config", &conflicting, "config"])); + assert!(layer.last_stderr.contains("Conflicting bind mount")); // A higher precedence config does not excuse a conflict in a lower one - assert!(sandbox.xfail(&[ + assert!(layer.xfail(&[ "--config", &conflicting, "--config", @@ -85,47 +85,47 @@ fn ai_test_bind_conflict_within_config_fails( // Bind and mask for the same target in one config also conflict let bind_and_mask = write_config( - &sandbox, + &layer, "bind_and_mask", &format!("bind = [\"{dir}\"]\nmask = [\"{dir}\"]"), )?; - assert!(sandbox.xfail(&["--config", &bind_and_mask, "config"])); + assert!(layer.xfail(&["--config", &bind_and_mask, "config"])); Ok(()) } #[rstest] fn ai_test_bind_identical_within_config_is_deduplicated( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - let dir = make_dir(&sandbox, "bind_dir")?; + let dir = make_dir(&layer, "bind_dir")?; let config = write_config( - &sandbox, + &layer, "duplicate", &format!("bind = [\"{dir}\", \"{dir}:{dir}:rw\"]"), )?; - sandbox.run(&[ + layer.run(&[ "--no-default-binds", "--config", &config, "config", "bind", ])?; - assert_eq!(sandbox.last_stdout.trim(), dir); + assert_eq!(layer.last_stdout.trim(), dir); Ok(()) } #[rstest] fn ai_test_mask_in_higher_config_overrides_bind( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - let dir = make_dir(&sandbox, "bind_dir")?; - let low = write_config(&sandbox, "low", &format!("bind = [\"{dir}\"]"))?; - let high = write_config(&sandbox, "high", &format!("mask = [\"{dir}\"]"))?; + let dir = make_dir(&layer, "bind_dir")?; + let low = write_config(&layer, "low", &format!("bind = [\"{dir}\"]"))?; + let high = write_config(&layer, "high", &format!("mask = [\"{dir}\"]"))?; - sandbox.run(&[ + layer.run(&[ "--no-default-binds", "--config", &low, @@ -135,10 +135,10 @@ fn ai_test_mask_in_higher_config_overrides_bind( "bind", "mask", ])?; - assert!(sandbox.last_stdout.contains("bind=\n")); + assert!(layer.last_stdout.contains("bind=\n")); let target = fs::canonicalize(&dir)?; assert!( - sandbox + layer .last_stdout .contains(&format!("mask={}\n", target.display())) ); @@ -147,22 +147,20 @@ fn ai_test_mask_in_higher_config_overrides_bind( } #[rstest] -fn ai_test_bind_env_overrides_config( - mut sandbox: SandboxManager, -) -> Result<()> { - let dir = make_dir(&sandbox, "bind_dir")?; +fn ai_test_bind_env_overrides_config(mut layer: LayerManager) -> Result<()> { + let dir = make_dir(&layer, "bind_dir")?; let config = - write_config(&sandbox, "config", &format!("bind = [\"{dir}\"]"))?; + write_config(&layer, "config", &format!("bind = [\"{dir}\"]"))?; - sandbox.run_with_env( + layer.run_with_env( &["--no-default-binds", "--config", &config, "config", "bind"], "DEVLAYER_BIND", &format!("{dir}::ro"), )?; - assert_eq!(sandbox.last_stdout.trim(), format!("{dir}::ro")); + assert_eq!(layer.last_stdout.trim(), format!("{dir}::ro")); // Conflicts within the environment layer still fail - assert!(sandbox.exfail( + assert!(layer.exfail( &["--no-default-binds", "config"], "DEVLAYER_BIND", &format!("{dir},{dir}::ro"), @@ -173,13 +171,13 @@ fn ai_test_bind_env_overrides_config( #[rstest] fn ai_test_bind_cli_overrides_config_and_env( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - let dir = make_dir(&sandbox, "bind_dir")?; + let dir = make_dir(&layer, "bind_dir")?; let config = - write_config(&sandbox, "config", &format!("bind = [\"{dir}::ro\"]"))?; + write_config(&layer, "config", &format!("bind = [\"{dir}::ro\"]"))?; - sandbox.run_with_env( + layer.run_with_env( &[ "--no-default-binds", "--config", @@ -192,10 +190,10 @@ fn ai_test_bind_cli_overrides_config_and_env( "DEVLAYER_BIND", &format!("{dir}::ro"), )?; - assert_eq!(sandbox.last_stdout.trim(), dir); + assert_eq!(layer.last_stdout.trim(), dir); // A CLI mask overrides a bind from a config file - sandbox.run(&[ + layer.run(&[ "--no-default-binds", "--config", &config, @@ -205,10 +203,10 @@ fn ai_test_bind_cli_overrides_config_and_env( "bind", "mask", ])?; - assert!(sandbox.last_stdout.contains("bind=\n")); + assert!(layer.last_stdout.contains("bind=\n")); let target = fs::canonicalize(&dir)?; assert!( - sandbox + layer .last_stdout .contains(&format!("mask={}\n", target.display())) ); @@ -217,22 +215,14 @@ fn ai_test_bind_cli_overrides_config_and_env( } #[rstest] -fn ai_test_bind_overrides_default_binds( - mut sandbox: SandboxManager, -) -> Result<()> { +fn ai_test_bind_overrides_default_binds(mut layer: LayerManager) -> Result<()> { // /dev/fuse is a default bind when present on the host if !std::path::Path::new("/dev/fuse").exists() { return Ok(()); } - sandbox.run(&[ - "--no-config", - "--bind", - "/dev/fuse::ro", - "config", - "bind", - ])?; - let binds: Vec<&str> = sandbox.last_stdout.trim().split(',').collect(); + layer.run(&["--no-config", "--bind", "/dev/fuse::ro", "config", "bind"])?; + let binds: Vec<&str> = layer.last_stdout.trim().split(',').collect(); assert!(binds.contains(&"/dev/fuse::ro")); assert!(!binds.contains(&"/dev/fuse")); diff --git a/tests/ai_test_builtin_ignore_patterns.rs b/tests/ai_test_builtin_ignore_patterns.rs index 404e730..071c7c2 100644 --- a/tests/ai_test_builtin_ignore_patterns.rs +++ b/tests/ai_test_builtin_ignore_patterns.rs @@ -5,39 +5,39 @@ use fixtures::*; use rstest::*; #[rstest] -fn test_builtin_ignore_patterns_tmp(mut sandbox: SandboxManager) -> Result<()> { - sandbox.set_ignored(false); +fn test_builtin_ignore_patterns_tmp(mut layer: LayerManager) -> Result<()> { + layer.set_ignored(false); // Create parent .gitignore to ensure test directory isn't ignored let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), ])?; // Create files in /tmp that would normally be tracked - sandbox.run(&["sh", "-c", "mkdir -p /tmp/layer-builtin-test && echo 'test' > /tmp/layer-builtin-test/should-be-ignored.txt"])?; + layer.run(&["sh", "-c", "mkdir -p /tmp/layer-builtin-test && echo 'test' > /tmp/layer-builtin-test/should-be-ignored.txt"])?; // Also create a visible file for comparison - let test_dir = sandbox.test_filename("tmp-test"); + let test_dir = layer.test_filename("tmp-test"); std::fs::create_dir_all(&test_dir)?; - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!("echo 'visible' > {}/visible-file.txt", test_dir), ])?; // First verify with --ignored flag that /tmp files exist as changes - sandbox.set_ignored(true); - sandbox.run(&["status", "/"])?; - let stdout_ignored = sandbox.last_stdout.clone(); - sandbox.set_ignored(false); + layer.set_ignored(true); + layer.run(&["status", "/"])?; + let stdout_ignored = layer.last_stdout.clone(); + layer.set_ignored(false); // Run without --ignored - sandbox.run(&["status", "/"])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", "/"])?; + let stdout = layer.last_stdout.clone(); // The /tmp file should appear with --ignored but not without assert!( @@ -62,21 +62,21 @@ fn test_builtin_ignore_patterns_tmp(mut sandbox: SandboxManager) -> Result<()> { ); // Clean up - sandbox.run(&["sh", "-c", "rm -rf /tmp/layer-builtin-test"])?; + layer.run(&["sh", "-c", "rm -rf /tmp/layer-builtin-test"])?; Ok(()) } #[rstest] fn test_builtin_ignore_patterns_home_dotfiles( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - sandbox.set_ignored(false); + layer.set_ignored(false); // Create parent .gitignore to ensure test directory isn't ignored let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), @@ -84,31 +84,27 @@ fn test_builtin_ignore_patterns_home_dotfiles( // The patterns /home/*/.*/** and /home/*/.* ignore hidden files in home dirs // Create hidden files in user's home - sandbox.run(&["sh", "-c", "mkdir -p ~/.layer-builtin-test && echo 'hidden' > ~/.layer-builtin-test/file.txt"])?; - sandbox.run(&[ - "sh", - "-c", - "echo 'hidden' > ~/.layer-builtin-hidden-file", - ])?; + layer.run(&["sh", "-c", "mkdir -p ~/.layer-builtin-test && echo 'hidden' > ~/.layer-builtin-test/file.txt"])?; + layer.run(&["sh", "-c", "echo 'hidden' > ~/.layer-builtin-hidden-file"])?; // Create a visible file for comparison in test directory - let test_dir = sandbox.test_filename("home-test"); + let test_dir = layer.test_filename("home-test"); std::fs::create_dir_all(&test_dir)?; - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!("echo 'visible' > {}/visible-file.txt", test_dir), ])?; // Run with --ignored first to confirm files were created - sandbox.set_ignored(true); - sandbox.run(&["status", "/"])?; - let stdout_ignored = sandbox.last_stdout.clone(); - sandbox.set_ignored(false); + layer.set_ignored(true); + layer.run(&["status", "/"])?; + let stdout_ignored = layer.last_stdout.clone(); + layer.set_ignored(false); // Run without --ignored - sandbox.run(&["status", "/"])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", "/"])?; + let stdout = layer.last_stdout.clone(); // Hidden files should show with --ignored but not without assert!( @@ -132,7 +128,7 @@ fn test_builtin_ignore_patterns_home_dotfiles( ); // Clean up - sandbox.run(&[ + layer.run(&[ "sh", "-c", "rm -rf ~/.layer-builtin-test ~/.layer-builtin-hidden-file", @@ -142,25 +138,25 @@ fn test_builtin_ignore_patterns_home_dotfiles( } #[rstest] -fn test_builtin_ignore_patterns_git(mut sandbox: SandboxManager) -> Result<()> { - sandbox.set_ignored(false); +fn test_builtin_ignore_patterns_git(mut layer: LayerManager) -> Result<()> { + layer.set_ignored(false); // Create parent .gitignore to ensure test directory isn't ignored let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), ])?; // Create test directory - let test_dir = sandbox.test_filename("builtin-git-test"); + let test_dir = layer.test_filename("builtin-git-test"); std::fs::create_dir_all(&test_dir)?; // The patterns **/.git/** and **/.git ignore .git directories // Create a .git directory with files - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -168,28 +164,28 @@ fn test_builtin_ignore_patterns_git(mut sandbox: SandboxManager) -> Result<()> { test_dir, test_dir ), ])?; - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!("echo 'HEAD' > {}/.git/HEAD", test_dir), ])?; // Create regular file - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!("echo 'regular' > {}/regular-file.txt", test_dir), ])?; // Run with --ignored first - sandbox.set_ignored(true); - sandbox.run(&["status", &test_dir])?; - let stdout_ignored = sandbox.last_stdout.clone(); - sandbox.set_ignored(false); + layer.set_ignored(true); + layer.run(&["status", &test_dir])?; + let stdout_ignored = layer.last_stdout.clone(); + layer.set_ignored(false); // Run without --ignored - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); // .git files should show with --ignored but not without assert!( diff --git a/tests/ai_test_can_mkdir_coverage.rs b/tests/ai_test_can_mkdir_coverage.rs index f8ea059..92a189d 100644 --- a/tests/ai_test_can_mkdir_coverage.rs +++ b/tests/ai_test_can_mkdir_coverage.rs @@ -6,9 +6,9 @@ use rstest::*; use std::path::Path; #[rstest] -fn test_can_mkdir_nested_paths(mut sandbox: SandboxManager) -> Result<()> { +fn test_can_mkdir_nested_paths(mut layer: LayerManager) -> Result<()> { // Create test directory - let test_dir = sandbox.test_filename("can-mkdir-test"); + let test_dir = layer.test_filename("can-mkdir-test"); std::fs::create_dir_all(&test_dir)?; // Create a deeply nested path that doesn't exist @@ -21,7 +21,7 @@ fn test_can_mkdir_nested_paths(mut sandbox: SandboxManager) -> Result<()> { // Try to create a file in this deeply nested path that doesn't exist // This should trigger the can_mkdir check with multiple parent traversals - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -32,8 +32,8 @@ fn test_can_mkdir_nested_paths(mut sandbox: SandboxManager) -> Result<()> { ])?; // Verify the file was created successfully - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); assert!( stdout.contains("test.txt"), @@ -44,23 +44,21 @@ fn test_can_mkdir_nested_paths(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_sandbox_creation_nested_storage( - mut sandbox: SandboxManager, -) -> Result<()> { +fn test_layer_creation_nested_storage(mut layer: LayerManager) -> Result<()> { let nested_storage = format!( "/tmp/{}", - sandbox.test_filename("nested/storage/path/for/layer") + layer.test_filename("nested/storage/path/for/layer") ); - sandbox.epass(&["true"], "DEVLAYER_STORAGE_DIR", &nested_storage); - sandbox.epass( + layer.epass(&["true"], "DEVLAYER_STORAGE_DIR", &nested_storage); + layer.epass( &["accept", "**/*.profraw"], "DEVLAYER_STORAGE_DIR", &nested_storage, ); - sandbox.epass(&["stop"], "DEVLAYER_STORAGE_DIR", &nested_storage); - sandbox.epass(&["delete"], "DEVLAYER_STORAGE_DIR", &nested_storage); + layer.epass(&["stop"], "DEVLAYER_STORAGE_DIR", &nested_storage); + layer.epass(&["delete"], "DEVLAYER_STORAGE_DIR", &nested_storage); Ok(()) } diff --git a/tests/ai_test_clean.rs b/tests/ai_test_clean.rs index 445c415..2d2c5bd 100644 --- a/tests/ai_test_clean.rs +++ b/tests/ai_test_clean.rs @@ -7,26 +7,23 @@ use rstest::*; use std::path::PathBuf; /* These tests use a private storage directory so that `clean` never touches - * real sandboxes, or test sandboxes belonging to other tests. Only stopped - * sandboxes are used: faking a running one would mean pointing its pid file + * real layers, or test layers belonging to other tests. Only stopped + * layers are used: faking a running one would mean pointing its pid file * at a host process, and stopping it would kill everything in the host pid * namespace. */ struct CleanEnv { - sandbox: SandboxManager, + layer: LayerManager, storage_dir: PathBuf, } impl CleanEnv { fn new() -> Result { - let sandbox = sandbox(); + let layer = layer(); let storage_dir = std::env::current_dir()? - .join(sandbox.test_filename_no_rid("storage")); + .join(layer.test_filename_no_rid("storage")); std::fs::create_dir_all(&storage_dir)?; - Ok(Self { - sandbox, - storage_dir, - }) + Ok(Self { layer, storage_dir }) } fn storage_arg(&self) -> String { @@ -37,12 +34,12 @@ impl CleanEnv { let storage_arg = self.storage_arg(); let mut full_args = vec![storage_arg.as_str()]; full_args.extend_from_slice(args); - self.sandbox.run(&full_args)?; + self.layer.run(&full_args)?; Ok(()) } - /// Lays out the on-disk structure of a stopped sandbox. Real sandboxes - /// can't be created in a non-default storage dir from within a sandbox + /// Lays out the on-disk structure of a stopped layer. Real layers + /// can't be created in a non-default storage dir from within a layer /// (overlayfs stacking limits), and `clean` only needs the layout. fn create_stopped(&self, name: &str) -> Result<()> { for sub in ["upper", "work", "overlay"] { @@ -60,7 +57,7 @@ impl CleanEnv { impl Drop for CleanEnv { fn drop(&mut self) { let storage_arg = self.storage_arg(); - let _ = self.sandbox.run(&[&storage_arg, "delete", "-y", "*"]); + let _ = self.layer.run(&[&storage_arg, "delete", "-y", "*"]); let _ = std::fs::remove_dir_all(&self.storage_dir); } } @@ -75,7 +72,7 @@ fn ephemeral_name(age: TimeDelta) -> String { } #[rstest] -fn test_clean_removes_old_ephemeral_and_test_sandboxes() -> Result<()> { +fn test_clean_removes_old_ephemeral_and_test_layers() -> Result<()> { let mut env = CleanEnv::new()?; let id = rid(); @@ -101,7 +98,7 @@ fn test_clean_removes_old_ephemeral_and_test_sandboxes() -> Result<()> { } env.run(&["clean", "-y"])?; - assert!(env.sandbox.last_stdout.contains("4 layers deleted")); + assert!(env.layer.last_stdout.contains("4 layers deleted")); for name in [&old, &coverage, &bind_empty, &bind_empty_dest] { assert!(!env.exists(name), "{} should have been cleaned", name); @@ -120,19 +117,14 @@ fn test_clean_prompts_for_confirmation() -> Result<()> { env.create_stopped(&old_stopped)?; let storage_arg = env.storage_arg(); - env.sandbox - .run_with_stdin(&[&storage_arg, "clean"], "n\n")?; + env.layer.run_with_stdin(&[&storage_arg, "clean"], "n\n")?; assert!( - env.sandbox + env.layer .last_stdout .contains("The following layers will be deleted") ); - assert!(env.sandbox.last_stdout.contains(&old_stopped)); - assert!( - env.sandbox - .last_stdout - .contains("Delete operation cancelled") - ); + assert!(env.layer.last_stdout.contains(&old_stopped)); + assert!(env.layer.last_stdout.contains("Delete operation cancelled")); assert!(env.exists(&old_stopped)); Ok(()) @@ -144,7 +136,7 @@ fn test_clean_nothing_to_clean() -> Result<()> { env.create_stopped(&ephemeral_name(TimeDelta::zero()))?; env.run(&["clean", "-y"])?; - assert!(env.sandbox.last_stdout.contains("No layers to clean.")); + assert!(env.layer.last_stdout.contains("No layers to clean.")); Ok(()) } diff --git a/tests/ai_test_config_impls.rs b/tests/ai_test_config_impls.rs index 39ce6da..3e33e1f 100644 --- a/tests/ai_test_config_impls.rs +++ b/tests/ai_test_config_impls.rs @@ -15,16 +15,16 @@ static CONFIG_TEST_MUTEX: Mutex<()> = Mutex::new(()); #[rstest] fn test_network_options_in_help() -> Result<()> { // Verify that network options are properly displayed in help - let mut sandbox = SandboxManager::new(); + let mut layer = LayerManager::new(); - assert!(sandbox.pass(&["--help"])); + assert!(layer.pass(&["--help"])); assert!( - sandbox.last_stdout.contains("--net"), + layer.last_stdout.contains("--net"), "Help should contain --net option" ); assert!( - sandbox.last_stdout.contains("none") - && sandbox.last_stdout.contains("host"), + layer.last_stdout.contains("none") + && layer.last_stdout.contains("host"), "Network options (none, host) should be visible in help" ); @@ -34,11 +34,11 @@ fn test_network_options_in_help() -> Result<()> { #[rstest] fn test_valid_config_formats() -> Result<()> { let _guard = CONFIG_TEST_MUTEX.lock().unwrap(); - let mut sandbox = SandboxManager::new(); - sandbox.no_sudo = true; + let mut layer = LayerManager::new(); + layer.no_sudo = true; // Create a local config file in test directory - let test_dir = format!("generated-test-data/{}", sandbox.name); + let test_dir = format!("generated-test-data/{}", layer.name); fs::create_dir_all(&test_dir)?; let config_file = format!("{}/.devlayer.toml", test_dir); @@ -61,23 +61,23 @@ fn test_valid_config_formats() -> Result<()> { for config in valid_configs.iter() { fs::write(&config_file, config)?; - let config_passed = sandbox.pass(&["config"]); + let config_passed = layer.pass(&["config"]); if config_passed { // For bind configs, verify they appear in the output if config.contains("bind") && config != r#"bind = null"# { assert!( - sandbox.last_stdout.contains("bind_mounts"), + layer.last_stdout.contains("bind_mounts"), "Config output should contain bind_mounts for config: {}", config ); } } else { // If it fails due to permissions, that's OK - if !sandbox.last_stderr.contains("Insufficient permissions") { + if !layer.last_stderr.contains("Insufficient permissions") { panic!( "Valid config '{}' should not cause errors, got: {}", - config, sandbox.last_stderr + config, layer.last_stderr ); } } @@ -89,12 +89,12 @@ fn test_valid_config_formats() -> Result<()> { #[rstest] fn test_config_file_locations() -> Result<()> { let _guard = CONFIG_TEST_MUTEX.lock().unwrap(); - let mut sandbox = SandboxManager::new(); - sandbox.no_sudo = true; + let mut layer = LayerManager::new(); + layer.no_sudo = true; - // Test that sandbox looks for config in the right places - // 1. .sandbox.toml in current directory - let test_dir = format!("generated-test-data/{}", sandbox.name); + // Test that layer looks for config in the right places + // 1. .layer.toml in current directory + let test_dir = format!("generated-test-data/{}", layer.name); fs::create_dir_all(&test_dir)?; let local_config = format!("{}/.devlayer.toml", test_dir); fs::write(&local_config, r#"log_level = "TRACE""#)?; @@ -103,9 +103,9 @@ fn test_config_file_locations() -> Result<()> { let original_dir = std::env::current_dir()?; std::env::set_current_dir(&test_dir)?; - if sandbox.pass(&["config"]) { + if layer.pass(&["config"]) { assert!( - sandbox.last_stdout.contains("TRACE"), + layer.last_stdout.contains("TRACE"), "Should pick up local .devlayer.toml config" ); } @@ -113,9 +113,9 @@ fn test_config_file_locations() -> Result<()> { // Don't change back yet, we need to test precedence // 2. Test precedence - CLI args should override config file - if sandbox.pass(&["--log-level", "ERROR", "config"]) { + if layer.pass(&["--log-level", "ERROR", "config"]) { assert!( - sandbox.last_stdout.contains("ERROR"), + layer.last_stdout.contains("ERROR"), "CLI args should override config file" ); } diff --git a/tests/ai_test_config_option.rs b/tests/ai_test_config_option.rs index 577366a..92dc92e 100644 --- a/tests/ai_test_config_option.rs +++ b/tests/ai_test_config_option.rs @@ -8,7 +8,7 @@ use std::fs; /// Test the --config CLI option behavior #[rstest] fn ai_test_config_option() -> Result<()> { - // Test config loading without running actual sandbox commands + // Test config loading without running actual layer commands // This tests the CLI parsing functionality directly // Create test config files @@ -29,7 +29,7 @@ ignored = true fs::write(&config2_file, config2_content)?; // Test 1: --config conflicts with --no-config (using direct command) - let output = std::process::Command::new(get_sandbox_bin()) + let output = std::process::Command::new(get_devlayer_bin()) .args([ "--config", config_file.to_str().unwrap(), @@ -42,7 +42,7 @@ ignored = true assert!(stderr.contains("cannot be used with")); // Test 2: Error when config file doesn't exist - let output = std::process::Command::new(get_sandbox_bin()) + let output = std::process::Command::new(get_devlayer_bin()) .args(["--config", "/nonexistent/file.toml", "config"]) .output()?; assert!(!output.status.success()); @@ -50,14 +50,14 @@ ignored = true assert!(stderr.contains("Config file not found")); // Test 3: Empty --config list means no config files loaded - let output = std::process::Command::new(get_sandbox_bin()) + let output = std::process::Command::new(get_devlayer_bin()) .args(["--config", "", "--help"]) .output()?; assert!(output.status.success()); // Test 4: Test that config action shows loaded config files // We need to use a working directory with an acceptable mount type - let output = std::process::Command::new(get_sandbox_bin()) + let output = std::process::Command::new(get_devlayer_bin()) .env("TEST_UNACCEPTABLE_MOUNT_TYPE", "") // Disable mount type check for test .args([ "--config", diff --git a/tests/ai_test_corrupted_settings.rs b/tests/ai_test_corrupted_settings.rs index 687f419..09dd430 100644 --- a/tests/ai_test_corrupted_settings.rs +++ b/tests/ai_test_corrupted_settings.rs @@ -1,5 +1,5 @@ -// Integration tests for corrupted sandbox settings handling -// These tests verify error handling when sandbox settings files are corrupted or unreadable +// Integration tests for corrupted layer settings handling +// These tests verify error handling when layer settings files are corrupted or unreadable mod fixtures; @@ -10,17 +10,17 @@ use std::fs; #[rstest] fn test_get_or_create_with_corrupted_settings( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - // First, create a working sandbox - let _output = sandbox.run(&["echo", "initial setup"])?; + // First, create a working layer + let _output = layer.run(&["echo", "initial setup"])?; - // Get the sandbox directory from the sandbox tool itself - let sandbox_dir = sandbox.dir()?; - let data_dir = sandbox_dir.join("data"); + // Get the layer directory from the layer tool itself + let layer_dir = layer.dir()?; + let data_dir = layer_dir.join("data"); let settings_file = data_dir.join("settings.json"); - // Verify the sandbox was created and settings file exists + // Verify the layer was created and settings file exists assert!( settings_file.exists(), "Settings file should exist after initial layer creation at {}", @@ -45,8 +45,8 @@ fn test_get_or_create_with_corrupted_settings( } // Now try to run another command - this should trigger the error path in get_or_create - // because the existing sandbox has corrupted settings - let success = sandbox.pass(&["echo", "second command"]); + // because the existing layer has corrupted settings + let success = layer.pass(&["echo", "second command"]); // The command should fail due to corrupted settings assert!( @@ -55,7 +55,7 @@ fn test_get_or_create_with_corrupted_settings( ); // Check that the error message contains the expected text - let error_output = sandbox.last_stderr.clone(); + let error_output = layer.last_stderr.clone(); assert!( error_output.contains("Failed to load existing layer settings") @@ -70,17 +70,17 @@ fn test_get_or_create_with_corrupted_settings( #[rstest] fn test_get_or_create_with_unreadable_settings( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - // First, create a working sandbox - let _output = sandbox.run(&["echo", "initial setup"])?; + // First, create a working layer + let _output = layer.run(&["echo", "initial setup"])?; - // Get the sandbox directory from the sandbox tool itself - let sandbox_dir = sandbox.dir()?; - let data_dir = sandbox_dir.join("data"); + // Get the layer directory from the layer tool itself + let layer_dir = layer.dir()?; + let data_dir = layer_dir.join("data"); let settings_file = data_dir.join("settings.json"); - // Verify the sandbox was created and settings file exists + // Verify the layer was created and settings file exists assert!( settings_file.exists(), "Settings file should exist after initial layer creation" @@ -96,7 +96,7 @@ fn test_get_or_create_with_unreadable_settings( // Only test this if we can actually change permissions (i.e., we're not root) if fs::set_permissions(&settings_file, perms).is_ok() { // Try to run another command - this should trigger the error path - let success = sandbox.pass(&["echo", "second command"]); + let success = layer.pass(&["echo", "second command"]); // The command should fail due to permission error assert!( @@ -105,7 +105,7 @@ fn test_get_or_create_with_unreadable_settings( ); // Check that the error message contains the expected text - let error_output = sandbox.last_stderr.clone(); + let error_output = layer.last_stderr.clone(); assert!( error_output.contains("Failed to load existing layer settings") @@ -127,17 +127,17 @@ fn test_get_or_create_with_unreadable_settings( #[rstest] fn test_get_or_create_with_directory_as_settings_file( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - // First, create a working sandbox - let _output = sandbox.run(&["echo", "initial setup"])?; + // First, create a working layer + let _output = layer.run(&["echo", "initial setup"])?; - // Get the sandbox directory from the sandbox tool itself - let sandbox_dir = sandbox.dir()?; - let data_dir = sandbox_dir.join("data"); + // Get the layer directory from the layer tool itself + let layer_dir = layer.dir()?; + let data_dir = layer_dir.join("data"); let settings_file = data_dir.join("settings.json"); - // Verify the sandbox was created and settings file exists + // Verify the layer was created and settings file exists assert!( settings_file.exists(), "Settings file should exist after initial layer creation" @@ -154,7 +154,7 @@ fn test_get_or_create_with_directory_as_settings_file( ); // Try to run another command - this should trigger the error path - let success = sandbox.pass(&["echo", "second command"]); + let success = layer.pass(&["echo", "second command"]); // The command should fail assert!( @@ -163,7 +163,7 @@ fn test_get_or_create_with_directory_as_settings_file( ); // Check that the error message contains the expected text - let error_output = sandbox.last_stderr.clone(); + let error_output = layer.last_stderr.clone(); assert!( error_output.contains("Failed to load existing layer settings") diff --git a/tests/ai_test_delete.rs b/tests/ai_test_delete.rs index b21d813..f226157 100644 --- a/tests/ai_test_delete.rs +++ b/tests/ai_test_delete.rs @@ -6,391 +6,391 @@ use rstest::*; use std::path::{Path, PathBuf}; #[rstest] -fn test_delete_single_sandbox() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); +fn test_delete_single_layer() -> Result<()> { + let mut layer = layer(); + let name = layer.name.clone(); - // Create and run a sandbox - sandbox.run(&["true"])?; + // Create and run a layer + layer.run(&["true"])?; - // Verify sandbox exists - sandbox.run(&["list"])?; - assert!(sandbox.last_stdout.contains(&name)); + // Verify layer exists + layer.run(&["list"])?; + assert!(layer.last_stdout.contains(&name)); // Delete with confirmation (use -y flag) - sandbox.run(&["delete", "-y", &name])?; - assert!(sandbox.last_stdout.contains(&name)); - assert!(sandbox.last_stdout.contains("1 layers deleted")); + layer.run(&["delete", "-y", &name])?; + assert!(layer.last_stdout.contains(&name)); + assert!(layer.last_stdout.contains("1 layers deleted")); - // Verify sandbox no longer exists - sandbox.run(&["list"])?; - assert!(!sandbox.last_stdout.contains(&name)); + // Verify layer no longer exists + layer.run(&["list"])?; + assert!(!layer.last_stdout.contains(&name)); Ok(()) } #[rstest] -fn test_delete_current_sandbox_without_y() -> Result<()> { - let mut sandbox = sandbox(); - let _name = sandbox.name.clone(); +fn test_delete_current_layer_without_y() -> Result<()> { + let mut layer = layer(); + let _name = layer.name.clone(); - // Create and run the sandbox - sandbox.run(&["true"])?; + // Create and run the layer + layer.run(&["true"])?; - // Delete without patterns and without -y should prompt for current sandbox - // TODO: Once the bug is fixed, this should show the current sandbox + // Delete without patterns and without -y should prompt for current layer + // TODO: Once the bug is fixed, this should show the current layer // For now it will show "No default layer found" - sandbox.run_with_stdin(&["delete"], "n\n")?; + layer.run_with_stdin(&["delete"], "n\n")?; assert!( - sandbox + layer .last_stdout .contains("The following layers will be deleted") ); - assert!(sandbox.last_stdout.contains(&sandbox.name)); + assert!(layer.last_stdout.contains(&layer.name)); Ok(()) } #[rstest] -fn test_delete_current_sandbox_no_pattern() -> Result<()> { - let mut sandbox = sandbox(); - let _name = sandbox.name.clone(); +fn test_delete_current_layer_no_pattern() -> Result<()> { + let mut layer = layer(); + let _name = layer.name.clone(); - // Create and run a sandbox - sandbox.run(&["true"])?; + // Create and run a layer + layer.run(&["true"])?; - // Delete without pattern should delete current sandbox + // Delete without pattern should delete current layer // NOTE: There's a bug in the current implementation where patterns.is_empty() // is checked twice with contradictory logic, so it currently shows "No default layer" - sandbox.run(&["delete", "-y"])?; + layer.run(&["delete", "-y"])?; - // TODO: Once the bug is fixed, this should delete the current sandbox + // TODO: Once the bug is fixed, this should delete the current layer // For now, we test what it actually does - assert!(sandbox.last_stdout.contains("1 layers deleted")); + assert!(layer.last_stdout.contains("1 layers deleted")); Ok(()) } #[rstest] -fn test_delete_current_non_existent_sandbox() -> Result<()> { - let mut sandbox = sandbox(); - let _name = sandbox.name.clone(); +fn test_delete_current_non_existent_layer() -> Result<()> { + let mut layer = layer(); + let _name = layer.name.clone(); - sandbox.run_with_stdin(&["delete"], "y\n")?; - assert!(sandbox.last_stdout.contains("No layer by the name")); + layer.run_with_stdin(&["delete"], "y\n")?; + assert!(layer.last_stdout.contains("No layer by the name")); Ok(()) } #[rstest] -fn test_delete_shows_sandbox_status() -> Result<()> { - let mut sandbox1 = sandbox(); - let mut sandbox2 = sandbox(); +fn test_delete_shows_layer_status() -> Result<()> { + let mut layer1 = layer(); + let mut layer2 = layer(); // Give them unique but similar names let base_name = format!("devlayer-coverage-test-del-status-{}", rid()); - sandbox1.name = format!("{}-1", base_name); - sandbox2.name = format!("{}-2", base_name); - let name1 = sandbox1.name.clone(); - let name2 = sandbox2.name.clone(); + layer1.name = format!("{}-1", base_name); + layer2.name = format!("{}-2", base_name); + let name1 = layer1.name.clone(); + let name2 = layer2.name.clone(); - // Create running sandbox - sandbox1.run(&["true"])?; + // Create running layer + layer1.run(&["true"])?; - // Create and stop another sandbox - sandbox2.run(&["true"])?; - sandbox2.run(&["stop", &name2])?; + // Create and stop another layer + layer2.run(&["true"])?; + layer2.run(&["stop", &name2])?; // Delete both with specific pattern - sandbox1.run(&["delete", "-y", &format!("{}*", base_name)])?; + layer1.run(&["delete", "-y", &format!("{}*", base_name)])?; // Check output shows status information - assert!(sandbox1.last_stdout.contains(&name1)); - assert!(sandbox1.last_stdout.contains(&name2)); - // The actual output format shows "running" or "stopped" before the sandbox name - assert!(sandbox1.last_stdout.contains("2 layers deleted")); + assert!(layer1.last_stdout.contains(&name1)); + assert!(layer1.last_stdout.contains(&name2)); + // The actual output format shows "running" or "stopped" before the layer name + assert!(layer1.last_stdout.contains("2 layers deleted")); Ok(()) } #[rstest] -fn test_delete_multiple_sandboxes_with_pattern() -> Result<()> { - let mut sandbox1 = sandbox(); - let mut sandbox2 = sandbox(); - let mut sandbox3 = sandbox(); +fn test_delete_multiple_layers_with_pattern() -> Result<()> { + let mut layer1 = layer(); + let mut layer2 = layer(); + let mut layer3 = layer(); // Give them related names - sandbox1.name = format!("devlayer-coverage-test-delete-{}", rid()); - sandbox2.name = format!("devlayer-coverage-test-delete-{}", rid()); - sandbox3.name = format!("devlayer-coverage-test-other-{}", rid()); + layer1.name = format!("devlayer-coverage-test-delete-{}", rid()); + layer2.name = format!("devlayer-coverage-test-delete-{}", rid()); + layer3.name = format!("devlayer-coverage-test-other-{}", rid()); - // Create sandboxes - sandbox1.run(&["true"])?; - sandbox2.run(&["true"])?; - sandbox3.run(&["true"])?; + // Create layers + layer1.run(&["true"])?; + layer2.run(&["true"])?; + layer3.run(&["true"])?; - // Delete sandboxes matching pattern - sandbox1.run(&["delete", "-y", "devlayer-coverage-test-delete*"])?; + // Delete layers matching pattern + layer1.run(&["delete", "-y", "devlayer-coverage-test-delete*"])?; - // Should show the sandboxes being deleted - assert!(sandbox1.last_stdout.contains(&sandbox1.name)); - assert!(sandbox1.last_stdout.contains(&sandbox2.name)); - assert!(!sandbox1.last_stdout.contains(&sandbox3.name)); + // Should show the layers being deleted + assert!(layer1.last_stdout.contains(&layer1.name)); + assert!(layer1.last_stdout.contains(&layer2.name)); + assert!(!layer1.last_stdout.contains(&layer3.name)); // Count how many were actually deleted (at least 2) - let deleted_count = sandbox1 + let deleted_count = layer1 .last_stdout .lines() .filter(|line| line.contains("Deleted layer:")) .count(); assert!(deleted_count >= 2); - // Verify only matching sandboxes were deleted - sandbox1.run(&["list"])?; - assert!(!sandbox1.last_stdout.contains(&sandbox1.name)); - assert!(!sandbox1.last_stdout.contains(&sandbox2.name)); - assert!(sandbox1.last_stdout.contains(&sandbox3.name)); + // Verify only matching layers were deleted + layer1.run(&["list"])?; + assert!(!layer1.last_stdout.contains(&layer1.name)); + assert!(!layer1.last_stdout.contains(&layer2.name)); + assert!(layer1.last_stdout.contains(&layer3.name)); Ok(()) } #[rstest] -fn test_delete_no_matching_sandboxes() -> Result<()> { - let mut sandbox = sandbox(); +fn test_delete_no_matching_layers() -> Result<()> { + let mut layer = layer(); - // Try to delete non-existent sandbox - sandbox.run(&["delete", "-y", "non-existent-layer"])?; - assert!(sandbox.last_stdout.contains("No layers found matching")); + // Try to delete non-existent layer + layer.run(&["delete", "-y", "non-existent-layer"])?; + assert!(layer.last_stdout.contains("No layers found matching")); Ok(()) } #[rstest] -fn test_delete_stopped_sandbox() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); +fn test_delete_stopped_layer() -> Result<()> { + let mut layer = layer(); + let name = layer.name.clone(); - // Create and run a sandbox - sandbox.run(&["true"])?; + // Create and run a layer + layer.run(&["true"])?; - // Stop the sandbox - sandbox.run(&["stop"])?; - sandbox.run(&["accept"])?; + // Stop the layer + layer.run(&["stop"])?; + layer.run(&["accept"])?; - // Delete the stopped sandbox - sandbox.run_with_stdin(&["delete"], "y\n")?; - println!("{}", sandbox.last_stdout); - assert!(sandbox.last_stdout.contains("0 entries")); - assert!(sandbox.last_stdout.contains("stopped")); - assert!(sandbox.last_stdout.contains(&name)); - assert!(sandbox.last_stdout.contains("1 layers deleted")); + // Delete the stopped layer + layer.run_with_stdin(&["delete"], "y\n")?; + println!("{}", layer.last_stdout); + assert!(layer.last_stdout.contains("0 entries")); + assert!(layer.last_stdout.contains("stopped")); + assert!(layer.last_stdout.contains(&name)); + assert!(layer.last_stdout.contains("1 layers deleted")); Ok(()) } #[rstest] -fn test_delete_modified_sandbox_n() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); - let filename = sandbox.test_filename("test_file"); - - // Create and run a sandbox - sandbox.run(&["touch", &filename])?; - - // Delete the stopped sandbox - sandbox.run_with_stdin(&["delete", &name], "n\n")?; - eprintln!("{}", sandbox.last_stdout); - assert!(sandbox.last_stdout.contains("3 entries")); - assert!(sandbox.last_stdout.contains("0 ignored")); - assert!(sandbox.last_stdout.contains("running")); - assert!(sandbox.last_stdout.contains(&name)); +fn test_delete_modified_layer_n() -> Result<()> { + let mut layer = layer(); + let name = layer.name.clone(); + let filename = layer.test_filename("test_file"); + + // Create and run a layer + layer.run(&["touch", &filename])?; + + // Delete the stopped layer + layer.run_with_stdin(&["delete", &name], "n\n")?; + eprintln!("{}", layer.last_stdout); + assert!(layer.last_stdout.contains("3 entries")); + assert!(layer.last_stdout.contains("0 ignored")); + assert!(layer.last_stdout.contains("running")); + assert!(layer.last_stdout.contains(&name)); Ok(()) } #[rstest] -fn test_delete_modified_ignored_sandbox_n() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); - let filename = sandbox.test_filename("test_file"); - - // Create and run a sandbox - sandbox.run(&["touch", &filename])?; - - // Delete the stopped sandbox - sandbox.set_ignored(false); - sandbox.run_with_stdin(&["delete", &name], "n\n")?; - eprintln!("{}", sandbox.last_stdout); - assert!(sandbox.last_stdout.contains("0 entries")); - assert!(sandbox.last_stdout.contains("3 ignored")); - assert!(sandbox.last_stdout.contains("running")); - assert!(sandbox.last_stdout.contains(&name)); +fn test_delete_modified_ignored_layer_n() -> Result<()> { + let mut layer = layer(); + let name = layer.name.clone(); + let filename = layer.test_filename("test_file"); + + // Create and run a layer + layer.run(&["touch", &filename])?; + + // Delete the stopped layer + layer.set_ignored(false); + layer.run_with_stdin(&["delete", &name], "n\n")?; + eprintln!("{}", layer.last_stdout); + assert!(layer.last_stdout.contains("0 entries")); + assert!(layer.last_stdout.contains("3 ignored")); + assert!(layer.last_stdout.contains("running")); + assert!(layer.last_stdout.contains(&name)); Ok(()) } #[rstest] -fn test_delete_stopped_sandbox_by_name() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); +fn test_delete_stopped_layer_by_name() -> Result<()> { + let mut layer = layer(); + let name = layer.name.clone(); - // Create and run a sandbox - sandbox.run(&["true"])?; + // Create and run a layer + layer.run(&["true"])?; - // Stop the sandbox - sandbox.run(&["stop"])?; - sandbox.run(&["accept"])?; + // Stop the layer + layer.run(&["stop"])?; + layer.run(&["accept"])?; - // Delete the stopped sandbox - sandbox.run_with_stdin(&["delete", &name], "y\n")?; - assert!(sandbox.last_stdout.contains("0 entries")); - assert!(sandbox.last_stdout.contains("stopped")); - assert!(sandbox.last_stdout.contains(&name)); - assert!(sandbox.last_stdout.contains("1 layers deleted")); + // Delete the stopped layer + layer.run_with_stdin(&["delete", &name], "y\n")?; + assert!(layer.last_stdout.contains("0 entries")); + assert!(layer.last_stdout.contains("stopped")); + assert!(layer.last_stdout.contains(&name)); + assert!(layer.last_stdout.contains("1 layers deleted")); Ok(()) } #[rstest] -fn test_delete_failure(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run(&["true"])?; - assert!(sandbox.epass(&["delete", "-y"], "TEST_DELETE_FAILURE", "1")); - assert!(sandbox.last_stdout.contains("Error deleting layer")); +fn test_delete_failure(mut layer: LayerManager) -> Result<()> { + layer.run(&["true"])?; + assert!(layer.epass(&["delete", "-y"], "TEST_DELETE_FAILURE", "1")); + assert!(layer.last_stdout.contains("Error deleting layer")); Ok(()) } #[rstest] -fn test_delete_running_sandbox_by_name() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); +fn test_delete_running_layer_by_name() -> Result<()> { + let mut layer = layer(); + let name = layer.name.clone(); - // Create and run a sandbox - sandbox.run(&["true"])?; + // Create and run a layer + layer.run(&["true"])?; - // Accept the sandbox - sandbox.run(&["accept"])?; + // Accept the layer + layer.run(&["accept"])?; - // Delete the running sandbox - sandbox.run_with_stdin(&["delete", &name], "y\n")?; - assert!(sandbox.last_stdout.contains("running")); - assert!(sandbox.last_stdout.contains(&name)); - assert!(sandbox.last_stdout.contains("1 layers deleted")); + // Delete the running layer + layer.run_with_stdin(&["delete", &name], "y\n")?; + assert!(layer.last_stdout.contains("running")); + assert!(layer.last_stdout.contains(&name)); + assert!(layer.last_stdout.contains("1 layers deleted")); Ok(()) } #[rstest] -fn test_delete_running_sandbox_no_modifications_no_confirm() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); +fn test_delete_running_layer_no_modifications_no_confirm() -> Result<()> { + let mut layer = layer(); + let name = layer.name.clone(); - // Create and run a sandbox without any modifications - sandbox.run(&["true"])?; + // Create and run a layer without any modifications + layer.run(&["true"])?; // Delete should work even though there are no modifications - sandbox.run(&["delete", "-y", &name])?; - assert!(sandbox.last_stdout.contains(&name)); - assert!(sandbox.last_stdout.contains("1 layers deleted")); + layer.run(&["delete", "-y", &name])?; + assert!(layer.last_stdout.contains(&name)); + assert!(layer.last_stdout.contains("1 layers deleted")); - // Verify sandbox no longer exists - sandbox.run(&["list"])?; - assert!(!sandbox.last_stdout.contains(&name)); + // Verify layer no longer exists + layer.run(&["list"])?; + assert!(!layer.last_stdout.contains(&name)); Ok(()) } #[rstest] -fn test_delete_multiple_stopped_sandboxes() -> Result<()> { - let mut sandbox1 = sandbox(); - let mut sandbox2 = sandbox(); - let mut sandbox3 = sandbox(); +fn test_delete_multiple_stopped_layers() -> Result<()> { + let mut layer1 = layer(); + let mut layer2 = layer(); + let mut layer3 = layer(); // Give them related names let base_name = format!("devlayer-coverage-test-del-stopped-{}", rid()); - sandbox1.name = format!("{}-1", base_name); - sandbox2.name = format!("{}-2", base_name); - sandbox3.name = format!("{}-3", base_name); - let name1 = sandbox1.name.clone(); - let name2 = sandbox2.name.clone(); - let name3 = sandbox3.name.clone(); + layer1.name = format!("{}-1", base_name); + layer2.name = format!("{}-2", base_name); + layer3.name = format!("{}-3", base_name); + let name1 = layer1.name.clone(); + let name2 = layer2.name.clone(); + let name3 = layer3.name.clone(); - // Create and stop all sandboxes - sandbox1.run(&["true"])?; - sandbox1.run(&["stop", &name1])?; + // Create and stop all layers + layer1.run(&["true"])?; + layer1.run(&["stop", &name1])?; - sandbox2.run(&["true"])?; - sandbox2.run(&["stop", &name2])?; + layer2.run(&["true"])?; + layer2.run(&["stop", &name2])?; - sandbox3.run(&["true"])?; - sandbox3.run(&["stop", &name3])?; + layer3.run(&["true"])?; + layer3.run(&["stop", &name3])?; - // Delete all stopped sandboxes with pattern - sandbox1.run(&["delete", "-y", &format!("{}*", base_name)])?; + // Delete all stopped layers with pattern + layer1.run(&["delete", "-y", &format!("{}*", base_name)])?; - // Should show all sandboxes as stopped - assert!(sandbox1.last_stdout.contains(&name1)); - assert!(sandbox1.last_stdout.contains(&name2)); - assert!(sandbox1.last_stdout.contains(&name3)); - assert!(sandbox1.last_stdout.contains("3 layers deleted")); + // Should show all layers as stopped + assert!(layer1.last_stdout.contains(&name1)); + assert!(layer1.last_stdout.contains(&name2)); + assert!(layer1.last_stdout.contains(&name3)); + assert!(layer1.last_stdout.contains("3 layers deleted")); Ok(()) } #[rstest] -fn test_delete_mixed_running_and_stopped_sandboxes() -> Result<()> { - let mut sandbox1 = sandbox(); - let mut sandbox2 = sandbox(); - let mut sandbox3 = sandbox(); +fn test_delete_mixed_running_and_stopped_layers() -> Result<()> { + let mut layer1 = layer(); + let mut layer2 = layer(); + let mut layer3 = layer(); // Give them related names let base_name = format!("devlayer-coverage-test-del-mixed-{}", rid()); - sandbox1.name = format!("{}-running", base_name); - sandbox2.name = format!("{}-stopped", base_name); - sandbox3.name = format!("{}-also-running", base_name); - let name1 = sandbox1.name.clone(); - let name2 = sandbox2.name.clone(); - let name3 = sandbox3.name.clone(); + layer1.name = format!("{}-running", base_name); + layer2.name = format!("{}-stopped", base_name); + layer3.name = format!("{}-also-running", base_name); + let name1 = layer1.name.clone(); + let name2 = layer2.name.clone(); + let name3 = layer3.name.clone(); - // Create mixed state sandboxes - sandbox1.run(&["true"])?; // Keep running + // Create mixed state layers + layer1.run(&["true"])?; // Keep running - sandbox2.run(&["true"])?; - sandbox2.run(&["stop", &name2])?; // Stop this one + layer2.run(&["true"])?; + layer2.run(&["stop", &name2])?; // Stop this one - sandbox3.run(&["true"])?; // Keep running + layer3.run(&["true"])?; // Keep running // Delete all with pattern - sandbox1.run(&["delete", "-y", &format!("{}*", base_name)])?; + layer1.run(&["delete", "-y", &format!("{}*", base_name)])?; // Check that output distinguishes between running and stopped - assert!(sandbox1.last_stdout.contains(&name1)); - assert!(sandbox1.last_stdout.contains(&name2)); - assert!(sandbox1.last_stdout.contains(&name3)); - assert!(sandbox1.last_stdout.contains("3 layers deleted")); + assert!(layer1.last_stdout.contains(&name1)); + assert!(layer1.last_stdout.contains(&name2)); + assert!(layer1.last_stdout.contains(&name3)); + assert!(layer1.last_stdout.contains("3 layers deleted")); // Verify all are deleted - sandbox1.run(&["list"])?; - assert!(!sandbox1.last_stdout.contains(&name1)); - assert!(!sandbox1.last_stdout.contains(&name2)); - assert!(!sandbox1.last_stdout.contains(&name3)); + layer1.run(&["list"])?; + assert!(!layer1.last_stdout.contains(&name1)); + assert!(!layer1.last_stdout.contains(&name2)); + assert!(!layer1.last_stdout.contains(&name3)); Ok(()) } #[rstest] fn test_delete_json_output() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); + let mut layer = layer(); + let name = layer.name.clone(); - // Create sandbox - sandbox.run(&["true"])?; + // Create layer + layer.run(&["true"])?; // Delete with JSON output - sandbox.run(&["--json", "delete", "-y", &name])?; + layer.run(&["--json", "delete", "-y", &name])?; // Parse JSON output - let output: serde_json::Value = serde_json::from_str(&sandbox.last_stdout)?; + let output: serde_json::Value = serde_json::from_str(&layer.last_stdout)?; assert_eq!(output["status"], "success"); assert!( output["deleted"] @@ -405,135 +405,135 @@ fn test_delete_json_output() -> Result<()> { #[rstest] fn test_delete_confirmation_yes() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); + let mut layer = layer(); + let name = layer.name.clone(); - // Create and run a sandbox - sandbox.run(&["true"])?; + // Create and run a layer + layer.run(&["true"])?; // Test confirming with 'y' - sandbox.run_with_stdin(&["delete", &name], "y\n")?; - assert!(sandbox.last_stdout.contains("1 layers deleted")); - assert!(sandbox.last_stdout.contains(&name)); + layer.run_with_stdin(&["delete", &name], "y\n")?; + assert!(layer.last_stdout.contains("1 layers deleted")); + assert!(layer.last_stdout.contains(&name)); Ok(()) } #[rstest] fn test_delete_confirmation_no() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); + let mut layer = layer(); + let name = layer.name.clone(); - // Create and run a sandbox - sandbox.run(&["true"])?; + // Create and run a layer + layer.run(&["true"])?; // Test cancelling with 'n' - sandbox.run_with_stdin(&["delete", &name], "n\n")?; - assert!(sandbox.last_stdout.contains("Delete operation cancelled")); + layer.run_with_stdin(&["delete", &name], "n\n")?; + assert!(layer.last_stdout.contains("Delete operation cancelled")); - // Verify sandbox still exists - sandbox.run(&["list"])?; - assert!(sandbox.last_stdout.contains(&name)); + // Verify layer still exists + layer.run(&["list"])?; + assert!(layer.last_stdout.contains(&name)); Ok(()) } #[rstest] fn test_delete_confirmation_capital_n() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); + let mut layer = layer(); + let name = layer.name.clone(); - // Create and run a sandbox - sandbox.run(&["true"])?; + // Create and run a layer + layer.run(&["true"])?; // Test cancelling with 'N' - sandbox.run_with_stdin(&["delete", &name], "N\n")?; - assert!(sandbox.last_stdout.contains("Delete operation cancelled")); + layer.run_with_stdin(&["delete", &name], "N\n")?; + assert!(layer.last_stdout.contains("Delete operation cancelled")); - // Verify sandbox still exists - sandbox.run(&["list"])?; - assert!(sandbox.last_stdout.contains(&name)); + // Verify layer still exists + layer.run(&["list"])?; + assert!(layer.last_stdout.contains(&name)); Ok(()) } #[rstest] fn test_delete_confirmation_default_no() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); + let mut layer = layer(); + let name = layer.name.clone(); - // Create and run a sandbox - sandbox.run(&["true"])?; + // Create and run a layer + layer.run(&["true"])?; // Test pressing just Enter (should default to No) - sandbox.run_with_stdin(&["delete", &name], "\n")?; - assert!(sandbox.last_stdout.contains("Delete operation cancelled")); + layer.run_with_stdin(&["delete", &name], "\n")?; + assert!(layer.last_stdout.contains("Delete operation cancelled")); - // Verify sandbox still exists - sandbox.run(&["list"])?; - assert!(sandbox.last_stdout.contains(&name)); + // Verify layer still exists + layer.run(&["list"])?; + assert!(layer.last_stdout.contains(&name)); Ok(()) } #[rstest] fn test_delete_cleans_all_files() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); + let mut layer = layer(); + let name = layer.name.clone(); - // Create sandbox - sandbox.run(&["true"])?; + // Create layer + layer.run(&["true"])?; // Get storage directory to verify files - sandbox.run(&["config", "storage_dir"])?; - let storage_dir = PathBuf::from(sandbox.last_stdout.trim()); + layer.run(&["config", "storage_dir"])?; + let storage_dir = PathBuf::from(layer.last_stdout.trim()); let lock_file = storage_dir.join(format!("{}.lock", name)); let pid_file = storage_dir.join(format!("{}.pid", name)); - let sandbox_dir = storage_dir.join(&name); + let layer_dir = storage_dir.join(&name); // Verify files exist before deletion - assert!(lock_file.exists() || pid_file.exists() || sandbox_dir.exists()); + assert!(lock_file.exists() || pid_file.exists() || layer_dir.exists()); - // Delete sandbox - sandbox.run(&["delete", "-y", &name])?; + // Delete layer + layer.run(&["delete", "-y", &name])?; // Verify all files are removed assert!(!lock_file.exists()); assert!(!pid_file.exists()); - assert!(!sandbox_dir.exists()); + assert!(!layer_dir.exists()); Ok(()) } #[rstest] fn test_delete_with_modifications() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); + let mut layer = layer(); + let name = layer.name.clone(); - // Create sandbox and make some modifications - sandbox.run(&["true"])?; - let test_file = sandbox.test_filename("test_file"); - sandbox.run(&["sh", "-c", &format!("echo 'test' > {}", test_file)])?; + // Create layer and make some modifications + layer.run(&["true"])?; + let test_file = layer.test_filename("test_file"); + layer.run(&["sh", "-c", &format!("echo 'test' > {}", test_file)])?; // Delete with -y flag just shows success messages - sandbox.run(&["delete", "-y", &name])?; - assert!(sandbox.last_stdout.contains(&name)); - assert!(sandbox.last_stdout.contains("1 layers deleted")); + layer.run(&["delete", "-y", &name])?; + assert!(layer.last_stdout.contains(&name)); + assert!(layer.last_stdout.contains("1 layers deleted")); Ok(()) } #[rstest] fn test_delete_ignore_invalid_upper_dirs( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - sandbox.run(&["config", "storage_dir"])?; - let storage_dir = sandbox.last_stdout.trim(); - let sandbox_upper_dir = - Path::new(storage_dir).join(&sandbox.name).join("upper"); + layer.run(&["config", "storage_dir"])?; + let storage_dir = layer.last_stdout.trim(); + let layer_upper_dir = + Path::new(storage_dir).join(&layer.name).join("upper"); - let invalid_base32_dir = sandbox_upper_dir.join("@@@INVALID@@@"); + let invalid_base32_dir = layer_upper_dir.join("@@@INVALID@@@"); std::fs::create_dir_all(&invalid_base32_dir)?; std::fs::create_dir_all(invalid_base32_dir.join("subdir"))?; std::fs::write(invalid_base32_dir.join("subdir/file.txt"), "test")?; @@ -541,18 +541,18 @@ fn test_delete_ignore_invalid_upper_dirs( let invalid_utf8_bytes = vec![0xFF, 0xFE]; let base32_invalid_utf8 = data_encoding::BASE32_NOPAD_NOCASE.encode(&invalid_utf8_bytes); - let invalid_utf8_dir = sandbox_upper_dir.join(&base32_invalid_utf8); + let invalid_utf8_dir = layer_upper_dir.join(&base32_invalid_utf8); std::fs::create_dir_all(&invalid_utf8_dir)?; std::fs::create_dir_all(invalid_utf8_dir.join("subdir"))?; std::fs::write(invalid_utf8_dir.join("subdir/file.txt"), "test")?; - let filename = sandbox.test_filename("file"); - sandbox.run(&["touch", &filename])?; + let filename = layer.test_filename("file"); + layer.run(&["touch", &filename])?; // Run it - //sandbox.run(&["true"])?; + //layer.run(&["true"])?; // Now delete should process these directories and skip them - sandbox.run_with_stdin(&["delete"], "y\n")?; - assert!(sandbox.last_stdout.contains("1 layers deleted")); + layer.run_with_stdin(&["delete"], "y\n")?; + assert!(layer.last_stdout.contains("1 layers deleted")); Ok(()) } diff --git a/tests/ai_test_diff_coverage.rs b/tests/ai_test_diff_coverage.rs index 8502605..1cc4329 100644 --- a/tests/ai_test_diff_coverage.rs +++ b/tests/ai_test_diff_coverage.rs @@ -6,72 +6,72 @@ use rstest::*; use std::fs; #[rstest] -fn test_diff_rename_operation(mut sandbox: SandboxManager) -> Result<()> { +fn test_diff_rename_operation(mut layer: LayerManager) -> Result<()> { // Test rename operation - directories show as "### Moved" - let dir1 = sandbox.test_filename("dir1"); - let dir2 = sandbox.test_filename("dir2"); + let dir1 = layer.test_filename("dir1"); + let dir2 = layer.test_filename("dir2"); fs::create_dir(&dir1)?; // Rename the directory - sandbox.run(&["mv", &dir1, &dir2])?; + layer.run(&["mv", &dir1, &dir2])?; // Diff should show the rename - sandbox.run(&["diff"])?; - assert!(sandbox.last_stdout.contains("### Moved")); - assert!(sandbox.last_stdout.contains(&dir1)); - assert!(sandbox.last_stdout.contains(&dir2)); + layer.run(&["diff"])?; + assert!(layer.last_stdout.contains("### Moved")); + assert!(layer.last_stdout.contains(&dir1)); + assert!(layer.last_stdout.contains(&dir2)); Ok(()) } #[rstest] -fn test_diff_colorized_output(mut sandbox: SandboxManager) -> Result<()> { +fn test_diff_colorized_output(mut layer: LayerManager) -> Result<()> { // Test colorized diff output - let file = sandbox.test_filename("color_test.txt"); + let file = layer.test_filename("color_test.txt"); fs::write(&file, "original")?; // Modify file - sandbox.run(&["sh", "-c", &format!("echo 'modified' > {}", file)])?; + layer.run(&["sh", "-c", &format!("echo 'modified' > {}", file)])?; // Check diff output with color forced - sandbox.run_with_env(&["diff"], "TEST_FORCE_DIFF_COLOR", "1")?; - assert!(sandbox.last_stdout.contains("-original")); - assert!(sandbox.last_stdout.contains("+modified")); + layer.run_with_env(&["diff"], "TEST_FORCE_DIFF_COLOR", "1")?; + assert!(layer.last_stdout.contains("-original")); + assert!(layer.last_stdout.contains("+modified")); // The actual color codes would be in the output when TEST_FORCE_DIFF_COLOR is set Ok(()) } #[rstest] -fn test_diff_no_color(mut sandbox: SandboxManager) -> Result<()> { +fn test_diff_no_color(mut layer: LayerManager) -> Result<()> { // Test non-colorized diff output - let file = sandbox.test_filename("no_color.txt"); + let file = layer.test_filename("no_color.txt"); fs::write(&file, "content")?; // Modify file - sandbox.run(&["sh", "-c", &format!("echo 'changed' > {}", file)])?; + layer.run(&["sh", "-c", &format!("echo 'changed' > {}", file)])?; // Check diff output with NO_COLOR set - sandbox.run_with_env(&["diff"], "NO_COLOR", "1")?; - assert!(sandbox.last_stdout.contains("-content")); - assert!(sandbox.last_stdout.contains("+changed")); + layer.run_with_env(&["diff"], "NO_COLOR", "1")?; + assert!(layer.last_stdout.contains("-content")); + assert!(layer.last_stdout.contains("+changed")); Ok(()) } #[rstest] -fn test_diff_rename_colorized(mut sandbox: SandboxManager) -> Result<()> { +fn test_diff_rename_colorized(mut layer: LayerManager) -> Result<()> { // Test colorized rename output - directories show as "### Moved" - let dir1 = sandbox.test_filename("color_dir1"); - let dir2 = sandbox.test_filename("color_dir2"); + let dir1 = layer.test_filename("color_dir1"); + let dir2 = layer.test_filename("color_dir2"); fs::create_dir(&dir1)?; // Rename the directory - sandbox.run(&["mv", &dir1, &dir2])?; + layer.run(&["mv", &dir1, &dir2])?; // Diff with color forced - sandbox.run_with_env(&["diff"], "TEST_FORCE_DIFF_COLOR", "1")?; - assert!(sandbox.last_stdout.contains("### Moved")); + layer.run_with_env(&["diff"], "TEST_FORCE_DIFF_COLOR", "1")?; + assert!(layer.last_stdout.contains("### Moved")); // When colorized, the output would have ANSI color codes Ok(()) @@ -79,172 +79,166 @@ fn test_diff_rename_colorized(mut sandbox: SandboxManager) -> Result<()> { #[rstest] fn test_diff_error_operation_unsupported_file_type( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { // Create a FIFO (named pipe) - unsupported file type - let fifo_path = sandbox.test_filename("test.fifo"); + let fifo_path = layer.test_filename("test.fifo"); nix::unistd::mkfifo( fifo_path.as_str(), nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR, )?; // Try to modify it - sandbox.run(&["sh", "-c", "echo 'data' > test.fifo &"])?; + layer.run(&["sh", "-c", "echo 'data' > test.fifo &"])?; // Check diff - should skip error entries - sandbox.run(&["diff"])?; + layer.run(&["diff"])?; // Error operations are silently skipped in diff Ok(()) } #[rstest] -fn test_diff_non_file_destination(mut sandbox: SandboxManager) -> Result<()> { +fn test_diff_non_file_destination(mut layer: LayerManager) -> Result<()> { // Create a directory - let dir_path = sandbox.test_filename("test_dir"); + let dir_path = layer.test_filename("test_dir"); fs::create_dir(&dir_path)?; // Modify directory permissions - sandbox.run(&["chmod", "755", &dir_path])?; + layer.run(&["chmod", "755", &dir_path])?; // Diff should skip directories - sandbox.run(&["diff"])?; + layer.run(&["diff"])?; // Should not contain diff output for directory - assert!(!sandbox.last_stdout.contains("test_dir")); + assert!(!layer.last_stdout.contains("test_dir")); Ok(()) } #[rstest] -fn test_diff_staged_non_file(mut sandbox: SandboxManager) -> Result<()> { +fn test_diff_staged_non_file(mut layer: LayerManager) -> Result<()> { // Create a regular file - let file_path = sandbox.test_filename("regular.txt"); + let file_path = layer.test_filename("regular.txt"); fs::write(&file_path, "content")?; - // Replace it with a directory in sandbox - sandbox.run(&["rm", &file_path])?; - sandbox.run(&["mkdir", &file_path])?; + // Replace it with a directory in layer + layer.run(&["rm", &file_path])?; + layer.run(&["mkdir", &file_path])?; // Diff should handle this case - sandbox.run(&["diff"])?; + layer.run(&["diff"])?; Ok(()) } #[rstest] -fn test_diff_missing_destination_file( - mut sandbox: SandboxManager, -) -> Result<()> { +fn test_diff_missing_destination_file(mut layer: LayerManager) -> Result<()> { // Create a new file (destination doesn't exist) - sandbox.run(&["sh", "-c", "echo 'new content' > newfile.txt"])?; + layer.run(&["sh", "-c", "echo 'new content' > newfile.txt"])?; // Diff should use /dev/null as left path - sandbox.run(&["diff"])?; - assert!(sandbox.last_stdout.contains("+new content")); + layer.run(&["diff"])?; + assert!(layer.last_stdout.contains("+new content")); Ok(()) } #[rstest] -fn test_diff_remove_operation(mut sandbox: SandboxManager) -> Result<()> { +fn test_diff_remove_operation(mut layer: LayerManager) -> Result<()> { // Create a file - let file_path = sandbox.test_filename("to_remove.txt"); + let file_path = layer.test_filename("to_remove.txt"); fs::write(&file_path, "content to remove")?; // Remove it - sandbox.run(&["rm", &file_path])?; + layer.run(&["rm", &file_path])?; // Diff should show deletion - sandbox.run(&["diff"])?; - assert!(sandbox.last_stdout.contains("-content to remove")); + layer.run(&["diff"])?; + assert!(layer.last_stdout.contains("-content to remove")); Ok(()) } #[rstest] -fn test_diff_path_replacement_in_output( - mut sandbox: SandboxManager, -) -> Result<()> { +fn test_diff_path_replacement_in_output(mut layer: LayerManager) -> Result<()> { // Create a file with content - let file_path = sandbox.test_filename("path_test.txt"); + let file_path = layer.test_filename("path_test.txt"); fs::write(&file_path, "Original content")?; // Modify it - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!("echo 'Modified content' > {}", file_path), ])?; // Check diff output - sandbox.run(&["diff"])?; - assert!(sandbox.last_stdout.contains("-Original content")); - assert!(sandbox.last_stdout.contains("+Modified content")); + layer.run(&["diff"])?; + assert!(layer.last_stdout.contains("-Original content")); + assert!(layer.last_stdout.contains("+Modified content")); Ok(()) } #[rstest] -fn test_diff_force_color_env_variable( - mut sandbox: SandboxManager, -) -> Result<()> { +fn test_diff_force_color_env_variable(mut layer: LayerManager) -> Result<()> { // Create and modify a file - let file_path = sandbox.test_filename("color_test.txt"); + let file_path = layer.test_filename("color_test.txt"); fs::write(&file_path, "original")?; - sandbox.run(&["sh", "-c", &format!("echo 'modified' > {}", file_path)])?; + layer.run(&["sh", "-c", &format!("echo 'modified' > {}", file_path)])?; // Test with TEST_FORCE_DIFF_COLOR set - sandbox.run_with_env(&["diff"], "TEST_FORCE_DIFF_COLOR", "1")?; - assert!(sandbox.last_stdout.contains("-original")); - assert!(sandbox.last_stdout.contains("+modified")); + layer.run_with_env(&["diff"], "TEST_FORCE_DIFF_COLOR", "1")?; + assert!(layer.last_stdout.contains("-original")); + assert!(layer.last_stdout.contains("+modified")); // Color codes would be in the actual diff output Ok(()) } #[rstest] -fn test_diff_with_patterns(mut sandbox: SandboxManager) -> Result<()> { +fn test_diff_with_patterns(mut layer: LayerManager) -> Result<()> { // Create multiple files - let file1 = sandbox.test_filename("file1.txt"); - let file2 = sandbox.test_filename("file2.txt"); - let other = sandbox.test_filename("other.log"); + let file1 = layer.test_filename("file1.txt"); + let file2 = layer.test_filename("file2.txt"); + let other = layer.test_filename("other.log"); fs::write(&file1, "content1")?; fs::write(&file2, "content2")?; fs::write(&other, "log content")?; // Modify all files - sandbox.run(&["sh", "-c", + layer.run(&["sh", "-c", &format!("echo 'modified1' > {} && echo 'modified2' > {} && echo 'modified log' > {}", file1, file2, other)])?; // Diff with pattern - test filtering by specific file - sandbox.run(&["diff", &file1])?; - assert!(sandbox.last_stdout.contains("modified1")); - assert!(!sandbox.last_stdout.contains("modified2")); - assert!(!sandbox.last_stdout.contains("modified log")); + layer.run(&["diff", &file1])?; + assert!(layer.last_stdout.contains("modified1")); + assert!(!layer.last_stdout.contains("modified2")); + assert!(!layer.last_stdout.contains("modified log")); // Diff with pattern matching - show all changes - sandbox.run(&["diff"])?; - assert!(sandbox.last_stdout.contains("modified1")); - assert!(sandbox.last_stdout.contains("modified2")); - assert!(sandbox.last_stdout.contains("modified log")); + layer.run(&["diff"])?; + assert!(layer.last_stdout.contains("modified1")); + assert!(layer.last_stdout.contains("modified2")); + assert!(layer.last_stdout.contains("modified log")); Ok(()) } #[rstest] -fn test_diff_edge_case_null_staged(mut sandbox: SandboxManager) -> Result<()> { +fn test_diff_edge_case_null_staged(mut layer: LayerManager) -> Result<()> { // Create a file - let file_path = sandbox.test_filename("edge.txt"); + let file_path = layer.test_filename("edge.txt"); fs::write(&file_path, "original")?; - // Modify in sandbox - sandbox.run(&["sh", "-c", &format!("echo 'new' > {}", file_path)])?; + // Modify in layer + layer.run(&["sh", "-c", &format!("echo 'new' > {}", file_path)])?; // Diff should work normally - sandbox.run(&["diff"])?; - assert!(sandbox.last_stdout.contains("-original")); - assert!(sandbox.last_stdout.contains("+new")); + layer.run(&["diff"])?; + assert!(layer.last_stdout.contains("-original")); + assert!(layer.last_stdout.contains("+new")); Ok(()) } diff --git a/tests/ai_test_error_paths.rs b/tests/ai_test_error_paths.rs index dbe4155..973265c 100644 --- a/tests/ai_test_error_paths.rs +++ b/tests/ai_test_error_paths.rs @@ -9,76 +9,76 @@ use std::fs; use std::path::PathBuf; #[rstest] -fn ai_test_bind_source_missing(mut sandbox: SandboxManager) -> Result<()> { +fn ai_test_bind_source_missing(mut layer: LayerManager) -> Result<()> { let missing = format!("/does-not-exist-{}", rid()); let bind = format!("--bind={}", missing); - assert!(sandbox.xfail(&[&bind, "config", "bind"])); + assert!(layer.xfail(&[&bind, "config", "bind"])); assert!( - sandbox.last_stderr.contains(&format!( + layer.last_stderr.contains(&format!( "Failed to canonicalize source path: {}", missing )), "{}", - sandbox.last_stderr + layer.last_stderr ); Ok(()) } #[rstest] -fn ai_test_config_file_unreadable(mut sandbox: SandboxManager) -> Result<()> { +fn ai_test_config_file_unreadable(mut layer: LayerManager) -> Result<()> { // The path exists, but it's a directory so it can't be read - let dir = sandbox.test_filename("config-dir"); + let dir = layer.test_filename("config-dir"); fs::create_dir_all(&dir)?; - assert!(sandbox.xfail(&["--config", &dir, "config"])); + assert!(layer.xfail(&["--config", &dir, "config"])); assert!( - sandbox + layer .last_stderr .contains(&format!("Failed to read config file {}", dir)), "{}", - sandbox.last_stderr + layer.last_stderr ); Ok(()) } #[rstest] fn ai_test_new_with_unusable_storage_dir( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { // --new looks for an unused name in the storage directory, which fails // when the storage directory can't be used. --new conflicts with the // --name the fixture normally adds. - sandbox.no_default_options = true; + layer.no_default_options = true; let storage_dir = format!("--storage-dir=/proc/devlayer-coverage-{}", rid()); - assert!(sandbox.xfail(&["--new", &storage_dir, "config", "name"])); + assert!(layer.xfail(&["--new", &storage_dir, "config", "name"])); assert!( - sandbox + layer .last_stderr .contains("Failed to find a suitable storage directory"), "{}", - sandbox.last_stderr + layer.last_stderr ); Ok(()) } #[rstest] -fn ai_test_running_sandbox_without_settings( - mut sandbox: SandboxManager, +fn ai_test_running_layer_without_settings( + mut layer: LayerManager, ) -> Result<()> { - sandbox.run(&["true"])?; + layer.run(&["true"])?; - // Sandboxes started before settings were recorded don't have a + // Layers started before settings were recorded don't have a // settings file, so there is nothing to validate the config against - sandbox.run(&["config", "sandbox_dir"])?; + layer.run(&["config", "layer_dir"])?; let settings = - PathBuf::from(sandbox.last_stdout.trim()).join("data/settings.json"); + PathBuf::from(layer.last_stdout.trim()).join("data/settings.json"); assert!(settings.exists()); let removed = std::process::Command::new("sudo") .args(["rm", &settings.to_string_lossy()]) .status()?; assert!(removed.success()); - sandbox.run(&["echo", "still running"])?; - assert_eq!(sandbox.last_stdout.trim(), "still running"); + layer.run(&["echo", "still running"])?; + assert_eq!(layer.last_stdout.trim(), "still running"); Ok(()) } diff --git a/tests/ai_test_gitignore_anchored_pattern.rs b/tests/ai_test_gitignore_anchored_pattern.rs index a30718c..aeae08b 100644 --- a/tests/ai_test_gitignore_anchored_pattern.rs +++ b/tests/ai_test_gitignore_anchored_pattern.rs @@ -7,18 +7,18 @@ use std::path::Path; #[rstest] fn test_gitignore_anchored_directory_pattern( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - sandbox.set_ignored(false); // Don't automatically add --ignored for gitignore tests + layer.set_ignored(false); // Don't automatically add --ignored for gitignore tests // Create a working directory using test_filename - let test_dir = sandbox.test_filename("anchored-dir-test"); + let test_dir = layer.test_filename("anchored-dir-test"); std::fs::create_dir_all(&test_dir)?; // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), @@ -33,7 +33,7 @@ fn test_gitignore_anchored_directory_pattern( std::fs::create_dir_all(Path::new(&test_dir).join("dist/assets"))?; std::fs::create_dir_all(Path::new(&test_dir).join("src"))?; - // Create .gitignore file within the sandbox + // Create .gitignore file within the layer let gitignore_contents = r#" # Anchored directory pattern /target @@ -42,7 +42,7 @@ fn test_gitignore_anchored_directory_pattern( /dist/ "#; let gitignore_path = Path::new(&test_dir).join(".gitignore"); - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -52,7 +52,7 @@ fn test_gitignore_anchored_directory_pattern( ), ])?; - // Create test files - we need to create them in the sandbox to see changes + // Create test files - we need to create them in the layer to see changes let test_files = vec![ // Files under /target - should all be ignored ("target/foo", true), @@ -69,10 +69,10 @@ fn test_gitignore_anchored_directory_pattern( ("src/main.rs", false), ]; - // Create files within the sandbox + // Create files within the layer for (file, _) in &test_files { let file_path = Path::new(&test_dir).join(file); - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!("echo 'test content' > {}", file_path.to_str().unwrap()), @@ -80,15 +80,15 @@ fn test_gitignore_anchored_directory_pattern( } // Run status WITHOUT --ignored flag to see only non-ignored files - sandbox.run(&["status", &test_dir])?; - let status_without_ignored = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let status_without_ignored = layer.last_stdout.clone(); // Now run with --ignored flag to see all files // We need to temporarily set ignored to true to add the flag - sandbox.set_ignored(true); - sandbox.run(&["status", &test_dir])?; - let status_with_ignored = sandbox.last_stdout.clone(); - sandbox.set_ignored(false); // Reset it back + layer.set_ignored(true); + layer.run(&["status", &test_dir])?; + let status_with_ignored = layer.last_stdout.clone(); + layer.set_ignored(false); // Reset it back // Check which files appear in each output for (file, should_be_ignored) in &test_files { diff --git a/tests/ai_test_ignore_rules.rs b/tests/ai_test_ignore_rules.rs index 6ba5c6a..4a10ad9 100644 --- a/tests/ai_test_ignore_rules.rs +++ b/tests/ai_test_ignore_rules.rs @@ -10,17 +10,17 @@ use std::process::Command; // cspell:ignore файл filea fileb filex #[rstest] -fn test_gitignore_functionality(mut sandbox: SandboxManager) -> Result<()> { - sandbox.set_ignored(false); // Don't automatically add --ignored for gitignore tests +fn test_gitignore_functionality(mut layer: LayerManager) -> Result<()> { + layer.set_ignored(false); // Don't automatically add --ignored for gitignore tests // Create test directory using test_filename - let test_dir = sandbox.test_filename("gitignore-test-dir"); + let test_dir = layer.test_filename("gitignore-test-dir"); std::fs::create_dir_all(&test_dir)?; // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), @@ -44,9 +44,9 @@ dir/*.tmp negate-me !negate-me/keep "#; - // Create .gitignore file within the sandbox + // Create .gitignore file within the layer let gitignore_path = Path::new(&test_dir).join(".gitignore"); - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -74,7 +74,7 @@ negate-me let included_negate_keep = Path::new(&test_dir).join("negate-me/keep"); // Create directories - sandbox.run(&[ + layer.run(&[ "mkdir", "-p", Path::new(&test_dir).join("ignored-dir").to_str().unwrap(), @@ -96,12 +96,12 @@ negate-me &included_keep_tmp, &included_negate_keep, ] { - sandbox.run(&["touch", path.to_str().unwrap()])?; + layer.run(&["touch", path.to_str().unwrap()])?; } // 1) Run `status` WITHOUT the --ignored flag - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); // Files that should be present for inc in [ &included_file, @@ -117,11 +117,11 @@ negate-me assert!(!stdout.contains(ign.to_str().unwrap())); } - // 2) Run `status` WITH the --ignored flag via SandboxManager - sandbox.set_ignored(true); - sandbox.run(&["status", &test_dir])?; - let stdout_flag = sandbox.last_stdout.clone(); - sandbox.set_ignored(false); + // 2) Run `status` WITH the --ignored flag via LayerManager + layer.set_ignored(true); + layer.run(&["status", &test_dir])?; + let stdout_flag = layer.last_stdout.clone(); + layer.set_ignored(false); // Now every file should appear because we are passing --ignored implicitly for path in [ &ignored_file, @@ -143,21 +143,21 @@ negate-me #[rstest] fn test_gitignore_double_asterisk_patterns( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - sandbox.set_ignored(false); // Don't automatically add --ignored for gitignore tests + layer.set_ignored(false); // Don't automatically add --ignored for gitignore tests // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), ])?; // Create test directory using test_filename - let test_dir = sandbox.test_filename("double-asterisk-test"); + let test_dir = layer.test_filename("double-asterisk-test"); std::fs::create_dir_all(&test_dir)?; let gitignore_contents = r#" @@ -170,9 +170,9 @@ fn test_gitignore_double_asterisk_patterns( # Match any file under docs docs/** "#; - // Create .gitignore file within the sandbox + // Create .gitignore file within the layer let gitignore_path = Path::new(&test_dir).join(".gitignore"); - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -206,7 +206,7 @@ docs/** ]; // Create all directories needed - sandbox.run(&[ + layer.run(&[ "mkdir", "-p", Path::new(&test_dir).join("foo").to_str().unwrap(), @@ -228,12 +228,12 @@ docs/** // Create all files for file in ignored_files.iter().chain(included_files.iter()) { - sandbox.run(&["touch", file.to_str().unwrap()])?; + layer.run(&["touch", file.to_str().unwrap()])?; } // Test without --ignored flag - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); // Verify included files are shown for file in &included_files { @@ -257,31 +257,31 @@ docs/** } #[rstest] -fn test_gitignore_hierarchy(mut sandbox: SandboxManager) -> Result<()> { - sandbox.set_ignored(false); // Don't automatically add --ignored for gitignore tests +fn test_gitignore_hierarchy(mut layer: LayerManager) -> Result<()> { + layer.set_ignored(false); // Don't automatically add --ignored for gitignore tests // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), ])?; // Create test directory using test_filename - let test_dir = sandbox.test_filename("hierarchy-test"); + let test_dir = layer.test_filename("hierarchy-test"); std::fs::create_dir_all(Path::new(&test_dir).join("subdir/deep"))?; // Root .gitignore - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!("echo '*.root' > {}/.gitignore", test_dir), ])?; // Subdirectory with its own .gitignore - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -291,7 +291,7 @@ fn test_gitignore_hierarchy(mut sandbox: SandboxManager) -> Result<()> { ])?; // Deeper subdirectory - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!("echo '*.deep' > {}/subdir/deep/.gitignore", test_dir), @@ -312,11 +312,11 @@ fn test_gitignore_hierarchy(mut sandbox: SandboxManager) -> Result<()> { ]; for (file, _) in &test_files { - sandbox.run(&["touch", file.to_str().unwrap()])?; + layer.run(&["touch", file.to_str().unwrap()])?; } - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); for (file, should_be_ignored) in &test_files { if *should_be_ignored { @@ -338,20 +338,20 @@ fn test_gitignore_hierarchy(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_gitignore_special_patterns(mut sandbox: SandboxManager) -> Result<()> { - sandbox.set_ignored(false); // Don't automatically add --ignored for gitignore tests +fn test_gitignore_special_patterns(mut layer: LayerManager) -> Result<()> { + layer.set_ignored(false); // Don't automatically add --ignored for gitignore tests // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), ])?; // Create test directory using test_filename - let test_dir = sandbox.test_filename("special-patterns-test"); + let test_dir = layer.test_filename("special-patterns-test"); std::fs::create_dir_all(&test_dir)?; let gitignore_contents = r#" @@ -375,7 +375,7 @@ trailing.txt path\ with\ spaces/ "#; let gitignore_path = Path::new(&test_dir).join(".gitignore"); - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -413,7 +413,7 @@ path\ with\ spaces/ ]; // Create directories - sandbox.run(&[ + layer.run(&[ "mkdir", "-p", Path::new(&test_dir) @@ -421,7 +421,7 @@ path\ with\ spaces/ .to_str() .unwrap(), ])?; - sandbox.run(&[ + layer.run(&[ "mkdir", "-p", Path::new(&test_dir) @@ -432,11 +432,11 @@ path\ with\ spaces/ // Create all files for file in ignored_files.iter().chain(included_files.iter()) { - sandbox.run(&["touch", file.to_str().unwrap()])?; + layer.run(&["touch", file.to_str().unwrap()])?; } - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); for file in &included_files { assert!( @@ -458,22 +458,20 @@ path\ with\ spaces/ } #[rstest] -fn test_gitignore_directory_patterns( - mut sandbox: SandboxManager, -) -> Result<()> { - sandbox.set_ignored(false); // Don't automatically add --ignored for gitignore tests +fn test_gitignore_directory_patterns(mut layer: LayerManager) -> Result<()> { + layer.set_ignored(false); // Don't automatically add --ignored for gitignore tests // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), ])?; // Create test directory using test_filename - let test_dir = sandbox.test_filename("directory-patterns-test"); + let test_dir = layer.test_filename("directory-patterns-test"); std::fs::create_dir_all(&test_dir)?; let gitignore_contents = r#" @@ -487,7 +485,7 @@ temp **/node_modules/ "#; let gitignore_path = Path::new(&test_dir).join(".gitignore"); - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -498,7 +496,7 @@ temp ])?; // Create directory structure - sandbox.run(&[ + layer.run(&[ "mkdir", "-p", Path::new(&test_dir).join("build").to_str().unwrap(), @@ -535,11 +533,11 @@ temp // Create files for (file, _) in &test_files { - sandbox.run(&["touch", file.to_str().unwrap()])?; + layer.run(&["touch", file.to_str().unwrap()])?; } - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); for (file, should_be_ignored) in &test_files { if *should_be_ignored { @@ -561,20 +559,20 @@ temp } #[rstest] -fn test_gitignore_complex_negation(mut sandbox: SandboxManager) -> Result<()> { - sandbox.set_ignored(false); // Don't automatically add --ignored for gitignore tests +fn test_gitignore_complex_negation(mut layer: LayerManager) -> Result<()> { + layer.set_ignored(false); // Don't automatically add --ignored for gitignore tests // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), ])?; // Create test directory using test_filename - let test_dir = sandbox.test_filename("complex-negation-test"); + let test_dir = layer.test_filename("complex-negation-test"); std::fs::create_dir_all(&test_dir)?; let gitignore_contents = r#" @@ -592,7 +590,7 @@ logs/*error*.gz # But do ignore backup data files even in config config/*.data.bak "#; - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -602,7 +600,7 @@ config/*.data.bak ), ])?; - sandbox.run(&[ + layer.run(&[ "mkdir", "-p", Path::new(&test_dir).join("logs").to_str().unwrap(), @@ -625,11 +623,11 @@ config/*.data.bak ]; for (file, _) in &test_files { - sandbox.run(&["touch", file.to_str().unwrap()])?; + layer.run(&["touch", file.to_str().unwrap()])?; } - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); for (file, should_be_ignored) in &test_files { if *should_be_ignored { @@ -650,24 +648,24 @@ config/*.data.bak Ok(()) } -/// Verify that the SANDBOX_IGNORED environment variable enables inclusion of +/// Verify that the LAYER_IGNORED environment variable enables inclusion of /// ignored files even when the --ignored CLI flag is not provided. #[rstest] -fn test_env_flag_includes_ignored(mut sandbox: SandboxManager) -> Result<()> { +fn test_env_flag_includes_ignored(mut layer: LayerManager) -> Result<()> { // Create test directory using test_filename - let test_dir = sandbox.test_filename("env-ignore-test"); + let test_dir = layer.test_filename("env-ignore-test"); std::fs::create_dir_all(&test_dir)?; // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), ])?; - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!("echo 'ignored-file' > {}/.gitignore", test_dir), @@ -677,60 +675,56 @@ fn test_env_flag_includes_ignored(mut sandbox: SandboxManager) -> Result<()> { let included_file = Path::new(&test_dir).join("included"); // Create the files (using --ignored via helper, fine for creation phase) - sandbox.run(&["touch", ignored_file.to_str().unwrap()])?; - sandbox.run(&["touch", included_file.to_str().unwrap()])?; + layer.run(&["touch", ignored_file.to_str().unwrap()])?; + layer.run(&["touch", included_file.to_str().unwrap()])?; // Call `status` WITHOUT any env var or flag - should not show ignored files - sandbox.set_ignored(false); // Temporarily disable automatic --ignored - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); - sandbox.set_ignored(true); // Reset back + layer.set_ignored(false); // Temporarily disable automatic --ignored + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); + layer.set_ignored(true); // Reset back assert!(!stdout.contains(ignored_file.to_str().unwrap())); assert!(stdout.contains(included_file.to_str().unwrap())); // Call `status` WITHOUT the flag but WITH env var set to true - sandbox.set_ignored(false); // Disable automatic --ignored - sandbox.run_with_env(&["status", &test_dir], "DEVLAYER_IGNORED", "true")?; - let stdout = sandbox.last_stdout.clone(); - sandbox.set_ignored(true); // Reset back + layer.set_ignored(false); // Disable automatic --ignored + layer.run_with_env(&["status", &test_dir], "DEVLAYER_IGNORED", "true")?; + let stdout = layer.last_stdout.clone(); + layer.set_ignored(true); // Reset back // Both files should be reported now assert!(stdout.contains(ignored_file.to_str().unwrap())); assert!(stdout.contains(included_file.to_str().unwrap())); - // Invalid value for SANDBOX_IGNORED - sandbox.set_ignored(false); // Disable automatic --ignored + // Invalid value for LAYER_IGNORED + layer.set_ignored(false); // Disable automatic --ignored let result = - sandbox.run_with_env(&["status", &test_dir], "DEVLAYER_IGNORED", "cow"); - sandbox.set_ignored(true); // Reset back + layer.run_with_env(&["status", &test_dir], "DEVLAYER_IGNORED", "cow"); + layer.set_ignored(true); // Reset back assert!( result.is_err(), "Expected error for invalid DEVLAYER_IGNORED value" ); - // False value for SANDBOX_IGNORED - sandbox.set_ignored(false); // Disable automatic --ignored - sandbox.run_with_env( - &["status", &test_dir], - "DEVLAYER_IGNORED", - "false", - )?; - let stdout = sandbox.last_stdout.clone(); - sandbox.set_ignored(true); // Reset back + // False value for LAYER_IGNORED + layer.set_ignored(false); // Disable automatic --ignored + layer.run_with_env(&["status", &test_dir], "DEVLAYER_IGNORED", "false")?; + let stdout = layer.last_stdout.clone(); + layer.set_ignored(true); // Reset back assert!(!stdout.contains(ignored_file.to_str().unwrap())); assert!(stdout.contains(included_file.to_str().unwrap())); // Override values for ignored - CLI flag should take precedence over env var // This one needs to stay as Command::new because we need to pass --ignored directly // and test that it overrides the env var - sandbox.set_ignored(false); // Disable automatic --ignored + layer.set_ignored(false); // Disable automatic --ignored let output = Command::new("sudo") .env("DEVLAYER_IGNORED", "false") - .args(["-E", &sandbox.sandbox_bin]) + .args(["-E", &layer.devlayer_bin]) .args([ "-v", "--ignored", - &format!("--name={}", &sandbox.name), + &format!("--name={}", &layer.name), "status", &test_dir, ]) @@ -740,32 +734,32 @@ fn test_env_flag_includes_ignored(mut sandbox: SandboxManager) -> Result<()> { let stdout = String::from_utf8_lossy(&output.stdout); assert!(stdout.contains(ignored_file.to_str().unwrap())); assert!(stdout.contains(included_file.to_str().unwrap())); - sandbox.set_ignored(true); // Reset back + layer.set_ignored(true); // Reset back Ok(()) } #[rstest] -fn test_builtin_tmp_ignore(mut sandbox: SandboxManager) -> Result<()> { - sandbox.set_ignored(false); // Don't automatically add --ignored for gitignore tests +fn test_builtin_tmp_ignore(mut layer: LayerManager) -> Result<()> { + layer.set_ignored(false); // Don't automatically add --ignored for gitignore tests - let test_dir = sandbox.test_filename("builtin_ignore"); + let test_dir = layer.test_filename("builtin_ignore"); fs::create_dir_all(&test_dir)?; let ignore_id = rid(); let ignored_file = format!("{}/builtin-ignore-{}", test_dir, ignore_id); - sandbox.run(&["touch", &ignored_file])?; + layer.run(&["touch", &ignored_file])?; - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); assert!(!stdout.contains(&format!("builtin-ignore-{}", ignore_id))); // with --ignored - sandbox.set_ignored(true); - sandbox.run(&["status", &test_dir])?; - let stdout_flag = sandbox.last_stdout.clone(); - sandbox.set_ignored(false); + layer.set_ignored(true); + layer.run(&["status", &test_dir])?; + let stdout_flag = layer.last_stdout.clone(); + layer.set_ignored(false); assert!(stdout_flag.contains(&format!("builtin-ignore-{}", ignore_id))); @@ -773,20 +767,20 @@ fn test_builtin_tmp_ignore(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_gitignore_edge_cases(mut sandbox: SandboxManager) -> Result<()> { - sandbox.set_ignored(false); // Don't automatically add --ignored for gitignore tests +fn test_gitignore_edge_cases(mut layer: LayerManager) -> Result<()> { + layer.set_ignored(false); // Don't automatically add --ignored for gitignore tests // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), ])?; // Create test directory using test_filename - let test_dir = sandbox.test_filename("edge-cases-test"); + let test_dir = layer.test_filename("edge-cases-test"); std::fs::create_dir_all(&test_dir)?; let gitignore_contents = r#" @@ -824,7 +818,7 @@ very/long/path/that/goes/on/and/on/and/on/and/on/and/on/and/on/file.txt *allow-file-that-starts-with-a-bang !!allow-file-that-starts-with-a-bang "#; - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -835,7 +829,7 @@ very/long/path/that/goes/on/and/on/and/on/and/on/and/on/and/on/file.txt ])?; // Create nested directories for path normalization test - sandbox.run(&["mkdir", "-p", + layer.run(&["mkdir", "-p", Path::new(&test_dir).join("path/to").to_str().unwrap(), Path::new(&test_dir).join("very/long/path/that/goes/on/and/on/and/on/and/on/and/on/and/on").to_str().unwrap() ])?; @@ -864,11 +858,11 @@ very/long/path/that/goes/on/and/on/and/on/and/on/and/on/and/on/file.txt ]; for (file, _) in &test_files { - sandbox.run(&["touch", file.to_str().unwrap()])?; + layer.run(&["touch", file.to_str().unwrap()])?; } - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); for (file, should_be_ignored) in &test_files { if *should_be_ignored { @@ -890,20 +884,20 @@ very/long/path/that/goes/on/and/on/and/on/and/on/and/on/and/on/file.txt } #[rstest] -fn test_gitignore_case_sensitivity(mut sandbox: SandboxManager) -> Result<()> { - sandbox.set_ignored(false); // Don't automatically add --ignored for gitignore tests +fn test_gitignore_case_sensitivity(mut layer: LayerManager) -> Result<()> { + layer.set_ignored(false); // Don't automatically add --ignored for gitignore tests // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), ])?; // Create test directory using test_filename - let test_dir = sandbox.test_filename("case-sensitivity-test"); + let test_dir = layer.test_filename("case-sensitivity-test"); std::fs::create_dir_all(&test_dir)?; // Git ignore patterns are case-sensitive on case-sensitive filesystems @@ -914,7 +908,7 @@ README.md Build/ "#; let gitignore_path = Path::new(&test_dir).join(".gitignore"); - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -924,7 +918,7 @@ Build/ ), ])?; - sandbox.run(&[ + layer.run(&[ "mkdir", "-p", Path::new(&test_dir).join("Build").to_str().unwrap(), @@ -946,11 +940,11 @@ Build/ ]; for (file, _) in &test_files { - sandbox.run(&["touch", file.to_str().unwrap()])?; + layer.run(&["touch", file.to_str().unwrap()])?; } - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); for (file, should_be_ignored) in &test_files { if *should_be_ignored { diff --git a/tests/ai_test_ignore_rules_coverage.rs b/tests/ai_test_ignore_rules_coverage.rs index 467c747..424bacd 100644 --- a/tests/ai_test_ignore_rules_coverage.rs +++ b/tests/ai_test_ignore_rules_coverage.rs @@ -7,19 +7,19 @@ use std::path::Path; #[rstest] fn test_resolve_ignores_with_preference_upper_exists( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - sandbox.set_ignored(false); + layer.set_ignored(false); // Create test directory using test_filename - let test_dir = sandbox.test_filename("resolve-ignores-upper-test"); + let test_dir = layer.test_filename("resolve-ignores-upper-test"); std::fs::create_dir_all(&test_dir)?; let sub_dir = Path::new(&test_dir).join("test"); std::fs::create_dir_all(&sub_dir)?; // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), @@ -29,7 +29,7 @@ fn test_resolve_ignores_with_preference_upper_exists( // Should use upper's .gitignore and ignore lower's // Create upper .gitignore that ignores "upper-pattern" - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -38,13 +38,13 @@ fn test_resolve_ignores_with_preference_upper_exists( ), ])?; - // Create files to test within the sandbox - sandbox.run(&["touch", sub_dir.join("upper-pattern").to_str().unwrap()])?; - sandbox.run(&["touch", sub_dir.join("other-file").to_str().unwrap()])?; + // Create files to test within the layer + layer.run(&["touch", sub_dir.join("upper-pattern").to_str().unwrap()])?; + layer.run(&["touch", sub_dir.join("other-file").to_str().unwrap()])?; // Run status without --ignored flag - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); // upper-pattern should be ignored, other-file should be shown assert!( @@ -61,17 +61,17 @@ fn test_resolve_ignores_with_preference_upper_exists( #[rstest] fn test_resolve_ignores_with_preference_fallback_to_lower( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - sandbox.set_ignored(false); + layer.set_ignored(false); // Create test directory using test_filename - let test_dir = sandbox.test_filename("resolve-ignores-fallback-test"); + let test_dir = layer.test_filename("resolve-ignores-fallback-test"); std::fs::create_dir_all(&test_dir)?; // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), @@ -83,7 +83,7 @@ fn test_resolve_ignores_with_preference_fallback_to_lower( std::fs::create_dir_all(&child_dir)?; // Only parent has .gitignore - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -93,12 +93,12 @@ fn test_resolve_ignores_with_preference_fallback_to_lower( ])?; // Create files in child directory - sandbox + layer .run(&["touch", child_dir.join("parent-pattern").to_str().unwrap()])?; - sandbox.run(&["touch", child_dir.join("other-file").to_str().unwrap()])?; + layer.run(&["touch", child_dir.join("other-file").to_str().unwrap()])?; - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); // Parent's gitignore should apply to child assert!( @@ -114,20 +114,18 @@ fn test_resolve_ignores_with_preference_fallback_to_lower( } #[rstest] -fn test_resolve_ignores_no_lower_dir( - mut sandbox: SandboxManager, -) -> Result<()> { - sandbox.set_ignored(false); +fn test_resolve_ignores_no_lower_dir(mut layer: LayerManager) -> Result<()> { + layer.set_ignored(false); // Create test directory using test_filename - let test_dir = sandbox.test_filename("resolve-no-lower-test"); + let test_dir = layer.test_filename("resolve-no-lower-test"); std::fs::create_dir_all(&test_dir)?; let empty_dir = Path::new(&test_dir).join("empty"); std::fs::create_dir_all(&empty_dir)?; // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), @@ -136,10 +134,10 @@ fn test_resolve_ignores_no_lower_dir( // Test with a directory that has no ignore files // Create a file - should not be ignored since there are no ignore files - sandbox.run(&["touch", empty_dir.join("test-file").to_str().unwrap()])?; + layer.run(&["touch", empty_dir.join("test-file").to_str().unwrap()])?; - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); println!("Status output:\n{}", stdout); @@ -152,27 +150,25 @@ fn test_resolve_ignores_no_lower_dir( } #[rstest] -fn test_resolve_ignores_empty_gitignore( - mut sandbox: SandboxManager, -) -> Result<()> { - sandbox.set_ignored(false); +fn test_resolve_ignores_empty_gitignore(mut layer: LayerManager) -> Result<()> { + layer.set_ignored(false); // Create test directory using test_filename - let test_dir = sandbox.test_filename("resolve-empty-test"); + let test_dir = layer.test_filename("resolve-empty-test"); std::fs::create_dir_all(&test_dir)?; let empty_ignore_dir = Path::new(&test_dir).join("empty-ignore"); std::fs::create_dir_all(&empty_ignore_dir)?; // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), ])?; // Create an empty .gitignore file - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -182,18 +178,18 @@ fn test_resolve_ignores_empty_gitignore( ])?; // Create test files - sandbox.run(&[ + layer.run(&[ "touch", empty_ignore_dir.join("test-pattern").to_str().unwrap(), ])?; - sandbox.run(&[ + layer.run(&[ "touch", empty_ignore_dir.join("other-file").to_str().unwrap(), ])?; // Both files should be included since .gitignore is empty - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); // Empty .gitignore means nothing is ignored assert!( @@ -210,26 +206,26 @@ fn test_resolve_ignores_empty_gitignore( #[rstest] fn test_resolve_ignores_with_both_gitignore_and_ignore( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - sandbox.set_ignored(false); + layer.set_ignored(false); // Create test directory using test_filename - let test_dir = sandbox.test_filename("resolve-both-ignore-files-test"); + let test_dir = layer.test_filename("resolve-both-ignore-files-test"); std::fs::create_dir_all(&test_dir)?; let sub_dir = Path::new(&test_dir).join("test"); std::fs::create_dir_all(&sub_dir)?; // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), ])?; // Create both .gitignore and .ignore files - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -237,7 +233,7 @@ fn test_resolve_ignores_with_both_gitignore_and_ignore( sub_dir.join(".gitignore").to_str().unwrap() ), ])?; - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -247,14 +243,13 @@ fn test_resolve_ignores_with_both_gitignore_and_ignore( ])?; // Create test files - sandbox + layer .run(&["touch", sub_dir.join("gitignore-pattern").to_str().unwrap()])?; - sandbox - .run(&["touch", sub_dir.join("ignore-pattern").to_str().unwrap()])?; - sandbox.run(&["touch", sub_dir.join("other-file").to_str().unwrap()])?; + layer.run(&["touch", sub_dir.join("ignore-pattern").to_str().unwrap()])?; + layer.run(&["touch", sub_dir.join("other-file").to_str().unwrap()])?; - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); // Both patterns should be applied assert!( diff --git a/tests/ai_test_ignore_rules_overlay.rs b/tests/ai_test_ignore_rules_overlay.rs index 8eff439..6bb8a2f 100644 --- a/tests/ai_test_ignore_rules_overlay.rs +++ b/tests/ai_test_ignore_rules_overlay.rs @@ -8,12 +8,12 @@ use std::path::Path; // This test specifically tests the overlay filesystem scenario where // resolve_ignores_with_preference is called with both upper and lower directories #[rstest] -fn test_overlay_ignore_preference(mut sandbox: SandboxManager) -> Result<()> { +fn test_overlay_ignore_preference(mut layer: LayerManager) -> Result<()> { // This test simulates the overlay filesystem scenario - // We create files on the host (lower layer) and then modify in sandbox (upper layer) + // We create files on the host (lower layer) and then modify in layer (upper layer) // Create a test directory on the host filesystem (this will be the lower layer) - let test_dir = sandbox.test_filename("overlay-ignore-test"); + let test_dir = layer.test_filename("overlay-ignore-test"); std::fs::create_dir_all(&test_dir)?; // Create .gitignore in lower layer (host filesystem) @@ -30,8 +30,8 @@ fn test_overlay_ignore_preference(mut sandbox: SandboxManager) -> Result<()> { std::fs::write(Path::new(&test_dir).join("upper-ignored"), "content")?; std::fs::write(Path::new(&test_dir).join("not-ignored"), "content")?; - // Now in the sandbox (upper layer), create a new .gitignore that overrides the lower - sandbox.run(&[ + // Now in the layer (upper layer), create a new .gitignore that overrides the lower + layer.run(&[ "sh", "-c", &format!( @@ -42,28 +42,28 @@ fn test_overlay_ignore_preference(mut sandbox: SandboxManager) -> Result<()> { // Note: We don't create .ignore in upper, so it should use lower's .ignore // Test scenario 1: Check that upper .gitignore completely replaces lower .gitignore - // Run status to see files (SandboxManager automatically adds --ignored flag) - sandbox.run(&["status", &test_dir])?; - let _all_files = &sandbox.last_stdout; + // Run status to see files (LayerManager automatically adds --ignored flag) + layer.run(&["status", &test_dir])?; + let _all_files = &layer.last_stdout; // Verify that the .gitignore was modified - sandbox.run(&[ + layer.run(&[ "cat", Path::new(&test_dir).join(".gitignore").to_str().unwrap(), ])?; assert_eq!( - sandbox.last_stdout.trim(), + layer.last_stdout.trim(), "upper-ignored", ".gitignore should contain only 'upper-ignored'" ); // The .ignore file should still be from lower layer - sandbox.run(&[ + layer.run(&[ "cat", Path::new(&test_dir).join(".ignore").to_str().unwrap(), ])?; assert_eq!( - sandbox.last_stdout.trim(), + layer.last_stdout.trim(), "also-ignored", ".ignore should still contain 'also-ignored' from lower" ); @@ -84,26 +84,26 @@ fn test_overlay_ignore_preference(mut sandbox: SandboxManager) -> Result<()> { // the patterns list remains unchanged #[rstest] fn test_resolve_ignores_with_invalid_content( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - sandbox.set_ignored(false); // Don't automatically add --ignored for gitignore tests + layer.set_ignored(false); // Don't automatically add --ignored for gitignore tests // Create test directory using test_filename - let test_dir = sandbox.test_filename("resolve-invalid-content-test"); + let test_dir = layer.test_filename("resolve-invalid-content-test"); std::fs::create_dir_all(&test_dir)?; let sub_dir = Path::new(&test_dir).join("test"); std::fs::create_dir_all(&sub_dir)?; // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), ])?; // Create a .gitignore with only whitespace and comments - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -113,13 +113,13 @@ fn test_resolve_ignores_with_invalid_content( ])?; // Create test files - sandbox.run(&[ + layer.run(&[ "touch", sub_dir.join("should-not-be-ignored").to_str().unwrap(), ])?; - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); // File should be included since .gitignore has no valid patterns assert!( @@ -134,17 +134,17 @@ fn test_resolve_ignores_with_invalid_content( // so we check the lower dir #[rstest] fn test_resolve_ignores_upper_no_gitignore_lower_has( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - sandbox.set_ignored(false); // Don't automatically add --ignored for gitignore tests + layer.set_ignored(false); // Don't automatically add --ignored for gitignore tests // Create test directory using test_filename - let test_dir = sandbox.test_filename("upper-no-gitignore-test"); + let test_dir = layer.test_filename("upper-no-gitignore-test"); std::fs::create_dir_all(&test_dir)?; // Create parent .gitignore to un-ignore test directory let parent_gitignore_path = - format!("generated-test-data/{}/.gitignore", &sandbox.name); - sandbox.run(&[ + format!("generated-test-data/{}/.gitignore", &layer.name); + layer.run(&[ "sh", "-c", &format!("echo '!*/' > {}", parent_gitignore_path), @@ -153,7 +153,7 @@ fn test_resolve_ignores_upper_no_gitignore_lower_has( // Create a parent directory with .gitignore (simulating lower) let parent_dir = Path::new(&test_dir).join("parent"); std::fs::create_dir_all(&parent_dir)?; - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -168,11 +168,11 @@ fn test_resolve_ignores_upper_no_gitignore_lower_has( // No .gitignore in child // Create test files in child - sandbox.run(&["touch", child_dir.join("from-parent").to_str().unwrap()])?; - sandbox.run(&["touch", child_dir.join("other-file").to_str().unwrap()])?; + layer.run(&["touch", child_dir.join("from-parent").to_str().unwrap()])?; + layer.run(&["touch", child_dir.join("other-file").to_str().unwrap()])?; - sandbox.run(&["status", &test_dir])?; - let stdout = sandbox.last_stdout.clone(); + layer.run(&["status", &test_dir])?; + let stdout = layer.last_stdout.clone(); // Parent's pattern should apply assert!( diff --git a/tests/ai_test_sandbox_settings.rs b/tests/ai_test_layer_settings.rs similarity index 89% rename from tests/ai_test_sandbox_settings.rs rename to tests/ai_test_layer_settings.rs index 2b8be4f..dda675e 100644 --- a/tests/ai_test_sandbox_settings.rs +++ b/tests/ai_test_layer_settings.rs @@ -1,4 +1,4 @@ -// Integration tests for SandboxSettings +// Integration tests for LayerSettings // These tests verify that settings serialization, validation, and file operations work correctly mod fixtures; @@ -9,17 +9,17 @@ use rstest::*; use serde_json; use std::{fs, path::PathBuf}; -use ::sandbox::config::{BindMount, BindMountOptions, Network}; -use ::sandbox::sandbox::{SandboxSettings, mount_overlays::MountHash}; +use ::devlayer::config::{BindMount, BindMountOptions, Network}; +use ::devlayer::layer::{LayerSettings, mount_overlays::MountHash}; use std::collections::HashMap; // Helper to create a minimal Config for testing -fn create_test_config() -> ::sandbox::config::Config { - ::sandbox::config::Config { +fn create_test_config() -> ::devlayer::config::Config { + ::devlayer::config::Config { log_level: log::LevelFilter::Info, name: "test_layer".to_string(), storage_dir: PathBuf::from("/tmp/test_storage"), - sandbox_dir: PathBuf::from("/tmp/test_layer"), + layer_dir: PathBuf::from("/tmp/test_layer"), upper_cwd: PathBuf::from("/tmp/test_upper"), overlay_cwd: PathBuf::from("/tmp/test_overlay"), net: Network::None, @@ -52,7 +52,7 @@ fn test_from_config() -> Result<()> { dir: "/test/dir".to_string(), }]; - let settings = SandboxSettings::from_config(&config, &mounts); + let settings = LayerSettings::from_config(&config, &mounts); assert_eq!(settings.version, env!("CARGO_PKG_VERSION")); assert_eq!(settings.mounts, mounts); @@ -81,7 +81,7 @@ fn test_user_bind_mounts_filtering_through_validation() -> Result<()> { }; config.bind_mounts = vec![user_bind.clone(), data_bind.clone()]; - let settings = SandboxSettings::from_config(&config, &[]); + let settings = LayerSettings::from_config(&config, &[]); // Test that "data" bind mount is filtered out by trying validation with only data bind let mut config_with_data_only = create_test_config(); @@ -100,8 +100,8 @@ fn test_user_bind_mounts_filtering_through_validation() -> Result<()> { #[rstest] fn test_save_and_load_from_file() -> Result<()> { - let sandbox = SandboxManager::new(); - let test_dir = format!("generated-test-data/settings-{}", sandbox.name); + let layer = LayerManager::new(); + let test_dir = format!("generated-test-data/settings-{}", layer.name); fs::create_dir_all(&test_dir)?; let settings_path = PathBuf::from(format!("{}/settings.json", test_dir)); @@ -127,7 +127,7 @@ fn test_save_and_load_from_file() -> Result<()> { }, ]; - let original_settings = SandboxSettings::from_config(&config, &mounts); + let original_settings = LayerSettings::from_config(&config, &mounts); // Test save_to_file original_settings.save_to_file(&settings_path)?; @@ -138,7 +138,7 @@ fn test_save_and_load_from_file() -> Result<()> { let _: serde_json::Value = serde_json::from_str(&file_content)?; // Verify it's valid JSON // Test load_from_file - let loaded_settings = SandboxSettings::load_from_file(&settings_path)?; + let loaded_settings = LayerSettings::load_from_file(&settings_path)?; assert_eq!(loaded_settings, original_settings); assert_eq!(loaded_settings.network, Network::None); @@ -153,7 +153,7 @@ fn test_save_and_load_from_file() -> Result<()> { fn test_load_from_nonexistent_file() -> Result<()> { let nonexistent_path = PathBuf::from("/nonexistent/path/settings.json"); - let result = SandboxSettings::load_from_file(&nonexistent_path); + let result = LayerSettings::load_from_file(&nonexistent_path); assert!(result.is_err()); let error_msg = result.unwrap_err().to_string(); @@ -164,15 +164,15 @@ fn test_load_from_nonexistent_file() -> Result<()> { #[rstest] fn test_load_from_invalid_json_file() -> Result<()> { - let sandbox = SandboxManager::new(); - let test_dir = format!("generated-test-data/invalid-json-{}", sandbox.name); + let layer = LayerManager::new(); + let test_dir = format!("generated-test-data/invalid-json-{}", layer.name); fs::create_dir_all(&test_dir)?; let settings_path = PathBuf::from(format!("{}/invalid.json", test_dir)); // Write invalid JSON fs::write(&settings_path, "{ invalid json }")?; - let result = SandboxSettings::load_from_file(&settings_path); + let result = LayerSettings::load_from_file(&settings_path); assert!(result.is_err()); let error_msg = result.unwrap_err().to_string(); @@ -184,7 +184,7 @@ fn test_load_from_invalid_json_file() -> Result<()> { #[rstest] fn test_save_to_invalid_path() -> Result<()> { let config = create_test_config(); - let settings = SandboxSettings::from_config(&config, &[]); + let settings = LayerSettings::from_config(&config, &[]); let invalid_path = PathBuf::from("/nonexistent/directory/settings.json"); @@ -215,7 +215,7 @@ fn test_validate_against_config_identical() -> Result<()> { dir: "/test/dir".to_string(), }]; - let settings = SandboxSettings::from_config(&config, &mounts); + let settings = LayerSettings::from_config(&config, &mounts); // Validation against the same config should succeed let result = settings.validate_against_config(&config, &mounts); @@ -234,7 +234,7 @@ fn test_validate_against_config_network_change() -> Result<()> { dir: "/test/dir".to_string(), }]; - let settings = SandboxSettings::from_config(&original_config, &mounts); + let settings = LayerSettings::from_config(&original_config, &mounts); // Change network configuration let mut new_config = original_config.clone(); @@ -270,7 +270,7 @@ fn test_validate_against_config_mounts_removed() -> Result<()> { }, ]; - let settings = SandboxSettings::from_config(&config, &original_mounts); + let settings = LayerSettings::from_config(&config, &original_mounts); // Remove one mount let new_mounts = vec![MountHash { @@ -303,7 +303,7 @@ fn test_validate_against_config_mounts_added() -> Result<()> { dir: "/dir1".to_string(), }]; - let settings = SandboxSettings::from_config(&config, &original_mounts); + let settings = LayerSettings::from_config(&config, &original_mounts); // Add another mount let new_mounts = vec![ @@ -348,7 +348,7 @@ fn test_validate_against_config_bind_mounts_removed() -> Result<()> { original_config.bind_mounts = vec![bind1.clone(), bind2]; - let settings = SandboxSettings::from_config(&original_config, &[]); + let settings = LayerSettings::from_config(&original_config, &[]); // Remove one bind mount let mut new_config = original_config.clone(); @@ -381,7 +381,7 @@ fn test_validate_against_config_bind_mounts_added() -> Result<()> { original_config.bind_mounts = vec![bind1.clone()]; - let settings = SandboxSettings::from_config(&original_config, &[]); + let settings = LayerSettings::from_config(&original_config, &[]); // Add another bind mount let bind2 = BindMount { @@ -425,7 +425,7 @@ fn test_validate_against_config_data_bind_mount_ignored() -> Result<()> { original_config.bind_mounts = vec![user_bind.clone(), data_bind.clone()]; - let settings = SandboxSettings::from_config(&original_config, &[]); + let settings = LayerSettings::from_config(&original_config, &[]); // New config has only the data bind mount (user bind removed) let mut new_config = original_config.clone(); @@ -469,7 +469,7 @@ fn test_validate_against_config_multiple_changes() -> Result<()> { let original_mounts = vec![mount1, mount2]; let settings = - SandboxSettings::from_config(&original_config, &original_mounts); + LayerSettings::from_config(&original_config, &original_mounts); // Change everything let mut new_config = original_config.clone(); diff --git a/tests/ai_test_resource_limits.rs b/tests/ai_test_resource_limits.rs index 0f87614..a5051a4 100644 --- a/tests/ai_test_resource_limits.rs +++ b/tests/ai_test_resource_limits.rs @@ -13,34 +13,34 @@ fn available_cpus() -> usize { } fn write_config( - sandbox: &SandboxManager, + layer: &LayerManager, prefix: &str, contents: &str, ) -> Result { - let path = format!("{}.toml", sandbox.test_filename(prefix)); + let path = format!("{}.toml", layer.test_filename(prefix)); fs::write(&path, contents)?; Ok(path) } -/// Starts the sandbox with a CPU limit to find out if this machine lets us +/// Starts the layer with a CPU limit to find out if this machine lets us /// manage cgroups. When it doesn't, e.g. because we're running inside a -/// container or another sandbox, we check that we fail with a helpful error. -fn limits_available(sandbox: &mut SandboxManager) -> bool { - if sandbox.pass(&["--cpus=1", "true"]) { +/// container or another layer, we check that we fail with a helpful error. +fn limits_available(layer: &mut LayerManager) -> bool { + if layer.pass(&["--cpus=1", "true"]) { return true; } assert!( - sandbox.last_stderr.contains(UNAVAILABLE), + layer.last_stderr.contains(UNAVAILABLE), "{}", - sandbox.last_stderr + layer.last_stderr ); eprintln!("cgroup resource limits are not available, skipping"); false } -/// Finds our sandbox's cgroup on the host, if it has one -fn host_cgroup(sandbox: &SandboxManager) -> Option { - let suffix = format!("-{}", sandbox.name); +/// Finds our layer's cgroup on the host, if it has one +fn host_cgroup(layer: &LayerManager) -> Option { + let suffix = format!("-{}", layer.name); fs::read_dir("/sys/fs/cgroup/layer") .ok()? .filter_map(|entry| entry.ok()) @@ -53,137 +53,135 @@ fn host_cgroup(sandbox: &SandboxManager) -> Option { */ #[rstest] -fn ai_test_limits_unlimited_by_default( - mut sandbox: SandboxManager, -) -> Result<()> { +fn ai_test_limits_unlimited_by_default(mut layer: LayerManager) -> Result<()> { // Skip config files, which may set limits - sandbox.run(&["--no-config", "config", "cpus", "memory"])?; - assert!(sandbox.last_stdout.contains("cpus=unlimited")); - assert!(sandbox.last_stdout.contains("memory=unlimited")); + layer.run(&["--no-config", "config", "cpus", "memory"])?; + assert!(layer.last_stdout.contains("cpus=unlimited")); + assert!(layer.last_stdout.contains("memory=unlimited")); // Both keys are part of the full config listing - sandbox.run(&["--no-config", "config"])?; - assert!(sandbox.last_stdout.contains("cpus=unlimited")); - assert!(sandbox.last_stdout.contains("memory=unlimited")); + layer.run(&["--no-config", "config"])?; + assert!(layer.last_stdout.contains("cpus=unlimited")); + assert!(layer.last_stdout.contains("memory=unlimited")); Ok(()) } #[rstest] -fn ai_test_limits_cli(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run(&["--cpus=2", "config", "cpus"])?; - assert_eq!(sandbox.last_stdout.trim(), "2"); +fn ai_test_limits_cli(mut layer: LayerManager) -> Result<()> { + layer.run(&["--cpus=2", "config", "cpus"])?; + assert_eq!(layer.last_stdout.trim(), "2"); - sandbox.run(&["--cpus=1.5", "config", "cpus"])?; - assert_eq!(sandbox.last_stdout.trim(), "1.5"); + layer.run(&["--cpus=1.5", "config", "cpus"])?; + assert_eq!(layer.last_stdout.trim(), "1.5"); // Negative values are relative to the number of available CPUs, and // work with or without an equals sign let expected = (available_cpus() - 1).to_string(); - sandbox.run(&["--cpus=-1", "config", "cpus"])?; - assert_eq!(sandbox.last_stdout.trim(), expected); - sandbox.run(&["--cpus", "-1", "config", "cpus"])?; - assert_eq!(sandbox.last_stdout.trim(), expected); + layer.run(&["--cpus=-1", "config", "cpus"])?; + assert_eq!(layer.last_stdout.trim(), expected); + layer.run(&["--cpus", "-1", "config", "cpus"])?; + assert_eq!(layer.last_stdout.trim(), expected); - sandbox.run(&["--memory=512M", "config", "memory"])?; - assert_eq!(sandbox.last_stdout.trim(), (512u64 << 20).to_string()); + layer.run(&["--memory=512M", "config", "memory"])?; + assert_eq!(layer.last_stdout.trim(), (512u64 << 20).to_string()); - sandbox.run(&["--memory", "1.5G", "config", "memory"])?; - assert_eq!(sandbox.last_stdout.trim(), (3u64 << 29).to_string()); + layer.run(&["--memory", "1.5G", "config", "memory"])?; + assert_eq!(layer.last_stdout.trim(), (3u64 << 29).to_string()); Ok(()) } #[rstest] -fn ai_test_limits_env(mut sandbox: SandboxManager) -> Result<()> { +fn ai_test_limits_env(mut layer: LayerManager) -> Result<()> { // Config files are skipped so they can't set limits of their own let args = ["--no-config", "config"]; - sandbox.run_with_env( + layer.run_with_env( &[&args[..], &["cpus"]].concat(), "DEVLAYER_CPUS", "3", )?; - assert_eq!(sandbox.last_stdout.trim(), "3"); + assert_eq!(layer.last_stdout.trim(), "3"); - sandbox.run_with_env( + layer.run_with_env( &[&args[..], &["memory"]].concat(), "DEVLAYER_MEMORY", "2G", )?; - assert_eq!(sandbox.last_stdout.trim(), (2u64 << 30).to_string()); + assert_eq!(layer.last_stdout.trim(), (2u64 << 30).to_string()); // Empty values are ignored - sandbox.run_with_env( + layer.run_with_env( &[&args[..], &["cpus"]].concat(), "DEVLAYER_CPUS", "", )?; - assert_eq!(sandbox.last_stdout.trim(), "unlimited"); + assert_eq!(layer.last_stdout.trim(), "unlimited"); // The CLI takes precedence over the environment - sandbox.run_with_env( + layer.run_with_env( &["--no-config", "--cpus=1", "config", "cpus"], "DEVLAYER_CPUS", "3", )?; - assert_eq!(sandbox.last_stdout.trim(), "1"); + assert_eq!(layer.last_stdout.trim(), "1"); Ok(()) } #[rstest] -fn ai_test_limits_config_file(mut sandbox: SandboxManager) -> Result<()> { +fn ai_test_limits_config_file(mut layer: LayerManager) -> Result<()> { let config = - write_config(&sandbox, "limits", "cpus = -1\nmemory = \"4G\"\n")?; - sandbox.run(&["--config", &config, "config", "cpus", "memory"])?; + write_config(&layer, "limits", "cpus = -1\nmemory = \"4G\"\n")?; + layer.run(&["--config", &config, "config", "cpus", "memory"])?; assert!( - sandbox + layer .last_stdout .contains(&format!("cpus={}", available_cpus() - 1)) ); assert!( - sandbox + layer .last_stdout .contains(&format!("memory={}", 4u64 << 30)) ); // Numbers and strings are both accepted let config = write_config( - &sandbox, + &layer, "limits-types", "cpus = \"0.5\"\nmemory = 1073741824\n", )?; - sandbox.run(&["--config", &config, "config", "cpus", "memory"])?; - assert!(sandbox.last_stdout.contains("cpus=0.5")); - assert!(sandbox.last_stdout.contains("memory=1073741824")); + layer.run(&["--config", &config, "config", "cpus", "memory"])?; + assert!(layer.last_stdout.contains("cpus=0.5")); + assert!(layer.last_stdout.contains("memory=1073741824")); // The environment takes precedence over config files - sandbox.run_with_env( + layer.run_with_env( &["--config", &config, "config", "cpus"], "DEVLAYER_CPUS", "2", )?; - assert_eq!(sandbox.last_stdout.trim(), "2"); + assert_eq!(layer.last_stdout.trim(), "2"); Ok(()) } #[rstest] -fn ai_test_limits_invalid(mut sandbox: SandboxManager) -> Result<()> { +fn ai_test_limits_invalid(mut layer: LayerManager) -> Result<()> { for cpus in ["--cpus=0", "--cpus=abc", "--cpus=0.001"] { - assert!(sandbox.xfail(&[cpus, "config", "cpus"])); + assert!(layer.xfail(&[cpus, "config", "cpus"])); assert!( - sandbox.last_stderr.contains("Invalid cpus value"), + layer.last_stderr.contains("Invalid cpus value"), "{}", - sandbox.last_stderr + layer.last_stderr ); } let all_cpus = format!("--cpus=-{}", available_cpus()); - assert!(sandbox.xfail(&[&all_cpus, "config", "cpus"])); - assert!(sandbox.last_stderr.contains("leaves 0 of the")); + assert!(layer.xfail(&[&all_cpus, "config", "cpus"])); + assert!(layer.last_stderr.contains("leaves 0 of the")); - assert!(sandbox.xfail(&["--memory=lots", "config", "memory"])); - assert!(sandbox.last_stderr.contains("Invalid memory value 'lots'")); + assert!(layer.xfail(&["--memory=lots", "config", "memory"])); + assert!(layer.last_stderr.contains("Invalid memory value 'lots'")); - let config = write_config(&sandbox, "bad-type", "cpus = true\n")?; - assert!(sandbox.xfail(&["--config", &config, "config", "cpus"])); + let config = write_config(&layer, "bad-type", "cpus = true\n")?; + assert!(layer.xfail(&["--config", &config, "config", "cpus"])); Ok(()) } @@ -192,37 +190,37 @@ fn ai_test_limits_invalid(mut sandbox: SandboxManager) -> Result<()> { */ #[rstest] -fn ai_test_limits_applied(mut sandbox: SandboxManager) -> Result<()> { - if !limits_available(&mut sandbox) { +fn ai_test_limits_applied(mut layer: LayerManager) -> Result<()> { + if !limits_available(&mut layer) { return Ok(()); } - sandbox.run(&["stop"])?; + layer.run(&["stop"])?; let args = ["--cpus=2", "--memory=256M"]; - let run = |sandbox: &mut SandboxManager, command: &[&str]| { + let run = |layer: &mut LayerManager, command: &[&str]| { let mut full = args.to_vec(); full.extend_from_slice(command); - sandbox + layer .run(&full) - .map(|_| sandbox.last_stdout.trim().to_string()) + .map(|_| layer.last_stdout.trim().to_string()) }; - // Our limits are visible inside the sandbox, whose cgroup namespace is - // rooted at the sandbox's cgroup + // Our limits are visible inside the layer, whose cgroup namespace is + // rooted at the layer's cgroup assert_eq!( - run(&mut sandbox, &["cat", "/sys/fs/cgroup/cpu.max"])?, + run(&mut layer, &["cat", "/sys/fs/cgroup/cpu.max"])?, "200000 100000" ); assert_eq!( - run(&mut sandbox, &["cat", "/sys/fs/cgroup/memory.max"])?, + run(&mut layer, &["cat", "/sys/fs/cgroup/memory.max"])?, (256u64 << 20).to_string() ); - assert_eq!(run(&mut sandbox, &["cat", "/proc/self/cgroup"])?, "0::/"); + assert_eq!(run(&mut layer, &["cat", "/proc/self/cgroup"])?, "0::/"); - // Processes that join the running sandbox are in its cgroup too - let cgroup = host_cgroup(&sandbox).expect("layer cgroup should exist"); + // Processes that join the running layer are in its cgroup too + let cgroup = host_cgroup(&layer).expect("layer cgroup should exist"); let mut child = - sandbox.run_in_background(&[args[0], args[1], "sleep", "30"])?; + layer.run_in_background(&[args[0], args[1], "sleep", "30"])?; let mut joined = false; for _ in 0..100 { let procs = fs::read_to_string(cgroup.join("cgroup.procs"))?; @@ -234,39 +232,39 @@ fn ai_test_limits_applied(mut sandbox: SandboxManager) -> Result<()> { } assert!(joined, "sleep should have joined the layer cgroup"); - // Stopping the sandbox removes its cgroup - sandbox.run(&["stop"])?; + // Stopping the layer removes its cgroup + layer.run(&["stop"])?; let _ = child.wait(); assert!(!cgroup.exists()); Ok(()) } #[rstest] -fn ai_test_limits_negative_cpus(mut sandbox: SandboxManager) -> Result<()> { - if !limits_available(&mut sandbox) { +fn ai_test_limits_negative_cpus(mut layer: LayerManager) -> Result<()> { + if !limits_available(&mut layer) { return Ok(()); } - sandbox.run(&["stop"])?; + layer.run(&["stop"])?; - sandbox.run(&["--cpus=-1", "cat", "/sys/fs/cgroup/cpu.max"])?; + layer.run(&["--cpus=-1", "cat", "/sys/fs/cgroup/cpu.max"])?; assert_eq!( - sandbox.last_stdout.trim(), + layer.last_stdout.trim(), format!("{} 100000", (available_cpus() - 1) * 100000) ); Ok(()) } #[rstest] -fn ai_test_limits_memory_enforced(mut sandbox: SandboxManager) -> Result<()> { - if !limits_available(&mut sandbox) { +fn ai_test_limits_memory_enforced(mut layer: LayerManager) -> Result<()> { + if !limits_available(&mut layer) { return Ok(()); } - sandbox.run(&["stop"])?; + layer.run(&["stop"])?; // tail has to buffer the whole newline-free input, which won't fit. // memory.events is read in the same command so we see this cgroup's // counters even if the OOM killer took down more than tail. - sandbox.run(&[ + layer.run(&[ "--memory=32M", "sh", "-c", @@ -274,7 +272,7 @@ fn ai_test_limits_memory_enforced(mut sandbox: SandboxManager) -> Result<()> { echo \"tail exited with $?\"; \ cat /sys/fs/cgroup/memory.events", ])?; - let output = sandbox.last_stdout.clone(); + let output = layer.last_stdout.clone(); assert!(output.contains("tail exited with 137"), "{}", output); let oom_kills: u64 = output .lines() @@ -286,53 +284,53 @@ fn ai_test_limits_memory_enforced(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn ai_test_limits_changed(mut sandbox: SandboxManager) -> Result<()> { - if !limits_available(&mut sandbox) { +fn ai_test_limits_changed(mut layer: LayerManager) -> Result<()> { + if !limits_available(&mut layer) { return Ok(()); } // Restart without config files, which may set limits of their own - sandbox.run(&["stop"])?; - sandbox.run(&["--no-config", "--cpus=1", "true"])?; + layer.run(&["stop"])?; + layer.run(&["--no-config", "--cpus=1", "true"])?; - // The sandbox is running with --cpus=1, so other limits are rejected - assert!(sandbox.xfail(&["--no-config", "true"])); - assert!(sandbox.last_stderr.contains("Resource limits have changed")); + // The layer is running with --cpus=1, so other limits are rejected + assert!(layer.xfail(&["--no-config", "true"])); + assert!(layer.last_stderr.contains("Resource limits have changed")); assert!( - sandbox + layer .last_stderr .contains("Existing: cpus=1 memory=unlimited") ); assert!( - sandbox + layer .last_stderr .contains("Current: cpus=unlimited memory=unlimited") ); - assert!(sandbox.xfail(&["--no-config", "--cpus=1", "--memory=1G", "true"])); + assert!(layer.xfail(&["--no-config", "--cpus=1", "--memory=1G", "true"])); assert!( - sandbox + layer .last_stderr .contains(&format!("Current: cpus=1 memory={} bytes", 1u64 << 30)) ); // The same limits are fine, and stopping lets us change them - sandbox.run(&["--no-config", "--cpus=1", "true"])?; - sandbox.run(&["stop"])?; - sandbox.run(&["--no-config", "--cpus=2", "true"])?; + layer.run(&["--no-config", "--cpus=1", "true"])?; + layer.run(&["stop"])?; + layer.run(&["--no-config", "--cpus=2", "true"])?; Ok(()) } #[rstest] -fn ai_test_limits_stale_cgroup(mut sandbox: SandboxManager) -> Result<()> { - if !limits_available(&mut sandbox) { +fn ai_test_limits_stale_cgroup(mut layer: LayerManager) -> Result<()> { + if !limits_available(&mut layer) { return Ok(()); } - // Kill the sandbox without cleaning up, leaving an empty cgroup behind - let cgroup = host_cgroup(&sandbox).expect("layer cgroup should exist"); - sandbox.run(&["config", "sandbox_dir"])?; - let pid_file = format!("{}.pid", sandbox.last_stdout.trim()); + // Kill the layer without cleaning up, leaving an empty cgroup behind + let cgroup = host_cgroup(&layer).expect("layer cgroup should exist"); + layer.run(&["config", "layer_dir"])?; + let pid_file = format!("{}.pid", layer.last_stdout.trim()); let pid = fs::read_to_string(&pid_file)?; std::process::Command::new("sudo") .args(["kill", "-9", pid.trim()]) @@ -346,26 +344,26 @@ fn ai_test_limits_stale_cgroup(mut sandbox: SandboxManager) -> Result<()> { assert!(cgroup.exists()); // Starting again replaces the stale cgroup - sandbox.run(&["--cpus=2", "cat", "/sys/fs/cgroup/cpu.max"])?; - assert_eq!(sandbox.last_stdout.trim(), "200000 100000"); + layer.run(&["--cpus=2", "cat", "/sys/fs/cgroup/cpu.max"])?; + assert_eq!(layer.last_stdout.trim(), "200000 100000"); Ok(()) } #[rstest] -fn ai_test_limits_cgroup_in_use(mut sandbox: SandboxManager) -> Result<()> { - if !limits_available(&mut sandbox) { +fn ai_test_limits_cgroup_in_use(mut layer: LayerManager) -> Result<()> { + if !limits_available(&mut layer) { return Ok(()); } - // A sandbox with the same name in another storage directory would + // A layer with the same name in another storage directory would // need the same cgroup, which is in use let storage_dir = - std::env::current_dir()?.join(sandbox.test_filename("storage")); + std::env::current_dir()?.join(layer.test_filename("storage")); fs::create_dir_all(&storage_dir)?; let storage_arg = format!("--storage-dir={}", storage_dir.display()); - assert!(sandbox.xfail(&[&storage_arg, "--cpus=1", "true"])); + assert!(layer.xfail(&[&storage_arg, "--cpus=1", "true"])); assert!( - sandbox + layer .last_stderr .contains("from a different storage directory") ); @@ -373,66 +371,66 @@ fn ai_test_limits_cgroup_in_use(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn ai_test_limits_setup_failures(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.exfail(&["--cpus=1", "true"], "TEST_NO_CGROUP2", "1")); - assert!(sandbox.last_stderr.contains(UNAVAILABLE)); +fn ai_test_limits_setup_failures(mut layer: LayerManager) -> Result<()> { + assert!(layer.exfail(&["--cpus=1", "true"], "TEST_NO_CGROUP2", "1")); + assert!(layer.last_stderr.contains(UNAVAILABLE)); assert!( - sandbox + layer .last_stderr .contains("requires cgroup v2, which is not mounted") ); - if !limits_available(&mut sandbox) { + if !limits_available(&mut layer) { return Ok(()); } - sandbox.run(&["stop"])?; + layer.run(&["stop"])?; // Failing to apply limits cleans up the cgroup for (file, args) in [ ("cpu.max", vec!["--cpus=1", "true"]), ("memory.max", vec!["--memory=1G", "true"]), ] { - assert!(sandbox.exfail(&args, "TEST_CGROUP_WRITE_FAILURE", file)); - assert!(sandbox.last_stderr.contains(UNAVAILABLE)); - assert!(sandbox.last_stderr.contains("Failed to write")); - assert!(host_cgroup(&sandbox).is_none()); + assert!(layer.exfail(&args, "TEST_CGROUP_WRITE_FAILURE", file)); + assert!(layer.last_stderr.contains(UNAVAILABLE)); + assert!(layer.last_stderr.contains("Failed to write")); + assert!(host_cgroup(&layer).is_none()); } - // As does failing to start the sandbox - assert!(sandbox.exfail( + // As does failing to start the layer + assert!(layer.exfail( &["--cpus=1", "true"], - "TEST_START_SANDBOX_FAILURE", + "TEST_START_LAYER_FAILURE", "1" )); - assert!(sandbox.last_stderr.contains("Failed to start layer")); - assert!(host_cgroup(&sandbox).is_none()); + assert!(layer.last_stderr.contains("Failed to start layer")); + assert!(host_cgroup(&layer).is_none()); Ok(()) } #[rstest] -fn ai_test_limits_new_parent_cgroup(mut sandbox: SandboxManager) -> Result<()> { - if !limits_available(&mut sandbox) { +fn ai_test_limits_new_parent_cgroup(mut layer: LayerManager) -> Result<()> { + if !limits_available(&mut layer) { return Ok(()); } - sandbox.run(&["stop"])?; + layer.run(&["stop"])?; - // The first sandbox with limits creates the parent cgroup and enables + // The first layer with limits creates the parent cgroup and enables // the controllers we need in it - let parent = format!("{}-parent", sandbox.name); + let parent = format!("{}-parent", layer.name); let parent_path = PathBuf::from("/sys/fs/cgroup").join(&parent); assert!(!parent_path.exists()); - sandbox.run_with_env( + layer.run_with_env( &["--cpus=1", "--memory=64M", "cat", "/sys/fs/cgroup/cpu.max"], "TEST_CGROUP_PARENT", &parent, )?; - assert_eq!(sandbox.last_stdout.trim(), "100000 100000"); + assert_eq!(layer.last_stdout.trim(), "100000 100000"); let enabled = fs::read_to_string(parent_path.join("cgroup.subtree_control"))?; assert!(enabled.split_whitespace().any(|c| c == "cpu")); assert!(enabled.split_whitespace().any(|c| c == "memory")); - sandbox.run_with_env(&["stop"], "TEST_CGROUP_PARENT", &parent)?; + layer.run_with_env(&["stop"], "TEST_CGROUP_PARENT", &parent)?; assert_eq!( fs::read_dir(&parent_path)? .filter(|e| { e.as_ref().is_ok_and(|e| e.path().is_dir()) }) @@ -446,73 +444,71 @@ fn ai_test_limits_new_parent_cgroup(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn ai_test_limits_no_swap_accounting( - mut sandbox: SandboxManager, -) -> Result<()> { - if !limits_available(&mut sandbox) { +fn ai_test_limits_no_swap_accounting(mut layer: LayerManager) -> Result<()> { + if !limits_available(&mut layer) { return Ok(()); } - sandbox.run(&["stop"])?; + layer.run(&["stop"])?; // Only memory is limited (config files are skipped since they may limit // cpus too). Without swap accounting we can limit memory but not swap. let memory_only = ["--no-config", "--memory=64M", "cat"]; - sandbox.run_with_env( + layer.run_with_env( &[&memory_only[..], &["/sys/fs/cgroup/memory.max"]].concat(), "TEST_NO_SWAP_ACCOUNTING", "1", )?; - assert_eq!(sandbox.last_stdout.trim(), (64u64 << 20).to_string()); - sandbox.run(&[&memory_only[..], &["/sys/fs/cgroup/cpu.max"]].concat())?; - assert_eq!(sandbox.last_stdout.trim(), "max 100000"); - sandbox.run( + assert_eq!(layer.last_stdout.trim(), (64u64 << 20).to_string()); + layer.run(&[&memory_only[..], &["/sys/fs/cgroup/cpu.max"]].concat())?; + assert_eq!(layer.last_stdout.trim(), "max 100000"); + layer.run( &[&memory_only[..], &["/sys/fs/cgroup/memory.swap.max"]].concat(), )?; - assert_eq!(sandbox.last_stdout.trim(), "max"); - sandbox.run(&["stop"])?; + assert_eq!(layer.last_stdout.trim(), "max"); + layer.run(&["stop"])?; // Normally swap is disabled - sandbox.run( + layer.run( &[&memory_only[..], &["/sys/fs/cgroup/memory.swap.max"]].concat(), )?; - assert_eq!(sandbox.last_stdout.trim(), "0"); + assert_eq!(layer.last_stdout.trim(), "0"); Ok(()) } #[rstest] -fn ai_test_limits_join_failure(mut sandbox: SandboxManager) -> Result<()> { - if !limits_available(&mut sandbox) { +fn ai_test_limits_join_failure(mut layer: LayerManager) -> Result<()> { + if !limits_available(&mut layer) { return Ok(()); } - // The sandbox is running with --cpus=1, joining it requires moving + // The layer is running with --cpus=1, joining it requires moving // into its cgroup - assert!(sandbox.exfail( + assert!(layer.exfail( &["--cpus=1", "true"], "TEST_CGROUP_WRITE_FAILURE", "cgroup.procs" )); - assert!(sandbox.last_stderr.contains("Failed to write")); - assert!(sandbox.last_stderr.contains("cgroup.procs")); + assert!(layer.last_stderr.contains("Failed to write")); + assert!(layer.last_stderr.contains("cgroup.procs")); Ok(()) } #[rstest] -fn ai_test_limits_stop_cgroup_busy(mut sandbox: SandboxManager) -> Result<()> { - if !limits_available(&mut sandbox) { +fn ai_test_limits_stop_cgroup_busy(mut layer: LayerManager) -> Result<()> { + if !limits_available(&mut layer) { return Ok(()); } - // A child cgroup keeps the sandbox's cgroup from being removed, so stop + // A child cgroup keeps the layer's cgroup from being removed, so stop // retries for a while and then gives up without failing - let cgroup = host_cgroup(&sandbox).expect("layer cgroup should exist"); + let cgroup = host_cgroup(&layer).expect("layer cgroup should exist"); let child = cgroup.join("busy"); let sudo = |args: &[&str]| std::process::Command::new("sudo").args(args).status(); sudo(&["mkdir", &child.to_string_lossy()])?; let started = std::time::Instant::now(); - sandbox.run(&["stop"])?; + layer.run(&["stop"])?; assert!(started.elapsed() >= std::time::Duration::from_secs(5)); assert!(cgroup.exists()); @@ -523,13 +519,11 @@ fn ai_test_limits_stop_cgroup_busy(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn ai_test_limits_unlimited_override( - mut sandbox: SandboxManager, -) -> Result<()> { +fn ai_test_limits_unlimited_override(mut layer: LayerManager) -> Result<()> { // "unlimited" removes a limit set by a less specific source let config = - write_config(&sandbox, "limited", "cpus = 2\nmemory = \"4G\"\n")?; - sandbox.run(&[ + write_config(&layer, "limited", "cpus = 2\nmemory = \"4G\"\n")?; + layer.run(&[ "--config", &config, "--cpus=unlimited", @@ -538,47 +532,47 @@ fn ai_test_limits_unlimited_override( "cpus", "memory", ])?; - assert!(sandbox.last_stdout.contains("cpus=unlimited")); - assert!(sandbox.last_stdout.contains("memory=unlimited")); + assert!(layer.last_stdout.contains("cpus=unlimited")); + assert!(layer.last_stdout.contains("memory=unlimited")); - sandbox.run_with_env( + layer.run_with_env( &["--config", &config, "config", "cpus"], "DEVLAYER_CPUS", "unlimited", )?; - assert_eq!(sandbox.last_stdout.trim(), "unlimited"); + assert_eq!(layer.last_stdout.trim(), "unlimited"); let unlimited = - write_config(&sandbox, "unlimited", "memory = \"unlimited\"\n")?; - sandbox.run(&["--config", &unlimited, "config", "memory"])?; - assert_eq!(sandbox.last_stdout.trim(), "unlimited"); - - // Without any limits the sandbox doesn't get a cgroup - if limits_available(&mut sandbox) { - sandbox.run(&["stop"])?; - sandbox.run(&[ + write_config(&layer, "unlimited", "memory = \"unlimited\"\n")?; + layer.run(&["--config", &unlimited, "config", "memory"])?; + assert_eq!(layer.last_stdout.trim(), "unlimited"); + + // Without any limits the layer doesn't get a cgroup + if limits_available(&mut layer) { + layer.run(&["stop"])?; + layer.run(&[ "--config", &config, "--cpus=unlimited", "--memory=unlimited", "true", ])?; - assert!(host_cgroup(&sandbox).is_none()); + assert!(host_cgroup(&layer).is_none()); } Ok(()) } #[rstest] -fn ai_test_limits_nested(mut sandbox: SandboxManager) -> Result<()> { - if !limits_available(&mut sandbox) { +fn ai_test_limits_nested(mut layer: LayerManager) -> Result<()> { + if !limits_available(&mut layer) { return Ok(()); } - sandbox.run(&["stop"])?; + layer.run(&["stop"])?; - // A sandbox inside another one can't manage cgroups, so instead of its - // own limits it shares the limits of the sandbox it's running in - let inner = get_sandbox_bin() + "-setuid"; - sandbox.run(&[ + // A layer inside another one can't manage cgroups, so instead of its + // own limits it shares the limits of the layer it's running in + let inner = get_devlayer_bin() + "-setuid"; + layer.run(&[ "--no-config", "--cpus=2", &inner, @@ -587,41 +581,39 @@ fn ai_test_limits_nested(mut sandbox: SandboxManager) -> Result<()> { "cat", "/sys/fs/cgroup/cpu.max", ])?; - assert_eq!(sandbox.last_stdout.trim(), "200000 100000"); + assert_eq!(layer.last_stdout.trim(), "200000 100000"); assert!( - sandbox.last_stderr.contains( + layer.last_stderr.contains( "shares the limits of the layer it's running in (cpus=2 memory=unlimited)" ), "{}", - sandbox.last_stderr + layer.last_stderr ); // The warning makes it clear when that means no limits at all - sandbox.run(&["stop"])?; - sandbox.run(&["--no-config", &inner, "--no-config", "--cpus=1", "true"])?; + layer.run(&["stop"])?; + layer.run(&["--no-config", &inner, "--no-config", "--cpus=1", "true"])?; assert!( - sandbox.last_stderr.contains( + layer.last_stderr.contains( "shares the limits of the layer it's running in (cpus=unlimited memory=unlimited)" ), "{}", - sandbox.last_stderr + layer.last_stderr ); Ok(()) } #[rstest] -fn ai_test_limits_delete_removes_cgroup( - mut sandbox: SandboxManager, -) -> Result<()> { - if !limits_available(&mut sandbox) { +fn ai_test_limits_delete_removes_cgroup(mut layer: LayerManager) -> Result<()> { + if !limits_available(&mut layer) { return Ok(()); } - // delete stops sandboxes without knowing which user started them, so - // it has to find the cgroup from the running sandbox - let cgroup = host_cgroup(&sandbox).expect("layer cgroup should exist"); - let name = sandbox.name.clone(); - sandbox.run(&["delete", "-y", &name])?; + // delete stops layers without knowing which user started them, so + // it has to find the cgroup from the running layer + let cgroup = host_cgroup(&layer).expect("layer cgroup should exist"); + let name = layer.name.clone(); + layer.run(&["delete", "-y", &name])?; assert!(!cgroup.exists()); Ok(()) } diff --git a/tests/ai_test_run_media_mount.rs b/tests/ai_test_run_media_mount.rs index c4da550..f37b855 100644 --- a/tests/ai_test_run_media_mount.rs +++ b/tests/ai_test_run_media_mount.rs @@ -5,9 +5,9 @@ use fixtures::*; use rstest::*; #[rstest] -fn test_bind_mount_under_run_media(mut sandbox: SandboxManager) -> Result<()> { +fn test_bind_mount_under_run_media(mut layer: LayerManager) -> Result<()> { // Create a temporary directory to bind mount - let test_dir = sandbox.test_filename("bind_test"); + let test_dir = layer.test_filename("bind_test"); std::fs::create_dir(&test_dir)?; // Create a test file in the temp directory @@ -20,7 +20,7 @@ fn test_bind_mount_under_run_media(mut sandbox: SandboxManager) -> Result<()> { // Try to bind mount the temp directory to /run/media/test // This should work with our fix, as we now create parent directories - let success = sandbox.pass(&[ + let success = layer.pass(&[ "--bind", &format!("{}:/run/media/devlayer-coverage-testing", test_dir), "ls", @@ -31,10 +31,10 @@ fn test_bind_mount_under_run_media(mut sandbox: SandboxManager) -> Result<()> { assert!( success, "Failed to bind mount to /run/media/devlayer-coverage-testing: {}", - sandbox.last_stderr + layer.last_stderr ); assert!( - sandbox.last_stdout.contains("test.txt"), + layer.last_stdout.contains("test.txt"), "Test file not found in bind mount" ); diff --git a/tests/ai_test_sigterm.rs b/tests/ai_test_sigterm.rs index e5f877d..13af501 100644 --- a/tests/ai_test_sigterm.rs +++ b/tests/ai_test_sigterm.rs @@ -7,16 +7,16 @@ use std::path::Path; use std::time::{Duration, Instant}; #[rstest] -fn ai_test_sigterm_stops_sandbox(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run(&["true"])?; +fn ai_test_sigterm_stops_layer(mut layer: LayerManager) -> Result<()> { + layer.run(&["true"])?; - sandbox.run(&["config", "sandbox_dir"])?; - let pid_file = format!("{}.pid", sandbox.last_stdout.trim()); + layer.run(&["config", "layer_dir"])?; + let pid_file = format!("{}.pid", layer.last_stdout.trim()); let pid = std::fs::read_to_string(&pid_file)?.trim().to_string(); let proc_dir = format!("/proc/{}", pid); assert!(Path::new(&proc_dir).exists()); - // The sandbox's PID 1 exits when asked to terminate + // The layer's PID 1 exits when asked to terminate let status = std::process::Command::new("sudo") .args(["kill", "-TERM", &pid]) .status()?; @@ -27,8 +27,8 @@ fn ai_test_sigterm_stops_sandbox(mut sandbox: SandboxManager) -> Result<()> { } assert!(!Path::new(&proc_dir).exists()); - // and the sandbox starts again the next time it's used - sandbox.run(&["echo", "restarted"])?; - assert_eq!(sandbox.last_stdout.trim(), "restarted"); + // and the layer starts again the next time it's used + layer.run(&["echo", "restarted"])?; + assert_eq!(layer.last_stdout.trim(), "restarted"); Ok(()) } diff --git a/tests/fixtures/fixture_sandbox.rs b/tests/fixtures/fixture_layer.rs similarity index 92% rename from tests/fixtures/fixture_sandbox.rs rename to tests/fixtures/fixture_layer.rs index 6632969..e35bdb6 100644 --- a/tests/fixtures/fixture_sandbox.rs +++ b/tests/fixtures/fixture_layer.rs @@ -17,7 +17,7 @@ pub fn rid() -> String { rid } -pub fn get_sandbox_bin() -> String { +pub fn get_devlayer_bin() -> String { // Get the original working directory when the tests start // This is needed because tests may change directories let cargo_manifest_dir = std::env::var("CARGO_MANIFEST_DIR") @@ -56,7 +56,7 @@ pub fn get_sandbox_bin() -> String { absolute_path.to_string_lossy().to_string() } -pub struct SandboxManager { +pub struct LayerManager { pub name: String, pub last_stdout: String, pub last_stderr: String, @@ -64,13 +64,13 @@ pub struct SandboxManager { pub all_stderr: String, pub debug_mode: bool, pub no_sudo: bool, - /* we store the sandbox binary path so we can chdir as necessary */ - pub sandbox_bin: String, + /* we store the layer binary path so we can chdir as necessary */ + pub devlayer_bin: String, pub no_default_options: bool, pub ignored: bool, // Controls whether --ignored is automatically added } -impl SandboxManager { +impl LayerManager { pub fn new() -> Self { let name = format!("devlayer-coverage-test-{}", rid()); @@ -95,13 +95,13 @@ impl SandboxManager { all_stderr: String::new(), debug_mode: false, no_sudo: false, - sandbox_bin: get_sandbox_bin(), + devlayer_bin: get_devlayer_bin(), no_default_options: false, ignored: true, // Default to true to maintain existing behavior } } - /* When debug mode is on, the sandbox will not be cleaned up when the fixture is dropped */ + /* When debug mode is on, the layer will not be cleaned up when the fixture is dropped */ #[allow(dead_code)] pub fn set_debug_mode(&mut self, debug_mode: bool) { self.debug_mode = debug_mode; @@ -116,14 +116,14 @@ impl SandboxManager { #[allow(dead_code)] pub fn dir(&self) -> Result { let mut cmd = Command::new("sudo"); - cmd.args(["-E", &self.sandbox_bin]); + cmd.args(["-E", &self.devlayer_bin]); if self.no_sudo { - cmd = Command::new(&self.sandbox_bin); + cmd = Command::new(&self.devlayer_bin); } cmd.args([format!("--name={}", &self.name)]); - cmd.args(["config", "sandbox_dir"]); + cmd.args(["config", "layer_dir"]); let output = cmd.output()?; let base = String::from_utf8_lossy(&output.stdout).to_string(); let base = base.trim(); @@ -160,10 +160,10 @@ impl SandboxManager { use std::process::Stdio; let mut cmd = Command::new("sudo"); - cmd.args(["-E", &self.sandbox_bin]); + cmd.args(["-E", &self.devlayer_bin]); if self.no_sudo { - cmd = Command::new(&self.sandbox_bin); + cmd = Command::new(&self.devlayer_bin); } if !self.no_default_options @@ -253,10 +253,10 @@ impl SandboxManager { println!("Setting env var: {}={}", env_key, env_value); cmd.env(env_key, env_value); } - cmd.args(["-E", &self.sandbox_bin]); + cmd.args(["-E", &self.devlayer_bin]); if self.no_sudo { - cmd = Command::new(&self.sandbox_bin); + cmd = Command::new(&self.devlayer_bin); } if !self.no_default_options @@ -320,10 +320,10 @@ impl SandboxManager { #[allow(dead_code)] pub fn run_in_background(&mut self, args: &[&str]) -> Result { let mut cmd = Command::new("sudo"); - cmd.args(["-E", &self.sandbox_bin]); + cmd.args(["-E", &self.devlayer_bin]); if self.no_sudo { - cmd = Command::new(&self.sandbox_bin); + cmd = Command::new(&self.devlayer_bin); } if !self.no_default_options { @@ -394,7 +394,7 @@ impl SandboxManager { } } -impl Drop for SandboxManager { +impl Drop for LayerManager { fn drop(&mut self) { // Reset flags to default state for cleanup commands self.no_default_options = false; @@ -421,8 +421,8 @@ impl Drop for SandboxManager { warn!("Failed to remove {} dir: {}", dirname.display(), e); } } - let sandbox_name = self.name.clone(); - match self.run(&["delete", "-y", sandbox_name.as_str()]) { + let layer_name = self.name.clone(); + match self.run(&["delete", "-y", layer_name.as_str()]) { Ok(_) => (), Err(e) => { warn!("Failed to delete layer: {}", e); @@ -437,6 +437,6 @@ impl Drop for SandboxManager { } #[fixture] -pub fn sandbox() -> SandboxManager { - SandboxManager::new() +pub fn layer() -> LayerManager { + LayerManager::new() } diff --git a/tests/fixtures/mod.rs b/tests/fixtures/mod.rs index b37db02..785ca13 100644 --- a/tests/fixtures/mod.rs +++ b/tests/fixtures/mod.rs @@ -1,3 +1,3 @@ -mod fixture_sandbox; +mod fixture_layer; -pub use fixture_sandbox::*; +pub use fixture_layer::*; diff --git a/tests/isolated_test_accept_rename_across_mount.rs b/tests/isolated_test_accept_rename_across_mount.rs index dbe84df..551b44a 100644 --- a/tests/isolated_test_accept_rename_across_mount.rs +++ b/tests/isolated_test_accept_rename_across_mount.rs @@ -17,9 +17,9 @@ use std::{path::Path, process::Command}; */ #[rstest] -fn test_accept_rename_across_mount(mut sandbox: SandboxManager) -> Result<()> { +fn test_accept_rename_across_mount(mut layer: LayerManager) -> Result<()> { let dest_host_dir = "/delete-me-this-is-a-devlayer-coverage-test-dir-for-rename-across-mount"; - let dir_to_move = sandbox.test_filename("dir_to_move"); + let dir_to_move = layer.test_filename("dir_to_move"); Command::new("sudo") .arg("mkdir") .arg(dest_host_dir) @@ -42,7 +42,7 @@ fn test_accept_rename_across_mount(mut sandbox: SandboxManager) -> Result<()> { let path = Path::new(&dir_to_move); let dest_path = Path::new(&dest_host_dir); - sandbox.run(&["mv", &dir_to_move, dest_host_dir])?; + layer.run(&["mv", &dir_to_move, dest_host_dir])?; assert!(path.exists()); assert!(dest_path.exists()); @@ -50,7 +50,7 @@ fn test_accept_rename_across_mount(mut sandbox: SandboxManager) -> Result<()> { // relative change it will not accept it let cwd = std::env::current_dir()?; chdir("/")?; - assert!(sandbox.pass(&["accept", &dir_to_move])); + assert!(layer.pass(&["accept", &dir_to_move])); chdir(&cwd)?; // restore for cleanup Command::new("sudo") diff --git a/tests/isolated_test_accept_root.rs b/tests/isolated_test_accept_root.rs index 352fefe..0862aa4 100644 --- a/tests/isolated_test_accept_root.rs +++ b/tests/isolated_test_accept_root.rs @@ -9,7 +9,7 @@ use std::{path::Path, process::Command}; * and tests are run in parallel per file. */ #[rstest] -fn test_accept_root_file(mut sandbox: SandboxManager) -> Result<()> { +fn test_accept_root_file(mut layer: LayerManager) -> Result<()> { let dirname = "/delete-me-this-is-a-devlayer-coverage-test-dir"; let filename = dirname.to_string() + "/delete-me-this-is-a-devlayer-coverage-test-file"; @@ -26,10 +26,10 @@ fn test_accept_root_file(mut sandbox: SandboxManager) -> Result<()> { .arg(dirname) .output()?; let path = Path::new(&filename); - sandbox.run(&["rm", &filename])?; + layer.run(&["rm", &filename])?; assert!(path.exists()); - sandbox.run(&["accept", &filename])?; + layer.run(&["accept", &filename])?; assert!(!path.exists()); Command::new("sudo").arg("rmdir").arg(dirname).output()?; diff --git a/tests/isolated_test_clean_running.rs b/tests/isolated_test_clean_running.rs index 4b1e490..006f61f 100644 --- a/tests/isolated_test_clean_running.rs +++ b/tests/isolated_test_clean_running.rs @@ -5,24 +5,24 @@ use fixtures::*; use rstest::*; /* This test runs `clean` against the default storage directory, so it will - * also delete any real stopped ephemeral sandboxes older than a week. */ + * also delete any real stopped ephemeral layers older than a week. */ #[rstest] #[ignore = "Ignoring as this will delete old non test ephemeral layers"] -fn test_clean_deletes_running_test_sandboxes() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); +fn test_clean_deletes_running_test_layers() -> Result<()> { + let mut layer = layer(); + let name = layer.name.clone(); - sandbox.run(&["true"])?; - sandbox.run(&["list"])?; - assert!(sandbox.last_stdout.contains("Running layers:")); - assert!(sandbox.last_stdout.contains(&name)); + layer.run(&["true"])?; + layer.run(&["list"])?; + assert!(layer.last_stdout.contains("Running layers:")); + assert!(layer.last_stdout.contains(&name)); - sandbox.run(&["clean", "-y"])?; - assert!(sandbox.last_stdout.contains(&name)); + layer.run(&["clean", "-y"])?; + assert!(layer.last_stdout.contains(&name)); - sandbox.run(&["list"])?; - assert!(!sandbox.last_stdout.contains(&name)); + layer.run(&["list"])?; + assert!(!layer.last_stdout.contains(&name)); Ok(()) } diff --git a/tests/isolated_test_create_old_root_host_path_failure.rs b/tests/isolated_test_create_old_root_host_path_failure.rs index 092acdd..09d3348 100644 --- a/tests/isolated_test_create_old_root_host_path_failure.rs +++ b/tests/isolated_test_create_old_root_host_path_failure.rs @@ -6,15 +6,15 @@ use rstest::*; #[rstest] fn test_create_old_root_host_path_failure( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - assert!(sandbox.exfail( + assert!(layer.exfail( &["true"], "TEST_CREATE_OLD_ROOT_HOST_PATH_FAILURE", "1" )); assert!( - sandbox + layer .last_stderr .contains("Failed to create place to pivot our old root to") ); diff --git a/tests/isolated_test_new.rs b/tests/isolated_test_new.rs index 5aaa851..2bd207a 100644 --- a/tests/isolated_test_new.rs +++ b/tests/isolated_test_new.rs @@ -6,28 +6,28 @@ use rstest::*; #[rstest] fn test_new_last_name_with_ms() -> Result<()> { - let mut sandboxes: Vec = Vec::new(); + let mut layers: Vec = Vec::new(); for _ in 0..6 { - let mut sandbox: SandboxManager = SandboxManager::new(); - sandbox.no_default_options = true; - sandboxes.push(sandbox); + let mut layer: LayerManager = LayerManager::new(); + layer.no_default_options = true; + layers.push(layer); } - for sandbox in &mut sandboxes { + for layer in &mut layers { // We spin here to test to ensure we've exercised the code that // dedupes names at the ms level. 6 times in case this test case // is crossing a second-boundary (the clock second is rolling over that is) - assert!(sandbox.epass( + assert!(layer.epass( &["--new", "-v", "true"], "TEST_NAME_WITH_MS", "devlayer-coverage-new-with-ms" )); - sandbox.run(&["--last", "config", "name"])?; - sandbox.name = sandbox.last_stdout.trim().to_string(); + layer.run(&["--last", "config", "name"])?; + layer.name = layer.last_stdout.trim().to_string(); - println!("layer.name: {}", sandbox.name); + println!("layer.name: {}", layer.name); } Ok(()) diff --git a/tests/isolated_test_new_last.rs b/tests/isolated_test_new_last.rs index 8f0c5f9..9fcf824 100644 --- a/tests/isolated_test_new_last.rs +++ b/tests/isolated_test_new_last.rs @@ -6,37 +6,37 @@ use rstest::*; #[rstest] fn test_new_last() -> Result<()> { - let mut sandbox1 = SandboxManager::new(); - let mut sandbox2 = SandboxManager::new(); - let mut sandbox3 = SandboxManager::new(); - - sandbox1.no_default_options = true; - sandbox2.no_default_options = true; - sandbox3.no_default_options = true; - - assert!(sandbox1.pass(&["--new", "-v", "ls"])); - assert!(sandbox1.pass(&["--last", "config", "name"])); - let sandbox1_name = sandbox1.last_stdout.trim(); - sandbox1.name = sandbox1_name.to_string(); - - assert!(sandbox2.pass(&["--new", "-v", "ls"])); - assert!(sandbox2.pass(&["--last", "config", "name"])); - let sandbox2_name = sandbox2.last_stdout.trim(); - sandbox2.name = sandbox2_name.to_string(); - - assert!(sandbox3.pass(&["--new", "-v", "ls"])); - assert!(sandbox3.pass(&["--last", "config", "name"])); - let sandbox3_name = sandbox3.last_stdout.to_string(); - sandbox3.name = sandbox3_name.trim().to_string(); - - assert!(sandbox3.pass(&["--last", "-v", "ls"])); - assert!(sandbox3.pass(&["--last", "config", "name"])); - let sandbox3_last_name = sandbox3.last_stdout.trim().to_string(); - - assert_ne!(sandbox1_name, sandbox2_name); - assert_ne!(sandbox1_name, sandbox3_name); - assert_ne!(sandbox2_name, sandbox3_name); - assert_eq!(sandbox3_name.trim(), sandbox3_last_name); + let mut layer1 = LayerManager::new(); + let mut layer2 = LayerManager::new(); + let mut layer3 = LayerManager::new(); + + layer1.no_default_options = true; + layer2.no_default_options = true; + layer3.no_default_options = true; + + assert!(layer1.pass(&["--new", "-v", "ls"])); + assert!(layer1.pass(&["--last", "config", "name"])); + let layer1_name = layer1.last_stdout.trim(); + layer1.name = layer1_name.to_string(); + + assert!(layer2.pass(&["--new", "-v", "ls"])); + assert!(layer2.pass(&["--last", "config", "name"])); + let layer2_name = layer2.last_stdout.trim(); + layer2.name = layer2_name.to_string(); + + assert!(layer3.pass(&["--new", "-v", "ls"])); + assert!(layer3.pass(&["--last", "config", "name"])); + let layer3_name = layer3.last_stdout.to_string(); + layer3.name = layer3_name.trim().to_string(); + + assert!(layer3.pass(&["--last", "-v", "ls"])); + assert!(layer3.pass(&["--last", "config", "name"])); + let layer3_last_name = layer3.last_stdout.trim().to_string(); + + assert_ne!(layer1_name, layer2_name); + assert_ne!(layer1_name, layer3_name); + assert_ne!(layer2_name, layer3_name); + assert_eq!(layer3_name.trim(), layer3_last_name); Ok(()) } diff --git a/tests/isolated_test_pivot_root_failure.rs b/tests/isolated_test_pivot_root_failure.rs index f52de49..9f69d2a 100644 --- a/tests/isolated_test_pivot_root_failure.rs +++ b/tests/isolated_test_pivot_root_failure.rs @@ -5,8 +5,8 @@ use fixtures::*; use rstest::*; #[rstest] -fn test_pivot_root_failure(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.exfail(&["true"], "TEST_PIVOT_ROOT_FAILURE", "1")); - assert!(sandbox.last_stderr.contains("failed to pivot_root")); +fn test_pivot_root_failure(mut layer: LayerManager) -> Result<()> { + assert!(layer.exfail(&["true"], "TEST_PIVOT_ROOT_FAILURE", "1")); + assert!(layer.last_stderr.contains("failed to pivot_root")); Ok(()) } diff --git a/tests/isolated_test_special_files.rs b/tests/isolated_test_special_files.rs index 0ba6986..bf82ced 100644 --- a/tests/isolated_test_special_files.rs +++ b/tests/isolated_test_special_files.rs @@ -8,10 +8,10 @@ use fixtures::*; use rstest::*; #[rstest] -fn test_exercise_unmovable_files(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run(&["true"])?; - sandbox.run(&["config", "sandbox_dir"])?; - let base = sandbox.last_stdout.trim(); +fn test_exercise_unmovable_files(mut layer: LayerManager) -> Result<()> { + layer.run(&["true"])?; + layer.run(&["config", "layer_dir"])?; + let base = layer.last_stdout.trim(); let upper_dir = Path::new(base).join("upper"); // F4 = / let char_device = upper_dir.join("F4").join("char-device"); @@ -21,16 +21,16 @@ fn test_exercise_unmovable_files(mut sandbox: SandboxManager) -> Result<()> { .output()?; assert!(output.status.success()); - sandbox.run(&["status", "/"])?; - let status = sandbox.last_stdout.trim(); + layer.run(&["status", "/"])?; + let status = layer.last_stdout.trim(); assert!(status.contains("!")); assert!(status.contains("char-device")); let cwd = std::env::current_dir()?; chdir("/")?; - assert!(sandbox.xfail(&["accept", "/char-device"])); + assert!(layer.xfail(&["accept", "/char-device"])); chdir(&cwd)?; // restore for cleanup - let status = sandbox.last_stderr.trim(); + let status = layer.last_stderr.trim(); assert!(status.contains("Unsupported file type")); Ok(()) diff --git a/tests/isolated_test_special_files_remove.rs b/tests/isolated_test_special_files_remove.rs index 621de71..e8797fd 100644 --- a/tests/isolated_test_special_files_remove.rs +++ b/tests/isolated_test_special_files_remove.rs @@ -7,20 +7,18 @@ use fixtures::*; use rstest::*; #[rstest] -fn test_exercise_unmovable_files_remove( - mut sandbox: SandboxManager, -) -> Result<()> { - let char_device = sandbox.test_filename("test-file"); +fn test_exercise_unmovable_files_remove(mut layer: LayerManager) -> Result<()> { + let char_device = layer.test_filename("test-file"); println!("setting up char_device: {}", char_device); let output = Command::new("sudo") .args(["mknod", char_device.as_str(), "c", "1", "3"]) .output()?; assert!(output.status.success()); - sandbox.run(&["rm", char_device.as_str()])?; + layer.run(&["rm", char_device.as_str()])?; - assert!(sandbox.xfail(&["accept", char_device.as_str()])); - let status = sandbox.last_stderr.trim(); + assert!(layer.xfail(&["accept", char_device.as_str()])); + let status = layer.last_stderr.trim(); assert!(status.contains("cowardly refusing to remove special file")); Ok(()) diff --git a/tests/isolated_test_stop_all.rs b/tests/isolated_test_stop_all.rs index dd2557f..8124204 100644 --- a/tests/isolated_test_stop_all.rs +++ b/tests/isolated_test_stop_all.rs @@ -6,16 +6,16 @@ use rstest::*; use std::{io::Write, process::Command, thread::sleep, time::Duration}; /* This test needs to be the only test in this file since it - * kills all running sandboxes, which would interfere with other + * kills all running layers, which would interfere with other * tests that were running in parallel. */ #[rstest] #[ignore = "Ignoring as this will stop non test layers"] fn test_stop_all() -> Result<()> { - let mut sandbox1 = sandbox(); - let mut sandbox2 = sandbox(); - let mut c1 = sandbox1.run_in_background(&["sleep", "9897135"])?; - let mut c2 = sandbox2.run_in_background(&["sleep", "9897135"])?; + let mut layer1 = layer(); + let mut layer2 = layer(); + let mut c1 = layer1.run_in_background(&["sleep", "9897135"])?; + let mut c2 = layer2.run_in_background(&["sleep", "9897135"])?; // ensure they start up let mut ok = false; @@ -26,7 +26,7 @@ fn test_stop_all() -> Result<()> { let lines: Vec<&str> = ps_output .lines() .filter(|line| { - // excluding --name excludes the sandbox binary call lines + // excluding --name excludes the layer binary call lines line.contains("sleep 9897135") && !line.contains("--name") }) .collect(); @@ -57,7 +57,7 @@ fn test_stop_all() -> Result<()> { assert!(lines.len() == 2); - assert!(sandbox1.pass(&["stop", "--all"])); + assert!(layer1.pass(&["stop", "--all"])); c1.wait()?; let ps = Command::new("ps").arg("aux").output()?; @@ -70,6 +70,6 @@ fn test_stop_all() -> Result<()> { .collect(); assert!(lines.is_empty()); - c2.wait()?; // if this doesn't hang, then the sandbox was killed! + c2.wait()?; // if this doesn't hang, then the layer was killed! Ok(()) } diff --git a/tests/isolated_test_stop_all_partial_fail.rs b/tests/isolated_test_stop_all_partial_fail.rs index 4944805..ab9db97 100644 --- a/tests/isolated_test_stop_all_partial_fail.rs +++ b/tests/isolated_test_stop_all_partial_fail.rs @@ -6,31 +6,31 @@ use rstest::*; use std::{process::Command, thread::sleep, time::Duration}; /* This test needs to be the only test in this file since it - * kills all running sandboxes, which would interfere with other + * kills all running layers, which would interfere with other * tests that were running in parallel. */ #[rstest] #[ignore = "Problematic on dev machines with running layers"] fn test_stop_all_partial_fail() -> Result<()> { - let mut bad_sandbox = sandbox(); - bad_sandbox.run(&["true"])?; - bad_sandbox.run(&["config", "sandbox_dir"])?; - let sandbox_dir = String::from(bad_sandbox.last_stdout.trim()); - let lock_file = format!("{}.lock", sandbox_dir); + let mut bad_layer = layer(); + bad_layer.run(&["true"])?; + bad_layer.run(&["config", "layer_dir"])?; + let layer_dir = String::from(bad_layer.last_stdout.trim()); + let lock_file = format!("{}.lock", layer_dir); println!("lock_file: {}", lock_file); Command::new("sudo") .args(["rm", "-f", lock_file.as_str()]) .output()?; std::fs::create_dir_all(&lock_file)?; // lock file is now a directory, should fail - assert!(bad_sandbox.xfail(&["true"])); - assert!(bad_sandbox.all_stderr.contains("Failed to open lock")); + assert!(bad_layer.xfail(&["true"])); + assert!(bad_layer.all_stderr.contains("Failed to open lock")); /* Despite bad state that the above "devlayer" is in, the following is expected to work. */ - let mut sandbox1 = sandbox(); - let mut sandbox2 = sandbox(); - let mut c1 = sandbox1.run_in_background(&["sleep", "9897135"])?; - let mut c2 = sandbox2.run_in_background(&["sleep", "9897135"])?; + let mut layer1 = layer(); + let mut layer2 = layer(); + let mut c1 = layer1.run_in_background(&["sleep", "9897135"])?; + let mut c2 = layer2.run_in_background(&["sleep", "9897135"])?; // ensure they start up for _ in 0..100 { @@ -59,7 +59,7 @@ fn test_stop_all_partial_fail() -> Result<()> { .collect(); assert!(lines.len() == 2); - assert!(sandbox1.pass(&["stop", "--all"])); + assert!(layer1.pass(&["stop", "--all"])); c1.wait()?; let ps = Command::new("ps").arg("aux").output()?; @@ -72,12 +72,12 @@ fn test_stop_all_partial_fail() -> Result<()> { .collect(); assert!(lines.is_empty()); - c2.wait()?; // if this doesn't hang, then the sandbox was killed! + c2.wait()?; // if this doesn't hang, then the layer was killed! - /* Restore the bad sandbox to a working state so our cleanup works. */ + /* Restore the bad layer to a working state so our cleanup works. */ // remove directory std::fs::remove_dir(&lock_file)?; // lock file is now a file, should succeed - assert!(bad_sandbox.pass(&["true"])); + assert!(bad_layer.pass(&["true"])); Ok(()) } diff --git a/tests/isolated_test_stop_pattern.rs b/tests/isolated_test_stop_pattern.rs index a0696df..edf4f5a 100644 --- a/tests/isolated_test_stop_pattern.rs +++ b/tests/isolated_test_stop_pattern.rs @@ -6,15 +6,15 @@ use rstest::*; use std::{process::Command, thread::sleep, time::Duration}; /* This test needs to be the only test in this file since it - * kills all running sandboxes, which would interfere with other + * kills all running layers, which would interfere with other * tests that were running in parallel. */ #[rstest] fn test_stop_pattern() -> Result<()> { - let mut sandbox1 = sandbox(); - let mut sandbox2 = sandbox(); - let mut c1 = sandbox1.run_in_background(&["sleep", "9897135"])?; - let mut c2 = sandbox2.run_in_background(&["sleep", "9897135"])?; + let mut layer1 = layer(); + let mut layer2 = layer(); + let mut c1 = layer1.run_in_background(&["sleep", "9897135"])?; + let mut c2 = layer2.run_in_background(&["sleep", "9897135"])?; // ensure they start up for _ in 0..1000 { @@ -43,7 +43,7 @@ fn test_stop_pattern() -> Result<()> { .collect(); assert!(lines.len() == 2); - assert!(sandbox1.pass(&["stop", sandbox2.name.as_str()])); + assert!(layer1.pass(&["stop", layer2.name.as_str()])); c2.wait()?; let ps = Command::new("ps").arg("aux").output()?; @@ -56,8 +56,8 @@ fn test_stop_pattern() -> Result<()> { .collect(); assert!(lines.len() == 1); - sandbox1.run(&["stop"])?; + layer1.run(&["stop"])?; - c1.wait()?; // if this doesn't hang, then the sandbox was killed! + c1.wait()?; // if this doesn't hang, then the layer was killed! Ok(()) } diff --git a/tests/isolated_test_stop_stops_children.rs b/tests/isolated_test_stop_stops_children.rs index 407ff4d..12be982 100644 --- a/tests/isolated_test_stop_stops_children.rs +++ b/tests/isolated_test_stop_stops_children.rs @@ -8,9 +8,9 @@ use std::thread::sleep; use std::time::Duration; #[rstest] -fn test_stop_stop_children(mut sandbox: SandboxManager) -> Result<()> { - let mut c1 = sandbox.run_in_background(&["sleep", "9897135"])?; - let mut c2 = sandbox.run_in_background(&["sleep", "9897135"])?; +fn test_stop_stop_children(mut layer: LayerManager) -> Result<()> { + let mut c1 = layer.run_in_background(&["sleep", "9897135"])?; + let mut c2 = layer.run_in_background(&["sleep", "9897135"])?; // ensure they start up for _ in 0..1000 { @@ -40,7 +40,7 @@ fn test_stop_stop_children(mut sandbox: SandboxManager) -> Result<()> { assert!(lines.len() == 2); // kill them - assert!(sandbox.pass(&["stop"])); + assert!(layer.pass(&["stop"])); // wait for that to happen c1.wait()?; diff --git a/tests/isolated_test_sync.rs b/tests/isolated_test_sync.rs index 84869d1..f3ce559 100644 --- a/tests/isolated_test_sync.rs +++ b/tests/isolated_test_sync.rs @@ -6,16 +6,16 @@ use rstest::*; use std::path::PathBuf; #[rstest] -fn test_sync(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run(&["true"])?; - sandbox.run(&["config", "upper_cwd"])?; - let base = sandbox.last_stdout.trim(); +fn test_sync(mut layer: LayerManager) -> Result<()> { + layer.run(&["true"])?; + layer.run(&["config", "upper_cwd"])?; + let base = layer.last_stdout.trim(); let upper_dir = PathBuf::from(base); - let t = sandbox.test_filename("test-file"); + let t = layer.test_filename("test-file"); std::fs::write(&t, "hello")?; - sandbox.run(&[ + layer.run(&[ "bash", "-c", format!("echo -n 'from layer echo' > {}", t.as_str()).as_str(), @@ -23,8 +23,8 @@ fn test_sync(mut sandbox: SandboxManager) -> Result<()> { std::fs::write(&t, "goodbye")?; - sandbox.run(&["cat", t.clone().as_str()])?; - let stdout = sandbox.last_stdout.trim(); + layer.run(&["cat", t.clone().as_str()])?; + let stdout = layer.last_stdout.trim(); assert_eq!(stdout, "from layer echo"); // remove the file from the upper directory @@ -35,12 +35,12 @@ fn test_sync(mut sandbox: SandboxManager) -> Result<()> { ))?; assert!(PathBuf::from(&t).exists()); - sandbox.run(&["sync"])?; + layer.run(&["sync"])?; - // after a sync, programs run in the sandbox should see the changes. Before, the results are + // after a sync, programs run in the layer should see the changes. Before, the results are // undefined. - sandbox.run(&["cat", t.clone().as_str()])?; - let stdout = sandbox.last_stdout.trim(); + layer.run(&["cat", t.clone().as_str()])?; + let stdout = layer.last_stdout.trim(); assert_eq!(stdout, "goodbye"); Ok(()) diff --git a/tests/isolated_test_twisted.rs b/tests/isolated_test_twisted.rs index 97f77a1..df71f43 100644 --- a/tests/isolated_test_twisted.rs +++ b/tests/isolated_test_twisted.rs @@ -9,42 +9,41 @@ use std::{ }; #[rstest] -fn test_twisted(mut sandbox: SandboxManager) -> Result<()> { - let path = PathBuf::from(&sandbox.test_filename_no_rid("source")); +fn test_twisted(mut layer: LayerManager) -> Result<()> { + let path = PathBuf::from(&layer.test_filename_no_rid("source")); create_dir_all(format!("{}/a/b/c", path.display()))?; write(format!("{}/a/b/c/file_c", path.display()), "file_c")?; write(format!("{}/a/b/file_b", path.display()), "file_b")?; - sandbox.run(&[ + layer.run(&[ "mkdir", "-p", format!("{}/a/b/c/d", path.display()).as_str(), ])?; - sandbox.run(&[ + layer.run(&[ "mv", format!("{}/a/b/c/d", path.display()).as_str(), format!("{}/d", path.display()).as_str(), ])?; - sandbox.run(&[ + layer.run(&[ "mv", format!("{}/a", path.display()).as_str(), format!("{}/d/a", path.display()).as_str(), ])?; - sandbox.run(&[ + layer.run(&[ "cp", format!("{}/d/a/b/c/file_c", path.display()).as_str(), format!("{}/d/file_c_v2", path.display()).as_str(), ])?; - sandbox.run(&[ + layer.run(&[ "cp", format!("{}/d/a/b/file_b", path.display()).as_str(), format!("{}/d/a/b/c/file_c", path.display()).as_str(), ])?; - sandbox - .run(&["rm", format!("{}/d/a/b/file_b", path.display()).as_str()])?; + layer.run(&["rm", format!("{}/d/a/b/file_b", path.display()).as_str()])?; - sandbox.run(&["accept"])?; + layer.run(&["accept"])?; assert!( std::fs::read_to_string(format!("{}/d/file_c_v2", path.display()))? @@ -64,43 +63,42 @@ fn test_twisted(mut sandbox: SandboxManager) -> Result<()> { #[rstest] fn test_twisted_fail_rmdir_on_separate_device( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - let path = PathBuf::from(&sandbox.test_filename_no_rid("source")); + let path = PathBuf::from(&layer.test_filename_no_rid("source")); create_dir_all(format!("{}/a/b/c", path.display()))?; write(format!("{}/a/b/c/file_c", path.display()), "file_c")?; write(format!("{}/a/b/file_b", path.display()), "file_b")?; - sandbox.run(&[ + layer.run(&[ "mkdir", "-p", format!("{}/a/b/c/d", path.display()).as_str(), ])?; - sandbox.run(&[ + layer.run(&[ "mv", format!("{}/a/b/c/d", path.display()).as_str(), format!("{}/d", path.display()).as_str(), ])?; - sandbox.run(&[ + layer.run(&[ "mv", format!("{}/a", path.display()).as_str(), format!("{}/d/a", path.display()).as_str(), ])?; - sandbox.run(&[ + layer.run(&[ "cp", format!("{}/d/a/b/c/file_c", path.display()).as_str(), format!("{}/d/file_c_v2", path.display()).as_str(), ])?; - sandbox.run(&[ + layer.run(&[ "cp", format!("{}/d/a/b/file_b", path.display()).as_str(), format!("{}/d/a/b/c/file_c", path.display()).as_str(), ])?; - sandbox - .run(&["rm", format!("{}/d/a/b/file_b", path.display()).as_str()])?; + layer.run(&["rm", format!("{}/d/a/b/file_b", path.display()).as_str()])?; - assert!(sandbox.exfail( + assert!(layer.exfail( &["accept"], "TEST_ACCEPT_FAIL_RMDIR_ON_DIFFERENT_DEVICE", "1" diff --git a/tests/test_accept.rs b/tests/test_accept.rs index c071ab6..b41982b 100644 --- a/tests/test_accept.rs +++ b/tests/test_accept.rs @@ -8,28 +8,28 @@ use std::os::unix::fs::MetadataExt; use std::{fs::create_dir, path::Path}; #[rstest] -fn test_accept_file(mut sandbox: SandboxManager) -> Result<()> { - let filename = sandbox.test_filename("file"); +fn test_accept_file(mut layer: LayerManager) -> Result<()> { + let filename = layer.test_filename("file"); let path = Path::new(&filename); - sandbox.run(&["touch", &filename])?; + layer.run(&["touch", &filename])?; assert!(!path.exists()); - sandbox.run(&["accept", &filename])?; - assert!(sandbox.last_stdout.contains("1 changes accepted")); + layer.run(&["accept", &filename])?; + assert!(layer.last_stdout.contains("1 changes accepted")); assert!(path.exists()); std::fs::remove_file(path)?; assert!(!path.exists()); - sandbox.run(&["accept", &filename])?; + layer.run(&["accept", &filename])?; assert!(!path.exists()); Ok(()) } #[rstest] -fn test_accept_directory(mut sandbox: SandboxManager) -> Result<()> { - let dirname = sandbox.test_filename("dir"); +fn test_accept_directory(mut layer: LayerManager) -> Result<()> { + let dirname = layer.test_filename("dir"); let path = Path::new(&dirname); - sandbox.run(&["mkdir", &dirname])?; + layer.run(&["mkdir", &dirname])?; assert!(!path.exists()); - sandbox.run(&["accept", &dirname])?; + layer.run(&["accept", &dirname])?; assert!(path.exists()); std::fs::remove_dir(path)?; assert!(!path.exists()); @@ -37,11 +37,11 @@ fn test_accept_directory(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_accept_symlink(mut sandbox: SandboxManager) -> Result<()> { - let dirname = sandbox.test_filename("test-dir"); - let symlink = sandbox.test_filename("test-symlink"); - sandbox.run(&["mkdir", &dirname])?; - sandbox.run(&[ +fn test_accept_symlink(mut layer: LayerManager) -> Result<()> { + let dirname = layer.test_filename("test-dir"); + let symlink = layer.test_filename("test-symlink"); + layer.run(&["mkdir", &dirname])?; + layer.run(&[ "ln", "-s", Path::new(&dirname).file_name().unwrap().to_str().unwrap(), @@ -49,7 +49,7 @@ fn test_accept_symlink(mut sandbox: SandboxManager) -> Result<()> { ])?; assert!(!Path::new(&dirname).exists()); assert!(!Path::new(&symlink).exists()); - sandbox.run(&["accept", "**/test-*"])?; + layer.run(&["accept", "**/test-*"])?; assert!(Path::new(&dirname).exists()); assert!(Path::new(&symlink).exists()); std::fs::remove_dir(Path::new(&dirname))?; @@ -58,9 +58,9 @@ fn test_accept_symlink(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_accept_rename_file(mut sandbox: SandboxManager) -> Result<()> { - let filename = sandbox.test_filename("test-file"); - let new_filename = sandbox.test_filename("test-file-new"); +fn test_accept_rename_file(mut layer: LayerManager) -> Result<()> { + let filename = layer.test_filename("test-file"); + let new_filename = layer.test_filename("test-file-new"); let path = Path::new(&filename); let new_path = Path::new(&new_filename); assert!(!path.exists()); @@ -68,10 +68,10 @@ fn test_accept_rename_file(mut sandbox: SandboxManager) -> Result<()> { std::fs::write(path, "test")?; assert!(path.exists()); assert!(!new_path.exists()); - sandbox.run(&["mv", &filename, &new_filename])?; + layer.run(&["mv", &filename, &new_filename])?; assert!(path.exists()); assert!(!new_path.exists()); - sandbox.run(&["accept"])?; + layer.run(&["accept"])?; assert!(!path.exists()); assert!(new_path.exists()); Ok(()) @@ -79,13 +79,13 @@ fn test_accept_rename_file(mut sandbox: SandboxManager) -> Result<()> { #[rstest] fn test_accept_check_ownership_and_permissions( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - let filename = sandbox.test_filename("test-file"); - sandbox.run(&["touch", &filename])?; + let filename = layer.test_filename("test-file"); + layer.run(&["touch", &filename])?; assert!(!Path::new(&filename).exists()); - sandbox.run(&["chmod", "664", &filename])?; - sandbox.run(&["accept", &filename])?; + layer.run(&["chmod", "664", &filename])?; + layer.run(&["accept", &filename])?; assert!(Path::new(&filename).exists()); let metadata = std::fs::metadata(Path::new(&filename))?; assert_eq!(metadata.uid(), unsafe { getuid() }); @@ -95,40 +95,36 @@ fn test_accept_check_ownership_and_permissions( } #[rstest] -fn test_accept_rename_upper_directory( - mut sandbox: SandboxManager, -) -> Result<()> { - let dirname = sandbox.test_filename("test-dir"); - let new_dirname = sandbox.test_filename("test-dir-new"); +fn test_accept_rename_upper_directory(mut layer: LayerManager) -> Result<()> { + let dirname = layer.test_filename("test-dir"); + let new_dirname = layer.test_filename("test-dir-new"); let path = Path::new(&dirname); let new_path = Path::new(&new_dirname); assert!(!path.exists()); assert!(!new_path.exists()); - sandbox.run(&["mkdir", &dirname])?; + layer.run(&["mkdir", &dirname])?; assert!(!path.exists()); assert!(!new_path.exists()); - sandbox.run(&["mv", &dirname, &new_dirname])?; - sandbox.run(&["accept"])?; + layer.run(&["mv", &dirname, &new_dirname])?; + layer.run(&["accept"])?; assert!(!path.exists()); assert!(new_path.exists()); Ok(()) } #[rstest] -fn test_accept_rename_lower_directory( - mut sandbox: SandboxManager, -) -> Result<()> { - let dirname = sandbox.test_filename("test-dir"); - let new_dirname = sandbox.test_filename("test-dir-new"); +fn test_accept_rename_lower_directory(mut layer: LayerManager) -> Result<()> { + let dirname = layer.test_filename("test-dir"); + let new_dirname = layer.test_filename("test-dir-new"); let path = Path::new(&dirname); let new_path = Path::new(&new_dirname); std::fs::create_dir(path)?; assert!(path.exists()); assert!(!new_path.exists()); - sandbox.run(&["mv", &dirname, &new_dirname])?; + layer.run(&["mv", &dirname, &new_dirname])?; assert!(path.exists()); assert!(!new_path.exists()); - sandbox.run(&["accept"])?; + layer.run(&["accept"])?; assert!(!path.exists()); assert!(new_path.exists()); Ok(()) @@ -136,20 +132,20 @@ fn test_accept_rename_lower_directory( #[rstest] fn test_accept_rename_lower_directory_with_stuff( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - let dirname = sandbox.test_filename("test-dir"); - let new_dirname = sandbox.test_filename("test-dir-new"); + let dirname = layer.test_filename("test-dir"); + let new_dirname = layer.test_filename("test-dir-new"); let path = Path::new(&dirname); let new_path = Path::new(&new_dirname); std::fs::create_dir(path)?; std::fs::write(path.join("test-file"), "test")?; assert!(path.exists()); assert!(!new_path.exists()); - sandbox.run(&["mv", &dirname, &new_dirname])?; + layer.run(&["mv", &dirname, &new_dirname])?; assert!(path.exists()); assert!(!new_path.exists()); - sandbox.run(&["accept"])?; + layer.run(&["accept"])?; assert!(!path.exists()); assert!(new_path.exists()); assert!(new_path.join("test-file").exists()); @@ -157,12 +153,12 @@ fn test_accept_rename_lower_directory_with_stuff( } #[rstest] -fn test_accept_rename_symlink(mut sandbox: SandboxManager) -> Result<()> { - let filename = sandbox.test_filename("test-file"); - let lower_symlink = sandbox.test_filename("test-symlink-lower"); - let new_lower_symlink = sandbox.test_filename("test-symlink-lower-new"); - let upper_symlink = sandbox.test_filename("test-symlink-upper"); - let new_upper_symlink = sandbox.test_filename("test-symlink-upper-new"); +fn test_accept_rename_symlink(mut layer: LayerManager) -> Result<()> { + let filename = layer.test_filename("test-file"); + let lower_symlink = layer.test_filename("test-symlink-lower"); + let new_lower_symlink = layer.test_filename("test-symlink-lower-new"); + let upper_symlink = layer.test_filename("test-symlink-upper"); + let new_upper_symlink = layer.test_filename("test-symlink-upper-new"); let filename_path = Path::new(&filename); let lower_symlink_path = Path::new(&lower_symlink); @@ -181,7 +177,7 @@ fn test_accept_rename_symlink(mut sandbox: SandboxManager) -> Result<()> { assert!(!upper_symlink_path.exists()); assert!(!new_upper_symlink_path.exists()); - sandbox.run(&[ + layer.run(&[ "ln", "-s", filename_path.file_name().unwrap().to_str().unwrap(), @@ -193,10 +189,10 @@ fn test_accept_rename_symlink(mut sandbox: SandboxManager) -> Result<()> { assert!(!upper_symlink_path.exists()); assert!(!new_upper_symlink_path.exists()); - sandbox.run(&["mv", &upper_symlink, &new_upper_symlink])?; - sandbox.run(&["mv", &lower_symlink, &new_lower_symlink])?; + layer.run(&["mv", &upper_symlink, &new_upper_symlink])?; + layer.run(&["mv", &lower_symlink, &new_lower_symlink])?; - sandbox.run(&["accept"])?; + layer.run(&["accept"])?; assert!(filename_path.exists()); assert!(!lower_symlink_path.exists()); assert!(new_lower_symlink_path.exists()); @@ -213,35 +209,35 @@ fn test_accept_rename_symlink(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_accept_remove_file(mut sandbox: SandboxManager) -> Result<()> { - let filename = sandbox.test_filename("test-file"); +fn test_accept_remove_file(mut layer: LayerManager) -> Result<()> { + let filename = layer.test_filename("test-file"); let path = Path::new(&filename); std::fs::write(path, "test")?; assert!(path.exists()); - sandbox.run(&["rm", &filename])?; + layer.run(&["rm", &filename])?; assert!(path.exists()); - sandbox.run(&["accept"])?; + layer.run(&["accept"])?; assert!(!path.exists()); Ok(()) } #[rstest] -fn test_accept_remove_directory(mut sandbox: SandboxManager) -> Result<()> { - let dirname = sandbox.test_filename("test-dir"); +fn test_accept_remove_directory(mut layer: LayerManager) -> Result<()> { + let dirname = layer.test_filename("test-dir"); let path = Path::new(&dirname); std::fs::create_dir(path)?; assert!(path.exists()); - sandbox.run(&["rmdir", &dirname])?; + layer.run(&["rmdir", &dirname])?; assert!(path.exists()); - sandbox.run(&["accept"])?; + layer.run(&["accept"])?; assert!(!path.exists()); Ok(()) } #[rstest] -fn test_accept_remove_symlink(mut sandbox: SandboxManager) -> Result<()> { - let filename = sandbox.test_filename("test-file"); - let symlink = sandbox.test_filename("test-symlink"); +fn test_accept_remove_symlink(mut layer: LayerManager) -> Result<()> { + let filename = layer.test_filename("test-file"); + let symlink = layer.test_filename("test-symlink"); let path = Path::new(&symlink); std::fs::write(Path::new(&filename), "test")?; std::os::unix::fs::symlink( @@ -249,9 +245,9 @@ fn test_accept_remove_symlink(mut sandbox: SandboxManager) -> Result<()> { path, )?; assert!(path.exists()); - sandbox.run(&["rm", &symlink])?; + layer.run(&["rm", &symlink])?; assert!(path.exists()); - sandbox.run(&["accept"])?; + layer.run(&["accept"])?; assert!(Path::new(&filename).exists()); assert!(!path.exists()); Ok(()) @@ -261,10 +257,10 @@ fn test_accept_remove_symlink(mut sandbox: SandboxManager) -> Result<()> { * have been moved/removed in the upper, and then a new directory created * in the same place. */ #[rstest] -fn test_accept_opaque_directory(mut sandbox: SandboxManager) -> Result<()> { - let dirname = sandbox.test_filename("test-dir"); +fn test_accept_opaque_directory(mut layer: LayerManager) -> Result<()> { + let dirname = layer.test_filename("test-dir"); let dirname_path = Path::new(&dirname); - let dir_renamed = sandbox.test_filename("renamed-dir"); + let dir_renamed = layer.test_filename("renamed-dir"); let dir_renamed_path = Path::new(&dir_renamed); let masked_file = dirname_path.join("somefile"); let post_moved_masked_file = dir_renamed_path.join("somefile"); @@ -275,12 +271,12 @@ fn test_accept_opaque_directory(mut sandbox: SandboxManager) -> Result<()> { std::fs::write(&masked_file, "test")?; assert!(masked_file.exists()); - sandbox.run(&["mv", &dirname, &dir_renamed])?; + layer.run(&["mv", &dirname, &dir_renamed])?; assert!(dirname_path.exists()); assert!(!dir_renamed_path.exists()); - sandbox.run(&["mkdir", &dirname])?; - sandbox.run(&["touch", new_file.to_str().unwrap()])?; + layer.run(&["mkdir", &dirname])?; + layer.run(&["touch", new_file.to_str().unwrap()])?; assert!(dirname_path.exists()); assert!(!dir_renamed_path.exists()); @@ -288,7 +284,7 @@ fn test_accept_opaque_directory(mut sandbox: SandboxManager) -> Result<()> { assert!(!new_file.exists()); assert!(!post_moved_masked_file.exists()); - sandbox.run(&["accept"])?; + layer.run(&["accept"])?; assert!(dirname_path.exists()); assert!(dir_renamed_path.exists()); assert!(!masked_file.exists()); @@ -302,10 +298,8 @@ fn test_accept_opaque_directory(mut sandbox: SandboxManager) -> Result<()> { * have been moved/removed in the upper, and then a new directory created * in the same place. */ #[rstest] -fn test_accept_removed_opaque_directory( - mut sandbox: SandboxManager, -) -> Result<()> { - let dirname = sandbox.test_filename("test-dir"); +fn test_accept_removed_opaque_directory(mut layer: LayerManager) -> Result<()> { + let dirname = layer.test_filename("test-dir"); let dirname_path = Path::new(&dirname); let old_file = dirname_path.join("oldfile"); let new_file = dirname_path.join("newfile"); @@ -315,18 +309,18 @@ fn test_accept_removed_opaque_directory( std::fs::write(&old_file, "test")?; assert!(old_file.exists()); - sandbox.run(&["rm", "-Rf", &dirname])?; + layer.run(&["rm", "-Rf", &dirname])?; assert!(dirname_path.exists()); assert!(old_file.exists()); - sandbox.run(&["mkdir", &dirname])?; - sandbox.run(&["touch", new_file.to_str().unwrap()])?; + layer.run(&["mkdir", &dirname])?; + layer.run(&["touch", new_file.to_str().unwrap()])?; assert!(dirname_path.exists()); assert!(old_file.exists()); assert!(!new_file.exists()); - sandbox.run(&["accept"])?; + layer.run(&["accept"])?; assert!(dirname_path.exists()); assert!(!old_file.exists()); assert!(new_file.exists()); @@ -335,12 +329,12 @@ fn test_accept_removed_opaque_directory( } #[rstest] -fn test_accept_negated_pattern(mut sandbox: SandboxManager) -> Result<()> { - let filename = sandbox.test_filename("test-file"); - let filename2 = sandbox.test_filename("test-file2"); - sandbox.run(&["touch", &filename])?; - sandbox.run(&["touch", &filename2])?; - sandbox.run(&["accept", "!**/test-file2*"])?; +fn test_accept_negated_pattern(mut layer: LayerManager) -> Result<()> { + let filename = layer.test_filename("test-file"); + let filename2 = layer.test_filename("test-file2"); + layer.run(&["touch", &filename])?; + layer.run(&["touch", &filename2])?; + layer.run(&["accept", "!**/test-file2*"])?; assert!(Path::new(&filename).exists()); assert!(!Path::new(&filename2).exists()); Ok(()) @@ -348,39 +342,39 @@ fn test_accept_negated_pattern(mut sandbox: SandboxManager) -> Result<()> { #[rstest] fn test_accept_file_ignore_invalid_upper_dirs( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - sandbox.run(&["config", "sandbox_dir"])?; - let base = sandbox.last_stdout.trim(); + layer.run(&["config", "layer_dir"])?; + let base = layer.last_stdout.trim(); let upper_dir = Path::new(base).join("upper"); let invalid_base32_dir = Path::new(&upper_dir).join("invalid"); let invalid_utf8_dir = Path::new(&upper_dir).join("777Q"); std::fs::create_dir_all(&invalid_base32_dir)?; std::fs::create_dir_all(&invalid_utf8_dir)?; - let filename = sandbox.test_filename("file"); + let filename = layer.test_filename("file"); let path = Path::new(&filename); - sandbox.run(&["touch", &filename])?; + layer.run(&["touch", &filename])?; assert!(!path.exists()); - sandbox.run(&["accept", &filename])?; + layer.run(&["accept", &filename])?; assert!(path.exists()); std::fs::remove_file(path)?; assert!(!path.exists()); - sandbox.run(&["accept", &filename])?; + layer.run(&["accept", &filename])?; assert!(!path.exists()); Ok(()) } #[rstest] -fn test_file_overwrite(mut sandbox: SandboxManager) -> Result<()> { - let filename = sandbox.test_filename("file"); +fn test_file_overwrite(mut layer: LayerManager) -> Result<()> { + let filename = layer.test_filename("file"); let path = Path::new(&filename); std::fs::write(&filename, "test")?; - sandbox.run(&["rm", &filename])?; + layer.run(&["rm", &filename])?; assert!(path.exists()); - sandbox.run(&["touch", &filename])?; + layer.run(&["touch", &filename])?; assert!(path.exists()); - sandbox.run(&["accept", &filename])?; + layer.run(&["accept", &filename])?; assert!(path.exists()); let contents = std::fs::read(path)?; assert_eq!(contents, b""); @@ -388,16 +382,16 @@ fn test_file_overwrite(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_chmod_file(mut sandbox: SandboxManager) -> Result<()> { - let filename = sandbox.test_filename("file"); +fn test_chmod_file(mut layer: LayerManager) -> Result<()> { + let filename = layer.test_filename("file"); let path = Path::new(&filename); std::fs::write(&filename, "test")?; let orig_metadata = std::fs::metadata(path)?; - sandbox.run(&["chmod", "660", &filename])?; + layer.run(&["chmod", "660", &filename])?; assert!(path.exists()); let metadata = std::fs::metadata(path)?; assert_eq!(metadata.permissions(), orig_metadata.permissions()); - sandbox.run(&["accept", &filename])?; + layer.run(&["accept", &filename])?; assert!(path.exists()); let metadata = std::fs::metadata(path)?; assert_ne!(metadata.mode() & 0o777, orig_metadata.mode() & 0o777); @@ -405,16 +399,16 @@ fn test_chmod_file(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_chmod_directory(mut sandbox: SandboxManager) -> Result<()> { - let dirname = sandbox.test_filename("dir"); +fn test_chmod_directory(mut layer: LayerManager) -> Result<()> { + let dirname = layer.test_filename("dir"); let path = Path::new(&dirname); std::fs::create_dir(path)?; let orig_metadata = std::fs::metadata(path)?; - sandbox.run(&["chmod", "770", &dirname])?; + layer.run(&["chmod", "770", &dirname])?; assert!(path.exists()); let metadata = std::fs::metadata(path)?; assert_eq!(metadata.permissions(), orig_metadata.permissions()); - sandbox.run(&["accept", &dirname])?; + layer.run(&["accept", &dirname])?; assert!(path.exists()); let metadata = std::fs::metadata(path)?; println!(); @@ -423,8 +417,8 @@ fn test_chmod_directory(mut sandbox: SandboxManager) -> Result<()> { println!(); println!(); println!(); - println!("output: {}", sandbox.last_stdout); - println!("error: {}", sandbox.last_stderr); + println!("output: {}", layer.last_stdout); + println!("error: {}", layer.last_stderr); println!(); println!(); println!(); @@ -433,11 +427,11 @@ fn test_chmod_directory(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_accept_symlink_overwrites(mut sandbox: SandboxManager) -> Result<()> { - let dir = sandbox.test_filename("test-dir"); +fn test_accept_symlink_overwrites(mut layer: LayerManager) -> Result<()> { + let dir = layer.test_filename("test-dir"); let dir_file = Path::new(&dir).join("subfile"); - let file = sandbox.test_filename("test-file"); - let file2 = sandbox.test_filename("test-file2"); + let file = layer.test_filename("test-file"); + let file2 = layer.test_filename("test-file2"); std::fs::create_dir_all(&dir)?; std::fs::write(&dir_file, "subfile")?; std::fs::write(&file, "test")?; @@ -445,13 +439,13 @@ fn test_accept_symlink_overwrites(mut sandbox: SandboxManager) -> Result<()> { let file2_symlink_name = Path::new(&file2).file_name().unwrap().to_str().unwrap(); - sandbox.run(&["rm", dir_file.to_str().unwrap()])?; - sandbox.run(&["rmdir", &dir])?; - sandbox.run(&["rm", &file])?; - sandbox.run(&["ln", "-s", file2_symlink_name, &file])?; - sandbox.run(&["ln", "-s", file2_symlink_name, &dir])?; + layer.run(&["rm", dir_file.to_str().unwrap()])?; + layer.run(&["rmdir", &dir])?; + layer.run(&["rm", &file])?; + layer.run(&["ln", "-s", file2_symlink_name, &file])?; + layer.run(&["ln", "-s", file2_symlink_name, &dir])?; - assert!(sandbox.pass(&["accept"])); + assert!(layer.pass(&["accept"])); let file_contents = std::fs::read(&file)?; let dir_contents = std::fs::read(&dir)?; @@ -462,13 +456,13 @@ fn test_accept_symlink_overwrites(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_accept_directory_overwrite(mut sandbox: SandboxManager) -> Result<()> { - let p = sandbox.test_filename("test-file"); +fn test_accept_directory_overwrite(mut layer: LayerManager) -> Result<()> { + let p = layer.test_filename("test-file"); std::fs::write(&p, "test")?; - sandbox.run(&["rm", &p])?; - sandbox.run(&["mkdir", &p])?; - assert!(sandbox.pass(&["accept"])); + layer.run(&["rm", &p])?; + layer.run(&["mkdir", &p])?; + assert!(layer.pass(&["accept"])); let path = Path::new(&p); assert!(path.exists()); assert!(path.is_dir()); @@ -483,11 +477,11 @@ fn test_accept_directory_overwrite(mut sandbox: SandboxManager) -> Result<()> { #[allow(non_snake_case)] #[rstest] -fn test_accept_inside_out(mut sandbox: SandboxManager) -> Result<()> { - let A_str = sandbox.test_filename_no_rid("A"); - let B_str = sandbox.test_filename_no_rid("A/B"); - let post_A_str = sandbox.test_filename_no_rid("B/A"); - let post_B_str = sandbox.test_filename_no_rid("B"); +fn test_accept_inside_out(mut layer: LayerManager) -> Result<()> { + let A_str = layer.test_filename_no_rid("A"); + let B_str = layer.test_filename_no_rid("A/B"); + let post_A_str = layer.test_filename_no_rid("B/A"); + let post_B_str = layer.test_filename_no_rid("B"); let A = Path::new(&A_str); let A_file_pre = A.join("a_file_pre"); @@ -523,43 +517,43 @@ fn test_accept_inside_out(mut sandbox: SandboxManager) -> Result<()> { std::fs::write(&B_file_del_post, "B_file_del_post")?; // modify before - sandbox.run(&[ + layer.run(&[ "bash", "-c", format!("echo -n 'modified_A_pre' > {}", A_file_pre.display()).as_str(), ])?; - sandbox.run(&[ + layer.run(&[ "bash", "-c", format!("echo -n 'modified_B_pre' > {}", B_file_pre.display()).as_str(), ])?; // remove before - sandbox.run(&["rm", A_file_del_pre.to_str().unwrap()])?; - sandbox.run(&["rm", B_file_del_pre.to_str().unwrap()])?; + layer.run(&["rm", A_file_del_pre.to_str().unwrap()])?; + layer.run(&["rm", B_file_del_pre.to_str().unwrap()])?; // move A/B -> B/A - sandbox.run(&["mv", B.to_str().unwrap(), post_B.to_str().unwrap()])?; - sandbox.run(&["mv", A.to_str().unwrap(), post_A.to_str().unwrap()])?; + layer.run(&["mv", B.to_str().unwrap(), post_B.to_str().unwrap()])?; + layer.run(&["mv", A.to_str().unwrap(), post_A.to_str().unwrap()])?; // modify after - sandbox.run(&[ + layer.run(&[ "bash", "-c", format!("echo -n 'modified_A_post' > {}", post_A_file_post.display()) .as_str(), ])?; - sandbox.run(&[ + layer.run(&[ "bash", "-c", format!("echo -n 'modified_B_post' > {}", post_B_file_post.display()) .as_str(), ])?; // remove after - sandbox.run(&["rm", post_A_file_del_post.to_str().unwrap()])?; - sandbox.run(&["rm", post_B_file_del_post.to_str().unwrap()])?; + layer.run(&["rm", post_A_file_del_post.to_str().unwrap()])?; + layer.run(&["rm", post_B_file_del_post.to_str().unwrap()])?; // Accept the changes and verify the contents - assert!(sandbox.pass(&["accept"])); + assert!(layer.pass(&["accept"])); assert!(post_A.exists()); assert!(post_B.exists()); assert!(post_A_file_pre.exists()); @@ -598,9 +592,9 @@ fn test_accept_inside_out(mut sandbox: SandboxManager) -> Result<()> { #[allow(non_snake_case)] #[rstest] -fn test_accept_opaque(mut sandbox: SandboxManager) -> Result<()> { - let A_str = sandbox.test_filename_no_rid("A"); - let C_str = sandbox.test_filename_no_rid("C"); +fn test_accept_opaque(mut layer: LayerManager) -> Result<()> { + let A_str = layer.test_filename_no_rid("A"); + let C_str = layer.test_filename_no_rid("C"); let A = Path::new(&A_str); let A_B = A.join("B"); @@ -613,10 +607,10 @@ fn test_accept_opaque(mut sandbox: SandboxManager) -> Result<()> { std::fs::write(&A_B_file, "A_B_file")?; std::fs::write(&A_B_file_removed, "A_B_file_removed")?; - sandbox.run(&["mv", A.to_str().unwrap(), C.to_str().unwrap()])?; - sandbox.run(&["rm", "-Rf", C_B.to_str().unwrap()])?; - sandbox.run(&["mkdir", C_B.to_str().unwrap()])?; - sandbox.run(&[ + layer.run(&["mv", A.to_str().unwrap(), C.to_str().unwrap()])?; + layer.run(&["rm", "-Rf", C_B.to_str().unwrap()])?; + layer.run(&["mkdir", C_B.to_str().unwrap()])?; + layer.run(&[ "bash", "-c", format!( @@ -625,7 +619,7 @@ fn test_accept_opaque(mut sandbox: SandboxManager) -> Result<()> { ) .as_str(), ])?; - sandbox.run(&[ + layer.run(&[ "bash", "-c", format!( @@ -635,7 +629,7 @@ fn test_accept_opaque(mut sandbox: SandboxManager) -> Result<()> { .as_str(), ])?; - assert!(sandbox.pass(&["accept"])); + assert!(layer.pass(&["accept"])); assert!(!A_B.exists()); assert!(C.exists()); diff --git a/tests/test_accept_deep_reshuffle.rs b/tests/test_accept_deep_reshuffle.rs index 710873b..552a94e 100644 --- a/tests/test_accept_deep_reshuffle.rs +++ b/tests/test_accept_deep_reshuffle.rs @@ -20,10 +20,10 @@ fn entry(base: &Path, name: &str) -> Result { } /* This test creates a deep directory structure on the host system, - * then sorts the directory structure in the sandbox */ + * then sorts the directory structure in the layer */ #[rstest] -fn test_accept_deep_reshuffle(mut sandbox: SandboxManager) -> Result<()> { - let mut path = PathBuf::from(&sandbox.test_filename_no_rid("source")); +fn test_accept_deep_reshuffle(mut layer: LayerManager) -> Result<()> { + let mut path = PathBuf::from(&layer.test_filename_no_rid("source")); let base = path.clone(); let disorder = ["3", "1", "5", "2", "8", "4", "9", "7", "6", "0"]; @@ -31,25 +31,25 @@ fn test_accept_deep_reshuffle(mut sandbox: SandboxManager) -> Result<()> { path = entry(&path, name)?; } - /* Sorts the directory structure in the sandbox so we end up with */ + /* Sorts the directory structure in the layer so we end up with */ /* 0/1/2/3/4/5/6/7/8/9 */ let mut to_path = base.clone(); for i in 0..10 { - sandbox.run(&[ + layer.run(&[ "bash", "-c", format!("find {} | grep '{}$'", base.display(), i).as_str(), ])?; - let from_path = sandbox.last_stdout.trim().to_string(); + let from_path = layer.last_stdout.trim().to_string(); to_path = to_path.join(format!("{}", i)); let to_path_str = to_path.display().to_string(); - sandbox.run(&["mv", &from_path, &to_path_str])?; + layer.run(&["mv", &from_path, &to_path_str])?; } - //sandbox.run(&["status"])?; - sandbox.run(&["accept"])?; + //layer.run(&["status"])?; + layer.run(&["accept"])?; - //let output = sandbox.run(&["ls", "-R", base.display().as_str()])?; + //let output = layer.run(&["ls", "-R", base.display().as_str()])?; //println!("{}", output.stdout); /* Verify the contents of the directory structure and files */ diff --git a/tests/test_bind_and_mask.rs b/tests/test_bind_and_mask.rs index da5531e..c69a9df 100644 --- a/tests/test_bind_and_mask.rs +++ b/tests/test_bind_and_mask.rs @@ -5,57 +5,50 @@ use fixtures::*; use rstest::*; #[rstest] -fn test_mask_no_mask(mut sandbox: SandboxManager) -> Result<()> { - let test_dir = sandbox.test_filename("not_masked"); +fn test_mask_no_mask(mut layer: LayerManager) -> Result<()> { + let test_dir = layer.test_filename("not_masked"); std::fs::create_dir(&test_dir)?; let test_file = format!("{}/should-not-be-masked", test_dir); std::fs::write(&test_file, "test")?; - sandbox.run(&["ls", "-l", &test_dir])?; - println!("{}", sandbox.last_stdout); - assert!(sandbox.last_stdout.contains("should-not-be-masked")); + layer.run(&["ls", "-l", &test_dir])?; + println!("{}", layer.last_stdout); + assert!(layer.last_stdout.contains("should-not-be-masked")); Ok(()) } #[rstest] -fn test_mask_mask_cli(mut sandbox: SandboxManager) -> Result<()> { - let test_dir = sandbox.test_filename("mask_from_env"); +fn test_mask_mask_cli(mut layer: LayerManager) -> Result<()> { + let test_dir = layer.test_filename("mask_from_env"); std::fs::create_dir(&test_dir)?; let test_file = format!("{}/should-be-masked", test_dir); std::fs::write(&test_file, "test")?; - sandbox.run(&["--mask", &test_dir, "ls", "-l", &test_dir])?; - println!("{}", sandbox.last_stdout); - assert!(!sandbox.last_stdout.contains("should-be-masked")); + layer.run(&["--mask", &test_dir, "ls", "-l", &test_dir])?; + println!("{}", layer.last_stdout); + assert!(!layer.last_stdout.contains("should-be-masked")); Ok(()) } #[rstest] -fn test_mask_mask_cli_no_config(mut sandbox: SandboxManager) -> Result<()> { - let test_dir = sandbox.test_filename("mask_from_env"); +fn test_mask_mask_cli_no_config(mut layer: LayerManager) -> Result<()> { + let test_dir = layer.test_filename("mask_from_env"); std::fs::create_dir(&test_dir)?; let test_file = format!("{}/should-be-masked", test_dir); std::fs::write(&test_file, "test")?; - sandbox.run(&[ - "--no-config", - "--mask", - &test_dir, - "ls", - "-l", - &test_dir, - ])?; - println!("{}", sandbox.last_stdout); - assert!(!sandbox.last_stdout.contains("should-be-masked")); + layer.run(&["--no-config", "--mask", &test_dir, "ls", "-l", &test_dir])?; + println!("{}", layer.last_stdout); + assert!(!layer.last_stdout.contains("should-be-masked")); Ok(()) } #[rstest] -fn test_mask_config(mut sandbox: SandboxManager) -> Result<()> { - let config_file1 = sandbox.test_filename("config.toml"); - let config_file2 = sandbox.test_filename("config2.toml"); +fn test_mask_config(mut layer: LayerManager) -> Result<()> { + let config_file1 = layer.test_filename("config.toml"); + let config_file2 = layer.test_filename("config2.toml"); std::fs::write(&config_file1, "mask = [\"/tmp\"]")?; std::fs::write(&config_file2, "mask = [\"/run\"]")?; - sandbox.run(&[ + layer.run(&[ "--config", &config_file1, "--config", @@ -63,12 +56,12 @@ fn test_mask_config(mut sandbox: SandboxManager) -> Result<()> { "config", "config_files", ])?; - println!("{}", sandbox.last_stdout); - println!("{}", sandbox.last_stderr); - assert!(sandbox.last_stdout.contains(&config_file1)); - assert!(sandbox.last_stdout.contains(&config_file2)); + println!("{}", layer.last_stdout); + println!("{}", layer.last_stderr); + assert!(layer.last_stdout.contains(&config_file1)); + assert!(layer.last_stdout.contains(&config_file2)); - sandbox.run(&[ + layer.run(&[ "--config", &config_file1, "--config", @@ -76,103 +69,103 @@ fn test_mask_config(mut sandbox: SandboxManager) -> Result<()> { "config", "mask", ])?; - println!("{}", sandbox.last_stdout); - println!("{}", sandbox.last_stderr); - assert!(sandbox.last_stdout.contains("/tmp")); - assert!(sandbox.last_stdout.contains("/run")); + println!("{}", layer.last_stdout); + println!("{}", layer.last_stderr); + assert!(layer.last_stdout.contains("/tmp")); + assert!(layer.last_stdout.contains("/run")); Ok(()) } #[rstest] -fn test_mask_env(mut sandbox: SandboxManager) -> Result<()> { - let test_dir = sandbox.test_filename("mask_from_env"); +fn test_mask_env(mut layer: LayerManager) -> Result<()> { + let test_dir = layer.test_filename("mask_from_env"); std::fs::create_dir(&test_dir)?; let test_file = format!("{}/should-be-masked", test_dir); std::fs::write(&test_file, "test")?; - sandbox.run_with_env( + layer.run_with_env( &["--no-config", "ls", "-l", &test_dir], "DEVLAYER_MASK", &test_dir, )?; - println!("{}", sandbox.last_stdout); - assert!(!sandbox.last_stdout.contains("should-be-masked")); + println!("{}", layer.last_stdout); + assert!(!layer.last_stdout.contains("should-be-masked")); Ok(()) } #[rstest] -fn test_mask_empty_env(mut sandbox: SandboxManager) -> Result<()> { - let test_dir = sandbox.test_filename("mask_from_env"); +fn test_mask_empty_env(mut layer: LayerManager) -> Result<()> { + let test_dir = layer.test_filename("mask_from_env"); std::fs::create_dir(&test_dir)?; let test_file = format!("{}/should-not-be-masked", test_dir); std::fs::write(&test_file, "test")?; - sandbox.run_with_env( + layer.run_with_env( &["--no-config", "ls", "-l", &test_dir], "DEVLAYER_MASK", "", )?; - println!("{}", sandbox.last_stdout); - assert!(sandbox.last_stdout.contains("should-not-be-masked")); + println!("{}", layer.last_stdout); + assert!(layer.last_stdout.contains("should-not-be-masked")); Ok(()) } #[rstest] -fn test_mask_bind_mask(mut sandbox: SandboxManager) -> Result<()> { - let test_dir = sandbox.test_filename("mask_from_env"); +fn test_mask_bind_mask(mut layer: LayerManager) -> Result<()> { + let test_dir = layer.test_filename("mask_from_env"); std::fs::create_dir(&test_dir)?; let test_file = format!("{}/should-be-masked", test_dir); std::fs::write(&test_file, "test")?; - sandbox.run_with_env( + layer.run_with_env( &["ls", "-l", &test_dir], "DEVLAYER_BIND", &format!("{}:{}:mask", test_dir, test_dir), )?; - println!("{}", sandbox.last_stdout); - assert!(!sandbox.last_stdout.contains("should-be-masked")); + println!("{}", layer.last_stdout); + assert!(!layer.last_stdout.contains("should-be-masked")); Ok(()) } #[rstest] -fn test_mask_file(mut sandbox: SandboxManager) -> Result<()> { - let test_dir = sandbox.test_filename("mask_from_env"); +fn test_mask_file(mut layer: LayerManager) -> Result<()> { + let test_dir = layer.test_filename("mask_from_env"); std::fs::create_dir(&test_dir)?; let test_file = format!("{}/should-be-masked", test_dir); std::fs::write(&test_file, "test")?; - sandbox.run_with_env( + layer.run_with_env( &["cat", &test_file], "DEVLAYER_BIND", &format!("{}:{}:mask", test_file, test_file), )?; // file exists but is masked so won't contain the test we wrote - assert!(!sandbox.last_stdout.contains("test")); + assert!(!layer.last_stdout.contains("test")); - sandbox.run_with_env( + layer.run_with_env( &["ls", &test_file], "DEVLAYER_BIND", &format!("{}:{}:mask", test_file, test_file), )?; - println!("{}", sandbox.last_stdout); + println!("{}", layer.last_stdout); // we should see it with ls - assert!(sandbox.last_stdout.contains("should-be-masked")); + assert!(layer.last_stdout.contains("should-be-masked")); Ok(()) } #[rstest] -fn test_mask_combined(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run_with_env( +fn test_mask_combined(mut layer: LayerManager) -> Result<()> { + layer.run_with_env( &["--mask", "/tmp", "config"], "DEVLAYER_MASK", "/run", )?; - assert!(sandbox.last_stdout.contains("/tmp")); - assert!(sandbox.last_stdout.contains("/run")); + assert!(layer.last_stdout.contains("/tmp")); + assert!(layer.last_stdout.contains("/run")); Ok(()) } #[rstest] -fn test_bind_conflict(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.xfail(&["--bind", "/tmp::ro,/tmp::rw"])); +fn test_bind_conflict(mut layer: LayerManager) -> Result<()> { + assert!(layer.xfail(&["--bind", "/tmp::ro,/tmp::rw"])); Ok(()) } diff --git a/tests/test_cli.rs b/tests/test_cli.rs index d976953..31e6122 100644 --- a/tests/test_cli.rs +++ b/tests/test_cli.rs @@ -5,45 +5,45 @@ use fixtures::*; use rstest::*; #[rstest] -fn test_cli(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.pass(&["--version"])); - assert!(sandbox.pass(&["--", "ls"])); - assert!(sandbox.xfail(&["--bad-option"])); - - assert!(sandbox.pass(&["--net", "config"])); - assert!(sandbox.last_stdout.contains("net=host")); - assert!(sandbox.pass(&["--net=none", "config"])); - assert!(sandbox.last_stdout.contains("net=none")); - assert!(sandbox.pass(&["--net=host", "config"])); - assert!(sandbox.last_stdout.contains("net=host")); - assert!(sandbox.xfail(&["--net=foobar", "config"])); - - assert!(sandbox.pass(&["--name", "test-cli", "config"])); - assert!(sandbox.last_stdout.contains("name=test-cli")); - assert!(sandbox.pass(&["--name=test-cli", "config"])); - assert!(sandbox.last_stdout.contains("name=test-cli")); - - assert!(sandbox.pass(&["--storage-dir=/tmp/layer", "config"])); - assert!(sandbox.last_stdout.contains("storage_dir=/tmp/layer")); - - assert!(sandbox.pass(&["--storage-dir=/tmp/layer", "config"])); - assert!(sandbox.last_stdout.contains("storage_dir=/tmp/layer")); +fn test_cli(mut layer: LayerManager) -> Result<()> { + assert!(layer.pass(&["--version"])); + assert!(layer.pass(&["--", "ls"])); + assert!(layer.xfail(&["--bad-option"])); + + assert!(layer.pass(&["--net", "config"])); + assert!(layer.last_stdout.contains("net=host")); + assert!(layer.pass(&["--net=none", "config"])); + assert!(layer.last_stdout.contains("net=none")); + assert!(layer.pass(&["--net=host", "config"])); + assert!(layer.last_stdout.contains("net=host")); + assert!(layer.xfail(&["--net=foobar", "config"])); + + assert!(layer.pass(&["--name", "test-cli", "config"])); + assert!(layer.last_stdout.contains("name=test-cli")); + assert!(layer.pass(&["--name=test-cli", "config"])); + assert!(layer.last_stdout.contains("name=test-cli")); + + assert!(layer.pass(&["--storage-dir=/tmp/layer", "config"])); + assert!(layer.last_stdout.contains("storage_dir=/tmp/layer")); + + assert!(layer.pass(&["--storage-dir=/tmp/layer", "config"])); + assert!(layer.last_stdout.contains("storage_dir=/tmp/layer")); // default values check - sandbox.no_default_options = true; - assert!(sandbox.pass(&["--no-config", "config"])); - assert!(sandbox.last_stdout.contains("name=layer")); - assert!(sandbox.last_stdout.contains("net=none")); + layer.no_default_options = true; + assert!(layer.pass(&["--no-config", "config"])); + assert!(layer.last_stdout.contains("name=layer")); + assert!(layer.last_stdout.contains("net=none")); // Test config_files display - assert!(sandbox.pass(&["--no-config", "config", "config_files"])); - assert!(sandbox.last_stdout == "\n"); // Should be empty with --no-config + assert!(layer.pass(&["--no-config", "config", "config_files"])); + assert!(layer.last_stdout == "\n"); // Should be empty with --no-config Ok(()) } #[rstest] -fn test_cli_with_config(mut sandbox: SandboxManager) -> Result<()> { +fn test_cli_with_config(mut layer: LayerManager) -> Result<()> { let parent_config = r#" net = "none" name = "parent" @@ -63,22 +63,22 @@ fn test_cli_with_config(mut sandbox: SandboxManager) -> Result<()> { let _ = std::fs::remove_file("../.devlayer.conf"); std::fs::write("../.devlayer.conf", parent_config)?; - sandbox.no_default_options = true; - assert!(sandbox.epass(&["config"], "DEVLAYER_BIND", ".cargo")); - assert!(sandbox.last_stdout.contains("name=parent")); - assert!(sandbox.last_stdout.contains("net=none")); - assert!(sandbox.last_stdout.contains("log_level=TRACE")); - assert!(sandbox.last_stdout.contains("storage_dir=/tmp/layer1")); - assert!(sandbox.last_stdout.contains(".cargo")); + layer.no_default_options = true; + assert!(layer.epass(&["config"], "DEVLAYER_BIND", ".cargo")); + assert!(layer.last_stdout.contains("name=parent")); + assert!(layer.last_stdout.contains("net=none")); + assert!(layer.last_stdout.contains("log_level=TRACE")); + assert!(layer.last_stdout.contains("storage_dir=/tmp/layer1")); + assert!(layer.last_stdout.contains(".cargo")); std::fs::write(".devlayer.toml", config)?; - sandbox.no_default_options = true; - assert!(sandbox.pass(&["config", "--bind=.cargo"])); - assert!(sandbox.last_stdout.contains("name=test-cli-with-config")); - assert!(sandbox.last_stdout.contains("net=host")); - println!("{}", sandbox.last_stdout); - assert!(sandbox.last_stdout.contains("log_level=INFO")); - assert!(sandbox.last_stdout.contains("storage_dir=/tmp/layer2")); + layer.no_default_options = true; + assert!(layer.pass(&["config", "--bind=.cargo"])); + assert!(layer.last_stdout.contains("name=test-cli-with-config")); + assert!(layer.last_stdout.contains("net=host")); + println!("{}", layer.last_stdout); + assert!(layer.last_stdout.contains("log_level=INFO")); + assert!(layer.last_stdout.contains("storage_dir=/tmp/layer2")); std::fs::remove_file(".devlayer.toml")?; std::fs::remove_file("../.devlayer.conf")?; @@ -87,38 +87,38 @@ fn test_cli_with_config(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_cli_with_env(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.epass(&["config"], "DEVLAYER_NET", "")); - assert!(sandbox.epass(&["config"], "DEVLAYER_NET", "host")); - assert!(sandbox.last_stdout.contains("net=host")); - assert!(sandbox.epass(&["config"], "DEVLAYER_NET", "none")); - assert!(sandbox.last_stdout.contains("net=none")); - assert!(sandbox.exfail(&["config"], "DEVLAYER_NET", "foobar")); - assert!(sandbox.last_stderr.contains("Invalid network type: foobar")); +fn test_cli_with_env(mut layer: LayerManager) -> Result<()> { + assert!(layer.epass(&["config"], "DEVLAYER_NET", "")); + assert!(layer.epass(&["config"], "DEVLAYER_NET", "host")); + assert!(layer.last_stdout.contains("net=host")); + assert!(layer.epass(&["config"], "DEVLAYER_NET", "none")); + assert!(layer.last_stdout.contains("net=none")); + assert!(layer.exfail(&["config"], "DEVLAYER_NET", "foobar")); + assert!(layer.last_stderr.contains("Invalid network type: foobar")); - assert!(sandbox.epass(&["config"], "DEVLAYER_LOG_LEVEL", "trace")); - assert!(sandbox.last_stdout.contains("log_level=TRACE")); + assert!(layer.epass(&["config"], "DEVLAYER_LOG_LEVEL", "trace")); + assert!(layer.last_stdout.contains("log_level=TRACE")); - assert!(sandbox.exfail(&["config"], "DEVLAYER_LOG_LEVEL", "foobar")); - assert!(sandbox.last_stderr.contains("Invalid log level: foobar")); + assert!(layer.exfail(&["config"], "DEVLAYER_LOG_LEVEL", "foobar")); + assert!(layer.last_stderr.contains("Invalid log level: foobar")); - assert!(sandbox.epass(&["config"], "DEVLAYER_NAME", "")); - assert!(sandbox.epass(&["config"], "DEVLAYER_NAME", "test-cli-with-env")); + assert!(layer.epass(&["config"], "DEVLAYER_NAME", "")); + assert!(layer.epass(&["config"], "DEVLAYER_NAME", "test-cli-with-env")); - assert!(sandbox.epass(&["config"], "DEVLAYER_STORAGE_DIR", "")); - assert!(sandbox.epass(&["config"], "DEVLAYER_STORAGE_DIR", "/tmp/layer")); - assert!(sandbox.last_stdout.contains("storage_dir=/tmp/layer")); + assert!(layer.epass(&["config"], "DEVLAYER_STORAGE_DIR", "")); + assert!(layer.epass(&["config"], "DEVLAYER_STORAGE_DIR", "/tmp/layer")); + assert!(layer.last_stdout.contains("storage_dir=/tmp/layer")); Ok(()) } #[rstest] -fn test_cli_resolve_failures(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.exfail(&["config"], "TEST_UNABLE_TO_OPEN_PROC_MOUNTS", "")); - assert!(sandbox.exfail(&["config"], "TEST_UNABLE_TO_FIND_MOUNT_POINT", "")); - assert!(sandbox.exfail(&["config"], "TEST_UNACCEPTABLE_MOUNT_TYPE", "")); - assert!(sandbox.xfail(&["--storage-dir=/bad/path", "config"])); - assert!(sandbox.last_stderr.contains("Insufficient access")); +fn test_cli_resolve_failures(mut layer: LayerManager) -> Result<()> { + assert!(layer.exfail(&["config"], "TEST_UNABLE_TO_OPEN_PROC_MOUNTS", "")); + assert!(layer.exfail(&["config"], "TEST_UNABLE_TO_FIND_MOUNT_POINT", "")); + assert!(layer.exfail(&["config"], "TEST_UNACCEPTABLE_MOUNT_TYPE", "")); + assert!(layer.xfail(&["--storage-dir=/bad/path", "config"])); + assert!(layer.last_stderr.contains("Insufficient access")); Ok(()) } diff --git a/tests/test_diff.rs b/tests/test_diff.rs index f2d76b4..5babda1 100644 --- a/tests/test_diff.rs +++ b/tests/test_diff.rs @@ -5,62 +5,62 @@ use fixtures::*; use rstest::*; #[rstest] -fn test_diff_patterns(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run(&["sh", "-c", "echo 'file_one' > file_one"])?; - sandbox.run(&["sh", "-c", "echo 'file_two' > file_two"])?; +fn test_diff_patterns(mut layer: LayerManager) -> Result<()> { + layer.run(&["sh", "-c", "echo 'file_one' > file_one"])?; + layer.run(&["sh", "-c", "echo 'file_two' > file_two"])?; // diff for all files should show both changes - sandbox.run(&["diff"])?; - assert!(sandbox.last_stdout.contains("file_one")); - assert!(sandbox.last_stdout.contains("file_two")); + layer.run(&["diff"])?; + assert!(layer.last_stdout.contains("file_one")); + assert!(layer.last_stdout.contains("file_two")); // root diff should show both files too - sandbox.run(&["diff", "/"])?; - assert!(sandbox.last_stdout.contains("file_one")); - assert!(sandbox.last_stdout.contains("file_two")); + layer.run(&["diff", "/"])?; + assert!(layer.last_stdout.contains("file_one")); + assert!(layer.last_stdout.contains("file_two")); // diff filtered to only the first file should not include the second - sandbox.run(&["diff", "file_one"])?; - assert!(sandbox.last_stdout.contains("file_one")); - assert!(!sandbox.last_stdout.contains("file_two")); + layer.run(&["diff", "file_one"])?; + assert!(layer.last_stdout.contains("file_one")); + assert!(!layer.last_stdout.contains("file_two")); // diff filtered to a pattern that matches nothing should have neither - sandbox.run(&["diff", "non_existent_pattern"])?; - assert!(!sandbox.last_stdout.contains("file_one")); - assert!(!sandbox.last_stdout.contains("file_two")); + layer.run(&["diff", "non_existent_pattern"])?; + assert!(!layer.last_stdout.contains("file_one")); + assert!(!layer.last_stdout.contains("file_two")); Ok(()) } #[rstest] -fn test_diff_operations(mut sandbox: SandboxManager) -> Result<()> { - let added = sandbox.test_filename("added_file"); - let removed = sandbox.test_filename("removed_file"); - let modified = sandbox.test_filename("modified_file"); - let moved_src = sandbox.test_filename("moved_dir"); - let moved_dst = sandbox.test_filename("moved_dir_new"); +fn test_diff_operations(mut layer: LayerManager) -> Result<()> { + let added = layer.test_filename("added_file"); + let removed = layer.test_filename("removed_file"); + let modified = layer.test_filename("modified_file"); + let moved_src = layer.test_filename("moved_dir"); + let moved_dst = layer.test_filename("moved_dir_new"); std::fs::write(&removed, "to be removed")?; std::fs::write(&modified, "old content")?; std::fs::create_dir(&moved_src)?; - sandbox.run(&["sh", "-c", &format!("echo 'added' > {}", added)])?; - sandbox.run(&["rm", &removed])?; - sandbox.run(&[ + layer.run(&["sh", "-c", &format!("echo 'added' > {}", added)])?; + layer.run(&["rm", &removed])?; + layer.run(&[ "bash", "-c", &format!("echo 'new content' > {}", modified), ])?; - sandbox.run(&["mv", &moved_src, &moved_dst])?; + layer.run(&["mv", &moved_src, &moved_dst])?; - sandbox.run(&["diff"])?; - assert!(sandbox.last_stdout.contains(&added)); - assert!(sandbox.last_stdout.contains(&removed)); - assert!(sandbox.last_stdout.contains(&modified)); - assert!(sandbox.last_stdout.contains("+new content")); - assert!(sandbox.last_stdout.contains("### Moved")); - assert!(sandbox.last_stdout.contains(&moved_src)); - assert!(sandbox.last_stdout.contains(&moved_dst)); + layer.run(&["diff"])?; + assert!(layer.last_stdout.contains(&added)); + assert!(layer.last_stdout.contains(&removed)); + assert!(layer.last_stdout.contains(&modified)); + assert!(layer.last_stdout.contains("+new content")); + assert!(layer.last_stdout.contains("### Moved")); + assert!(layer.last_stdout.contains(&moved_src)); + assert!(layer.last_stdout.contains(&moved_dst)); Ok(()) } diff --git a/tests/test_fuse.rs b/tests/test_fuse.rs index 7bbbe71..72982fc 100644 --- a/tests/test_fuse.rs +++ b/tests/test_fuse.rs @@ -5,7 +5,7 @@ use fixtures::*; use rstest::*; #[rstest] -fn test_disable_fuse(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.xfail(&["--bind-fuse=false", "ls", "-l", "/dev/fuse"])); +fn test_disable_fuse(mut layer: LayerManager) -> Result<()> { + assert!(layer.xfail(&["--bind-fuse=false", "ls", "-l", "/dev/fuse"])); Ok(()) } diff --git a/tests/test_json.rs b/tests/test_json.rs index e252f09..f998996 100644 --- a/tests/test_json.rs +++ b/tests/test_json.rs @@ -5,12 +5,12 @@ use fixtures::*; use rstest::*; #[rstest] -fn test_json(mut sandbox: SandboxManager) -> Result<()> { - let filename = sandbox.test_filename("file"); - sandbox.run(&["touch", &filename])?; - sandbox.run(&["--json", "status", &filename])?; +fn test_json(mut layer: LayerManager) -> Result<()> { + let filename = layer.test_filename("file"); + layer.run(&["touch", &filename])?; + layer.run(&["--json", "status", &filename])?; - let json_output = sandbox.last_stdout.clone(); + let json_output = layer.last_stdout.clone(); let json: serde_json::Value = serde_json::from_str(&json_output)?; println!("json: {}", json); println!("changes: {}", json["changes"].as_array().unwrap().len()); @@ -30,8 +30,8 @@ fn test_json(mut sandbox: SandboxManager) -> Result<()> { * support json diff output that would be great but we'll have to figure * out another way to exercise that code. */ #[rstest] -fn test_json_diff(mut sandbox: SandboxManager) -> Result<()> { - sandbox.xfail(&["--json", "diff"]); - assert!(sandbox.last_stdout.contains("\"status\": \"error\"")); +fn test_json_diff(mut layer: LayerManager) -> Result<()> { + layer.xfail(&["--json", "diff"]); + assert!(layer.last_stdout.contains("\"status\": \"error\"")); Ok(()) } diff --git a/tests/test_layer_failures.rs b/tests/test_layer_failures.rs new file mode 100644 index 0000000..d303746 --- /dev/null +++ b/tests/test_layer_failures.rs @@ -0,0 +1,143 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use rstest::*; +use std::{ + path::{Path, PathBuf}, + process::Command, +}; +#[rstest] +fn test_fail_to_start_layer(mut layer: LayerManager) -> Result<()> { + assert!(layer.exfail(&["env"], "TEST_START_LAYER_FAILURE", "1")); + assert!(layer.all_stderr.contains("Failed to start layer")); + Ok(()) +} + +#[rstest] +fn test_running_as_user(mut layer: LayerManager) -> Result<()> { + layer.no_sudo = true; + assert!(layer.xfail(&["env"])); + assert!(layer.all_stderr.contains("Insufficient permissions")); + layer.no_sudo = false; // so teardown can run without errors + Ok(()) +} + +#[rstest] +fn test_recover_from_bad_pid_file() -> Result<()> { + let mut s = layer(); + s.run(&["config", "layer_dir"])?; + let storage_dir = String::from(s.last_stdout.trim()); + let mut storage_dir = PathBuf::from(&storage_dir); + storage_dir.pop(); + + let pid_file_name = format!("{}/{}.pid", storage_dir.display(), s.name); + std::fs::write(&pid_file_name, "not a number")?; + println!("pid_file_name: {}", &pid_file_name); + let pid_file = std::fs::File::open(&pid_file_name)?; + let pid_file_content = std::io::read_to_string(pid_file)?; + println!("pid_file_content: {}", pid_file_content); + + assert!(s.run(&["true"]).is_ok()); + + let pid_file = std::fs::File::open(&pid_file_name)?; + let pid_file_content = std::io::read_to_string(pid_file)?; + println!("pid_file: {} contains {}", pid_file_name, pid_file_content); + assert!(pid_file_content.parse::().is_ok()); + Ok(()) +} + +#[rstest] +fn test_lock(mut layer: LayerManager) -> Result<()> { + layer.run(&["config", "layer_dir"])?; + let layer_dir = String::from(layer.last_stdout.trim()); + let lock_file = format!("{}.lock", layer_dir); + println!("lock_file: {}", lock_file); + Command::new("sudo") + .args(["rm", "-f", lock_file.as_str()]) + .output()?; + std::fs::create_dir_all(&lock_file)?; + // lock file is now a directory, should fail + assert!(layer.xfail(&["true"])); + assert!(layer.all_stderr.contains("Failed to open lock")); + + // remove directory + std::fs::remove_dir(&lock_file)?; + // lock file is now a file, should succeed + assert!(layer.pass(&["true"])); + + Ok(()) +} + +#[rstest] +fn test_unable_to_join_layer(mut layer: LayerManager) -> Result<()> { + assert!(layer.exfail(&["true"], "TEST_UNABLE_TO_JOIN_LAYER", "1")); + assert!( + layer + .last_stderr + .contains("Failed to join layer namespaces") + ); + + Ok(()) +} + +#[rstest] +fn test_rename_across_mount_points_failure( + mut layer: LayerManager, +) -> Result<()> { + let test_file = layer.test_filename("test-file"); + let test_file2 = layer.test_filename("test-file2"); + std::fs::create_dir_all(&test_file)?; + layer.run(&["mv", test_file.as_str(), test_file2.as_str()])?; + assert!(layer.exfail( + &["accept"], + "TEST_RENAME_ACROSS_MOUNT_POINTS_FAILURE", + "1" + )); + assert!(layer.last_stderr.contains("crosses a mount point")); + Ok(()) +} + +#[rstest] +fn test_bad_staged_file(mut layer: LayerManager) -> Result<()> { + let test_file = layer.test_filename("test-file"); + layer.run(&["touch", test_file.as_str()])?; + assert!(layer.exfail(&["accept"], "TEST_NO_STAGED_FILE", "1")); + + let test_file = layer.test_filename("test-file"); + layer.run(&["touch", test_file.as_str()])?; + assert!(layer.exfail(&["accept"], "TEST_BAD_STAGED_FILE", "1")); + assert!(!Path::new(test_file.as_str()).exists()); + Ok(()) +} + +#[rstest] +fn test_bad_staged_file_remove(mut layer: LayerManager) -> Result<()> { + let test_file = layer.test_filename("test-file"); + std::fs::write(&test_file, "test")?; + layer.run(&["rm", test_file.as_str()])?; + assert!(layer.exfail(&["accept"], "TEST_NO_STAGED_FILE", "1")); + + let test_file = layer.test_filename("test-file"); + layer.run(&["touch", test_file.as_str()])?; + assert!(layer.exfail(&["accept"], "TEST_BAD_STAGED_FILE", "1")); + assert!(!Path::new(test_file.as_str()).exists()); + Ok(()) +} + +#[rstest] +fn test_remove_underlying_dir_failure(mut layer: LayerManager) -> Result<()> { + let test_dir = layer.test_filename("test-dir"); + let test_dir2 = layer.test_filename("test-dir2"); + std::fs::create_dir_all(&test_dir)?; + layer.run(&["mv", test_dir.as_str(), test_dir2.as_str()])?; + std::fs::remove_dir(&test_dir)?; + assert!(layer.pass(&["status"])); + let last_stdout = layer.last_stdout.clone(); + assert!(last_stdout.contains("Redirect path not found")); + + assert!(layer.xfail(&["accept"])); + assert!(last_stdout.contains("Redirect path not found")); + + Ok(()) +} diff --git a/tests/test_sandbox_inception.rs b/tests/test_layer_inception.rs similarity index 71% rename from tests/test_sandbox_inception.rs rename to tests/test_layer_inception.rs index 6b26a7c..0ece7c7 100644 --- a/tests/test_sandbox_inception.rs +++ b/tests/test_layer_inception.rs @@ -7,8 +7,8 @@ use anyhow::Result; use fixtures::*; use rstest::*; -// Find all .profraw files in the sub-sandboxes upper and copy them over to coverage/profraw -fn copy_sub_sandbox_profraw(sub_dir: &Path) -> Result<()> { +// Find all .profraw files in the sub-layers upper and copy them over to coverage/profraw +fn copy_sub_layer_profraw(sub_dir: &Path) -> Result<()> { println!("sub_dir: {}", sub_dir.display()); let sub_upper = sub_dir.join("upper"); @@ -40,23 +40,21 @@ fn copy_sub_sandbox_profraw(sub_dir: &Path) -> Result<()> { } #[rstest] -fn test_overlayfs_stack_depth_message( - mut sandbox: SandboxManager, -) -> Result<()> { - sandbox.set_debug_mode(true); - let sandbox_bin = get_sandbox_bin() + "-setuid"; +fn test_overlayfs_stack_depth_message(mut layer: LayerManager) -> Result<()> { + layer.set_debug_mode(true); + let devlayer_bin = get_devlayer_bin() + "-setuid"; - assert!(sandbox.xfail(&[&sandbox_bin, &sandbox_bin, &sandbox_bin])); + assert!(layer.xfail(&[&devlayer_bin, &devlayer_bin, &devlayer_bin])); assert!( - sandbox + layer .all_stderr .contains("Maximum overlayfs stacking depth exceeded") ); - let sub_dir = sandbox.run(&[&sandbox_bin, "config", "sandbox_dir"])?; + let sub_dir = layer.run(&[&devlayer_bin, "config", "layer_dir"])?; let sub_dir = String::from_utf8_lossy(&sub_dir.stdout).to_string(); let sub_dir = sub_dir.trim().to_string(); - copy_sub_sandbox_profraw(Path::new(&sub_dir))?; + copy_sub_layer_profraw(Path::new(&sub_dir))?; Ok(()) } diff --git a/tests/test_list.rs b/tests/test_list.rs index f1eb932..3930d89 100644 --- a/tests/test_list.rs +++ b/tests/test_list.rs @@ -8,52 +8,52 @@ use rstest::*; #[rstest] fn test_list() -> Result<()> { - let mut sandbox1 = sandbox(); - let mut sandbox2 = sandbox(); + let mut layer1 = layer(); + let mut layer2 = layer(); - sandbox1.run(&["true"])?; - sandbox2.run(&["true"])?; + layer1.run(&["true"])?; + layer2.run(&["true"])?; - let name1 = sandbox1.name.clone(); - let name2 = sandbox2.name.clone(); + let name1 = layer1.name.clone(); + let name2 = layer2.name.clone(); - sandbox1.run(&["list"])?; - let running = sandbox1.last_stdout.clone(); + layer1.run(&["list"])?; + let running = layer1.last_stdout.clone(); println!("looking for {} in {}", name1, running); assert!(running.contains(&name1)); assert!(running.contains(&name2)); - sandbox1.run(&["list", &name1])?; - let running = sandbox1.last_stdout.clone(); + layer1.run(&["list", &name1])?; + let running = layer1.last_stdout.clone(); println!("looking for {} and {} in {}", name1, name2, running); assert!(running.contains(&name1)); assert!(!running.contains(&name2)); - sandbox1.run(&["list", &name1, &name2])?; - let running = sandbox1.last_stdout.clone(); + layer1.run(&["list", &name1, &name2])?; + let running = layer1.last_stdout.clone(); assert!(running.contains(&name1)); assert!(running.contains(&name2)); - sandbox1.run(&["list", "non existent"])?; - let running = sandbox1.last_stdout.clone(); + layer1.run(&["list", "non existent"])?; + let running = layer1.last_stdout.clone(); assert!(!running.contains(&name1)); assert!(!running.contains(&name2)); Ok(()) } #[rstest] -fn test_list_ignore_bad_pid_file(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run(&["config", "sandbox_dir"])?; - let mut t = PathBuf::from(sandbox.last_stdout.clone()); +fn test_list_ignore_bad_pid_file(mut layer: LayerManager) -> Result<()> { + layer.run(&["config", "layer_dir"])?; + let mut t = PathBuf::from(layer.last_stdout.clone()); println!("t: {}", t.display()); t.pop(); println!("t: {}", t.display()); - let bad_sandbox_base = + let bad_layer_base = format!("{}/{}", t.to_string_lossy(), "coverage_test_bad_pid_file"); - println!("bad_layer_base: {}", bad_sandbox_base); + println!("bad_layer_base: {}", bad_layer_base); - let pid_file_name = format!("{}.pid", bad_sandbox_base); - let lock_file_name = format!("{}.lock", bad_sandbox_base); + let pid_file_name = format!("{}.pid", bad_layer_base); + let lock_file_name = format!("{}.lock", bad_layer_base); std::fs::write(&lock_file_name, "1")?; std::fs::write(&pid_file_name, "not a number")?; @@ -64,9 +64,9 @@ fn test_list_ignore_bad_pid_file(mut sandbox: SandboxManager) -> Result<()> { println!("pid_file_content: {}", pid_file_content); assert!(pid_file_content.parse::().is_err()); - assert!(sandbox.run(&["list"]).is_ok()); + assert!(layer.run(&["list"]).is_ok()); // still expected to be listed - assert!(sandbox.all_stdout.contains("coverage_test_bad_pid_file")); + assert!(layer.all_stdout.contains("coverage_test_bad_pid_file")); std::fs::remove_file(&pid_file_name)?; std::fs::remove_file(&lock_file_name)?; @@ -75,18 +75,18 @@ fn test_list_ignore_bad_pid_file(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_list_stale_pid_file(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run(&["config", "sandbox_dir"])?; - let mut t = PathBuf::from(sandbox.last_stdout.clone()); +fn test_list_stale_pid_file(mut layer: LayerManager) -> Result<()> { + layer.run(&["config", "layer_dir"])?; + let mut t = PathBuf::from(layer.last_stdout.clone()); t.pop(); - let stale_sandbox_base = - format!("{}/{}", t.to_string_lossy(), sandbox.name.clone()); + let stale_layer_base = + format!("{}/{}", t.to_string_lossy(), layer.name.clone()); - let pid_file_name = format!("{}.pid", stale_sandbox_base); + let pid_file_name = format!("{}.pid", stale_layer_base); - sandbox.run(&["true"])?; + layer.run(&["true"])?; let pid = std::fs::read_to_string(&pid_file_name)?; - sandbox.run(&["stop"])?; + layer.run(&["stop"])?; // stop cleans up our pid, but let's restore it so we have a stale pid // file that shouldn't conflict with any existing processes on the system @@ -99,12 +99,12 @@ fn test_list_stale_pid_file(mut sandbox: SandboxManager) -> Result<()> { println!("pid_file_content: {}", pid_file_content); assert!(pid_file_content.parse::().is_ok()); - assert!(sandbox.run(&["list", &sandbox.name.clone()]).is_ok()); - eprintln!(">>>> {} <<<<", sandbox.last_stdout); - eprintln!(">>>> {} <<<<", sandbox.last_stderr); + assert!(layer.run(&["list", &layer.name.clone()]).is_ok()); + eprintln!(">>>> {} <<<<", layer.last_stdout); + eprintln!(">>>> {} <<<<", layer.last_stderr); // still expected to be listed - assert!(sandbox.all_stdout.contains("Stopped")); - assert!(sandbox.all_stdout.contains(&sandbox.name)); + assert!(layer.all_stdout.contains("Stopped")); + assert!(layer.all_stdout.contains(&layer.name)); Ok(()) } diff --git a/tests/test_misc.rs b/tests/test_misc.rs index c24ec15..276eeb8 100644 --- a/tests/test_misc.rs +++ b/tests/test_misc.rs @@ -8,24 +8,24 @@ use rstest::*; use serde_json::Value; #[rstest] -fn test_program_runs_with_no_args(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run(&["env"])?; - sandbox.run(&["status"])?; - sandbox.run(&["touch", "testfile"])?; - sandbox.run(&["status"])?; - sandbox.run(&["list"])?; - sandbox.run(&["diff"])?; - sandbox.run(&[])?; // should launch bash, which should exit without an input terminal +fn test_program_runs_with_no_args(mut layer: LayerManager) -> Result<()> { + layer.run(&["env"])?; + layer.run(&["status"])?; + layer.run(&["touch", "testfile"])?; + layer.run(&["status"])?; + layer.run(&["list"])?; + layer.run(&["diff"])?; + layer.run(&[])?; // should launch bash, which should exit without an input terminal Ok(()) } #[rstest] -fn test_weird_sudo_env_variables(sandbox: SandboxManager) -> Result<()> { - let sandbox_bin = sandbox.sandbox_bin.clone(); +fn test_weird_sudo_env_variables(layer: LayerManager) -> Result<()> { + let devlayer_bin = layer.devlayer_bin.clone(); let mut cmd = Command::new("sudo"); - cmd.args(["-E", "SUDO_UID=nan", &sandbox_bin]); - cmd.args([format!("--name={}", &sandbox.name)]); + cmd.args(["-E", "SUDO_UID=nan", &devlayer_bin]); + cmd.args([format!("--name={}", &layer.name)]); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); assert!( @@ -34,8 +34,8 @@ fn test_weird_sudo_env_variables(sandbox: SandboxManager) -> Result<()> { ); let mut cmd = Command::new("sudo"); - cmd.args(["-E", "SUDO_GID=nan", &sandbox_bin]); - cmd.args([format!("--name={}", &sandbox.name)]); + cmd.args(["-E", "SUDO_GID=nan", &devlayer_bin]); + cmd.args([format!("--name={}", &layer.name)]); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); assert!( @@ -44,8 +44,8 @@ fn test_weird_sudo_env_variables(sandbox: SandboxManager) -> Result<()> { ); let mut cmd = Command::new("sudo"); - cmd.args(["-E", "SUDO_HOME=", &sandbox_bin]); - cmd.args([format!("--name={}", &sandbox.name)]); + cmd.args(["-E", "SUDO_HOME=", &devlayer_bin]); + cmd.args([format!("--name={}", &layer.name)]); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); assert!( @@ -54,8 +54,8 @@ fn test_weird_sudo_env_variables(sandbox: SandboxManager) -> Result<()> { ); let mut cmd = Command::new("sudo"); - cmd.args(["-E", "SUDO_HOME=~/foobar", &sandbox_bin]); - cmd.args([format!("--name={}", &sandbox.name)]); + cmd.args(["-E", "SUDO_HOME=~/foobar", &devlayer_bin]); + cmd.args([format!("--name={}", &layer.name)]); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); @@ -65,8 +65,8 @@ fn test_weird_sudo_env_variables(sandbox: SandboxManager) -> Result<()> { ); let mut cmd = Command::new("sudo"); - cmd.args(["-E", "SUDO_HOME=/invalid-home-directory", &sandbox_bin]); - cmd.args([format!("--name={}", &sandbox.name)]); + cmd.args(["-E", "SUDO_HOME=/invalid-home-directory", &devlayer_bin]); + cmd.args([format!("--name={}", &layer.name)]); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); @@ -96,9 +96,9 @@ fn test_weird_sudo_env_variables(sandbox: SandboxManager) -> Result<()> { absolute_dir_with_spaces.display() ) .as_str(), - &sandbox_bin, + &devlayer_bin, ]); - cmd.args([format!("--name={}", &sandbox.name)]); + cmd.args([format!("--name={}", &layer.name)]); cmd.args(["true"]); println!("cmd: {:?}", cmd); let output = cmd.output()?; @@ -120,14 +120,14 @@ fn test_weird_sudo_env_variables(sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_setuid_works_like_sudo(mut sandbox: SandboxManager) -> Result<()> { - let sudo_output = sandbox.run(&["whoami"])?; +fn test_setuid_works_like_sudo(mut layer: LayerManager) -> Result<()> { + let sudo_output = layer.run(&["whoami"])?; - let sandbox_bin = sandbox.sandbox_bin.clone(); - let sandbox_setuid = sandbox_bin + "-setuid"; + let devlayer_bin = layer.devlayer_bin.clone(); + let devlayer_setuid = devlayer_bin + "-setuid"; - let mut cmd = Command::new(&sandbox_setuid); - cmd.args([format!("--name={}", &sandbox.name)]); + let mut cmd = Command::new(&devlayer_setuid); + cmd.args([format!("--name={}", &layer.name)]); cmd.args(["whoami"]); let setuid_output = cmd.output()?; @@ -137,51 +137,49 @@ fn test_setuid_works_like_sudo(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_sandbox_no_print_to_stdout_by_default( - mut sandbox: SandboxManager, +fn test_layer_no_print_to_stdout_by_default( + mut layer: LayerManager, ) -> Result<()> { - sandbox.run(&["echo", "-n", "Hello, world!"])?; - assert_eq!(&sandbox.last_stdout, "Hello, world!"); + layer.run(&["echo", "-n", "Hello, world!"])?; + assert_eq!(&layer.last_stdout, "Hello, world!"); Ok(()) } #[rstest] -fn test_devlayer_env_variable_is_set( - mut sandbox: SandboxManager, -) -> Result<()> { - let output = sandbox.run(&["sh", "-c", "echo -n $DEVLAYER"])?; - assert_eq!(String::from_utf8_lossy(&output.stdout), sandbox.name); +fn test_devlayer_env_variable_is_set(mut layer: LayerManager) -> Result<()> { + let output = layer.run(&["sh", "-c", "echo -n $DEVLAYER"])?; + assert_eq!(String::from_utf8_lossy(&output.stdout), layer.name); Ok(()) } #[rstest] -fn test_config(mut sandbox: SandboxManager) -> Result<()> { - let output = sandbox.run(&["config", "name"])?; +fn test_config(mut layer: LayerManager) -> Result<()> { + let output = layer.run(&["config", "name"])?; assert_eq!( String::from_utf8_lossy(&output.stdout), - format!("{}\n", sandbox.name) + format!("{}\n", layer.name) ); - let output = sandbox.run(&["config"])?; + let output = layer.run(&["config"])?; assert!(output.status.success()); - let output = sandbox.run(&["--json", "config"])?; + let output = layer.run(&["--json", "config"])?; assert!(output.status.success()); let json: Value = serde_json::from_str(&String::from_utf8_lossy(&output.stdout))?; - assert_eq!(json["name"], sandbox.name); + assert_eq!(json["name"], layer.name); - assert!(sandbox.xfail(&["config", "non-existent-key"])); + assert!(layer.xfail(&["config", "non-existent-key"])); Ok(()) } #[rstest] -fn test_shell_completion_generation(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.epass(&[], "COMPLETE", "zsh")); - assert!(sandbox.epass(&[], "COMPLETE", "bash")); - assert!(sandbox.epass(&[], "COMPLETE", "fish")); - assert!(sandbox.epass(&[], "COMPLETE", "elvish")); - assert!(sandbox.exfail(&[], "COMPLETE", "invalid-shell")); +fn test_shell_completion_generation(mut layer: LayerManager) -> Result<()> { + assert!(layer.epass(&[], "COMPLETE", "zsh")); + assert!(layer.epass(&[], "COMPLETE", "bash")); + assert!(layer.epass(&[], "COMPLETE", "fish")); + assert!(layer.epass(&[], "COMPLETE", "elvish")); + assert!(layer.exfail(&[], "COMPLETE", "invalid-shell")); Ok(()) } @@ -191,11 +189,11 @@ fn test_shell_completion_generation(mut sandbox: SandboxManager) -> Result<()> { * a real file but with the limits of filename sizes and redirect=off I think it's * hard to do, and the code is one line simple so meh. */ #[rstest] -fn exercise_large_xattr(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run(&["touch", "testfile"])?; +fn exercise_large_xattr(mut layer: LayerManager) -> Result<()> { + layer.run(&["touch", "testfile"])?; let long_value = "a".repeat(300); - let upper_cwd_output = sandbox.run(&["config", "upper_cwd"])?; + let upper_cwd_output = layer.run(&["config", "upper_cwd"])?; let upper_cwd = String::from_utf8_lossy(&upper_cwd_output.stdout) .trim() .to_string(); @@ -216,21 +214,21 @@ fn exercise_large_xattr(mut sandbox: SandboxManager) -> Result<()> { .status()?; //assert!(status.success()); - sandbox.run(&["status"])?; + layer.run(&["status"])?; Ok(()) } #[rstest] fn test_no_xdg() -> Result<()> { - let mut sandbox = SandboxManager::new(); - assert!(sandbox.epass(&["true"], "TEST_EMPTY_XDG_RUNTIME_DIR", "1")); + let mut layer = LayerManager::new(); + assert!(layer.epass(&["true"], "TEST_EMPTY_XDG_RUNTIME_DIR", "1")); Ok(()) } #[rstest] -fn test_empty_config(mut sandbox: SandboxManager) -> Result<()> { - let output = sandbox.run(&["--config=", "config", "config_files"])?; +fn test_empty_config(mut layer: LayerManager) -> Result<()> { + let output = layer.run(&["--config=", "config", "config_files"])?; assert_eq!(String::from_utf8_lossy(&output.stdout), "\n"); Ok(()) } diff --git a/tests/test_mount_unmount_kill.rs b/tests/test_mount_unmount_kill.rs index 6d4c0d0..274af76 100644 --- a/tests/test_mount_unmount_kill.rs +++ b/tests/test_mount_unmount_kill.rs @@ -7,58 +7,58 @@ use std::ffi::CStr; use std::path::Path; #[rstest] -fn test_fail_to_read_mounts(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.exfail(&["env"], "TEST_SYSTEM_MOUNTS_NULL", "1")); - assert!(sandbox.pass(&["true"])); - assert!(sandbox.exfail(&["stop"], "TEST_SYSTEM_MOUNTS_NULL", "1")); - assert!(sandbox.pass(&["stop"])); +fn test_fail_to_read_mounts(mut layer: LayerManager) -> Result<()> { + assert!(layer.exfail(&["env"], "TEST_SYSTEM_MOUNTS_NULL", "1")); + assert!(layer.pass(&["true"])); + assert!(layer.exfail(&["stop"], "TEST_SYSTEM_MOUNTS_NULL", "1")); + assert!(layer.pass(&["stop"])); Ok(()) } #[rstest] -fn test_no_mounts_found(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.exfail(&["env"], "TEST_NO_MOUNTS_FOUND", "1")); - assert!(sandbox.pass(&["true"])); - assert!(sandbox.epass(&["stop"], "TEST_NO_MOUNTS_FOUND", "1")); - assert!(sandbox.last_stderr.contains("No mounts found for layer")); +fn test_no_mounts_found(mut layer: LayerManager) -> Result<()> { + assert!(layer.exfail(&["env"], "TEST_NO_MOUNTS_FOUND", "1")); + assert!(layer.pass(&["true"])); + assert!(layer.epass(&["stop"], "TEST_NO_MOUNTS_FOUND", "1")); + assert!(layer.last_stderr.contains("No mounts found for layer")); Ok(()) } #[rstest] -fn test_unmount_race(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.pass(&["true"])); - assert!(sandbox.epass(&["stop"], "TEST_UNMOUNT_RACE", "1")); - assert!(sandbox.last_stderr.contains("Failed to unmount")); +fn test_unmount_race(mut layer: LayerManager) -> Result<()> { + assert!(layer.pass(&["true"])); + assert!(layer.epass(&["stop"], "TEST_UNMOUNT_RACE", "1")); + assert!(layer.last_stderr.contains("Failed to unmount")); Ok(()) } #[rstest] -fn test_kill_not_running(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.pass(&["stop"])); - assert!(sandbox.last_stderr.contains("doesn't appear to be running")); +fn test_kill_not_running(mut layer: LayerManager) -> Result<()> { + assert!(layer.pass(&["stop"])); + assert!(layer.last_stderr.contains("doesn't appear to be running")); - assert!(sandbox.pass(&["true"])); - assert!(sandbox.epass(&["stop"], "TEST_STOP_RACE", "1")); - assert!(sandbox.last_stderr.contains("already gone")); + assert!(layer.pass(&["true"])); + assert!(layer.epass(&["stop"], "TEST_STOP_RACE", "1")); + assert!(layer.last_stderr.contains("already gone")); - assert!(sandbox.pass(&["true"])); - assert!(sandbox.epass(&["stop"], "TEST_STOP_RACE2", "1")); - assert!(sandbox.last_stderr.contains("Failed to kill process")); + assert!(layer.pass(&["true"])); + assert!(layer.epass(&["stop"], "TEST_STOP_RACE2", "1")); + assert!(layer.last_stderr.contains("Failed to kill process")); - assert!(sandbox.pass(&["true"])); - assert!(sandbox.epass(&["stop"], "TEST_STOP_RACE3", "1")); + assert!(layer.pass(&["true"])); + assert!(layer.epass(&["stop"], "TEST_STOP_RACE3", "1")); Ok(()) } #[rstest] -fn test_kill_unmounts(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.pass(&["true"])); +fn test_kill_unmounts(mut layer: LayerManager) -> Result<()> { + assert!(layer.pass(&["true"])); - let mounts = get_mounts(&sandbox.dir()?); + let mounts = get_mounts(&layer.dir()?); assert!(!mounts.is_empty()); - assert!(sandbox.pass(&["stop"])); - let mounts = get_mounts(&sandbox.dir()?); + assert!(layer.pass(&["stop"])); + let mounts = get_mounts(&layer.dir()?); assert!(mounts.is_empty()); Ok(()) diff --git a/tests/test_net.rs b/tests/test_net.rs index e6db331..113178d 100644 --- a/tests/test_net.rs +++ b/tests/test_net.rs @@ -5,8 +5,8 @@ use fixtures::*; use rstest::*; #[rstest] -fn test_no_network(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.xfail(&[ +fn test_no_network(mut layer: LayerManager) -> Result<()> { + assert!(layer.xfail(&[ "--net=none", "ping", "-c", @@ -15,17 +15,13 @@ fn test_no_network(mut sandbox: SandboxManager) -> Result<()> { "1", "127.0.0.1" ])); - assert!( - sandbox - .last_stderr - .contains("Creating new network namespace") - ); + assert!(layer.last_stderr.contains("Creating new network namespace")); Ok(()) } #[rstest] -fn test_network(mut sandbox: SandboxManager) -> Result<()> { - let status = sandbox.run(&[ +fn test_network(mut layer: LayerManager) -> Result<()> { + let status = layer.run(&[ "--net=host", "ping", "-c", @@ -34,7 +30,7 @@ fn test_network(mut sandbox: SandboxManager) -> Result<()> { "1", "127.0.0.1", ])?; - assert!(sandbox.last_stderr.contains("Using host network")); + assert!(layer.last_stderr.contains("Using host network")); assert!(status.status.success()); Ok(()) } diff --git a/tests/test_new_last.rs b/tests/test_new_last.rs index ac83c40..dafd37d 100644 --- a/tests/test_new_last.rs +++ b/tests/test_new_last.rs @@ -5,29 +5,25 @@ use fixtures::*; use rstest::*; #[rstest] -fn test_new_last_mutual_exclusivity(mut sandbox: SandboxManager) -> Result<()> { - sandbox.no_default_options = true; +fn test_new_last_mutual_exclusivity(mut layer: LayerManager) -> Result<()> { + layer.no_default_options = true; - assert!(sandbox.xfail(&["--new", "--last", "ls"])); - assert!(sandbox.xfail(&["--name=foo", "--last", "ls"])); - assert!(sandbox.xfail(&["--name=foo", "--new", "ls"])); - assert!(sandbox.xfail(&["--name=foo", "--new", "--last", "ls"])); - assert!(sandbox.exfail(&["--new", "ls"], "DEVLAYER_NAME", "foo")); - assert!(sandbox.exfail(&["--last", "ls"], "DEVLAYER_NAME", "foo")); + assert!(layer.xfail(&["--new", "--last", "ls"])); + assert!(layer.xfail(&["--name=foo", "--last", "ls"])); + assert!(layer.xfail(&["--name=foo", "--new", "ls"])); + assert!(layer.xfail(&["--name=foo", "--new", "--last", "ls"])); + assert!(layer.exfail(&["--new", "ls"], "DEVLAYER_NAME", "foo")); + assert!(layer.exfail(&["--last", "ls"], "DEVLAYER_NAME", "foo")); Ok(()) } #[rstest] -fn test_last_is_empty(mut sandbox: SandboxManager) -> Result<()> { - sandbox.no_default_options = true; +fn test_last_is_empty(mut layer: LayerManager) -> Result<()> { + layer.no_default_options = true; - assert!(sandbox.exfail( - &["--last", "-v", "true"], - "TEST_LAST_IS_EMPTY", - "1" - )); - assert!(sandbox.last_stderr.contains("No layers found")); + assert!(layer.exfail(&["--last", "-v", "true"], "TEST_LAST_IS_EMPTY", "1")); + assert!(layer.last_stderr.contains("No layers found")); Ok(()) } diff --git a/tests/test_partial_move_failures.rs b/tests/test_partial_move_failures.rs index 197c11e..2b3a0f0 100644 --- a/tests/test_partial_move_failures.rs +++ b/tests/test_partial_move_failures.rs @@ -8,20 +8,20 @@ use rstest::*; /* Trying to accept a change that depends on another move */ #[rstest] -fn test_partial_move_failures(mut sandbox: SandboxManager) -> Result<()> { - let dir = sandbox.test_filename("dir"); - let dir2 = sandbox.test_filename("dir2"); +fn test_partial_move_failures(mut layer: LayerManager) -> Result<()> { + let dir = layer.test_filename("dir"); + let dir2 = layer.test_filename("dir2"); let dir2_path = Path::new(&dir2); let file = dir2_path.join("file"); create_dir(&dir)?; - sandbox.run(&["mv", dir.as_str(), dir2.as_str()])?; - sandbox.run(&["touch", file.to_str().unwrap()])?; + layer.run(&["mv", dir.as_str(), dir2.as_str()])?; + layer.run(&["touch", file.to_str().unwrap()])?; - sandbox.run(&["status", file.to_str().unwrap()])?; - assert!(sandbox.xfail(&["accept", file.to_str().unwrap()])); - //assert!(sandbox.last_stdout.contains("Cowardly refusing")); + layer.run(&["status", file.to_str().unwrap()])?; + assert!(layer.xfail(&["accept", file.to_str().unwrap()])); + //assert!(layer.last_stdout.contains("Cowardly refusing")); Ok(()) } diff --git a/tests/test_reject.rs b/tests/test_reject.rs index 3e83d7e..97ff81b 100644 --- a/tests/test_reject.rs +++ b/tests/test_reject.rs @@ -6,81 +6,79 @@ use rstest::*; use std::{fs::create_dir, fs::write, path::Path}; #[rstest] -fn test_reject_file(mut sandbox: SandboxManager) -> Result<()> { - let filename = sandbox.test_filename("file"); +fn test_reject_file(mut layer: LayerManager) -> Result<()> { + let filename = layer.test_filename("file"); let path = Path::new(&filename); assert!(!path.exists()); - sandbox.run(&["touch", &filename])?; + layer.run(&["touch", &filename])?; assert!(!path.exists()); - sandbox.run(&["reject", &filename])?; + layer.run(&["reject", &filename])?; assert!(!path.exists()); - sandbox.run(&["accept", &filename])?; + layer.run(&["accept", &filename])?; assert!(!path.exists()); Ok(()) } #[rstest] -fn test_reject_remove_file(mut sandbox: SandboxManager) -> Result<()> { - let filename = sandbox.test_filename("file"); +fn test_reject_remove_file(mut layer: LayerManager) -> Result<()> { + let filename = layer.test_filename("file"); let path = Path::new(&filename); write(path, "test")?; assert!(path.exists()); - sandbox.run(&["rm", &filename])?; + layer.run(&["rm", &filename])?; assert!(path.exists()); - sandbox.run(&["reject", &filename])?; + layer.run(&["reject", &filename])?; assert!(path.exists()); - sandbox.run(&["accept", &filename])?; + layer.run(&["accept", &filename])?; assert!(path.exists()); Ok(()) } #[rstest] -fn test_reject_remove_directory(mut sandbox: SandboxManager) -> Result<()> { - let dirname = sandbox.test_filename("dir"); +fn test_reject_remove_directory(mut layer: LayerManager) -> Result<()> { + let dirname = layer.test_filename("dir"); let path = Path::new(&dirname); create_dir(path)?; assert!(path.exists()); - sandbox.run(&["rm", "-r", &dirname])?; + layer.run(&["rm", "-r", &dirname])?; assert!(path.exists()); - sandbox.run(&["reject", &dirname])?; + layer.run(&["reject", &dirname])?; assert!(path.exists()); - sandbox.run(&["accept", &dirname])?; + layer.run(&["accept", &dirname])?; assert!(path.exists()); Ok(()) } #[rstest] -fn test_reject_remove_filled_directory( - mut sandbox: SandboxManager, -) -> Result<()> { - let dirname = sandbox.test_filename("dir"); +fn test_reject_remove_filled_directory(mut layer: LayerManager) -> Result<()> { + let dirname = layer.test_filename("dir"); let path = Path::new(&dirname); create_dir(path)?; write(path.join("file"), "test")?; assert!(path.exists()); - sandbox.run(&["rm", "-r", &dirname])?; + layer.run(&["rm", "-r", &dirname])?; assert!(path.exists()); - sandbox.run(&["reject", &dirname])?; + layer.run(&["reject", &dirname])?; assert!(path.exists()); - sandbox.run(&["accept", &dirname])?; + layer.run(&["accept", &dirname])?; assert!(path.exists()); Ok(()) } #[rstest] fn test_reject_remove_filled_directory_with_opaque_directory_not_empty( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - let dirname = sandbox.test_filename("dir"); + let dirname = layer.test_filename("dir"); let path = Path::new(&dirname); create_dir(path)?; write(path.join("file"), "test")?; assert!(path.exists()); - sandbox.run(&["rm", "-r", &dirname])?; + layer.run(&["rm", "-r", &dirname])?; assert!(path.exists()); - sandbox.run(&["mkdir", &dirname])?; - sandbox.run(&["touch", path.join("file2").to_str().unwrap()])?; - assert!(sandbox.pass(&["reject", &dirname])); + layer.run(&["mkdir", &dirname])?; + layer.run(&["touch", path.join("file2").to_str().unwrap()])?; + assert!(layer.pass(&["reject", &dirname])); assert!(path.exists()); assert!(path.join("file").exists()); assert!(!path.join("file2").exists()); @@ -89,20 +87,20 @@ fn test_reject_remove_filled_directory_with_opaque_directory_not_empty( #[rstest] fn test_reject_remove_filled_directory_with_opaque_directory( - mut sandbox: SandboxManager, + mut layer: LayerManager, ) -> Result<()> { - let dirname = sandbox.test_filename("dir"); + let dirname = layer.test_filename("dir"); let path = Path::new(&dirname); create_dir(path)?; write(path.join("file"), "test")?; assert!(path.exists()); - sandbox.run(&["rm", "-r", &dirname])?; + layer.run(&["rm", "-r", &dirname])?; assert!(path.exists()); - sandbox.run(&["mkdir", &dirname])?; - sandbox.run(&["touch", path.join("file2").to_str().unwrap()])?; - sandbox.run(&["reject"])?; + layer.run(&["mkdir", &dirname])?; + layer.run(&["touch", path.join("file2").to_str().unwrap()])?; + layer.run(&["reject"])?; assert!(path.exists()); - sandbox.run(&["accept"])?; + layer.run(&["accept"])?; assert!(path.exists()); assert!(path.join("file").exists()); assert!(!path.join("file2").exists()); diff --git a/tests/test_sandbox_failures.rs b/tests/test_sandbox_failures.rs deleted file mode 100644 index ff446ae..0000000 --- a/tests/test_sandbox_failures.rs +++ /dev/null @@ -1,145 +0,0 @@ -mod fixtures; - -use anyhow::Result; -use fixtures::*; -use rstest::*; -use std::{ - path::{Path, PathBuf}, - process::Command, -}; -#[rstest] -fn test_fail_to_start_sandbox(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.exfail(&["env"], "TEST_START_SANDBOX_FAILURE", "1")); - assert!(sandbox.all_stderr.contains("Failed to start layer")); - Ok(()) -} - -#[rstest] -fn test_running_as_user(mut sandbox: SandboxManager) -> Result<()> { - sandbox.no_sudo = true; - assert!(sandbox.xfail(&["env"])); - assert!(sandbox.all_stderr.contains("Insufficient permissions")); - sandbox.no_sudo = false; // so teardown can run without errors - Ok(()) -} - -#[rstest] -fn test_recover_from_bad_pid_file() -> Result<()> { - let mut s = sandbox(); - s.run(&["config", "sandbox_dir"])?; - let storage_dir = String::from(s.last_stdout.trim()); - let mut storage_dir = PathBuf::from(&storage_dir); - storage_dir.pop(); - - let pid_file_name = format!("{}/{}.pid", storage_dir.display(), s.name); - std::fs::write(&pid_file_name, "not a number")?; - println!("pid_file_name: {}", &pid_file_name); - let pid_file = std::fs::File::open(&pid_file_name)?; - let pid_file_content = std::io::read_to_string(pid_file)?; - println!("pid_file_content: {}", pid_file_content); - - assert!(s.run(&["true"]).is_ok()); - - let pid_file = std::fs::File::open(&pid_file_name)?; - let pid_file_content = std::io::read_to_string(pid_file)?; - println!("pid_file: {} contains {}", pid_file_name, pid_file_content); - assert!(pid_file_content.parse::().is_ok()); - Ok(()) -} - -#[rstest] -fn test_lock(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run(&["config", "sandbox_dir"])?; - let sandbox_dir = String::from(sandbox.last_stdout.trim()); - let lock_file = format!("{}.lock", sandbox_dir); - println!("lock_file: {}", lock_file); - Command::new("sudo") - .args(["rm", "-f", lock_file.as_str()]) - .output()?; - std::fs::create_dir_all(&lock_file)?; - // lock file is now a directory, should fail - assert!(sandbox.xfail(&["true"])); - assert!(sandbox.all_stderr.contains("Failed to open lock")); - - // remove directory - std::fs::remove_dir(&lock_file)?; - // lock file is now a file, should succeed - assert!(sandbox.pass(&["true"])); - - Ok(()) -} - -#[rstest] -fn test_unable_to_join_sandbox(mut sandbox: SandboxManager) -> Result<()> { - assert!(sandbox.exfail(&["true"], "TEST_UNABLE_TO_JOIN_SANDBOX", "1")); - assert!( - sandbox - .last_stderr - .contains("Failed to join layer namespaces") - ); - - Ok(()) -} - -#[rstest] -fn test_rename_across_mount_points_failure( - mut sandbox: SandboxManager, -) -> Result<()> { - let test_file = sandbox.test_filename("test-file"); - let test_file2 = sandbox.test_filename("test-file2"); - std::fs::create_dir_all(&test_file)?; - sandbox.run(&["mv", test_file.as_str(), test_file2.as_str()])?; - assert!(sandbox.exfail( - &["accept"], - "TEST_RENAME_ACROSS_MOUNT_POINTS_FAILURE", - "1" - )); - assert!(sandbox.last_stderr.contains("crosses a mount point")); - Ok(()) -} - -#[rstest] -fn test_bad_staged_file(mut sandbox: SandboxManager) -> Result<()> { - let test_file = sandbox.test_filename("test-file"); - sandbox.run(&["touch", test_file.as_str()])?; - assert!(sandbox.exfail(&["accept"], "TEST_NO_STAGED_FILE", "1")); - - let test_file = sandbox.test_filename("test-file"); - sandbox.run(&["touch", test_file.as_str()])?; - assert!(sandbox.exfail(&["accept"], "TEST_BAD_STAGED_FILE", "1")); - assert!(!Path::new(test_file.as_str()).exists()); - Ok(()) -} - -#[rstest] -fn test_bad_staged_file_remove(mut sandbox: SandboxManager) -> Result<()> { - let test_file = sandbox.test_filename("test-file"); - std::fs::write(&test_file, "test")?; - sandbox.run(&["rm", test_file.as_str()])?; - assert!(sandbox.exfail(&["accept"], "TEST_NO_STAGED_FILE", "1")); - - let test_file = sandbox.test_filename("test-file"); - sandbox.run(&["touch", test_file.as_str()])?; - assert!(sandbox.exfail(&["accept"], "TEST_BAD_STAGED_FILE", "1")); - assert!(!Path::new(test_file.as_str()).exists()); - Ok(()) -} - -#[rstest] -fn test_remove_underlying_dir_failure( - mut sandbox: SandboxManager, -) -> Result<()> { - let test_dir = sandbox.test_filename("test-dir"); - let test_dir2 = sandbox.test_filename("test-dir2"); - std::fs::create_dir_all(&test_dir)?; - sandbox.run(&["mv", test_dir.as_str(), test_dir2.as_str()])?; - std::fs::remove_dir(&test_dir)?; - assert!(sandbox.pass(&["status"])); - let last_stdout = sandbox.last_stdout.clone(); - assert!(last_stdout.contains("Redirect path not found")); - - assert!(sandbox.xfail(&["accept"])); - assert!(last_stdout.contains("Redirect path not found")); - - Ok(()) -} diff --git a/tests/test_status.rs b/tests/test_status.rs index 1f50680..f1e84ca 100644 --- a/tests/test_status.rs +++ b/tests/test_status.rs @@ -7,47 +7,47 @@ use fixtures::*; use rstest::*; #[rstest] -fn test_status(mut sandbox: SandboxManager) -> Result<()> { - let filename = sandbox.test_filename("file"); - let removed = sandbox.test_filename("removed"); - let moved = sandbox.test_filename("moved"); - let moved_2 = sandbox.test_filename("moved_2"); +fn test_status(mut layer: LayerManager) -> Result<()> { + let filename = layer.test_filename("file"); + let removed = layer.test_filename("removed"); + let moved = layer.test_filename("moved"); + let moved_2 = layer.test_filename("moved_2"); std::fs::write(&removed, "test")?; std::fs::create_dir(&moved)?; - sandbox.run(&["touch", &filename])?; - sandbox.run(&["mv", &moved, &moved_2])?; - sandbox.run(&["rm", &removed])?; + layer.run(&["touch", &filename])?; + layer.run(&["mv", &moved, &moved_2])?; + layer.run(&["rm", &removed])?; - sandbox.run(&["status", "/"])?; - assert!(sandbox.last_stdout.contains("Matching changes")); - assert!(sandbox.last_stdout.contains(&filename)); - assert!(!sandbox.last_stdout.contains("No changes in")); - println!("{}", sandbox.last_stdout); + layer.run(&["status", "/"])?; + assert!(layer.last_stdout.contains("Matching changes")); + assert!(layer.last_stdout.contains(&filename)); + assert!(!layer.last_stdout.contains("No changes in")); + println!("{}", layer.last_stdout); assert!( - !sandbox + !layer .last_stdout .contains("external or non-matching changes") ); - assert!(sandbox.last_stdout.contains(&format!("> {}", &moved))); - assert!(sandbox.last_stdout.contains(&format!("- {}", &removed))); + assert!(layer.last_stdout.contains(&format!("> {}", &moved))); + assert!(layer.last_stdout.contains(&format!("- {}", &removed))); - sandbox.run(&["status", "/", &filename])?; - assert!(sandbox.last_stdout.contains("Matching changes")); - assert!(sandbox.last_stdout.contains(&filename)); - assert!(!sandbox.last_stdout.contains("No changes in")); + layer.run(&["status", "/", &filename])?; + assert!(layer.last_stdout.contains("Matching changes")); + assert!(layer.last_stdout.contains(&filename)); + assert!(!layer.last_stdout.contains("No changes in")); assert!( - !sandbox + !layer .last_stdout .contains("external or non-matching changes") ); - sandbox.run(&["status", "/", "foobar"])?; - assert!(sandbox.last_stdout.contains("Matching changes")); - assert!(sandbox.last_stdout.contains(&filename)); + layer.run(&["status", "/", "foobar"])?; + assert!(layer.last_stdout.contains("Matching changes")); + assert!(layer.last_stdout.contains(&filename)); assert!( - !sandbox + !layer .last_stdout .contains("external or non-matching changes") ); @@ -56,55 +56,55 @@ fn test_status(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_status_outside(mut sandbox: SandboxManager) -> Result<()> { +fn test_status_outside(mut layer: LayerManager) -> Result<()> { let filename = "/tmp/test"; - sandbox.run(&["touch", filename])?; - sandbox.run(&["status"])?; - println!("{}", sandbox.last_stdout); + layer.run(&["touch", filename])?; + layer.run(&["status"])?; + println!("{}", layer.last_stdout); assert!( - sandbox + layer .last_stdout .contains("external or non-matching changes") ); - sandbox.run(&["status", "/", filename])?; - println!("{}", sandbox.last_stdout); - assert!(sandbox.last_stdout.contains("Matching changes")); - assert!(sandbox.last_stdout.contains(filename)); + layer.run(&["status", "/", filename])?; + println!("{}", layer.last_stdout); + assert!(layer.last_stdout.contains("Matching changes")); + assert!(layer.last_stdout.contains(filename)); Ok(()) } #[rstest] -fn test_status_no_matching_changes(mut sandbox: SandboxManager) -> Result<()> { +fn test_status_no_matching_changes(mut layer: LayerManager) -> Result<()> { let filename = "/tmp/test"; - sandbox.run(&["touch", filename])?; - sandbox.run(&["status", "not-the-file-name"])?; - assert!(sandbox.last_stdout.contains("No matching changes")); + layer.run(&["touch", filename])?; + layer.run(&["status", "not-the-file-name"])?; + assert!(layer.last_stdout.contains("No matching changes")); Ok(()) } #[rstest] -fn test_status_changed_attributes(mut sandbox: SandboxManager) -> Result<()> { - let mode_file = sandbox.test_filename("mode"); - let uid_file = sandbox.test_filename("uid"); - let gid_file = sandbox.test_filename("gid"); +fn test_status_changed_attributes(mut layer: LayerManager) -> Result<()> { + let mode_file = layer.test_filename("mode"); + let uid_file = layer.test_filename("uid"); + let gid_file = layer.test_filename("gid"); std::fs::write(&mode_file, "test")?; std::fs::write(&uid_file, "test")?; std::fs::write(&gid_file, "test")?; - sandbox.run(&["touch", mode_file.as_str()])?; - sandbox.run(&["touch", uid_file.as_str()])?; - sandbox.run(&["touch", gid_file.as_str()])?; + layer.run(&["touch", mode_file.as_str()])?; + layer.run(&["touch", uid_file.as_str()])?; + layer.run(&["touch", gid_file.as_str()])?; - assert!(sandbox.pass(&["status"])); - assert!(!sandbox.last_stderr.contains(&mode_file)); - assert!(!sandbox.last_stderr.contains(&uid_file)); - assert!(!sandbox.last_stderr.contains(&gid_file)); + assert!(layer.pass(&["status"])); + assert!(!layer.last_stderr.contains(&mode_file)); + assert!(!layer.last_stderr.contains(&uid_file)); + assert!(!layer.last_stderr.contains(&gid_file)); - sandbox.run(&["chmod", "777", mode_file.as_str()])?; - assert!(sandbox.pass(&["status"])); - assert!(sandbox.last_stderr.contains(&mode_file)); - assert!(!sandbox.last_stderr.contains(&uid_file)); - assert!(!sandbox.last_stderr.contains(&gid_file)); + layer.run(&["chmod", "777", mode_file.as_str()])?; + assert!(layer.pass(&["status"])); + assert!(layer.last_stderr.contains(&mode_file)); + assert!(!layer.last_stderr.contains(&uid_file)); + assert!(!layer.last_stderr.contains(&gid_file)); Command::new("sudo") .args(["chown", "2", uid_file.as_str()]) @@ -113,34 +113,30 @@ fn test_status_changed_attributes(mut sandbox: SandboxManager) -> Result<()> { .args(["chgrp", "2", gid_file.as_str()]) .output()?; - sandbox.run(&["chmod", "777", uid_file.as_str()])?; - assert!(sandbox.pass(&["status"])); - assert!(sandbox.last_stderr.contains(&mode_file)); - assert!(sandbox.last_stderr.contains(&uid_file)); - assert!(sandbox.last_stderr.contains(&gid_file)); + layer.run(&["chmod", "777", uid_file.as_str()])?; + assert!(layer.pass(&["status"])); + assert!(layer.last_stderr.contains(&mode_file)); + assert!(layer.last_stderr.contains(&uid_file)); + assert!(layer.last_stderr.contains(&gid_file)); Ok(()) } #[rstest] -fn test_external_changes(mut sandbox: SandboxManager) -> Result<()> { +fn test_external_changes(mut layer: LayerManager) -> Result<()> { let filename = "/tmp/test-external-changes-pre"; std::fs::write(filename, "test")?; - sandbox.run(&["touch", "/tmp/test-external-changes-post"])?; - sandbox.run(&[ + layer.run(&["touch", "/tmp/test-external-changes-post"])?; + layer.run(&[ "bash", "-c", "echo 'test2' > /tmp/test-external-changes-pre", ])?; - sandbox.run(&["status", "/"])?; - assert!(sandbox.last_stdout.contains("Matching changes")); + layer.run(&["status", "/"])?; + assert!(layer.last_stdout.contains("Matching changes")); + assert!(layer.last_stdout.contains("/tmp/test-external-changes-pre")); assert!( - sandbox - .last_stdout - .contains("/tmp/test-external-changes-pre") - ); - assert!( - sandbox + layer .last_stdout .contains("/tmp/test-external-changes-post") ); @@ -151,8 +147,8 @@ fn test_external_changes(mut sandbox: SandboxManager) -> Result<()> { } #[rstest] -fn test_status_gitignore(mut sandbox: SandboxManager) -> Result<()> { - let base = PathBuf::from(&sandbox.test_filename("test")); +fn test_status_gitignore(mut layer: LayerManager) -> Result<()> { + let base = PathBuf::from(&layer.test_filename("test")); std::fs::create_dir_all(base.to_str().unwrap())?; let gitignore_path = base.join(".gitignore"); std::fs::write( @@ -173,44 +169,42 @@ space-at-end\\ ", )?; - sandbox.run(&["mkdir", base.join("empty").to_str().unwrap()])?; - sandbox.run(&["mkdir", base.join("dir1").to_str().unwrap()])?; - sandbox.run(&["mkdir", base.join("suffix").to_str().unwrap()])?; - sandbox.run(&["mkdir", "-p", base.join("two/.part").to_str().unwrap()])?; - sandbox.run(&["mkdir", base.join("anchored").to_str().unwrap()])?; - sandbox.run(&["touch", base.join("space-at-end").to_str().unwrap()])?; - sandbox.run(&["touch", base.join("space-at-end ").to_str().unwrap()])?; - - sandbox.run(&["touch", base.join("dir1/file1").to_str().unwrap()])?; - sandbox.run(&["touch", base.join("suffix/file2").to_str().unwrap()])?; - sandbox.run(&["touch", base.join("two/.part/file3").to_str().unwrap()])?; - sandbox.run(&["touch", base.join("anchored/file4").to_str().unwrap()])?; - - sandbox.run(&["touch", base.join("dir1/present1").to_str().unwrap()])?; - sandbox.run(&["touch", base.join("suffix/present2").to_str().unwrap()])?; - sandbox - .run(&["touch", base.join("two/.part/present3").to_str().unwrap()])?; - sandbox - .run(&["touch", base.join("anchored/present4").to_str().unwrap()])?; - - sandbox.set_ignored(false); - sandbox.run(&["status", base.to_str().unwrap()])?; - - println!("{}", sandbox.last_stderr); - println!("{}", sandbox.last_stdout); - - assert!(!sandbox.last_stdout.contains("space-at-end ")); - assert!(!sandbox.last_stdout.contains("empty")); - assert!(!sandbox.last_stdout.contains("file1")); - assert!(!sandbox.last_stdout.contains("file2")); - assert!(!sandbox.last_stdout.contains("file3")); - assert!(!sandbox.last_stdout.contains("file4")); - - assert!(sandbox.last_stdout.contains("space-at-end")); - assert!(sandbox.last_stdout.contains("present1")); - assert!(sandbox.last_stdout.contains("present2")); - assert!(sandbox.last_stdout.contains("present3")); - assert!(sandbox.last_stdout.contains("present4")); + layer.run(&["mkdir", base.join("empty").to_str().unwrap()])?; + layer.run(&["mkdir", base.join("dir1").to_str().unwrap()])?; + layer.run(&["mkdir", base.join("suffix").to_str().unwrap()])?; + layer.run(&["mkdir", "-p", base.join("two/.part").to_str().unwrap()])?; + layer.run(&["mkdir", base.join("anchored").to_str().unwrap()])?; + layer.run(&["touch", base.join("space-at-end").to_str().unwrap()])?; + layer.run(&["touch", base.join("space-at-end ").to_str().unwrap()])?; + + layer.run(&["touch", base.join("dir1/file1").to_str().unwrap()])?; + layer.run(&["touch", base.join("suffix/file2").to_str().unwrap()])?; + layer.run(&["touch", base.join("two/.part/file3").to_str().unwrap()])?; + layer.run(&["touch", base.join("anchored/file4").to_str().unwrap()])?; + + layer.run(&["touch", base.join("dir1/present1").to_str().unwrap()])?; + layer.run(&["touch", base.join("suffix/present2").to_str().unwrap()])?; + layer.run(&["touch", base.join("two/.part/present3").to_str().unwrap()])?; + layer.run(&["touch", base.join("anchored/present4").to_str().unwrap()])?; + + layer.set_ignored(false); + layer.run(&["status", base.to_str().unwrap()])?; + + println!("{}", layer.last_stderr); + println!("{}", layer.last_stdout); + + assert!(!layer.last_stdout.contains("space-at-end ")); + assert!(!layer.last_stdout.contains("empty")); + assert!(!layer.last_stdout.contains("file1")); + assert!(!layer.last_stdout.contains("file2")); + assert!(!layer.last_stdout.contains("file3")); + assert!(!layer.last_stdout.contains("file4")); + + assert!(layer.last_stdout.contains("space-at-end")); + assert!(layer.last_stdout.contains("present1")); + assert!(layer.last_stdout.contains("present2")); + assert!(layer.last_stdout.contains("present3")); + assert!(layer.last_stdout.contains("present4")); Ok(()) } From 92ffd730dcc9fad0f4fbac4da83948bc34d650f4 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 05:56:12 -0500 Subject: [PATCH 04/32] Replace --name with --join --- README.adoc | 16 ++--- src/config/cli.rs | 8 +-- src/config/resolve.rs | 30 +++++----- src/config/structs.rs | 2 +- tests/ai_cli_flags.rs | 28 ++++----- tests/ai_test_bind_mounts.rs | 4 +- tests/ai_test_error_paths.rs | 2 +- tests/ai_test_ignore_rules.rs | 2 +- tests/ai_test_join.rs | 62 ++++++++++++++++++++ tests/fixtures/fixture_layer.rs | 12 ++-- tests/isolated_test_stop_all.rs | 8 +-- tests/isolated_test_stop_all_partial_fail.rs | 6 +- tests/isolated_test_stop_pattern.rs | 6 +- tests/isolated_test_stop_stops_children.rs | 6 +- tests/test_cli.rs | 12 ++-- tests/test_misc.rs | 14 ++--- tests/test_new_last.rs | 10 ++-- 17 files changed, 145 insertions(+), 83 deletions(-) create mode 100644 tests/ai_test_join.rs diff --git a/README.adoc b/README.adoc index 2252437..beb99a7 100644 --- a/README.adoc +++ b/README.adoc @@ -137,7 +137,7 @@ Synchronize changes that might have occurred in your host file system so that th Kill all processes in the layer and unmount the filesystems. Note this will not reject any changes `delete [PATTERNS]`:: -Stop and delete all files associated with the layers matching the provided patterns. If no patterns are provided, deletes the default or --name'd layer. +Stop and delete all files associated with the layers matching the provided patterns. If no patterns are provided, deletes the default or --join'ed layer. `clean`:: Delete stopped ephemeral layers (created with `--new`) that are more than a week old, and all layers left behind by the test suite. @@ -151,17 +151,17 @@ Print this message or the help of the given subcommand(s) `-v, --log-level=`:: Set the log level to one of trace, debug, info, warn, or error. `-v` is shorthand for enabling verbose (trace) logging. -`--name=`:: -Name of the layer, defaults to "devlayer". Executables run within the same layer +`--join=`:: +Join the named layer, creating it if it does not exist yet. Defaults to "devlayer". Executables run within the same layer name will be run in the same container. `--new`:: Create a new layer with an auto-generated timestamp name. This is useful for -creating ephemeral layers for one-off tasks. Cannot be used with --name or --last. +creating ephemeral layers for one-off tasks. Cannot be used with --join or --last. `--last`:: Use the most recently created layer. This is useful for quickly returning to -the last layer you were working in. Cannot be used with --name or --new. +the last layer you were working in. Cannot be used with --join or --new. `--storage-dir=`:: Base storage directory for all layers. Defaults to `~/.devlayer/` @@ -276,8 +276,8 @@ When invoked `devlayer` will look for files named `.devlayer.conf` and `.devlaye These config files can set most of the CLI options: ``` - # Name of the layer - name="my-layer" + # Name of the layer to join (like --join) + join="my-layer" # Path to the directory where the layer will store its data storage_dir="/path/to/devlayer/storage" @@ -311,7 +311,7 @@ These config files can set most of the CLI options: You can also set most of the options with environment variables if you wish: ``` - DEVLAYER_NAME="my-layer" + DEVLAYER_JOIN="my-layer" DEVLAYER_STORAGE_DIR="/path/to/devlayer/storage" DEVLAYER_NET="none" DEVLAYER_LOG_LEVEL="info" diff --git a/src/config/cli.rs b/src/config/cli.rs index 91804ee..eb09b05 100644 --- a/src/config/cli.rs +++ b/src/config/cli.rs @@ -23,16 +23,16 @@ pub struct Args { )] pub log_level: Option, - /// Name of the layer, defaults to "devlayer" + /// Join the named layer, creating it if it does not exist yet #[arg(long, global = true, value_hint = clap::ValueHint::Other, add = ArgValueCompleter::new(layer_name_completion), conflicts_with_all = &["new", "last"])] - pub name: Option, + pub join: Option, /// Create a new layer with an auto-generated timestamp name - #[arg(long, global = true, conflicts_with_all = &["name", "last"])] + #[arg(long, global = true, conflicts_with_all = &["join", "last"])] pub new: bool, /// Use the most recently created layer - #[arg(long, global = true, conflicts_with_all = &["name", "new"])] + #[arg(long, global = true, conflicts_with_all = &["join", "new"])] pub last: bool, /// Base storage directory for all layers. Defaults to `~/.devlayer/` diff --git a/src/config/resolve.rs b/src/config/resolve.rs index 615b530..42e4924 100644 --- a/src/config/resolve.rs +++ b/src/config/resolve.rs @@ -69,11 +69,11 @@ pub fn resolve_config(cli: Args) -> Result { // Check for mutually exclusive name options if (cli.new || cli.last) - && (partial_config.name.is_some() || env::var("DEVLAYER_NAME").is_ok()) + && (partial_config.join.is_some() || env::var("DEVLAYER_JOIN").is_ok()) { - // If --new or --last is specified, name must not be provided via env or config + // If --new or --last is specified, join must not be provided via env or config return Err(anyhow::anyhow!( - "Cannot use --new or --last when name is specified in config file or environment variable" + "Cannot use --new or --last when join is specified in config file or environment variable" )); } @@ -87,9 +87,9 @@ pub fn resolve_config(cli: Args) -> Result { } } if !cli.new && !cli.last { - if let Ok(name) = env::var("DEVLAYER_NAME") { + if let Ok(name) = env::var("DEVLAYER_JOIN") { if !name.is_empty() { - partial_config.name = Some(name); + partial_config.join = Some(name); sources.insert("name".into(), "environment".into()); } } @@ -203,7 +203,7 @@ pub fn resolve_config(cli: Args) -> Result { uid_gid_home.uid, uid_gid_home.gid, )?; - partial_config.name = Some(name); + partial_config.join = Some(name); sources.insert("name".into(), "cli --new".into()); } else if cli.last { // Find the most recently created layer @@ -212,11 +212,11 @@ pub fn resolve_config(cli: Args) -> Result { uid_gid_home.uid, uid_gid_home.gid, )?; - partial_config.name = Some(name); + partial_config.join = Some(name); sources.insert("name".into(), "cli --last".into()); - } else if let Some(name) = cli.name { - partial_config.name = Some(name); - sources.insert("name".into(), "cli".into()); + } else if let Some(name) = cli.join { + partial_config.join = Some(name); + sources.insert("name".into(), "cli --join".into()); } if let Some(net) = cli.net { @@ -261,7 +261,7 @@ pub fn resolve_config(cli: Args) -> Result { bind_layers.push(cli_bind_layer); // If nothing else, fill in with some default values - let name = partial_config.name.unwrap_or("devlayer".to_string()); + let name = partial_config.join.unwrap_or("devlayer".to_string()); if !sources.contains_key("name") { sources.insert("name".into(), "default".into()); } @@ -740,8 +740,8 @@ fn merge_configs( base.log_level = Some(log_level); sources.insert("log_level".into(), source.into()); } - if let Some(name) = override_config.name { - base.name = Some(name); + if let Some(name) = override_config.join { + base.join = Some(name); sources.insert("name".into(), source.into()); } if let Some(storage_dir) = override_config.storage_dir { @@ -1036,7 +1036,7 @@ mod tests { let override_config = PartialConfig { log_level: Some(LevelFilter::Debug), - name: Some("test-layer".to_string()), + join: Some("test-layer".to_string()), storage_dir: Some("/tmp/test".to_string()), net: Some(Network::Host), ignored: Some(true), @@ -1068,7 +1068,7 @@ mod tests { // Verify all fields were merged assert_eq!(base.log_level, Some(LevelFilter::Debug)); - assert_eq!(base.name, Some("test-layer".to_string())); + assert_eq!(base.join, Some("test-layer".to_string())); assert_eq!(base.storage_dir, Some("/tmp/test".to_string())); assert!(matches!(base.net, Some(Network::Host))); assert_eq!(base.ignored, Some(true)); diff --git a/src/config/structs.rs b/src/config/structs.rs index d9a70b6..bf45453 100644 --- a/src/config/structs.rs +++ b/src/config/structs.rs @@ -53,7 +53,7 @@ pub enum Network { pub struct PartialConfig { #[serde(deserialize_with = "deserialize_level_filter", default)] pub log_level: Option, - pub name: Option, + pub join: Option, pub storage_dir: Option, pub net: Option, pub ignored: Option, diff --git a/tests/ai_cli_flags.rs b/tests/ai_cli_flags.rs index d57b64a..5b95e56 100644 --- a/tests/ai_cli_flags.rs +++ b/tests/ai_cli_flags.rs @@ -11,30 +11,30 @@ fn test_flags_before_action(mut layer: LayerManager) -> Result<()> { let name = layer.name.clone(); // Test flags before action - traditional style - assert!(layer.pass(&["--name", &name, "config"])); + assert!(layer.pass(&["--join", &name, "config"])); assert!( layer .last_stdout .contains(format!("name={}", name).as_str()) ); - assert!(layer.pass(&["--name", &name, "--net=host", "config"])); + assert!(layer.pass(&["--join", &name, "--net=host", "config"])); assert!(layer.last_stdout.contains("net=host")); - assert!(layer.pass(&["--name", &name, "-v", "config"])); + assert!(layer.pass(&["--join", &name, "-v", "config"])); assert!(layer.last_stdout.contains("log_level=TRACE")); - assert!(layer.pass(&["--name", &name, "--log-level=debug", "config"])); + assert!(layer.pass(&["--join", &name, "--log-level=debug", "config"])); assert!(layer.last_stdout.contains("log_level=DEBUG")); - assert!(layer.pass(&["--name", &name, "--json", "config"])); + assert!(layer.pass(&["--join", &name, "--json", "config"])); // JSON output should be valid JSON assert!( serde_json::from_str::(&layer.last_stdout).is_ok() ); // Test a simple action without extra flags - assert!(layer.pass(&["--name", &name, "status"])); + assert!(layer.pass(&["--join", &name, "status"])); Ok(()) } @@ -46,26 +46,26 @@ fn test_flags_after_action(mut layer: LayerManager) -> Result<()> { let name = layer.name.clone(); // Test flags after action - new flexible style - assert!(layer.pass(&["config", "--name", "test-after"])); + assert!(layer.pass(&["config", "--join", "test-after"])); assert!(layer.last_stdout.contains("name=test-after")); - assert!(layer.pass(&["--name", &name, "config", "--net=host"])); + assert!(layer.pass(&["--join", &name, "config", "--net=host"])); assert!(layer.last_stdout.contains("net=host")); - assert!(layer.pass(&["--name", &name, "config", "-v"])); + assert!(layer.pass(&["--join", &name, "config", "-v"])); assert!(layer.last_stdout.contains("log_level=TRACE")); - assert!(layer.pass(&["--name", &name, "config", "--log-level=debug"])); + assert!(layer.pass(&["--join", &name, "config", "--log-level=debug"])); assert!(layer.last_stdout.contains("log_level=DEBUG")); - assert!(layer.pass(&["--name", &name, "config", "--json"])); + assert!(layer.pass(&["--join", &name, "config", "--json"])); // JSON output should be valid JSON assert!( serde_json::from_str::(&layer.last_stdout).is_ok() ); // Test a simple action without extra flags - assert!(layer.pass(&["--name", &name, "status"])); + assert!(layer.pass(&["--join", &name, "status"])); Ok(()) } @@ -73,7 +73,7 @@ fn test_flags_after_action(mut layer: LayerManager) -> Result<()> { #[rstest] fn test_flags_mixed_position(mut layer: LayerManager) -> Result<()> { // Test mixing flags before and after action - assert!(layer.pass(&["--name", "test-mixed", "config", "--net=host"])); + assert!(layer.pass(&["--join", "test-mixed", "config", "--net=host"])); assert!(layer.last_stdout.contains("name=test-mixed")); assert!(layer.last_stdout.contains("net=host")); @@ -81,7 +81,7 @@ fn test_flags_mixed_position(mut layer: LayerManager) -> Result<()> { assert!(layer.last_stdout.contains("log_level=TRACE")); assert!(layer.last_stdout.contains("net=none")); - assert!(layer.pass(&["--json", "config", "--name=json-test", "-v"])); + assert!(layer.pass(&["--json", "config", "--join=json-test", "-v"])); let json: serde_json::Value = serde_json::from_str(&layer.last_stdout)?; assert_eq!(json["name"], "json-test"); assert_eq!(json["log_level"], "TRACE"); diff --git a/tests/ai_test_bind_mounts.rs b/tests/ai_test_bind_mounts.rs index 9bd6402..c3c46a2 100644 --- a/tests/ai_test_bind_mounts.rs +++ b/tests/ai_test_bind_mounts.rs @@ -456,7 +456,7 @@ fn test_bind_mount_empty_destination() -> Result<()> { // Run a command that will definitely create a new layer and process bind mounts assert!(layer.pass(&[ - "--name", + "--join", &test_name, "--bind", &format!("{}:", tmp), @@ -484,7 +484,7 @@ fn test_bind_mount_empty_destination_with_sudo() -> Result<()> { let output = std::process::Command::new("sudo") .arg("-E") .arg(env!("CARGO_BIN_EXE_devlayer")) - .arg("--name") + .arg("--join") .arg(&unique_name) .arg("--bind") .arg(format!("{}:", tmp)) // Empty destination after colon diff --git a/tests/ai_test_error_paths.rs b/tests/ai_test_error_paths.rs index 973265c..8d0ddbd 100644 --- a/tests/ai_test_error_paths.rs +++ b/tests/ai_test_error_paths.rs @@ -46,7 +46,7 @@ fn ai_test_new_with_unusable_storage_dir( ) -> Result<()> { // --new looks for an unused name in the storage directory, which fails // when the storage directory can't be used. --new conflicts with the - // --name the fixture normally adds. + // --join the fixture normally adds. layer.no_default_options = true; let storage_dir = format!("--storage-dir=/proc/devlayer-coverage-{}", rid()); diff --git a/tests/ai_test_ignore_rules.rs b/tests/ai_test_ignore_rules.rs index 4a10ad9..c09badb 100644 --- a/tests/ai_test_ignore_rules.rs +++ b/tests/ai_test_ignore_rules.rs @@ -724,7 +724,7 @@ fn test_env_flag_includes_ignored(mut layer: LayerManager) -> Result<()> { .args([ "-v", "--ignored", - &format!("--name={}", &layer.name), + &format!("--join={}", &layer.name), "status", &test_dir, ]) diff --git a/tests/ai_test_join.rs b/tests/ai_test_join.rs new file mode 100644 index 0000000..c41f1db --- /dev/null +++ b/tests/ai_test_join.rs @@ -0,0 +1,62 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use rstest::*; +use std::path::Path; + +/// `--join` creates the named layer if needed, and later runs with the same +/// name reuse it. +#[rstest] +fn ai_test_join_creates_then_reuses(mut layer: LayerManager) -> Result<()> { + let join = format!("--join={}", layer.name); + let file = layer.test_filename("joined"); + + layer.run(&[&join, "touch", &file])?; + layer.run(&[&join, "test", "-f", &file])?; + + // The file only exists in the layer, not on the host + assert!(!Path::new(&file).exists()); + Ok(()) +} + +/// `--name` no longer exists. +#[rstest] +fn ai_test_name_flag_removed(mut layer: LayerManager) -> Result<()> { + layer.no_default_options = true; + let name = format!("--name={}-name", layer.name); + assert!(layer.xfail(&[&name, "config", "name"])); + assert!(layer.last_stderr.contains("--name")); + Ok(()) +} + +/// DEVLAYER_JOIN and the `join` config key select the layer like --join. +#[rstest] +fn ai_test_join_env_and_config(mut layer: LayerManager) -> Result<()> { + layer.no_default_options = true; + let name = layer.name.clone(); + + layer.run_with_env(&["config", "name"], "DEVLAYER_JOIN", &name)?; + assert_eq!(layer.last_stdout.trim(), name); + + let config = layer.test_filename("join.toml"); + std::fs::write(&config, format!("join = \"{}\"\n", name))?; + let config_arg = format!("--config={}", config); + layer.run(&[&config_arg, "config", "name"])?; + assert_eq!(layer.last_stdout.trim(), name); + Ok(()) +} + +/// --join cannot be combined with --new or --last, from the CLI or env. +#[rstest] +fn ai_test_join_conflicts_with_new_last(mut layer: LayerManager) -> Result<()> { + layer.no_default_options = true; + let join = format!("--join={}", layer.name); + + assert!(layer.xfail(&[&join, "--new", "config", "name"])); + assert!(layer.xfail(&[&join, "--last", "config", "name"])); + + assert!(layer.exfail(&["--new", "config", "name"], "DEVLAYER_JOIN", "x")); + assert!(layer.last_stderr.contains("Cannot use --new or --last")); + Ok(()) +} diff --git a/tests/fixtures/fixture_layer.rs b/tests/fixtures/fixture_layer.rs index e35bdb6..2f1eeed 100644 --- a/tests/fixtures/fixture_layer.rs +++ b/tests/fixtures/fixture_layer.rs @@ -122,7 +122,7 @@ impl LayerManager { cmd = Command::new(&self.devlayer_bin); } - cmd.args([format!("--name={}", &self.name)]); + cmd.args([format!("--join={}", &self.name)]); cmd.args(["config", "layer_dir"]); let output = cmd.output()?; let base = String::from_utf8_lossy(&output.stdout).to_string(); @@ -181,9 +181,9 @@ impl LayerManager { cmd.args(["--no-config"]); if !self.no_default_options - && !args.iter().any(|arg| arg.starts_with("--name")) + && !args.iter().any(|arg| arg.starts_with("--join")) { - cmd.args([format!("--name={}", &self.name)]); + cmd.args([format!("--join={}", &self.name)]); } cmd.args(args); @@ -272,9 +272,9 @@ impl LayerManager { } if !self.no_default_options - && !args.iter().any(|arg| arg.starts_with("--name")) + && !args.iter().any(|arg| arg.starts_with("--join")) { - cmd.args([format!("--name={}", &self.name)]); + cmd.args([format!("--join={}", &self.name)]); } cmd.args(args); println!( @@ -327,7 +327,7 @@ impl LayerManager { } if !self.no_default_options { - cmd.args([format!("--name={}", &self.name)]); + cmd.args([format!("--join={}", &self.name)]); } cmd.args(args); diff --git a/tests/isolated_test_stop_all.rs b/tests/isolated_test_stop_all.rs index 8124204..7881480 100644 --- a/tests/isolated_test_stop_all.rs +++ b/tests/isolated_test_stop_all.rs @@ -26,8 +26,8 @@ fn test_stop_all() -> Result<()> { let lines: Vec<&str> = ps_output .lines() .filter(|line| { - // excluding --name excludes the layer binary call lines - line.contains("sleep 9897135") && !line.contains("--name") + // excluding --join excludes the layer binary call lines + line.contains("sleep 9897135") && !line.contains("--join") }) .collect(); if lines.len() == 2 { @@ -46,7 +46,7 @@ fn test_stop_all() -> Result<()> { let lines: Vec<&str> = ps_output .lines() .filter(|line| { - line.contains("sleep 9897135") && !line.contains("--name") + line.contains("sleep 9897135") && !line.contains("--join") }) .collect(); println!("lines.len(): {:?}", lines.len()); @@ -65,7 +65,7 @@ fn test_stop_all() -> Result<()> { let lines: Vec<&str> = ps_output .lines() .filter(|line| { - line.contains("sleep 9897135") && !line.contains("--name") + line.contains("sleep 9897135") && !line.contains("--join") }) .collect(); assert!(lines.is_empty()); diff --git a/tests/isolated_test_stop_all_partial_fail.rs b/tests/isolated_test_stop_all_partial_fail.rs index ab9db97..e3a3611 100644 --- a/tests/isolated_test_stop_all_partial_fail.rs +++ b/tests/isolated_test_stop_all_partial_fail.rs @@ -40,7 +40,7 @@ fn test_stop_all_partial_fail() -> Result<()> { let lines: Vec<&str> = ps_output .lines() .filter(|line| { - line.contains("sleep 9897135") && !line.contains("--name") + line.contains("sleep 9897135") && !line.contains("--join") }) .collect(); if lines.len() == 2 { @@ -54,7 +54,7 @@ fn test_stop_all_partial_fail() -> Result<()> { let lines: Vec<&str> = ps_output .lines() .filter(|line| { - line.contains("sleep 9897135") && !line.contains("--name") + line.contains("sleep 9897135") && !line.contains("--join") }) .collect(); assert!(lines.len() == 2); @@ -67,7 +67,7 @@ fn test_stop_all_partial_fail() -> Result<()> { let lines: Vec<&str> = ps_output .lines() .filter(|line| { - line.contains("sleep 9897135") && !line.contains("--name") + line.contains("sleep 9897135") && !line.contains("--join") }) .collect(); assert!(lines.is_empty()); diff --git a/tests/isolated_test_stop_pattern.rs b/tests/isolated_test_stop_pattern.rs index edf4f5a..83e288c 100644 --- a/tests/isolated_test_stop_pattern.rs +++ b/tests/isolated_test_stop_pattern.rs @@ -24,7 +24,7 @@ fn test_stop_pattern() -> Result<()> { let lines: Vec<&str> = ps_output .lines() .filter(|line| { - line.contains("sleep 9897135") && !line.contains("--name") + line.contains("sleep 9897135") && !line.contains("--join") }) .collect(); if lines.len() == 2 { @@ -38,7 +38,7 @@ fn test_stop_pattern() -> Result<()> { let lines: Vec<&str> = ps_output .lines() .filter(|line| { - line.contains("sleep 9897135") && !line.contains("--name") + line.contains("sleep 9897135") && !line.contains("--join") }) .collect(); assert!(lines.len() == 2); @@ -51,7 +51,7 @@ fn test_stop_pattern() -> Result<()> { let lines: Vec<&str> = ps_output .lines() .filter(|line| { - line.contains("sleep 9897135") && !line.contains("--name") + line.contains("sleep 9897135") && !line.contains("--join") }) .collect(); assert!(lines.len() == 1); diff --git a/tests/isolated_test_stop_stops_children.rs b/tests/isolated_test_stop_stops_children.rs index 12be982..8f13822 100644 --- a/tests/isolated_test_stop_stops_children.rs +++ b/tests/isolated_test_stop_stops_children.rs @@ -20,7 +20,7 @@ fn test_stop_stop_children(mut layer: LayerManager) -> Result<()> { let lines: Vec<&str> = ps_output .lines() .filter(|line| { - line.contains("sleep 9897135") && !line.contains("--name") + line.contains("sleep 9897135") && !line.contains("--join") }) .collect(); if lines.len() == 2 { @@ -34,7 +34,7 @@ fn test_stop_stop_children(mut layer: LayerManager) -> Result<()> { let lines: Vec<&str> = ps_output .lines() .filter(|line| { - line.contains("sleep 9897135") && !line.contains("--name") + line.contains("sleep 9897135") && !line.contains("--join") }) .collect(); assert!(lines.len() == 2); @@ -52,7 +52,7 @@ fn test_stop_stop_children(mut layer: LayerManager) -> Result<()> { let lines: Vec<&str> = ps_output .lines() .filter(|line| { - line.contains("sleep 9897135") && !line.contains("--name") + line.contains("sleep 9897135") && !line.contains("--join") }) .collect(); assert!(lines.is_empty()); diff --git a/tests/test_cli.rs b/tests/test_cli.rs index 31e6122..9c4f3f5 100644 --- a/tests/test_cli.rs +++ b/tests/test_cli.rs @@ -18,9 +18,9 @@ fn test_cli(mut layer: LayerManager) -> Result<()> { assert!(layer.last_stdout.contains("net=host")); assert!(layer.xfail(&["--net=foobar", "config"])); - assert!(layer.pass(&["--name", "test-cli", "config"])); + assert!(layer.pass(&["--join", "test-cli", "config"])); assert!(layer.last_stdout.contains("name=test-cli")); - assert!(layer.pass(&["--name=test-cli", "config"])); + assert!(layer.pass(&["--join=test-cli", "config"])); assert!(layer.last_stdout.contains("name=test-cli")); assert!(layer.pass(&["--storage-dir=/tmp/layer", "config"])); @@ -46,14 +46,14 @@ fn test_cli(mut layer: LayerManager) -> Result<()> { fn test_cli_with_config(mut layer: LayerManager) -> Result<()> { let parent_config = r#" net = "none" - name = "parent" + join = "parent" log_level = "trace" storage_dir = "/tmp/layer1" bind = [".cargo"] "#; let config = r#" net = "host" - name = "test-cli-with-config" + join = "test-cli-with-config" log_level = "info" storage_dir = "/tmp/layer2" bind = [".cargo"] @@ -102,8 +102,8 @@ fn test_cli_with_env(mut layer: LayerManager) -> Result<()> { assert!(layer.exfail(&["config"], "DEVLAYER_LOG_LEVEL", "foobar")); assert!(layer.last_stderr.contains("Invalid log level: foobar")); - assert!(layer.epass(&["config"], "DEVLAYER_NAME", "")); - assert!(layer.epass(&["config"], "DEVLAYER_NAME", "test-cli-with-env")); + assert!(layer.epass(&["config"], "DEVLAYER_JOIN", "")); + assert!(layer.epass(&["config"], "DEVLAYER_JOIN", "test-cli-with-env")); assert!(layer.epass(&["config"], "DEVLAYER_STORAGE_DIR", "")); assert!(layer.epass(&["config"], "DEVLAYER_STORAGE_DIR", "/tmp/layer")); diff --git a/tests/test_misc.rs b/tests/test_misc.rs index 276eeb8..1b2b29c 100644 --- a/tests/test_misc.rs +++ b/tests/test_misc.rs @@ -25,7 +25,7 @@ fn test_weird_sudo_env_variables(layer: LayerManager) -> Result<()> { let mut cmd = Command::new("sudo"); cmd.args(["-E", "SUDO_UID=nan", &devlayer_bin]); - cmd.args([format!("--name={}", &layer.name)]); + cmd.args([format!("--join={}", &layer.name)]); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); assert!( @@ -35,7 +35,7 @@ fn test_weird_sudo_env_variables(layer: LayerManager) -> Result<()> { let mut cmd = Command::new("sudo"); cmd.args(["-E", "SUDO_GID=nan", &devlayer_bin]); - cmd.args([format!("--name={}", &layer.name)]); + cmd.args([format!("--join={}", &layer.name)]); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); assert!( @@ -45,7 +45,7 @@ fn test_weird_sudo_env_variables(layer: LayerManager) -> Result<()> { let mut cmd = Command::new("sudo"); cmd.args(["-E", "SUDO_HOME=", &devlayer_bin]); - cmd.args([format!("--name={}", &layer.name)]); + cmd.args([format!("--join={}", &layer.name)]); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); assert!( @@ -55,7 +55,7 @@ fn test_weird_sudo_env_variables(layer: LayerManager) -> Result<()> { let mut cmd = Command::new("sudo"); cmd.args(["-E", "SUDO_HOME=~/foobar", &devlayer_bin]); - cmd.args([format!("--name={}", &layer.name)]); + cmd.args([format!("--join={}", &layer.name)]); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); @@ -66,7 +66,7 @@ fn test_weird_sudo_env_variables(layer: LayerManager) -> Result<()> { let mut cmd = Command::new("sudo"); cmd.args(["-E", "SUDO_HOME=/invalid-home-directory", &devlayer_bin]); - cmd.args([format!("--name={}", &layer.name)]); + cmd.args([format!("--join={}", &layer.name)]); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); @@ -98,7 +98,7 @@ fn test_weird_sudo_env_variables(layer: LayerManager) -> Result<()> { .as_str(), &devlayer_bin, ]); - cmd.args([format!("--name={}", &layer.name)]); + cmd.args([format!("--join={}", &layer.name)]); cmd.args(["true"]); println!("cmd: {:?}", cmd); let output = cmd.output()?; @@ -127,7 +127,7 @@ fn test_setuid_works_like_sudo(mut layer: LayerManager) -> Result<()> { let devlayer_setuid = devlayer_bin + "-setuid"; let mut cmd = Command::new(&devlayer_setuid); - cmd.args([format!("--name={}", &layer.name)]); + cmd.args([format!("--join={}", &layer.name)]); cmd.args(["whoami"]); let setuid_output = cmd.output()?; diff --git a/tests/test_new_last.rs b/tests/test_new_last.rs index dafd37d..ce26a38 100644 --- a/tests/test_new_last.rs +++ b/tests/test_new_last.rs @@ -9,11 +9,11 @@ fn test_new_last_mutual_exclusivity(mut layer: LayerManager) -> Result<()> { layer.no_default_options = true; assert!(layer.xfail(&["--new", "--last", "ls"])); - assert!(layer.xfail(&["--name=foo", "--last", "ls"])); - assert!(layer.xfail(&["--name=foo", "--new", "ls"])); - assert!(layer.xfail(&["--name=foo", "--new", "--last", "ls"])); - assert!(layer.exfail(&["--new", "ls"], "DEVLAYER_NAME", "foo")); - assert!(layer.exfail(&["--last", "ls"], "DEVLAYER_NAME", "foo")); + assert!(layer.xfail(&["--join=foo", "--last", "ls"])); + assert!(layer.xfail(&["--join=foo", "--new", "ls"])); + assert!(layer.xfail(&["--join=foo", "--new", "--last", "ls"])); + assert!(layer.exfail(&["--new", "ls"], "DEVLAYER_JOIN", "foo")); + assert!(layer.exfail(&["--last", "ls"], "DEVLAYER_JOIN", "foo")); Ok(()) } From 4e2b8c1f0ad8f80cd6af8703ee6de8d603926f3a Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 05:57:51 -0500 Subject: [PATCH 05/32] Default to host networking --- README.adoc | 9 +++++---- src/config/cli.rs | 4 ++-- src/config/resolve.rs | 2 +- tests/ai_cli_flags.rs | 6 +++--- tests/ai_test_net_default.rs | 22 ++++++++++++++++++++++ tests/test_cli.rs | 4 ++-- 6 files changed, 35 insertions(+), 12 deletions(-) create mode 100644 tests/ai_test_net_default.rs diff --git a/README.adoc b/README.adoc index beb99a7..0dc1719 100644 --- a/README.adoc +++ b/README.adoc @@ -90,7 +90,7 @@ Try that trendy web based install script in a layer first Let AIs run wild in YOLO mode without too much risk ``` - devlayer --net=host aider + devlayer aider ``` Check what files were modified @@ -167,9 +167,10 @@ the last layer you were working in. Cannot be used with --join or --new. Base storage directory for all layers. Defaults to `~/.devlayer/` `--net[=host|none]`:: -Sets network access level. With no parameter this enables host networking. The -default value is `none`, which disables network access. If you want to enable -network access by default you can store net="host" in a config file. +Sets network access level. The default is `host`, which shares your host +network. Use `--net=none` (or `net="none"` in a config file) to disable network +access. With host networking the D-Bus and systemd sockets are also bound into +the layer by default; `--no-default-binds` turns them off. `--bind[=]`:: Specify directories or files to bind into the layer bypassing the layer diff --git a/src/config/cli.rs b/src/config/cli.rs index eb09b05..b2a08e7 100644 --- a/src/config/cli.rs +++ b/src/config/cli.rs @@ -39,8 +39,8 @@ pub struct Args { #[arg(long, global = true)] pub storage_dir: Option, - /// Enable host (or other) network. Defaults to `none`, which disables network access. If you - /// want to enable network access by default you can store net="host" in a config file. + /// Set network access. Defaults to `host`. Use `--net=none` (or net="none" in a config + /// file) to disable network access. #[arg( long, global = true, diff --git a/src/config/resolve.rs b/src/config/resolve.rs index 42e4924..d7b0d27 100644 --- a/src/config/resolve.rs +++ b/src/config/resolve.rs @@ -266,7 +266,7 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("name".into(), "default".into()); } - let net = partial_config.net.unwrap_or(Network::None); + let net = partial_config.net.unwrap_or(Network::Host); if !sources.contains_key("net") { sources.insert("net".into(), "default".into()); } diff --git a/tests/ai_cli_flags.rs b/tests/ai_cli_flags.rs index 5b95e56..6f42e33 100644 --- a/tests/ai_cli_flags.rs +++ b/tests/ai_cli_flags.rs @@ -180,11 +180,11 @@ fn test_no_config_flag_positioning(mut layer: LayerManager) -> Result<()> { // Test --no-config flag in different positions assert!(layer.pass(&["--no-config", "config"])); - // Should show defaults when no config is loaded - assert!(layer.last_stdout.contains("net=none")); + // Should show defaults (host network) when no config is loaded + assert!(layer.last_stdout.contains("net=host")); assert!(layer.pass(&["config", "--no-config"])); - assert!(layer.last_stdout.contains("net=none")); + assert!(layer.last_stdout.contains("net=host")); // Test with other flags assert!(layer.pass(&["--no-config", "--net=host", "config"])); diff --git a/tests/ai_test_net_default.rs b/tests/ai_test_net_default.rs new file mode 100644 index 0000000..e700359 --- /dev/null +++ b/tests/ai_test_net_default.rs @@ -0,0 +1,22 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use rstest::*; + +/// With no flag, env var or config, layers use the host network. +#[rstest] +fn ai_test_net_defaults_to_host(mut layer: LayerManager) -> Result<()> { + layer.run(&["--no-config", "config", "net"])?; + assert_eq!(layer.last_stdout.trim(), "host"); + assert!(layer.last_stderr.contains("net=host set from default")); + Ok(()) +} + +/// `--net=none` still disables networking. +#[rstest] +fn ai_test_net_none_disables(mut layer: LayerManager) -> Result<()> { + layer.run(&["--no-config", "--net=none", "config", "net"])?; + assert_eq!(layer.last_stdout.trim(), "none"); + Ok(()) +} diff --git a/tests/test_cli.rs b/tests/test_cli.rs index 9c4f3f5..e87195a 100644 --- a/tests/test_cli.rs +++ b/tests/test_cli.rs @@ -32,8 +32,8 @@ fn test_cli(mut layer: LayerManager) -> Result<()> { // default values check layer.no_default_options = true; assert!(layer.pass(&["--no-config", "config"])); - assert!(layer.last_stdout.contains("name=layer")); - assert!(layer.last_stdout.contains("net=none")); + assert!(layer.last_stdout.contains("name=devlayer")); + assert!(layer.last_stdout.contains("net=host")); // Test config_files display assert!(layer.pass(&["--no-config", "config", "config_files"])); From 841419b41d079750d0724c7669e08b747500fd87 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 05:59:51 -0500 Subject: [PATCH 06/32] Make audio binds part of the default binds --- README.adoc | 19 ++--- src/actions/config.rs | 3 - src/config/cli.rs | 7 +- src/config/resolve.rs | 42 +--------- src/config/structs.rs | 2 - tests/ai_test_audio.rs | 142 ++++++++++---------------------- tests/ai_test_layer_settings.rs | 1 - 7 files changed, 58 insertions(+), 158 deletions(-) diff --git a/README.adoc b/README.adoc index 0dc1719..49116a0 100644 --- a/README.adoc +++ b/README.adoc @@ -197,17 +197,14 @@ Examples: * `DEVLAYER_MASK="~/.ssh,~/.aws" devlayer` works as well `--no-default-binds`:: -Disable default system bind mounts (e.g., /dev/fuse, D-Bus sockets, user directories). -This is useful when you want complete control over what gets mounted into the layer. - -`--audio`:: -Allow audio inside the layer by binding the PipeWire and PulseAudio sockets -from `$XDG_RUNTIME_DIR` and the ALSA devices in `/dev/snd`. Audio is disabled -by default because this also allows programs in the layer to record from your -microphone. Audio works with or without `--net`, and is not affected by -`--no-default-binds`. To enable audio by default you can store `audio = true` -in a config file, and `DEVLAYER_AUDIO=false` will override that for a single -run. +Disable default system bind mounts: `/dev/fuse`, the D-Bus and systemd sockets +(with host networking), and audio. This is useful when you want complete +control over what gets mounted into the layer. ++ +Audio is on by default: the PipeWire and PulseAudio sockets from +`$XDG_RUNTIME_DIR` and the ALSA devices in `/dev/snd` are bound into the layer. +Note that this also allows programs in the layer to record from your +microphone. Use `--no-default-binds` to turn audio off. `--cpus=`:: Limit how many CPUs the layer can use. Fractional values such as `1.5` are diff --git a/src/actions/config.rs b/src/actions/config.rs index 6d391f8..7238394 100644 --- a/src/actions/config.rs +++ b/src/actions/config.rs @@ -16,7 +16,6 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { "bind", "mask", "no_default_binds", - "audio", "cpus", "memory", "storage_dir", @@ -48,7 +47,6 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { .join(","); let no_default_binds_str = format!("{}", config.no_default_binds); - let audio_str = format!("{}", config.audio); let cpus_str = config .cpus .map_or("unlimited".to_string(), |cpus| cpus.to_string()); @@ -84,7 +82,6 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { "no_default_binds" => { ("no_default_binds", no_default_binds_str.as_str()) } - "audio" => ("audio", audio_str.as_str()), "cpus" => ("cpus", cpus_str.as_str()), "memory" => ("memory", memory_str.as_str()), "name" => ("name", config.name.as_str()), diff --git a/src/config/cli.rs b/src/config/cli.rs index b2a08e7..5a92468 100644 --- a/src/config/cli.rs +++ b/src/config/cli.rs @@ -72,15 +72,10 @@ pub struct Args { )] pub mask: Option>, - /// Disable default system bind mounts (e.g., /dev/fuse, D-Bus sockets, user directories) + /// Disable default system bind mounts (e.g., /dev/fuse, D-Bus sockets, audio devices, user directories) #[arg(long, global = true, action = clap::ArgAction::SetTrue)] pub no_default_binds: bool, - /// Allow access to audio devices (PipeWire, PulseAudio, and ALSA). Note this - /// also allows recording from microphones. - #[arg(long, global = true, action = clap::ArgAction::SetTrue)] - pub audio: bool, - /// Limit how many CPUs the layer can use. Fractional values such as 1.5 /// are allowed. Negative values mean all but that many CPUs, so -2 on a /// 32 CPU machine allows the layer to use 30. Use "unlimited" to remove diff --git a/src/config/resolve.rs b/src/config/resolve.rs index d7b0d27..a2789d1 100644 --- a/src/config/resolve.rs +++ b/src/config/resolve.rs @@ -161,18 +161,6 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("no_default_binds".into(), "environment".into()); } - if let Ok(audio_env) = env::var("DEVLAYER_AUDIO") { - if let Ok(audio_val) = bool::from_str(&audio_env) { - partial_config.audio = Some(audio_val); - sources.insert("audio".into(), "environment".into()); - } else { - return Err(anyhow::anyhow!( - "Invalid value for DEVLAYER_AUDIO: {}", - audio_env - )); - } - } - for (var, key, field) in [ ("DEVLAYER_CPUS", "cpus", &mut partial_config.cpus), ("DEVLAYER_MEMORY", "memory", &mut partial_config.memory), @@ -234,11 +222,6 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("no_default_binds".into(), "cli".into()); } - if cli.audio { - partial_config.audio = Some(true); - sources.insert("audio".into(), "cli".into()); - } - if let Some(cpus) = cli.cpus { partial_config.cpus = Some(cpus); sources.insert("cpus".into(), "cli".into()); @@ -281,11 +264,6 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("no_default_binds".into(), "default".into()); } - let audio = partial_config.audio.unwrap_or(false); - if !sources.contains_key("audio") { - sources.insert("audio".into(), "default".into()); - } - let cpus = partial_config .cpus .map(|cpus| parse_cpus(&cpus, available_cpus())) @@ -336,15 +314,11 @@ pub fn resolve_config(cli: Args) -> Result { .join(cwd.strip_prefix(&mp)?); sources.insert("overlay_cwd".into(), "derived from storage_dir".into()); - // Audio bind mounts sit just above the default bind mounts. They are - // explicitly requested, so --no-default-binds does not disable them. - if audio { - bind_layers.insert(0, get_audio_bind_mounts()); - } - - // Default bind mounts are the lowest precedence layer + // Default bind mounts, including audio, are the lowest precedence layer if !no_default_binds { - bind_layers.insert(0, get_default_bind_mounts(&net, &uid_gid_home)); + let mut default_binds = get_default_bind_mounts(&net, &uid_gid_home); + default_binds.extend(get_audio_bind_mounts()); + bind_layers.insert(0, default_binds); } // Resolve bind mounts layer by layer from lowest to highest precedence. @@ -395,7 +369,6 @@ pub fn resolve_config(cli: Args) -> Result { sources, bind_mounts, no_default_binds, - audio, cpus, memory, config_files, @@ -760,10 +733,6 @@ fn merge_configs( base.no_default_binds = Some(no_default_binds); sources.insert("no_default_binds".into(), source.into()); } - if let Some(audio) = override_config.audio { - base.audio = Some(audio); - sources.insert("audio".into(), source.into()); - } if let Some(cpus) = override_config.cpus { base.cpus = Some(cpus); sources.insert("cpus".into(), source.into()); @@ -968,7 +937,6 @@ mod tests { log_level: LevelFilter::Info, bind_mounts: vec![], no_default_binds: false, - audio: false, cpus: None, memory: None, config_files: vec![], @@ -1046,7 +1014,6 @@ mod tests { ]), mask: Some(vec!["/tmp/test3".to_string()]), no_default_binds: Some(true), - audio: Some(true), cpus: Some("-2".to_string()), memory: Some("4G".to_string()), }; @@ -1072,7 +1039,6 @@ mod tests { assert_eq!(base.storage_dir, Some("/tmp/test".to_string())); assert!(matches!(base.net, Some(Network::Host))); assert_eq!(base.ignored, Some(true)); - assert_eq!(base.audio, Some(true)); assert_eq!(base.cpus, Some("-2".to_string())); assert_eq!(base.memory, Some("4G".to_string())); assert_eq!(sources.get("cpus"), Some(&"test-config".to_string())); diff --git a/src/config/structs.rs b/src/config/structs.rs index bf45453..8e510fc 100644 --- a/src/config/structs.rs +++ b/src/config/structs.rs @@ -60,7 +60,6 @@ pub struct PartialConfig { pub bind: Option>, pub mask: Option>, pub no_default_binds: Option, - pub audio: Option, #[serde(deserialize_with = "deserialize_number_or_string", default)] pub cpus: Option, #[serde(deserialize_with = "deserialize_number_or_string", default)] @@ -80,7 +79,6 @@ pub struct Config { pub ignored: bool, pub bind_mounts: Vec, pub no_default_binds: bool, - pub audio: bool, /// Number of CPUs the layer may use, None for unlimited pub cpus: Option, /// Bytes of memory the layer may use, None for unlimited diff --git a/tests/ai_test_audio.rs b/tests/ai_test_audio.rs index 11b4bb4..8fa57b1 100644 --- a/tests/ai_test_audio.rs +++ b/tests/ai_test_audio.rs @@ -4,10 +4,10 @@ use anyhow::Result; use fixtures::*; use rstest::*; use std::fs; -use std::path::Path; +use std::path::{Path, PathBuf}; -/// Host paths that --audio should bind into the layer, limited to the ones -/// that exist on this machine +/// Host audio paths that are bound into the layer by default, limited to the +/// ones that exist on this machine fn host_audio_paths() -> Vec { let mut paths = vec![]; if Path::new("/dev/snd").exists() { @@ -24,105 +24,50 @@ fn host_audio_paths() -> Vec { paths } -/// Writes a config file with the given contents and returns its path -fn write_config( - layer: &LayerManager, - prefix: &str, - contents: &str, -) -> Result { - let path = format!("{}.toml", layer.test_filename(prefix)); - fs::write(&path, contents)?; - Ok(path) +/// Creates a fake XDG_RUNTIME_DIR containing a `pulse` directory and returns +/// its absolute path +fn fake_runtime_dir(layer: &LayerManager) -> Result { + let dir = std::env::current_dir()?.join(layer.test_filename("xdg")); + fs::create_dir_all(dir.join("pulse"))?; + Ok(dir) } #[rstest] -fn ai_test_audio_disabled_by_default(mut layer: LayerManager) -> Result<()> { - layer.run(&["--no-config", "config", "audio"])?; - assert_eq!(layer.last_stdout.trim(), "false"); - - layer.run(&["--no-config", "config", "bind"])?; - for path in host_audio_paths() { - assert!(!layer.last_stdout.contains(&path)); - } - - Ok(()) -} - -#[rstest] -fn ai_test_audio_flag(mut layer: LayerManager) -> Result<()> { - layer.run(&["--no-config", "--audio", "config", "audio"])?; - assert_eq!(layer.last_stdout.trim(), "true"); - - layer.run(&["--no-config", "--audio", "config", "bind"])?; - for path in host_audio_paths() { - assert!(layer.last_stdout.contains(&path)); - } - - Ok(()) -} - -#[rstest] -fn ai_test_audio_env(mut layer: LayerManager) -> Result<()> { +fn ai_test_audio_on_by_default(mut layer: LayerManager) -> Result<()> { + let xdg = fake_runtime_dir(&layer)?; layer.run_with_env( - &["--no-config", "config", "audio"], - "DEVLAYER_AUDIO", - "true", - )?; - assert_eq!(layer.last_stdout.trim(), "true"); - - layer.run_with_env( - &["--no-config", "config", "audio"], - "DEVLAYER_AUDIO", - "false", + &["--no-config", "config", "bind"], + "XDG_RUNTIME_DIR", + xdg.to_str().unwrap_or_default(), )?; - assert_eq!(layer.last_stdout.trim(), "false"); - - assert!(layer.exfail( - &["--no-config", "config", "audio"], - "DEVLAYER_AUDIO", - "yes" - )); assert!( layer - .last_stderr - .contains("Invalid value for DEVLAYER_AUDIO") + .last_stdout + .contains(&format!("{}/pulse", xdg.display())) ); - Ok(()) } #[rstest] -fn ai_test_audio_config_file(mut layer: LayerManager) -> Result<()> { - let config = write_config(&layer, "audio", "audio = true")?; - - layer.run(&["--config", &config, "config", "audio"])?; - assert_eq!(layer.last_stdout.trim(), "true"); - - // The environment takes precedence over config files +fn ai_test_audio_off_with_no_default_binds( + mut layer: LayerManager, +) -> Result<()> { + let xdg = fake_runtime_dir(&layer)?; layer.run_with_env( - &["--config", &config, "config", "audio"], - "DEVLAYER_AUDIO", - "false", + &["--no-config", "--no-default-binds", "config", "bind"], + "XDG_RUNTIME_DIR", + xdg.to_str().unwrap_or_default(), )?; - assert_eq!(layer.last_stdout.trim(), "false"); - + assert!(!layer.last_stdout.contains("/pulse")); + assert!(!layer.last_stdout.contains("/dev/snd")); Ok(()) } #[rstest] -fn ai_test_audio_with_no_default_binds(mut layer: LayerManager) -> Result<()> { - layer.run(&[ - "--no-config", - "--no-default-binds", - "--audio", - "config", - "bind", - ])?; - assert!(!layer.last_stdout.contains("/dev/fuse")); - for path in host_audio_paths() { - assert!(layer.last_stdout.contains(&path)); - } - +fn ai_test_audio_flag_removed(mut layer: LayerManager) -> Result<()> { + assert!(layer.xfail(&["--no-config", "--audio", "config"])); + assert!(layer.xfail(&["--no-config", "config", "audio"])); + assert!(layer.last_stderr.contains("Unknown key: audio")); Ok(()) } @@ -130,23 +75,15 @@ fn ai_test_audio_with_no_default_binds(mut layer: LayerManager) -> Result<()> { fn ai_test_audio_mounted_in_layer(mut layer: LayerManager) -> Result<()> { let paths = host_audio_paths(); - // Without audio devices or sockets, e.g. on CI runners, --audio has - // nothing to bind, so there's nothing to check + // Without audio devices or sockets, e.g. on CI runners, there's nothing + // to bind, so there's nothing to check if paths.is_empty() { eprintln!("No audio devices or sockets found, skipping"); return Ok(()); } for path in &paths { - assert!(layer.xfail(&["--no-config", "test", "-e", path])); - } - - // Changing audio for a running layer requires a restart - assert!(layer.xfail(&["--no-config", "--audio", "true"])); - layer.run(&["stop"])?; - - for path in &paths { - assert!(layer.pass(&["--no-config", "--audio", "test", "-e", path])); + assert!(layer.pass(&["--no-config", "test", "-e", path])); } // Parent directories created for the sockets mirror the host's ownership @@ -155,7 +92,6 @@ fn ai_test_audio_mounted_in_layer(mut layer: LayerManager) -> Result<()> { if Path::new(&xdg_runtime_dir).join("pulse").exists() { layer.run(&[ "--no-config", - "--audio", "stat", "-c", "%u %a", @@ -170,6 +106,18 @@ fn ai_test_audio_mounted_in_layer(mut layer: LayerManager) -> Result<()> { } } + // Changing the default binds of a running layer requires a restart + layer.run(&["stop"])?; + for path in &paths { + assert!(layer.xfail(&[ + "--no-config", + "--no-default-binds", + "test", + "-e", + path + ])); + } + Ok(()) } @@ -180,7 +128,7 @@ fn ai_test_audio_without_xdg_runtime_dir( // Without XDG_RUNTIME_DIR we can't find the sockets, but /dev/snd is // still bound if it exists layer.run_with_env( - &["--no-config", "--audio", "config", "bind"], + &["--no-config", "config", "bind"], "XDG_RUNTIME_DIR", "", )?; diff --git a/tests/ai_test_layer_settings.rs b/tests/ai_test_layer_settings.rs index dda675e..07e7984 100644 --- a/tests/ai_test_layer_settings.rs +++ b/tests/ai_test_layer_settings.rs @@ -27,7 +27,6 @@ fn create_test_config() -> ::devlayer::config::Config { ignored: false, bind_mounts: Vec::new(), no_default_binds: false, - audio: false, cpus: None, memory: None, config_files: Vec::new(), From ded4846725880002d1717a4abda0ee80c79f3012 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 06:02:52 -0500 Subject: [PATCH 07/32] Add default LLM tool binds and --no-default-llm-binds --- README.adoc | 12 +++ src/actions/config.rs | 5 + src/config/cli.rs | 5 + src/config/resolve.rs | 155 ++++++++++++++++++++++++------- src/config/structs.rs | 2 + tests/ai_test_bind_mounts.rs | 35 +++++-- tests/ai_test_bind_precedence.rs | 17 +++- tests/ai_test_layer_settings.rs | 1 + tests/ai_test_llm_binds.rs | 92 ++++++++++++++++++ 9 files changed, 283 insertions(+), 41 deletions(-) create mode 100644 tests/ai_test_llm_binds.rs diff --git a/README.adoc b/README.adoc index 49116a0..7f87bdc 100644 --- a/README.adoc +++ b/README.adoc @@ -206,6 +206,18 @@ Audio is on by default: the PipeWire and PulseAudio sockets from Note that this also allows programs in the layer to record from your microphone. Use `--no-default-binds` to turn audio off. +`--no-default-llm-binds`:: +Disable the default binds of well-known AI tool config and state, so that +logins, history and settings of tools you run in the layer are not shared with +your host. By default the following paths in your home directory are bound into +the layer when they exist: `.claude`, `.claude.json`, `.codex`, `.pi`, +`.gemini`, `.qwen`, `.aider`, `.cursor`, `.config/opencode`, +`.local/share/opencode`, `.config/goose`, `.continue`, `.codeium`, +`.config/github-copilot`, `.factory`, `.config/crush` and `.local/share/crush`. +This is independent of `--no-default-binds`. Other credentials such as SSH keys +or GitHub tokens are never bound by default; add them with `--bind` if you want +them. + `--cpus=`:: Limit how many CPUs the layer can use. Fractional values such as `1.5` are allowed. Negative values mean all but that many CPUs, so `--cpus=-2` on a 32 diff --git a/src/actions/config.rs b/src/actions/config.rs index 7238394..2347931 100644 --- a/src/actions/config.rs +++ b/src/actions/config.rs @@ -16,6 +16,7 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { "bind", "mask", "no_default_binds", + "no_default_llm_binds", "cpus", "memory", "storage_dir", @@ -47,6 +48,7 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { .join(","); let no_default_binds_str = format!("{}", config.no_default_binds); + let no_default_llm_binds_str = format!("{}", config.no_default_llm_binds); let cpus_str = config .cpus .map_or("unlimited".to_string(), |cpus| cpus.to_string()); @@ -82,6 +84,9 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { "no_default_binds" => { ("no_default_binds", no_default_binds_str.as_str()) } + "no_default_llm_binds" => { + ("no_default_llm_binds", no_default_llm_binds_str.as_str()) + } "cpus" => ("cpus", cpus_str.as_str()), "memory" => ("memory", memory_str.as_str()), "name" => ("name", config.name.as_str()), diff --git a/src/config/cli.rs b/src/config/cli.rs index 5a92468..fc0cc34 100644 --- a/src/config/cli.rs +++ b/src/config/cli.rs @@ -76,6 +76,11 @@ pub struct Args { #[arg(long, global = true, action = clap::ArgAction::SetTrue)] pub no_default_binds: bool, + /// Disable default binds of well-known AI tool config and state, such as + /// ~/.claude, ~/.claude.json, ~/.codex and ~/.gemini + #[arg(long, global = true, action = clap::ArgAction::SetTrue)] + pub no_default_llm_binds: bool, + /// Limit how many CPUs the layer can use. Fractional values such as 1.5 /// are allowed. Negative values mean all but that many CPUs, so -2 on a /// 32 CPU machine allows the layer to use 30. Use "unlimited" to remove diff --git a/src/config/resolve.rs b/src/config/resolve.rs index a2789d1..b35e6a8 100644 --- a/src/config/resolve.rs +++ b/src/config/resolve.rs @@ -4,7 +4,7 @@ use crate::config::{BindMount, BindMountOptions, Network}; use crate::util::{ can_access, can_mkdir, expand_tilde_path, find_mount_point, mkdir, }; -use crate::{config::Config, types::UidGidHome, util::resolve_uid_gid_home}; +use crate::{config::Config, util::resolve_uid_gid_home}; use anyhow::{Context, Result}; use chrono::Local; use log::trace; @@ -161,6 +161,17 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("no_default_binds".into(), "environment".into()); } + if let Ok(value) = env::var("DEVLAYER_NO_DEFAULT_LLM_BINDS") { + let value = bool::from_str(&value).map_err(|_| { + anyhow::anyhow!( + "Invalid value for DEVLAYER_NO_DEFAULT_LLM_BINDS: {}", + value + ) + })?; + partial_config.no_default_llm_binds = Some(value); + sources.insert("no_default_llm_binds".into(), "environment".into()); + } + for (var, key, field) in [ ("DEVLAYER_CPUS", "cpus", &mut partial_config.cpus), ("DEVLAYER_MEMORY", "memory", &mut partial_config.memory), @@ -222,6 +233,11 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("no_default_binds".into(), "cli".into()); } + if cli.no_default_llm_binds { + partial_config.no_default_llm_binds = Some(true); + sources.insert("no_default_llm_binds".into(), "cli".into()); + } + if let Some(cpus) = cli.cpus { partial_config.cpus = Some(cpus); sources.insert("cpus".into(), "cli".into()); @@ -264,6 +280,12 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("no_default_binds".into(), "default".into()); } + let no_default_llm_binds = + partial_config.no_default_llm_binds.unwrap_or(false); + if !sources.contains_key("no_default_llm_binds") { + sources.insert("no_default_llm_binds".into(), "default".into()); + } + let cpus = partial_config .cpus .map(|cpus| parse_cpus(&cpus, available_cpus())) @@ -314,9 +336,14 @@ pub fn resolve_config(cli: Args) -> Result { .join(cwd.strip_prefix(&mp)?); sources.insert("overlay_cwd".into(), "derived from storage_dir".into()); + // LLM tool binds sit just above the default bind mounts + if !no_default_llm_binds { + bind_layers.insert(0, get_llm_bind_mounts(&uid_gid_home.home)); + } + // Default bind mounts, including audio, are the lowest precedence layer if !no_default_binds { - let mut default_binds = get_default_bind_mounts(&net, &uid_gid_home); + let mut default_binds = get_default_bind_mounts(&net); default_binds.extend(get_audio_bind_mounts()); bind_layers.insert(0, default_binds); } @@ -369,6 +396,7 @@ pub fn resolve_config(cli: Args) -> Result { sources, bind_mounts, no_default_binds, + no_default_llm_binds, cpus, memory, config_files, @@ -382,10 +410,7 @@ pub fn resolve_config(cli: Args) -> Result { Ok(config) } -fn get_default_bind_mounts( - net: &Network, - uid_gid_home: &UidGidHome, -) -> Vec { +fn get_default_bind_mounts(net: &Network) -> Vec { let mut default_binds = Vec::new(); // System binds @@ -427,23 +452,41 @@ fn get_default_bind_mounts( } } - // User directories for AI coding assistants - let user_dirs = [ - ".claude", // Claude artifacts and settings - ".aider", // Aider chat history and settings - ".cursor", // Cursor settings - ]; - - for dir in &user_dirs { - let user_dir = uid_gid_home.home.join(dir); - if user_dir.exists() { - default_binds.push(format!("{}", user_dir.display())); - } - } - default_binds } +/// Well-known AI tool config and state paths, relative to the home directory, +/// that are bound into layers by default unless --no-default-llm-binds is set +pub const LLM_BIND_PATHS: &[&str] = &[ + ".claude", + ".claude.json", + ".codex", + ".pi", + ".gemini", + ".qwen", + ".aider", + ".cursor", + ".config/opencode", + ".local/share/opencode", + ".config/goose", + ".continue", + ".codeium", + ".config/github-copilot", + ".factory", + ".config/crush", + ".local/share/crush", +]; + +/// Returns the LLM_BIND_PATHS that exist under `home`, as absolute paths +fn get_llm_bind_mounts(home: &Path) -> Vec { + LLM_BIND_PATHS + .iter() + .map(|path| home.join(path)) + .filter(|path| path.exists()) + .map(|path| path.display().to_string()) + .collect() +} + fn get_audio_bind_mounts() -> Vec { let mut audio_binds = Vec::new(); @@ -733,6 +776,10 @@ fn merge_configs( base.no_default_binds = Some(no_default_binds); sources.insert("no_default_binds".into(), source.into()); } + if let Some(value) = override_config.no_default_llm_binds { + base.no_default_llm_binds = Some(value); + sources.insert("no_default_llm_binds".into(), source.into()); + } if let Some(cpus) = override_config.cpus { base.cpus = Some(cpus); sources.insert("cpus".into(), source.into()); @@ -872,17 +919,54 @@ mod tests { // Mutex to ensure XDG_RUNTIME_DIR tests don't interfere with each other static XDG_TEST_MUTEX: Mutex<()> = Mutex::new(()); + /// Creates an empty, unique fake home directory for LLM bind tests + fn fake_home(tag: &str) -> PathBuf { + let home = std::env::temp_dir().join(format!( + "devlayer-coverage-llm-home-{}-{}", + tag, + std::process::id() + )); + let _ = std::fs::remove_dir_all(&home); + std::fs::create_dir_all(&home).unwrap(); + home + } + + #[test] + fn llm_binds_skip_missing_paths() { + let home = fake_home("missing"); + std::fs::create_dir_all(home.join(".codex")).unwrap(); + std::fs::write(home.join(".claude.json"), "{}").unwrap(); + + assert_eq!( + get_llm_bind_mounts(&home), + vec![ + home.join(".claude.json").display().to_string(), + home.join(".codex").display().to_string(), + ] + ); + std::fs::remove_dir_all(&home).unwrap(); + } + + #[test] + fn llm_binds_all_present() { + let home = fake_home("all"); + for path in LLM_BIND_PATHS { + std::fs::create_dir_all(home.join(path)).unwrap(); + } + + let binds = get_llm_bind_mounts(&home); + assert_eq!(binds.len(), 17); + let expected: Vec = LLM_BIND_PATHS + .iter() + .map(|p| home.join(p).display().to_string()) + .collect(); + assert_eq!(binds, expected); + std::fs::remove_dir_all(&home).unwrap(); + } + #[test] fn ai_test_get_default_bind_mounts_xdg_runtime_dir() { let _guard = XDG_TEST_MUTEX.lock().unwrap(); - use crate::types::UidGidHome; - use std::path::PathBuf; - - let uid_gid_home = UidGidHome { - uid: Uid::from_raw(1000), - gid: Gid::from_raw(1000), - home: PathBuf::from("/home/test"), - }; // Test 1: XDG_RUNTIME_DIR is set, but TEST_EMPTY_XDG_RUNTIME_DIR overrides it unsafe { @@ -890,7 +974,7 @@ mod tests { env::set_var("TEST_EMPTY_XDG_RUNTIME_DIR", "1"); } - let binds = get_default_bind_mounts(&Network::Host, &uid_gid_home); + let binds = get_default_bind_mounts(&Network::Host); assert!(!binds.iter().any(|b| b.contains("/tmp/xdg/bus"))); unsafe { @@ -902,7 +986,7 @@ mod tests { env::remove_var("XDG_RUNTIME_DIR"); } - let binds = get_default_bind_mounts(&Network::Host, &uid_gid_home); + let binds = get_default_bind_mounts(&Network::Host); assert!(!binds.iter().any(|b| b.contains("/bus"))); // Test 3: XDG_RUNTIME_DIR is set to a test path that doesn't exist @@ -911,7 +995,7 @@ mod tests { } // Since /tmp/test_xdg_runtime_dir/bus won't exist, it shouldn't be included - let binds = get_default_bind_mounts(&Network::Host, &uid_gid_home); + let binds = get_default_bind_mounts(&Network::Host); assert!( !binds .iter() @@ -919,7 +1003,7 @@ mod tests { ); // Test 4: Test with Network::None (should not include any XDG bus) - let binds = get_default_bind_mounts(&Network::None, &uid_gid_home); + let binds = get_default_bind_mounts(&Network::None); assert!(!binds.iter().any(|b| b.contains("/bus"))); } @@ -937,6 +1021,7 @@ mod tests { log_level: LevelFilter::Info, bind_mounts: vec![], no_default_binds: false, + no_default_llm_binds: false, cpus: None, memory: None, config_files: vec![], @@ -1014,6 +1099,7 @@ mod tests { ]), mask: Some(vec!["/tmp/test3".to_string()]), no_default_binds: Some(true), + no_default_llm_binds: Some(true), cpus: Some("-2".to_string()), memory: Some("4G".to_string()), }; @@ -1041,6 +1127,11 @@ mod tests { assert_eq!(base.ignored, Some(true)); assert_eq!(base.cpus, Some("-2".to_string())); assert_eq!(base.memory, Some("4G".to_string())); + assert_eq!(base.no_default_llm_binds, Some(true)); + assert_eq!( + sources.get("no_default_llm_binds"), + Some(&"test-config".to_string()) + ); assert_eq!(sources.get("cpus"), Some(&"test-config".to_string())); assert_eq!(sources.get("memory"), Some(&"test-config".to_string())); diff --git a/src/config/structs.rs b/src/config/structs.rs index 8e510fc..ea443d8 100644 --- a/src/config/structs.rs +++ b/src/config/structs.rs @@ -60,6 +60,7 @@ pub struct PartialConfig { pub bind: Option>, pub mask: Option>, pub no_default_binds: Option, + pub no_default_llm_binds: Option, #[serde(deserialize_with = "deserialize_number_or_string", default)] pub cpus: Option, #[serde(deserialize_with = "deserialize_number_or_string", default)] @@ -79,6 +80,7 @@ pub struct Config { pub ignored: bool, pub bind_mounts: Vec, pub no_default_binds: bool, + pub no_default_llm_binds: bool, /// Number of CPUs the layer may use, None for unlimited pub cpus: Option, /// Bytes of memory the layer may use, None for unlimited diff --git a/tests/ai_test_bind_mounts.rs b/tests/ai_test_bind_mounts.rs index c3c46a2..d248e64 100644 --- a/tests/ai_test_bind_mounts.rs +++ b/tests/ai_test_bind_mounts.rs @@ -107,7 +107,13 @@ fn test_no_default_binds_flag(mut layer: LayerManager) -> Result<()> { fs::create_dir_all(&test1)?; // Test that custom binds work with --no-default-binds - assert!(layer.pass(&["--no-default-binds", "--bind", &test1, "config"])); + assert!(layer.pass(&[ + "--no-default-binds", + "--no-default-llm-binds", + "--bind", + &test1, + "config" + ])); // Should only contain the custom bind mount assert!(layer.last_stdout.contains(&test1)); @@ -126,7 +132,7 @@ fn test_no_default_binds_env(mut layer: LayerManager) -> Result<()> { // Test that no default binds works via environment variable layer.run_with_env( - &["--no-config", "config"], + &["--no-default-llm-binds", "--no-config", "config"], "DEVLAYER_NO_DEFAULT_BINDS", "true", )?; @@ -158,7 +164,12 @@ fn test_bind_mount_env_parsing() -> Result<()> { // Test empty env var layer.run_with_env( - &["--no-default-binds", "--no-config", "config"], + &[ + "--no-default-binds", + "--no-default-llm-binds", + "--no-config", + "config", + ], "DEVLAYER_BIND", "", )?; @@ -175,7 +186,12 @@ fn test_bind_mount_env_parsing() -> Result<()> { fs::create_dir_all(&test2)?; layer.run_with_env( - &["--no-default-binds", "--no-config", "config"], + &[ + "--no-default-binds", + "--no-default-llm-binds", + "--no-config", + "config", + ], "DEVLAYER_BIND", &format!("{},{},", test1, test2), )?; @@ -196,7 +212,12 @@ fn test_bind_mount_env_parsing() -> Result<()> { // Test whitespace-only env var layer.run_with_env( - &["--no-default-binds", "--no-config", "config"], + &[ + "--no-default-binds", + "--no-default-llm-binds", + "--no-config", + "config", + ], "DEVLAYER_BIND", " ", )?; @@ -222,7 +243,7 @@ fn test_bind_mount_env_with_options(mut layer: LayerManager) -> Result<()> { // Test environment variable with read-only options layer.run_with_env( - &["--no-default-binds", "config"], + &["--no-default-binds", "--no-default-llm-binds", "config"], "DEVLAYER_BIND", &format!("{}::ro,{}::ro", test1, test2), )?; @@ -233,7 +254,7 @@ fn test_bind_mount_env_with_options(mut layer: LayerManager) -> Result<()> { // Test mixed read-only and read-write mounts layer.run_with_env( - &["--no-default-binds", "config"], + &["--no-default-binds", "--no-default-llm-binds", "config"], "DEVLAYER_BIND", &format!("{},{}", test3, test4), )?; diff --git a/tests/ai_test_bind_precedence.rs b/tests/ai_test_bind_precedence.rs index 2a1f110..b4d858c 100644 --- a/tests/ai_test_bind_precedence.rs +++ b/tests/ai_test_bind_precedence.rs @@ -35,6 +35,7 @@ fn ai_test_bind_higher_precedence_config_overrides( // Later --config files take precedence over earlier ones layer.run(&[ "--no-default-binds", + "--no-default-llm-binds", "--config", &low, "--config", @@ -46,6 +47,7 @@ fn ai_test_bind_higher_precedence_config_overrides( layer.run(&[ "--no-default-binds", + "--no-default-llm-binds", "--config", &high, "--config", @@ -107,6 +109,7 @@ fn ai_test_bind_identical_within_config_is_deduplicated( layer.run(&[ "--no-default-binds", + "--no-default-llm-binds", "--config", &config, "config", @@ -127,6 +130,7 @@ fn ai_test_mask_in_higher_config_overrides_bind( layer.run(&[ "--no-default-binds", + "--no-default-llm-binds", "--config", &low, "--config", @@ -153,7 +157,14 @@ fn ai_test_bind_env_overrides_config(mut layer: LayerManager) -> Result<()> { write_config(&layer, "config", &format!("bind = [\"{dir}\"]"))?; layer.run_with_env( - &["--no-default-binds", "--config", &config, "config", "bind"], + &[ + "--no-default-binds", + "--no-default-llm-binds", + "--config", + &config, + "config", + "bind", + ], "DEVLAYER_BIND", &format!("{dir}::ro"), )?; @@ -161,7 +172,7 @@ fn ai_test_bind_env_overrides_config(mut layer: LayerManager) -> Result<()> { // Conflicts within the environment layer still fail assert!(layer.exfail( - &["--no-default-binds", "config"], + &["--no-default-binds", "--no-default-llm-binds", "config"], "DEVLAYER_BIND", &format!("{dir},{dir}::ro"), )); @@ -180,6 +191,7 @@ fn ai_test_bind_cli_overrides_config_and_env( layer.run_with_env( &[ "--no-default-binds", + "--no-default-llm-binds", "--config", &config, "--bind", @@ -195,6 +207,7 @@ fn ai_test_bind_cli_overrides_config_and_env( // A CLI mask overrides a bind from a config file layer.run(&[ "--no-default-binds", + "--no-default-llm-binds", "--config", &config, "--mask", diff --git a/tests/ai_test_layer_settings.rs b/tests/ai_test_layer_settings.rs index 07e7984..3494365 100644 --- a/tests/ai_test_layer_settings.rs +++ b/tests/ai_test_layer_settings.rs @@ -27,6 +27,7 @@ fn create_test_config() -> ::devlayer::config::Config { ignored: false, bind_mounts: Vec::new(), no_default_binds: false, + no_default_llm_binds: false, cpus: None, memory: None, config_files: Vec::new(), diff --git a/tests/ai_test_llm_binds.rs b/tests/ai_test_llm_binds.rs new file mode 100644 index 0000000..e36faec --- /dev/null +++ b/tests/ai_test_llm_binds.rs @@ -0,0 +1,92 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use rstest::*; +use std::path::PathBuf; + +/// ~/.claude on this machine, if it exists. These tests use the real home +/// directory because the binary resolves it from the invoking user. +fn claude_dir() -> Option { + let home = std::env::var("HOME").ok()?; + let dir = PathBuf::from(home).join(".claude"); + dir.exists().then(|| dir.display().to_string()) +} + +fn binds_contain(stdout: &str, path: &str) -> bool { + stdout.trim().split(',').any(|b| b == path) +} + +#[rstest] +fn ai_test_llm_binds_default_on(mut layer: LayerManager) -> Result<()> { + let Some(claude) = claude_dir() else { + eprintln!("No ~/.claude on this machine, skipping"); + return Ok(()); + }; + layer.run(&["--no-config", "config", "bind"])?; + assert!(binds_contain(&layer.last_stdout, &claude)); + Ok(()) +} + +#[rstest] +fn ai_test_no_default_llm_binds_flag(mut layer: LayerManager) -> Result<()> { + let Some(claude) = claude_dir() else { + return Ok(()); + }; + layer.run(&["--no-config", "--no-default-llm-binds", "config", "bind"])?; + assert!(!binds_contain(&layer.last_stdout, &claude)); + Ok(()) +} + +#[rstest] +fn ai_test_no_default_llm_binds_env(mut layer: LayerManager) -> Result<()> { + let Some(claude) = claude_dir() else { + return Ok(()); + }; + layer.run_with_env( + &["--no-config", "config", "bind"], + "DEVLAYER_NO_DEFAULT_LLM_BINDS", + "true", + )?; + assert!(!binds_contain(&layer.last_stdout, &claude)); + + assert!(layer.exfail( + &["--no-config", "config", "bind"], + "DEVLAYER_NO_DEFAULT_LLM_BINDS", + "yes" + )); + assert!( + layer + .last_stderr + .contains("Invalid value for DEVLAYER_NO_DEFAULT_LLM_BINDS") + ); + Ok(()) +} + +#[rstest] +fn ai_test_no_default_llm_binds_config(mut layer: LayerManager) -> Result<()> { + let Some(claude) = claude_dir() else { + return Ok(()); + }; + let config = format!("{}.toml", layer.test_filename("llm")); + std::fs::write(&config, "no_default_llm_binds = true\n")?; + let config_arg = format!("--config={}", config); + layer.run(&[&config_arg, "config", "bind"])?; + assert!(!binds_contain(&layer.last_stdout, &claude)); + + layer.run(&[&config_arg, "config", "no_default_llm_binds"])?; + assert_eq!(layer.last_stdout.trim(), "true"); + Ok(()) +} + +#[rstest] +fn ai_test_llm_binds_independent_of_no_default_binds( + mut layer: LayerManager, +) -> Result<()> { + let Some(claude) = claude_dir() else { + return Ok(()); + }; + layer.run(&["--no-config", "--no-default-binds", "config", "bind"])?; + assert!(binds_contain(&layer.last_stdout, &claude)); + Ok(()) +} From 7be4cac25e21cfd0375b50be15c836e1f9e0eea1 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 06:06:51 -0500 Subject: [PATCH 08/32] Bind the current directory by default; add --no-bind-cwd --- README.adoc | 22 ++++- src/actions/config.rs | 11 +++ src/config/cli.rs | 5 ++ src/config/resolve.rs | 67 +++++++++++++++ src/config/structs.rs | 5 ++ src/layer/settings.rs | 10 ++- tests/ai_test_cwd_bind.rs | 140 ++++++++++++++++++++++++++++++++ tests/ai_test_layer_settings.rs | 2 + tests/fixtures/fixture_layer.rs | 37 +++++++++ 9 files changed, 294 insertions(+), 5 deletions(-) create mode 100644 tests/ai_test_cwd_bind.rs diff --git a/README.adoc b/README.adoc index 7f87bdc..85a34e6 100644 --- a/README.adoc +++ b/README.adoc @@ -172,14 +172,28 @@ network. Use `--net=none` (or `net="none"` in a config file) to disable network access. With host networking the D-Bus and systemd sockets are also bound into the layer by default; `--no-default-binds` turns them off. +`--no-bind-cwd`:: +By default the directory you start a layer in is bound read-write into the +layer, so changes there go straight to your host without having to +accept/reject them, while the rest of the system stays protected by the layer. +Use `--no-bind-cwd` (or `no_bind_cwd = true` in a config file, or +`DEVLAYER_NO_BIND_CWD=true`) to keep that directory layered too. +`devlayer` refuses to bind `/` this way; run it from a project directory or +pass `--no-bind-cwd`. ++ +A layer remembers the directory it was created in and whether it was bound. +Re-entering it later, from any directory and with or without +`--no-bind-cwd`, keeps those original choices. Note that config files are +still found by searching from your current directory, so joining a layer from +a different project can load a different `.devlayer.toml`; if that changes its +network, limits or binds, `devlayer` asks you to stop the layer first. + `--bind[=]`:: Specify directories or files to bind into the layer bypassing the layer OverlayFS system. Examples: - * `--bind=.` bind the current directory into the layer so that changes made - will be reflected in the host system without having to accept/reject them. - The rest of the system will still be mounted in OverlayFS FS layers to - protect your system. + * `--bind=../shared` bind a sibling directory into the layer as well as the + current directory, which is bound by default. * `--bind=data1:/data` to mount the relative `data1` directory into the layer as `/data`. * `--bind=my/protected/dir::ro` will mount the relative `my/protected/dir` directory into the layer as read only. diff --git a/src/actions/config.rs b/src/actions/config.rs index 2347931..63ad2fb 100644 --- a/src/actions/config.rs +++ b/src/actions/config.rs @@ -17,6 +17,9 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { "mask", "no_default_binds", "no_default_llm_binds", + "no_bind_cwd", + "bind_cwd", + "created_in", "cpus", "memory", "storage_dir", @@ -49,6 +52,8 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { let no_default_binds_str = format!("{}", config.no_default_binds); let no_default_llm_binds_str = format!("{}", config.no_default_llm_binds); + let bind_cwd_str = format!("{}", config.bind_cwd); + let no_bind_cwd_str = format!("{}", !config.bind_cwd); let cpus_str = config .cpus .map_or("unlimited".to_string(), |cpus| cpus.to_string()); @@ -87,6 +92,12 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { "no_default_llm_binds" => { ("no_default_llm_binds", no_default_llm_binds_str.as_str()) } + "bind_cwd" => ("bind_cwd", bind_cwd_str.as_str()), + "no_bind_cwd" => ("no_bind_cwd", no_bind_cwd_str.as_str()), + "created_in" => ( + "created_in", + config.created_in.to_str().unwrap_or(""), + ), "cpus" => ("cpus", cpus_str.as_str()), "memory" => ("memory", memory_str.as_str()), "name" => ("name", config.name.as_str()), diff --git a/src/config/cli.rs b/src/config/cli.rs index fc0cc34..768608c 100644 --- a/src/config/cli.rs +++ b/src/config/cli.rs @@ -81,6 +81,11 @@ pub struct Args { #[arg(long, global = true, action = clap::ArgAction::SetTrue)] pub no_default_llm_binds: bool, + /// Do not bind the current directory into the layer. By default it is bound + /// read-write, so changes there go straight to the host. + #[arg(long, global = true, action = clap::ArgAction::SetTrue)] + pub no_bind_cwd: bool, + /// Limit how many CPUs the layer can use. Fractional values such as 1.5 /// are allowed. Negative values mean all but that many CPUs, so -2 on a /// 32 CPU machine allows the layer to use 30. Use "unlimited" to remove diff --git a/src/config/resolve.rs b/src/config/resolve.rs index b35e6a8..8fdde7a 100644 --- a/src/config/resolve.rs +++ b/src/config/resolve.rs @@ -1,6 +1,7 @@ use super::PartialConfig; use super::limits::{available_cpus, parse_cpus, parse_memory}; use crate::config::{BindMount, BindMountOptions, Network}; +use crate::layer::LayerSettings; use crate::util::{ can_access, can_mkdir, expand_tilde_path, find_mount_point, mkdir, }; @@ -172,6 +173,14 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("no_default_llm_binds".into(), "environment".into()); } + if let Ok(value) = env::var("DEVLAYER_NO_BIND_CWD") { + let value = bool::from_str(&value).map_err(|_| { + anyhow::anyhow!("Invalid value for DEVLAYER_NO_BIND_CWD: {}", value) + })?; + partial_config.no_bind_cwd = Some(value); + sources.insert("no_bind_cwd".into(), "environment".into()); + } + for (var, key, field) in [ ("DEVLAYER_CPUS", "cpus", &mut partial_config.cpus), ("DEVLAYER_MEMORY", "memory", &mut partial_config.memory), @@ -238,6 +247,11 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("no_default_llm_binds".into(), "cli".into()); } + if cli.no_bind_cwd { + partial_config.no_bind_cwd = Some(true); + sources.insert("no_bind_cwd".into(), "cli".into()); + } + if let Some(cpus) = cli.cpus { partial_config.cpus = Some(cpus); sources.insert("cpus".into(), "cli".into()); @@ -286,6 +300,11 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("no_default_llm_binds".into(), "default".into()); } + let no_bind_cwd = partial_config.no_bind_cwd.unwrap_or(false); + if !sources.contains_key("no_bind_cwd") { + sources.insert("no_bind_cwd".into(), "default".into()); + } + let cpus = partial_config .cpus .map(|cpus| parse_cpus(&cpus, available_cpus())) @@ -336,6 +355,14 @@ pub fn resolve_config(cli: Args) -> Result { .join(cwd.strip_prefix(&mp)?); sources.insert("overlay_cwd".into(), "derived from storage_dir".into()); + // The directory the layer was created in is bound just above the LLM binds + let (created_in, bind_cwd) = resolve_origin(&layer_dir, &cwd, no_bind_cwd)?; + sources.insert("created_in".into(), "layer settings or cwd".into()); + sources.insert("bind_cwd".into(), "layer settings or no_bind_cwd".into()); + if bind_cwd { + bind_layers.insert(0, vec![created_in.display().to_string()]); + } + // LLM tool binds sit just above the default bind mounts if !no_default_llm_binds { bind_layers.insert(0, get_llm_bind_mounts(&uid_gid_home.home)); @@ -397,6 +424,8 @@ pub fn resolve_config(cli: Args) -> Result { bind_mounts, no_default_binds, no_default_llm_binds, + created_in, + bind_cwd, cpus, memory, config_files, @@ -455,6 +484,36 @@ fn get_default_bind_mounts(net: &Network) -> Vec { default_binds } +/// Returns the directory a layer was created in and whether that directory is +/// bound into the layer. An existing layer keeps the values recorded in its +/// settings when it was created, so re-entering it from another directory, or +/// without --no-bind-cwd, does not change its binds. A new layer uses `cwd`. +pub fn resolve_origin( + layer_dir: &Path, + cwd: &Path, + no_bind_cwd: bool, +) -> Result<(PathBuf, bool)> { + let settings_path = layer_dir.join("data").join("settings.json"); + if let Ok(settings) = LayerSettings::load_from_file(&settings_path) + && let (Some(created_in), Some(bind_cwd)) = + (settings.created_in, settings.bind_cwd) + { + return Ok((created_in, bind_cwd)); + } + + let created_in = cwd.canonicalize().context(format!( + "Failed to canonicalize current directory {}", + cwd.display() + ))?; + let bind_cwd = !no_bind_cwd; + if bind_cwd && created_in == Path::new("/") { + return Err(anyhow::anyhow!( + "Refusing to bind / into the layer; run from a project directory or pass --no-bind-cwd" + )); + } + Ok((created_in, bind_cwd)) +} + /// Well-known AI tool config and state paths, relative to the home directory, /// that are bound into layers by default unless --no-default-llm-binds is set pub const LLM_BIND_PATHS: &[&str] = &[ @@ -780,6 +839,10 @@ fn merge_configs( base.no_default_llm_binds = Some(value); sources.insert("no_default_llm_binds".into(), source.into()); } + if let Some(value) = override_config.no_bind_cwd { + base.no_bind_cwd = Some(value); + sources.insert("no_bind_cwd".into(), source.into()); + } if let Some(cpus) = override_config.cpus { base.cpus = Some(cpus); sources.insert("cpus".into(), source.into()); @@ -1022,6 +1085,8 @@ mod tests { bind_mounts: vec![], no_default_binds: false, no_default_llm_binds: false, + created_in: PathBuf::from("/tmp"), + bind_cwd: false, cpus: None, memory: None, config_files: vec![], @@ -1100,6 +1165,7 @@ mod tests { mask: Some(vec!["/tmp/test3".to_string()]), no_default_binds: Some(true), no_default_llm_binds: Some(true), + no_bind_cwd: Some(true), cpus: Some("-2".to_string()), memory: Some("4G".to_string()), }; @@ -1128,6 +1194,7 @@ mod tests { assert_eq!(base.cpus, Some("-2".to_string())); assert_eq!(base.memory, Some("4G".to_string())); assert_eq!(base.no_default_llm_binds, Some(true)); + assert_eq!(base.no_bind_cwd, Some(true)); assert_eq!( sources.get("no_default_llm_binds"), Some(&"test-config".to_string()) diff --git a/src/config/structs.rs b/src/config/structs.rs index ea443d8..a765b1d 100644 --- a/src/config/structs.rs +++ b/src/config/structs.rs @@ -61,6 +61,7 @@ pub struct PartialConfig { pub mask: Option>, pub no_default_binds: Option, pub no_default_llm_binds: Option, + pub no_bind_cwd: Option, #[serde(deserialize_with = "deserialize_number_or_string", default)] pub cpus: Option, #[serde(deserialize_with = "deserialize_number_or_string", default)] @@ -81,6 +82,10 @@ pub struct Config { pub bind_mounts: Vec, pub no_default_binds: bool, pub no_default_llm_binds: bool, + /// Canonical directory the layer was created in + pub created_in: PathBuf, + /// Whether created_in is bound read-write into the layer + pub bind_cwd: bool, /// Number of CPUs the layer may use, None for unlimited pub cpus: Option, /// Bytes of memory the layer may use, None for unlimited diff --git a/src/layer/settings.rs b/src/layer/settings.rs index 7d1d8f5..3ee17e3 100644 --- a/src/layer/settings.rs +++ b/src/layer/settings.rs @@ -2,7 +2,7 @@ use crate::config::{BindMount, Config}; use crate::layer::mount_overlays::MountHash; use anyhow::{Context, Result, anyhow}; use serde::{Deserialize, Serialize}; -use std::path::Path; +use std::path::{Path, PathBuf}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct LayerSettings { @@ -15,6 +15,12 @@ pub struct LayerSettings { pub cpus: Option, #[serde(default)] pub memory: Option, + /// Canonical directory the layer was created in + #[serde(default)] + pub created_in: Option, + /// Whether created_in is bound read-write into the layer + #[serde(default)] + pub bind_cwd: Option, } impl LayerSettings { @@ -26,6 +32,8 @@ impl LayerSettings { bind_mounts: config.bind_mounts.clone(), cpus: config.cpus, memory: config.memory, + created_in: Some(config.created_in.clone()), + bind_cwd: Some(config.bind_cwd), } } diff --git a/tests/ai_test_cwd_bind.rs b/tests/ai_test_cwd_bind.rs new file mode 100644 index 0000000..c9b4c1b --- /dev/null +++ b/tests/ai_test_cwd_bind.rs @@ -0,0 +1,140 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use rstest::*; +use std::path::{Path, PathBuf}; + +/// Creates an absolute project directory for this test and returns it +fn project_dir(layer: &LayerManager) -> Result { + let dir = std::env::current_dir()?.join(layer.test_filename("project")); + std::fs::create_dir_all(dir.join("sub"))?; + Ok(dir) +} + +/// A layer manager that runs from `dir` and leaves the cwd bind at its +/// default (on) +fn layer_in(dir: &Path) -> LayerManager { + let mut layer = LayerManager::new(); + layer.set_bind_cwd(true); + layer.cwd = Some(dir.to_path_buf()); + layer +} + +#[rstest] +fn ai_test_cwd_bound_by_default(mut layer: LayerManager) -> Result<()> { + let dir = project_dir(&layer)?; + layer.set_bind_cwd(true); + layer.cwd = Some(dir.clone()); + + layer.run(&["touch", "cwd-bound-file"])?; + + // The write went straight to the host, so it is not a layer change + assert!(dir.join("cwd-bound-file").exists()); + layer.run(&["status", "/"])?; + assert!(!layer.last_stdout.contains("cwd-bound-file")); + Ok(()) +} + +#[rstest] +fn ai_test_no_bind_cwd_flag_env_config(layer: LayerManager) -> Result<()> { + let dir = project_dir(&layer)?; + + let mut by_flag = layer_in(&dir); + by_flag.run(&["--no-bind-cwd", "touch", "by-flag"])?; + assert!(!dir.join("by-flag").exists()); + + let mut by_env = layer_in(&dir); + by_env.run_with_env( + &["touch", "by-env"], + "DEVLAYER_NO_BIND_CWD", + "true", + )?; + assert!(!dir.join("by-env").exists()); + + let mut by_config = layer_in(&dir); + let config = dir.join("no-bind-cwd.toml"); + std::fs::write(&config, "no_bind_cwd = true\n")?; + let config_arg = format!("--config={}", config.display()); + by_config.run(&[&config_arg, "touch", "by-config"])?; + assert!(!dir.join("by-config").exists()); + Ok(()) +} + +#[rstest] +fn ai_test_refuse_root(mut layer: LayerManager) -> Result<()> { + layer.set_bind_cwd(true); + layer.cwd = Some(PathBuf::from("/")); + + assert!(layer.xfail(&["true"])); + assert!(layer.last_stderr.contains( + "Refusing to bind / into the layer; run from a project directory or pass --no-bind-cwd" + )); + + assert!(layer.pass(&["--no-bind-cwd", "true"])); + Ok(()) +} + +#[rstest] +fn ai_test_home_allowed(mut layer: LayerManager) -> Result<()> { + let home = PathBuf::from(std::env::var("HOME")?); + layer.set_bind_cwd(true); + layer.cwd = Some(home.clone()); + + layer.run(&["config", "bind_cwd"])?; + assert_eq!(layer.last_stdout.trim(), "true"); + layer.run(&["config", "created_in"])?; + assert_eq!( + layer.last_stdout.trim(), + home.canonicalize()?.display().to_string() + ); + Ok(()) +} + +#[rstest] +fn ai_test_cwd_bind_reenter_from_subdir(mut layer: LayerManager) -> Result<()> { + let dir = project_dir(&layer)?; + layer.set_bind_cwd(true); + layer.cwd = Some(dir.clone()); + layer.run(&["true"])?; + + // Entering the running layer from a subdirectory keeps the original bind + layer.cwd = Some(dir.join("sub")); + layer.run(&["config", "created_in"])?; + assert_eq!(layer.last_stdout.trim(), dir.display().to_string()); + layer.run(&["touch", "from-sub"])?; + assert!(dir.join("sub/from-sub").exists()); + Ok(()) +} + +#[rstest] +fn ai_test_restart_keeps_origin(mut layer: LayerManager) -> Result<()> { + let dir = project_dir(&layer)?; + layer.set_bind_cwd(true); + layer.cwd = Some(dir.clone()); + layer.run(&["true"])?; + layer.run(&["stop"])?; + + layer.cwd = Some(dir.join("sub")); + layer.run(&["true"])?; + layer.run(&["config", "created_in"])?; + assert_eq!(layer.last_stdout.trim(), dir.display().to_string()); + layer.run(&["config", "bind_cwd"])?; + assert_eq!(layer.last_stdout.trim(), "true"); + Ok(()) +} + +#[rstest] +fn ai_test_no_bind_cwd_persists(mut layer: LayerManager) -> Result<()> { + let dir = project_dir(&layer)?; + layer.set_bind_cwd(true); + layer.cwd = Some(dir.clone()); + layer.run(&["--no-bind-cwd", "true"])?; + + // Re-entering without the flag keeps the layer's original choice + layer.run(&["config", "bind_cwd"])?; + assert_eq!(layer.last_stdout.trim(), "false"); + layer.run(&["touch", "still-layered"])?; + assert!(!dir.join("still-layered").exists()); + Ok(()) +} diff --git a/tests/ai_test_layer_settings.rs b/tests/ai_test_layer_settings.rs index 3494365..bacb099 100644 --- a/tests/ai_test_layer_settings.rs +++ b/tests/ai_test_layer_settings.rs @@ -28,6 +28,8 @@ fn create_test_config() -> ::devlayer::config::Config { bind_mounts: Vec::new(), no_default_binds: false, no_default_llm_binds: false, + created_in: PathBuf::from("/tmp"), + bind_cwd: false, cpus: None, memory: None, config_files: Vec::new(), diff --git a/tests/fixtures/fixture_layer.rs b/tests/fixtures/fixture_layer.rs index 2f1eeed..984fa76 100644 --- a/tests/fixtures/fixture_layer.rs +++ b/tests/fixtures/fixture_layer.rs @@ -68,6 +68,11 @@ pub struct LayerManager { pub devlayer_bin: String, pub no_default_options: bool, pub ignored: bool, // Controls whether --ignored is automatically added + /// When false (the default), --no-bind-cwd is added so that tests run + /// from the repository root do not write straight to the checkout + pub bind_cwd: bool, + /// Directory to run commands from, defaults to the test process cwd + pub cwd: Option, } impl LayerManager { @@ -98,6 +103,29 @@ impl LayerManager { devlayer_bin: get_devlayer_bin(), no_default_options: false, ignored: true, // Default to true to maintain existing behavior + bind_cwd: false, + cwd: None, + } + } + + /* Controls whether --no-bind-cwd is automatically added to commands */ + #[allow(dead_code)] + pub fn set_bind_cwd(&mut self, bind_cwd: bool) { + self.bind_cwd = bind_cwd; + } + + /// Adds --no-bind-cwd unless the test opted in to the cwd bind or passes + /// the flag itself + fn add_no_bind_cwd(&self, cmd: &mut Command, args: &[&str]) { + if !self.bind_cwd && !args.contains(&"--no-bind-cwd") { + cmd.args(["--no-bind-cwd"]); + } + } + + /// Applies the configured working directory to a command + fn apply_cwd(&self, cmd: &mut Command) { + if let Some(cwd) = &self.cwd { + cmd.current_dir(cwd); } } @@ -123,7 +151,9 @@ impl LayerManager { } cmd.args([format!("--join={}", &self.name)]); + self.add_no_bind_cwd(&mut cmd, &[]); cmd.args(["config", "layer_dir"]); + self.apply_cwd(&mut cmd); let output = cmd.output()?; let base = String::from_utf8_lossy(&output.stdout).to_string(); let base = base.trim(); @@ -185,6 +215,7 @@ impl LayerManager { { cmd.args([format!("--join={}", &self.name)]); } + self.add_no_bind_cwd(&mut cmd, args); cmd.args(args); // Set up stdin @@ -201,6 +232,7 @@ impl LayerManager { .join(" ") ); + self.apply_cwd(&mut cmd); let mut child = cmd .spawn() .map_err(|e| anyhow::anyhow!("Failed to spawn command: {:?}", e))?; @@ -276,6 +308,7 @@ impl LayerManager { { cmd.args([format!("--join={}", &self.name)]); } + self.add_no_bind_cwd(&mut cmd, args); cmd.args(args); println!( "Running command: {} {}", @@ -285,6 +318,7 @@ impl LayerManager { .collect::>() .join(" ") ); + self.apply_cwd(&mut cmd); match cmd.output() { Ok(output) => { self.last_stdout = @@ -329,6 +363,7 @@ impl LayerManager { if !self.no_default_options { cmd.args([format!("--join={}", &self.name)]); } + self.add_no_bind_cwd(&mut cmd, args); cmd.args(args); println!( @@ -340,6 +375,7 @@ impl LayerManager { .join(" ") ); + self.apply_cwd(&mut cmd); Ok(cmd.spawn()?) } @@ -399,6 +435,7 @@ impl Drop for LayerManager { // Reset flags to default state for cleanup commands self.no_default_options = false; self.ignored = true; + self.cwd = None; if let Err(e) = self.run(&["stop"]) { error!("Failed to kill layer: {}", e); From af2152f484f25467c7c79101058b1ddbfc5f8268 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 06:13:03 -0500 Subject: [PATCH 09/32] Default to a new layer; make --last directory-aware; actions default to --last --- README.adoc | 25 +++- src/config/cli.rs | 10 +- src/config/resolve.rs | 236 +++++++++++++++++++++++-------- tests/ai_test_cwd_bind.rs | 4 + tests/ai_test_layer_selection.rs | 220 ++++++++++++++++++++++++++++ tests/fixtures/fixture_layer.rs | 10 +- tests/test_new_last.rs | 2 +- 7 files changed, 436 insertions(+), 71 deletions(-) create mode 100644 tests/ai_test_layer_selection.rs diff --git a/README.adoc b/README.adoc index 85a34e6..f0e8f66 100644 --- a/README.adoc +++ b/README.adoc @@ -78,11 +78,17 @@ endif::[] == Quick examples: -Hop into a shell inside a layer +Hop into a shell inside a new layer. The current directory is live, the rest +of your system is layered. ``` devlayer ``` +Hop back into the last layer you started in this directory +``` + devlayer --last +``` + Try that trendy web based install script in a layer first ``` curl -s https://trustmebro.sh | devlayer sh @@ -152,16 +158,21 @@ Print this message or the help of the given subcommand(s) Set the log level to one of trace, debug, info, warn, or error. `-v` is shorthand for enabling verbose (trace) logging. `--join=`:: -Join the named layer, creating it if it does not exist yet. Defaults to "devlayer". Executables run within the same layer -name will be run in the same container. +Join the named layer, creating it if it does not exist yet. Executables run +within the same layer name will be run in the same container. `--new`:: -Create a new layer with an auto-generated timestamp name. This is useful for -creating ephemeral layers for one-off tasks. Cannot be used with --join or --last. +Create a new layer with an auto-generated timestamp name. This is the default +when you run a command or a shell, so every run starts with a fresh layer. +Cannot be used with --join or --last. `--last`:: -Use the most recently created layer. This is useful for quickly returning to -the last layer you were working in. Cannot be used with --join or --new. +Use the newest layer created in the current directory, or else in the nearest +parent directory that has layers. This is how you return to a layer, for +example `devlayer --last bash`. It is the default for `status`, `diff`, +`accept`, `reject`, and `stop`/`delete` without patterns, so those act on the +layer you last started in this project. `config` also reports that layer when +there is one. Cannot be used with --join or --new. `--storage-dir=`:: Base storage directory for all layers. Defaults to `~/.devlayer/` diff --git a/src/config/cli.rs b/src/config/cli.rs index 768608c..c78b031 100644 --- a/src/config/cli.rs +++ b/src/config/cli.rs @@ -23,15 +23,19 @@ pub struct Args { )] pub log_level: Option, - /// Join the named layer, creating it if it does not exist yet + /// Join the named layer, creating it if it does not exist yet. Also settable + /// with `join` in a config file or DEVLAYER_JOIN. #[arg(long, global = true, value_hint = clap::ValueHint::Other, add = ArgValueCompleter::new(layer_name_completion), conflicts_with_all = &["new", "last"])] pub join: Option, - /// Create a new layer with an auto-generated timestamp name + /// Create a new layer with an auto-generated timestamp name. This is the + /// default when running a command. #[arg(long, global = true, conflicts_with_all = &["join", "last"])] pub new: bool, - /// Use the most recently created layer + /// Use the newest layer created in the current directory, or else in the + /// nearest parent directory that has layers. This is the default for + /// status, diff, accept, reject, and stop/delete without patterns. #[arg(long, global = true, conflicts_with_all = &["join", "new"])] pub last: bool, diff --git a/src/config/resolve.rs b/src/config/resolve.rs index 8fdde7a..918b904 100644 --- a/src/config/resolve.rs +++ b/src/config/resolve.rs @@ -18,7 +18,7 @@ use std::{ path::{Path, PathBuf}, }; -use super::cli::Args; +use super::cli::{Action, Args}; /// Parses bind mount string and expands tildes /// Format: source[:target[:options]] @@ -203,28 +203,53 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("storage_dir".into(), "cli".into()); } - // Handle name resolution based on CLI flags - if cli.new { - // Generate a new timestamp-based name - let name = generate_timestamp_name( - &partial_config.storage_dir, - uid_gid_home.uid, - uid_gid_home.gid, - )?; - partial_config.join = Some(name); - sources.insert("name".into(), "cli --new".into()); + // Choose the layer. Explicit --new/--last/--join win, then a join from + // the environment or a config file, then the default for the action. + let cwd = std::env::current_dir()?; + let (selection, explicit) = if cli.new { + (LayerSelection::New, "cli --new") } else if cli.last { - // Find the most recently created layer - let name = find_last_layer( + (LayerSelection::Last, "cli --last") + } else if let Some(name) = cli.join.clone() { + (LayerSelection::Join(name), "cli --join") + } else if let Some(name) = partial_config.join.take() { + (LayerSelection::Join(name), "") + } else { + (default_selection(cli.action.as_ref()), "") + }; + let name = match selection { + LayerSelection::Join(name) => name, + LayerSelection::New => generate_timestamp_name( &partial_config.storage_dir, uid_gid_home.uid, uid_gid_home.gid, - )?; - partial_config.join = Some(name); - sources.insert("name".into(), "cli --last".into()); - } else if let Some(name) = cli.join { - partial_config.join = Some(name); - sources.insert("name".into(), "cli --join".into()); + )?, + LayerSelection::Last => find_last_layer( + &resolve_storage_dir( + partial_config.storage_dir.clone(), + uid_gid_home.uid, + uid_gid_home.gid, + )?, + &cwd, + )?, + LayerSelection::LastOrNew => match find_last_layer( + &resolve_storage_dir( + partial_config.storage_dir.clone(), + uid_gid_home.uid, + uid_gid_home.gid, + )?, + &cwd, + ) { + Ok(name) => name, + Err(_) => generate_timestamp_name( + &partial_config.storage_dir, + uid_gid_home.uid, + uid_gid_home.gid, + )?, + }, + }; + if !explicit.is_empty() { + sources.insert("name".into(), explicit.into()); } if let Some(net) = cli.net { @@ -274,7 +299,6 @@ pub fn resolve_config(cli: Args) -> Result { bind_layers.push(cli_bind_layer); // If nothing else, fill in with some default values - let name = partial_config.join.unwrap_or("devlayer".to_string()); if !sources.contains_key("name") { sources.insert("name".into(), "default".into()); } @@ -337,7 +361,6 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("layer_dir".into(), "derived from storage_dir".into()); } - let cwd = std::env::current_dir()?; let mp = find_mount_point(cwd.clone())?; let hash = data_encoding::BASE32_NOPAD.encode(mp.to_string_lossy().as_bytes()); @@ -920,55 +943,98 @@ fn generate_timestamp_name( } } -fn find_last_layer( - storage_dir: &Option, - uid: Uid, - gid: Gid, -) -> Result { - let storage_dir = resolve_storage_dir(storage_dir.clone(), uid, gid)?; - - let entries = std::fs::read_dir(&storage_dir).context(format!( - "Failed to read layer storage directory: {:?}", - storage_dir - ))?; - - let mut layers: Vec<(String, SystemTime)> = Vec::new(); - - for entry in entries { - let entry = entry?; - let path = entry.path(); +/// How the layer to use is chosen +#[derive(Debug, Clone, PartialEq)] +pub enum LayerSelection { + /// A new layer with a generated `ephemeral_*` name + New, + /// The newest layer created in the cwd, or else in its nearest ancestor + /// that has layers + Last, + /// Like `Last`, but falls back to a new name when no layer matches. Used + /// by `config` so it reports this directory's layer without failing. + LastOrNew, + /// The named layer, created if it does not exist + Join(String), +} - // Check if this is a valid layer directory - if path.is_dir() - && path.join("upper").is_dir() - && path.join("work").is_dir() - && path.join("overlay").is_dir() +/// The layer selection used when no --new, --last or --join is given and no +/// join is set in the environment or a config file +pub fn default_selection(action: Option<&Action>) -> LayerSelection { + match action { + None => LayerSelection::New, + Some( + Action::Status { .. } + | Action::Diff { .. } + | Action::Accept { .. } + | Action::Reject { .. } + | Action::Stop { + all: false, + patterns: None, + }, + ) => LayerSelection::Last, + Some(Action::Delete { patterns, .. }) + if patterns.as_ref().is_none_or(|p| p.is_empty()) => { - let name = entry.file_name().to_string_lossy().to_string(); - let metadata = entry.metadata()?; - let created = metadata - .created() - .or_else(|_| metadata.modified()) - .context("Failed to get creation time for layer")?; - layers.push((name, created)); + LayerSelection::Last } + Some(Action::Config { .. }) => LayerSelection::LastOrNew, + Some(_) => LayerSelection::New, } +} + +/// Finds the newest layer created in `cwd`, or else in the nearest ancestor +/// of `cwd` that has layers. Layers without a recorded creation directory are +/// ignored. +fn find_last_layer(storage_dir: &Path, cwd: &Path) -> Result { + let cwd = cwd.canonicalize().context(format!( + "Failed to canonicalize current directory {}", + cwd.display() + ))?; + + let layers: Vec<(PathBuf, String, SystemTime)> = + std::fs::read_dir(storage_dir) + .into_iter() + .flatten() + .flatten() + .filter_map(|entry| { + let path = entry.path(); + let settings = LayerSettings::load_from_file( + &path.join("data").join("settings.json"), + ) + .ok()?; + let metadata = entry.metadata().ok()?; + let created = + metadata.created().or_else(|_| metadata.modified()).ok()?; + Some(( + settings.created_in?, + entry.file_name().to_string_lossy().to_string(), + created, + )) + }) + .collect(); #[cfg(feature = "coverage")] - let mut layers = if std::env::var_os("TEST_LAST_IS_EMPTY").is_some() { + let layers = if std::env::var_os("TEST_LAST_IS_EMPTY").is_some() { vec![] } else { layers }; - if layers.is_empty() { - return Err(anyhow::anyhow!("No layers found")); - } - - // Sort by creation time (newest first) - layers.sort_by(|a, b| b.1.cmp(&a.1)); - - Ok(layers[0].0.clone()) + cwd.ancestors() + .find_map(|dir| { + layers + .iter() + .filter(|(created_in, _, _)| created_in == dir) + .max_by_key(|(_, _, created)| *created) + .map(|(_, name, _)| name.clone()) + }) + .ok_or_else(|| { + anyhow::anyhow!( + "No devlayer found for {} or its parent directories; use --join or `devlayer list`", + cwd.display() + ) + }) } #[cfg(test)] @@ -982,6 +1048,58 @@ mod tests { // Mutex to ensure XDG_RUNTIME_DIR tests don't interfere with each other static XDG_TEST_MUTEX: Mutex<()> = Mutex::new(()); + #[test] + fn default_selection_by_action() { + use LayerSelection::*; + let none = || None; + let some = |p: &[&str]| Some(p.iter().map(|s| s.to_string()).collect()); + + assert_eq!(default_selection(None), New); + for action in [ + Action::Status { patterns: none() }, + Action::Diff { patterns: none() }, + Action::Accept { patterns: none() }, + Action::Reject { patterns: none() }, + Action::Stop { + all: false, + patterns: none(), + }, + Action::Delete { + yes: true, + patterns: none(), + }, + Action::Delete { + yes: true, + patterns: some(&[]), + }, + ] { + assert_eq!(default_selection(Some(&action)), Last, "{action:?}"); + } + assert_eq!( + default_selection(Some(&Action::Config { keys: none() })), + LastOrNew + ); + for action in [ + Action::Stop { + all: true, + patterns: none(), + }, + Action::Stop { + all: false, + patterns: some(&["x"]), + }, + Action::Delete { + yes: true, + patterns: some(&["x"]), + }, + Action::List { patterns: none() }, + Action::Sync, + Action::Clean { yes: true }, + ] { + assert_eq!(default_selection(Some(&action)), New, "{action:?}"); + } + } + /// Creates an empty, unique fake home directory for LLM bind tests fn fake_home(tag: &str) -> PathBuf { let home = std::env::temp_dir().join(format!( diff --git a/tests/ai_test_cwd_bind.rs b/tests/ai_test_cwd_bind.rs index c9b4c1b..f695995 100644 --- a/tests/ai_test_cwd_bind.rs +++ b/tests/ai_test_cwd_bind.rs @@ -72,6 +72,10 @@ fn ai_test_refuse_root(mut layer: LayerManager) -> Result<()> { )); assert!(layer.pass(&["--no-bind-cwd", "true"])); + + // A layer created in / is an ancestor of every directory, so it would be + // picked by --last everywhere; delete it right away + layer.run(&["delete", "-y"])?; Ok(()) } diff --git a/tests/ai_test_layer_selection.rs b/tests/ai_test_layer_selection.rs new file mode 100644 index 0000000..04182e3 --- /dev/null +++ b/tests/ai_test_layer_selection.rs @@ -0,0 +1,220 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use rstest::*; +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; + +/// Runs devlayer with the default layer selection from project directories +/// under the system temp dir, outside the repository, so layers that other +/// tests create in the repository root never match --last. Layers created +/// here are tracked and deleted on drop. +struct Selection { + layer: LayerManager, + storage: PathBuf, + root: PathBuf, + before: BTreeSet, +} + +impl Selection { + fn new(layer: LayerManager) -> Result { + let mut layer = layer; + // No --join, so the default selection applies + layer.no_default_options = true; + let root = std::env::temp_dir() + .join(format!("devlayer-coverage-sel-{}", rid())); + std::fs::create_dir_all(&root)?; + layer.cwd = Some(root.clone()); + layer.run(&["--new", "config", "storage_dir"])?; + let storage = PathBuf::from(layer.last_stdout.trim()); + let mut sel = Self { + layer, + storage, + root, + before: BTreeSet::new(), + }; + sel.before = sel.layers()?; + Ok(sel) + } + + /// Creates (if needed) and returns `root/rel` + fn dir(&self, rel: &str) -> Result { + let dir = self.root.join(rel); + std::fs::create_dir_all(&dir)?; + Ok(dir) + } + + fn pass(&mut self, cwd: &Path, args: &[&str]) -> bool { + self.layer.cwd = Some(cwd.to_path_buf()); + self.layer.pass(args) + } + + fn xfail(&mut self, cwd: &Path, args: &[&str]) -> bool { + self.layer.cwd = Some(cwd.to_path_buf()); + self.layer.xfail(args) + } + + fn stdout(&self) -> String { + self.layer.last_stdout.trim().to_string() + } + + /// Names of all layers in the storage directory + fn layers(&self) -> Result> { + let mut names = BTreeSet::new(); + for entry in std::fs::read_dir(&self.storage)? { + let entry = entry?; + if entry.path().is_dir() { + names.insert(entry.file_name().to_string_lossy().to_string()); + } + } + Ok(names) + } + + /// Layers created since this Selection was made + fn created(&self) -> Result> { + Ok(self.layers()?.difference(&self.before).cloned().collect()) + } + + /// Runs `true` in `cwd` with the default selection and returns the name + /// of the layer it created + fn create_in(&mut self, cwd: &Path) -> Result { + let before = self.layers()?; + assert!(self.pass(cwd, &["true"])); + let after = self.layers()?; + let created: Vec<_> = after.difference(&before).cloned().collect(); + assert_eq!(created.len(), 1, "expected exactly one new layer"); + // Keep creation times strictly ordered + std::thread::sleep(std::time::Duration::from_millis(20)); + Ok(created[0].clone()) + } +} + +impl Drop for Selection { + fn drop(&mut self) { + let root = self.root.clone(); + for name in self.created().unwrap_or_default() { + let join = format!("--join={}", name); + let _ = self.pass(&root, &[&join, "delete", "-y"]); + } + self.layer.cwd = None; + let _ = std::fs::remove_dir_all(&self.root); + } +} + +#[rstest] +fn ai_test_bare_run_creates_new_each_time(layer: LayerManager) -> Result<()> { + let mut sel = Selection::new(layer)?; + let dir = sel.dir("project")?; + + let first = sel.create_in(&dir)?; + let second = sel.create_in(&dir)?; + assert_ne!(first, second); + assert!(first.starts_with("ephemeral_")); + assert!(second.starts_with("ephemeral_")); + Ok(()) +} + +#[rstest] +fn ai_test_last_nearest_ancestor_and_newest(layer: LayerManager) -> Result<()> { + let mut sel = Selection::new(layer)?; + let dir = sel.dir("project")?; + let sub = sel.dir("project/sub")?; + let deeper = sel.dir("project/sub/deeper")?; + + let _l1 = sel.create_in(&dir)?; + let l2 = sel.create_in(&dir)?; + let l3 = sel.create_in(&sub)?; + + // Newest of the layers created in this exact directory + assert!(sel.pass(&dir, &["--last", "config", "name"])); + assert_eq!(sel.stdout(), l2); + + // Nearest ancestor with layers wins + assert!(sel.pass(&deeper, &["--last", "config", "name"])); + assert_eq!(sel.stdout(), l3); + + // A layer created deeper down is never chosen from a parent directory + let parent = sel.root.clone(); + assert!(sel.xfail(&parent, &["--last", "config", "name"])); + assert!(sel.layer.last_stderr.contains("No devlayer found")); + Ok(()) +} + +#[rstest] +fn ai_test_actions_default_to_last(layer: LayerManager) -> Result<()> { + let mut sel = Selection::new(layer)?; + let dir = sel.dir("project")?; + let outside = sel.root.join("outside-file"); + let outside = outside.to_str().unwrap_or_default().to_string(); + + assert!(sel.pass(&dir, &["touch", &outside])); + let name = sel.created()?.into_iter().next(); + + assert!(sel.pass(&dir, &["status", "/"])); + assert!(sel.layer.last_stdout.contains("outside-file")); + + assert!(sel.pass(&dir, &["config", "name"])); + assert_eq!(Some(sel.stdout()), name); + Ok(()) +} + +#[rstest] +fn ai_test_stop_delete_default_to_last(layer: LayerManager) -> Result<()> { + let mut sel = Selection::new(layer)?; + let dir = sel.dir("project")?; + let other_dir = sel.dir("other")?; + let name = sel.create_in(&dir)?; + let other = sel.create_in(&other_dir)?; + + assert!(sel.pass(&dir, &["stop"])); + assert!(sel.pass(&dir, &["delete", "-y"])); + let layers = sel.layers()?; + assert!(!layers.contains(&name)); + assert!(layers.contains(&other)); + Ok(()) +} + +#[rstest] +fn ai_test_list_clean_sync_no_layer_ok(layer: LayerManager) -> Result<()> { + let mut sel = Selection::new(layer)?; + let empty = sel.dir("empty")?; + + assert!(sel.pass(&empty, &["list"])); + assert!(sel.pass(&empty, &["clean", "-y"])); + assert!(sel.pass(&empty, &["config"])); + // sync drops system caches, which may not be allowed inside containers; + // it must not fail because there is no layer for this directory + sel.pass(&empty, &["sync"]); + assert!(!sel.layer.last_stderr.contains("No devlayer found")); + + assert!(sel.created()?.is_empty()); + Ok(()) +} + +#[rstest] +fn ai_test_explicit_selector_wins(layer: LayerManager) -> Result<()> { + let mut sel = Selection::new(layer)?; + let dir = sel.dir("project")?; + let name = sel.create_in(&dir)?; + + assert!( + sel.pass(&dir, &["--join=devlayer-coverage-other", "config", "name"]) + ); + assert_eq!(sel.stdout(), "devlayer-coverage-other"); + + assert!(sel.pass(&dir, &["--new", "config", "name"])); + assert!(sel.stdout().starts_with("ephemeral_")); + assert_ne!(sel.stdout(), name); + Ok(()) +} + +#[rstest] +fn ai_test_last_errors_without_layer(layer: LayerManager) -> Result<()> { + let mut sel = Selection::new(layer)?; + let empty = sel.dir("empty")?; + + assert!(sel.xfail(&empty, &["status"])); + assert!(sel.layer.last_stderr.contains("No devlayer found")); + Ok(()) +} diff --git a/tests/fixtures/fixture_layer.rs b/tests/fixtures/fixture_layer.rs index 984fa76..12b3733 100644 --- a/tests/fixtures/fixture_layer.rs +++ b/tests/fixtures/fixture_layer.rs @@ -122,10 +122,18 @@ impl LayerManager { } } - /// Applies the configured working directory to a command + /// Applies the configured working directory to a command. A relative + /// LLVM_PROFILE_FILE is made absolute so coverage data from commands run + /// elsewhere still lands in this repository. fn apply_cwd(&self, cmd: &mut Command) { if let Some(cwd) = &self.cwd { cmd.current_dir(cwd); + if let (Ok(profile), Ok(here)) = + (std::env::var("LLVM_PROFILE_FILE"), std::env::current_dir()) + && Path::new(&profile).is_relative() + { + cmd.env("LLVM_PROFILE_FILE", here.join(profile)); + } } } diff --git a/tests/test_new_last.rs b/tests/test_new_last.rs index ce26a38..9dcebaf 100644 --- a/tests/test_new_last.rs +++ b/tests/test_new_last.rs @@ -23,7 +23,7 @@ fn test_last_is_empty(mut layer: LayerManager) -> Result<()> { layer.no_default_options = true; assert!(layer.exfail(&["--last", "-v", "true"], "TEST_LAST_IS_EMPTY", "1")); - assert!(layer.last_stderr.contains("No layers found")); + assert!(layer.last_stderr.contains("No devlayer found")); Ok(()) } From 8535ea9bda7cd4f57e2a8d128ce6b2d7658ed1b5 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 06:16:35 -0500 Subject: [PATCH 10/32] Whole-layer status/diff by default; accept/reject require a pattern --- README.adoc | 41 ++++++--- cspell.json | 3 + ...2026-11-13-devlayer-rename-and-defaults.md | 1 + src/actions/accept.rs | 6 ++ src/actions/reject.rs | 6 ++ src/config/cli.rs | 12 ++- src/layer/changes/change_entries.rs | 13 +-- tests/ai_cli_flags.rs | 4 +- tests/ai_test_accept.rs | 22 ++--- tests/ai_test_action_scope.rs | 92 +++++++++++++++++++ tests/ai_test_delete.rs | 6 +- tests/ai_test_diff_coverage.rs | 26 +++--- tests/isolated_test_twisted.rs | 4 +- tests/test_accept.rs | 28 +++--- tests/test_accept_deep_reshuffle.rs | 4 +- tests/test_diff.rs | 4 +- tests/test_json.rs | 2 +- tests/test_layer_failures.rs | 14 +-- tests/test_misc.rs | 8 +- tests/test_reject.rs | 4 +- tests/test_status.rs | 8 +- 21 files changed, 211 insertions(+), 97 deletions(-) create mode 100644 tests/ai_test_action_scope.rs diff --git a/README.adoc b/README.adoc index f0e8f66..8022ce3 100644 --- a/README.adoc +++ b/README.adoc @@ -99,15 +99,20 @@ Let AIs run wild in YOLO mode without too much risk devlayer aider ``` -Check what files were modified +Check what files were modified outside the current directory ``` devlayer status ``` -Accept changes to all the python files in the current directory, copying -them from the layer to the host system. +Accept changes to your shell config, copying them from the layer to the host +system ``` - devlayer accept '*.py' + devlayer accept ~/.bashrc +``` + +Accept every change in the layer +``` + devlayer accept / ``` Stop all running processes in the layer and unmount the copy on write filesystem overlays. @@ -124,17 +129,23 @@ Stop all running processes in the layer and unmount the copy on write filesystem List running layers matching these patterns (defaults to all) `status [PATTERNS]`:: -Show status of the layer matching the patterns in the current directory, or specified -patterns. Use `status /` to show status of all files in the layer. - -`diff`:: -Show changes in the layer relative to the current changes - -`reject [PATTERNS]`:: -Reject changes in the layer. This works relative to your current working directory only, and changes outside of your working directory are ignored. - -`accept [PATTERNS]`:: -Accept changes in the layer. This works relative to your current working directory only, and changes outside of your working directory are ignored. +Show the changes in the layer. With no patterns this shows every change in the +layer; patterns are relative to your current directory, for example +`status .` shows only changes under the current directory. + +`diff [PATTERNS]`:: +Show the content of the changes in the layer. Like `status`, with no patterns +this covers every change in the layer. + +`reject PATTERNS`:: +Reject the changes in the layer that match the patterns. At least one pattern +is required; use `devlayer reject /` to reject every change in the layer. +Relative patterns are relative to your current directory. + +`accept PATTERNS`:: +Accept the changes in the layer that match the patterns, copying them to your +host. At least one pattern is required; use `devlayer accept /` to accept every +change in the layer. Relative patterns are relative to your current directory. `sync`:: Synchronize changes that might have occurred in your host file system so that they are reflected in running layers. Note, this performs a system wide filesystem sync and flushes all caches. diff --git a/cspell.json b/cspell.json index a0e6fab..986aca1 100644 --- a/cspell.json +++ b/cspell.json @@ -195,6 +195,9 @@ "rustsec", "rustup", "devlayer", + "herdr", + "opencode", + "qwen", "sched", "serde", "setegid", diff --git a/docs/superpowers/plans/2026-11-13-devlayer-rename-and-defaults.md b/docs/superpowers/plans/2026-11-13-devlayer-rename-and-defaults.md index d1ff67f..c630a33 100644 --- a/docs/superpowers/plans/2026-11-13-devlayer-rename-and-defaults.md +++ b/docs/superpowers/plans/2026-11-13-devlayer-rename-and-defaults.md @@ -1,3 +1,4 @@ + # devlayer Rename and New Defaults Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/src/actions/accept.rs b/src/actions/accept.rs index 0251d0d..bd2b711 100644 --- a/src/actions/accept.rs +++ b/src/actions/accept.rs @@ -122,6 +122,12 @@ pub fn accept( ) -> Result<()> { trace!("Accepting changes from layer {}", layer.name); + if patterns.is_empty() { + return Err(anyhow::anyhow!( + "accept requires at least one pattern; use `devlayer accept /` to accept every change in the layer" + )); + } + let cwd = std::env::current_dir()?; let all_changes = layer.changes(config)?; diff --git a/src/actions/reject.rs b/src/actions/reject.rs index 46d3db8..b7ce90d 100644 --- a/src/actions/reject.rs +++ b/src/actions/reject.rs @@ -14,6 +14,12 @@ pub fn reject( ) -> Result<()> { trace!("Rejecting changes from layer {}", layer.name); + if patterns.is_empty() { + return Err(anyhow::anyhow!( + "reject requires at least one pattern; use `devlayer reject /` to reject every change in the layer" + )); + } + let cwd = std::env::current_dir()?; let changes = layer.changes(config)?; diff --git a/src/config/cli.rs b/src/config/cli.rs index c78b031..a1252d6 100644 --- a/src/config/cli.rs +++ b/src/config/cli.rs @@ -168,28 +168,30 @@ pub enum Action { patterns: Option>, }, - /// Show status of the layer matching the patterns in the current directory, or specified - /// patterns. Use `status /` to show status of all files in the layer. + /// Show the changes in the layer, all of them by default. Patterns are relative to the + /// current directory, so `status .` shows only changes under it. Status { /// Patterns of files to show #[arg(value_name = "PATTERNS", num_args = 0..)] patterns: Option>, }, - /// Show changes in the layer relative to the current changes + /// Show the content of the changes in the layer, all of them by default Diff { /// Patterns of files to diff #[arg(value_name = "PATTERNS", num_args = 0..)] patterns: Option>, }, - /// Accept changes in the layer + /// Accept the changes matching the patterns. At least one pattern is required; use + /// `accept /` to accept every change in the layer. Accept { #[arg(value_name = "PATTERNS", num_args = 0..)] patterns: Option>, }, - /// Reject changes in the layer + /// Reject the changes matching the patterns. At least one pattern is required; use + /// `reject /` to reject every change in the layer. Reject { #[arg(value_name = "PATTERNS", num_args = 0..)] patterns: Option>, diff --git a/src/layer/changes/change_entries.rs b/src/layer/changes/change_entries.rs index 5b82ad5..df09345 100644 --- a/src/layer/changes/change_entries.rs +++ b/src/layer/changes/change_entries.rs @@ -276,25 +276,18 @@ impl ChangeEntries { }) .collect(); - let cwd_str = format!("{}/", cwd.display()); ChangeEntries( self.0 .iter() .filter(|change| { - if patterns.is_empty() { - change - .destination - .display() - .to_string() - .starts_with(&cwd_str) - } else { - patterns.iter().any(|pattern| { + // With no patterns every change in the layer matches + patterns.is_empty() + || patterns.iter().any(|pattern| { glob_match( pattern, change.destination.display().to_string(), ) }) - } }) .cloned() .collect(), diff --git a/tests/ai_cli_flags.rs b/tests/ai_cli_flags.rs index 6f42e33..6f27c18 100644 --- a/tests/ai_cli_flags.rs +++ b/tests/ai_cli_flags.rs @@ -34,7 +34,7 @@ fn test_flags_before_action(mut layer: LayerManager) -> Result<()> { ); // Test a simple action without extra flags - assert!(layer.pass(&["--join", &name, "status"])); + assert!(layer.pass(&["--join", &name, "status", "."])); Ok(()) } @@ -65,7 +65,7 @@ fn test_flags_after_action(mut layer: LayerManager) -> Result<()> { ); // Test a simple action without extra flags - assert!(layer.pass(&["--join", &name, "status"])); + assert!(layer.pass(&["--join", &name, "status", "."])); Ok(()) } diff --git a/tests/ai_test_accept.rs b/tests/ai_test_accept.rs index 3579ab1..2369010 100644 --- a/tests/ai_test_accept.rs +++ b/tests/ai_test_accept.rs @@ -27,7 +27,7 @@ fn test_accept_directory_removal_counting( layer.run(&["rm", "-rf", &dirname])?; // First check the status to see what changes are detected - layer.run(&["status"])?; + layer.run(&["status", "."])?; let status_output = layer.last_stdout.clone(); println!("Full status output:\n{}", status_output); @@ -39,7 +39,7 @@ fn test_accept_directory_removal_counting( let removal_count = status_lines.len(); // Accept all changes - we'll filter by the dirname in our counting - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; // The output should show the actual count of changes // This will help us verify if there's double counting @@ -125,11 +125,11 @@ fn test_accept_pretend_count_mixed_operations( layer.run(&["touch", layer.test_filename("new-file.txt").as_str()])?; // Create // Check status first to see what changes exist - layer.run(&["status"])?; + layer.run(&["status", "."])?; println!("Status output:\n{}", layer.last_stdout); // Accept changes and verify counts - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; let output = layer.last_stdout.clone(); println!("Accept output:\n{}", output); @@ -178,7 +178,7 @@ fn test_accept_file_in_new_directory_counts_once( layer.run(&["sh", "-c", &format!("echo content > {}", filename)])?; // Check status to see what changes are detected - layer.run(&["status"])?; + layer.run(&["status", "."])?; let status_output = layer.last_stdout.clone(); println!("Status output:\n{}", status_output); @@ -194,7 +194,7 @@ fn test_accept_file_in_new_directory_counts_once( } // Accept changes - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; let output = layer.last_stdout.clone(); println!("Accept output:\n{}", output); @@ -239,7 +239,7 @@ fn test_accept_file_in_depth_2_directory( layer.run(&["touch", &filename])?; // Check status to see what changes are detected - layer.run(&["status"])?; + layer.run(&["status", "."])?; let status_output = layer.last_stdout.clone(); println!("Status output:\n{}", status_output); @@ -255,7 +255,7 @@ fn test_accept_file_in_depth_2_directory( } // Accept all changes (not just our directory) - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; let output = layer.last_stdout.clone(); println!("Accept output:\n{}", output); @@ -317,7 +317,7 @@ fn test_accept_directory_removal_counts_all_components( layer.run(&["rm", "-rf", &dir_a])?; // Check status - layer.run(&["status"])?; + layer.run(&["status", "."])?; let status_output = layer.last_stdout.clone(); println!("Status output:\n{}", status_output); @@ -329,7 +329,7 @@ fn test_accept_directory_removal_counts_all_components( println!("Removal count: {}", removal_count); // Accept all changes (not filtered by pattern to avoid issues) - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; let output = layer.last_stdout.clone(); println!("Accept output:\n{}", output); @@ -388,7 +388,7 @@ fn test_accept_non_matching_count_message( ])?; // Check status to see all changes - layer.run(&["status"])?; + layer.run(&["status", "."])?; let status_output = layer.last_stdout.clone(); println!("Status output:\n{}", status_output); diff --git a/tests/ai_test_action_scope.rs b/tests/ai_test_action_scope.rs new file mode 100644 index 0000000..1dbf8fe --- /dev/null +++ b/tests/ai_test_action_scope.rs @@ -0,0 +1,92 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use rstest::*; +use std::path::PathBuf; + +/// Creates `/a` and `/b`, runs the layer from `a`, and +/// writes `b/` inside the layer. Returns the host path of that file. +fn write_outside_cwd( + layer: &mut LayerManager, + file: &str, + contents: &str, +) -> Result { + let root = std::env::current_dir()?.join(layer.test_filename("scope")); + std::fs::create_dir_all(root.join("a"))?; + std::fs::create_dir_all(root.join("b"))?; + layer.cwd = Some(root.join("a")); + let path = root.join("b").join(file); + let script = format!("echo {} > {}", contents, path.display()); + layer.run(&["sh", "-c", &script])?; + Ok(path) +} + +#[rstest] +fn ai_test_status_default_whole_layer(mut layer: LayerManager) -> Result<()> { + write_outside_cwd(&mut layer, "scope-status-file", "x")?; + layer.run(&["status"])?; + assert!(layer.last_stdout.contains("scope-status-file")); + Ok(()) +} + +#[rstest] +fn ai_test_diff_default_whole_layer(mut layer: LayerManager) -> Result<()> { + write_outside_cwd(&mut layer, "scope-diff-file", "scope-diff-contents")?; + layer.run(&["diff"])?; + assert!(layer.last_stdout.contains("scope-diff-contents")); + Ok(()) +} + +#[rstest] +fn ai_test_status_diff_patterns_still_filter( + mut layer: LayerManager, +) -> Result<()> { + write_outside_cwd( + &mut layer, + "scope-filter-file", + "scope-filter-contents", + )?; + + layer.run(&["status", "./nothing-here"])?; + assert!(!layer.last_stdout.contains("scope-filter-file")); + layer.run(&["status", "../b"])?; + assert!(layer.last_stdout.contains("scope-filter-file")); + + layer.run(&["diff", "./nothing-here"])?; + assert!(!layer.last_stdout.contains("scope-filter-contents")); + layer.run(&["diff", "../b"])?; + assert!(layer.last_stdout.contains("scope-filter-contents")); + Ok(()) +} + +#[rstest] +fn ai_test_accept_requires_pattern(mut layer: LayerManager) -> Result<()> { + let path = write_outside_cwd(&mut layer, "scope-accept-file", "x")?; + + assert!(layer.xfail(&["accept"])); + assert!(layer.last_stderr.contains( + "accept requires at least one pattern; use `devlayer accept /` to accept every change in the layer" + )); + + // Nothing was accepted + assert!(!path.exists()); + layer.run(&["status", "/"])?; + assert!(layer.last_stdout.contains("scope-accept-file")); + Ok(()) +} + +#[rstest] +fn ai_test_reject_requires_pattern(mut layer: LayerManager) -> Result<()> { + write_outside_cwd(&mut layer, "scope-reject-file", "x")?; + + assert!(layer.xfail(&["reject"])); + assert!(layer.last_stderr.contains( + "reject requires at least one pattern; use `devlayer reject /` to reject every change in the layer" + )); + + // Nothing was rejected + layer.run(&["status", "/"])?; + assert!(layer.last_stdout.contains("scope-reject-file")); + Ok(()) +} diff --git a/tests/ai_test_delete.rs b/tests/ai_test_delete.rs index f226157..6384616 100644 --- a/tests/ai_test_delete.rs +++ b/tests/ai_test_delete.rs @@ -176,7 +176,7 @@ fn test_delete_stopped_layer() -> Result<()> { // Stop the layer layer.run(&["stop"])?; - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; // Delete the stopped layer layer.run_with_stdin(&["delete"], "y\n")?; @@ -240,7 +240,7 @@ fn test_delete_stopped_layer_by_name() -> Result<()> { // Stop the layer layer.run(&["stop"])?; - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; // Delete the stopped layer layer.run_with_stdin(&["delete", &name], "y\n")?; @@ -269,7 +269,7 @@ fn test_delete_running_layer_by_name() -> Result<()> { layer.run(&["true"])?; // Accept the layer - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; // Delete the running layer layer.run_with_stdin(&["delete", &name], "y\n")?; diff --git a/tests/ai_test_diff_coverage.rs b/tests/ai_test_diff_coverage.rs index 1cc4329..8447785 100644 --- a/tests/ai_test_diff_coverage.rs +++ b/tests/ai_test_diff_coverage.rs @@ -16,7 +16,7 @@ fn test_diff_rename_operation(mut layer: LayerManager) -> Result<()> { layer.run(&["mv", &dir1, &dir2])?; // Diff should show the rename - layer.run(&["diff"])?; + layer.run(&["diff", "."])?; assert!(layer.last_stdout.contains("### Moved")); assert!(layer.last_stdout.contains(&dir1)); assert!(layer.last_stdout.contains(&dir2)); @@ -34,7 +34,7 @@ fn test_diff_colorized_output(mut layer: LayerManager) -> Result<()> { layer.run(&["sh", "-c", &format!("echo 'modified' > {}", file)])?; // Check diff output with color forced - layer.run_with_env(&["diff"], "TEST_FORCE_DIFF_COLOR", "1")?; + layer.run_with_env(&["diff", "."], "TEST_FORCE_DIFF_COLOR", "1")?; assert!(layer.last_stdout.contains("-original")); assert!(layer.last_stdout.contains("+modified")); // The actual color codes would be in the output when TEST_FORCE_DIFF_COLOR is set @@ -52,7 +52,7 @@ fn test_diff_no_color(mut layer: LayerManager) -> Result<()> { layer.run(&["sh", "-c", &format!("echo 'changed' > {}", file)])?; // Check diff output with NO_COLOR set - layer.run_with_env(&["diff"], "NO_COLOR", "1")?; + layer.run_with_env(&["diff", "."], "NO_COLOR", "1")?; assert!(layer.last_stdout.contains("-content")); assert!(layer.last_stdout.contains("+changed")); @@ -70,7 +70,7 @@ fn test_diff_rename_colorized(mut layer: LayerManager) -> Result<()> { layer.run(&["mv", &dir1, &dir2])?; // Diff with color forced - layer.run_with_env(&["diff"], "TEST_FORCE_DIFF_COLOR", "1")?; + layer.run_with_env(&["diff", "."], "TEST_FORCE_DIFF_COLOR", "1")?; assert!(layer.last_stdout.contains("### Moved")); // When colorized, the output would have ANSI color codes @@ -92,7 +92,7 @@ fn test_diff_error_operation_unsupported_file_type( layer.run(&["sh", "-c", "echo 'data' > test.fifo &"])?; // Check diff - should skip error entries - layer.run(&["diff"])?; + layer.run(&["diff", "."])?; // Error operations are silently skipped in diff Ok(()) @@ -108,7 +108,7 @@ fn test_diff_non_file_destination(mut layer: LayerManager) -> Result<()> { layer.run(&["chmod", "755", &dir_path])?; // Diff should skip directories - layer.run(&["diff"])?; + layer.run(&["diff", "."])?; // Should not contain diff output for directory assert!(!layer.last_stdout.contains("test_dir")); @@ -126,7 +126,7 @@ fn test_diff_staged_non_file(mut layer: LayerManager) -> Result<()> { layer.run(&["mkdir", &file_path])?; // Diff should handle this case - layer.run(&["diff"])?; + layer.run(&["diff", "."])?; Ok(()) } @@ -137,7 +137,7 @@ fn test_diff_missing_destination_file(mut layer: LayerManager) -> Result<()> { layer.run(&["sh", "-c", "echo 'new content' > newfile.txt"])?; // Diff should use /dev/null as left path - layer.run(&["diff"])?; + layer.run(&["diff", "."])?; assert!(layer.last_stdout.contains("+new content")); Ok(()) @@ -153,7 +153,7 @@ fn test_diff_remove_operation(mut layer: LayerManager) -> Result<()> { layer.run(&["rm", &file_path])?; // Diff should show deletion - layer.run(&["diff"])?; + layer.run(&["diff", "."])?; assert!(layer.last_stdout.contains("-content to remove")); Ok(()) @@ -173,7 +173,7 @@ fn test_diff_path_replacement_in_output(mut layer: LayerManager) -> Result<()> { ])?; // Check diff output - layer.run(&["diff"])?; + layer.run(&["diff", "."])?; assert!(layer.last_stdout.contains("-Original content")); assert!(layer.last_stdout.contains("+Modified content")); @@ -189,7 +189,7 @@ fn test_diff_force_color_env_variable(mut layer: LayerManager) -> Result<()> { layer.run(&["sh", "-c", &format!("echo 'modified' > {}", file_path)])?; // Test with TEST_FORCE_DIFF_COLOR set - layer.run_with_env(&["diff"], "TEST_FORCE_DIFF_COLOR", "1")?; + layer.run_with_env(&["diff", "."], "TEST_FORCE_DIFF_COLOR", "1")?; assert!(layer.last_stdout.contains("-original")); assert!(layer.last_stdout.contains("+modified")); // Color codes would be in the actual diff output @@ -218,7 +218,7 @@ fn test_diff_with_patterns(mut layer: LayerManager) -> Result<()> { assert!(!layer.last_stdout.contains("modified log")); // Diff with pattern matching - show all changes - layer.run(&["diff"])?; + layer.run(&["diff", "."])?; assert!(layer.last_stdout.contains("modified1")); assert!(layer.last_stdout.contains("modified2")); assert!(layer.last_stdout.contains("modified log")); @@ -236,7 +236,7 @@ fn test_diff_edge_case_null_staged(mut layer: LayerManager) -> Result<()> { layer.run(&["sh", "-c", &format!("echo 'new' > {}", file_path)])?; // Diff should work normally - layer.run(&["diff"])?; + layer.run(&["diff", "."])?; assert!(layer.last_stdout.contains("-original")); assert!(layer.last_stdout.contains("+new")); diff --git a/tests/isolated_test_twisted.rs b/tests/isolated_test_twisted.rs index df71f43..9ded799 100644 --- a/tests/isolated_test_twisted.rs +++ b/tests/isolated_test_twisted.rs @@ -43,7 +43,7 @@ fn test_twisted(mut layer: LayerManager) -> Result<()> { ])?; layer.run(&["rm", format!("{}/d/a/b/file_b", path.display()).as_str()])?; - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; assert!( std::fs::read_to_string(format!("{}/d/file_c_v2", path.display()))? @@ -99,7 +99,7 @@ fn test_twisted_fail_rmdir_on_separate_device( layer.run(&["rm", format!("{}/d/a/b/file_b", path.display()).as_str()])?; assert!(layer.exfail( - &["accept"], + &["accept", "."], "TEST_ACCEPT_FAIL_RMDIR_ON_DIFFERENT_DEVICE", "1" )); diff --git a/tests/test_accept.rs b/tests/test_accept.rs index b41982b..7253b57 100644 --- a/tests/test_accept.rs +++ b/tests/test_accept.rs @@ -71,7 +71,7 @@ fn test_accept_rename_file(mut layer: LayerManager) -> Result<()> { layer.run(&["mv", &filename, &new_filename])?; assert!(path.exists()); assert!(!new_path.exists()); - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; assert!(!path.exists()); assert!(new_path.exists()); Ok(()) @@ -106,7 +106,7 @@ fn test_accept_rename_upper_directory(mut layer: LayerManager) -> Result<()> { assert!(!path.exists()); assert!(!new_path.exists()); layer.run(&["mv", &dirname, &new_dirname])?; - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; assert!(!path.exists()); assert!(new_path.exists()); Ok(()) @@ -124,7 +124,7 @@ fn test_accept_rename_lower_directory(mut layer: LayerManager) -> Result<()> { layer.run(&["mv", &dirname, &new_dirname])?; assert!(path.exists()); assert!(!new_path.exists()); - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; assert!(!path.exists()); assert!(new_path.exists()); Ok(()) @@ -145,7 +145,7 @@ fn test_accept_rename_lower_directory_with_stuff( layer.run(&["mv", &dirname, &new_dirname])?; assert!(path.exists()); assert!(!new_path.exists()); - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; assert!(!path.exists()); assert!(new_path.exists()); assert!(new_path.join("test-file").exists()); @@ -192,7 +192,7 @@ fn test_accept_rename_symlink(mut layer: LayerManager) -> Result<()> { layer.run(&["mv", &upper_symlink, &new_upper_symlink])?; layer.run(&["mv", &lower_symlink, &new_lower_symlink])?; - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; assert!(filename_path.exists()); assert!(!lower_symlink_path.exists()); assert!(new_lower_symlink_path.exists()); @@ -216,7 +216,7 @@ fn test_accept_remove_file(mut layer: LayerManager) -> Result<()> { assert!(path.exists()); layer.run(&["rm", &filename])?; assert!(path.exists()); - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; assert!(!path.exists()); Ok(()) } @@ -229,7 +229,7 @@ fn test_accept_remove_directory(mut layer: LayerManager) -> Result<()> { assert!(path.exists()); layer.run(&["rmdir", &dirname])?; assert!(path.exists()); - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; assert!(!path.exists()); Ok(()) } @@ -247,7 +247,7 @@ fn test_accept_remove_symlink(mut layer: LayerManager) -> Result<()> { assert!(path.exists()); layer.run(&["rm", &symlink])?; assert!(path.exists()); - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; assert!(Path::new(&filename).exists()); assert!(!path.exists()); Ok(()) @@ -284,7 +284,7 @@ fn test_accept_opaque_directory(mut layer: LayerManager) -> Result<()> { assert!(!new_file.exists()); assert!(!post_moved_masked_file.exists()); - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; assert!(dirname_path.exists()); assert!(dir_renamed_path.exists()); assert!(!masked_file.exists()); @@ -320,7 +320,7 @@ fn test_accept_removed_opaque_directory(mut layer: LayerManager) -> Result<()> { assert!(old_file.exists()); assert!(!new_file.exists()); - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; assert!(dirname_path.exists()); assert!(!old_file.exists()); assert!(new_file.exists()); @@ -445,7 +445,7 @@ fn test_accept_symlink_overwrites(mut layer: LayerManager) -> Result<()> { layer.run(&["ln", "-s", file2_symlink_name, &file])?; layer.run(&["ln", "-s", file2_symlink_name, &dir])?; - assert!(layer.pass(&["accept"])); + assert!(layer.pass(&["accept", "."])); let file_contents = std::fs::read(&file)?; let dir_contents = std::fs::read(&dir)?; @@ -462,7 +462,7 @@ fn test_accept_directory_overwrite(mut layer: LayerManager) -> Result<()> { std::fs::write(&p, "test")?; layer.run(&["rm", &p])?; layer.run(&["mkdir", &p])?; - assert!(layer.pass(&["accept"])); + assert!(layer.pass(&["accept", "."])); let path = Path::new(&p); assert!(path.exists()); assert!(path.is_dir()); @@ -553,7 +553,7 @@ fn test_accept_inside_out(mut layer: LayerManager) -> Result<()> { layer.run(&["rm", post_B_file_del_post.to_str().unwrap()])?; // Accept the changes and verify the contents - assert!(layer.pass(&["accept"])); + assert!(layer.pass(&["accept", "."])); assert!(post_A.exists()); assert!(post_B.exists()); assert!(post_A_file_pre.exists()); @@ -629,7 +629,7 @@ fn test_accept_opaque(mut layer: LayerManager) -> Result<()> { .as_str(), ])?; - assert!(layer.pass(&["accept"])); + assert!(layer.pass(&["accept", "."])); assert!(!A_B.exists()); assert!(C.exists()); diff --git a/tests/test_accept_deep_reshuffle.rs b/tests/test_accept_deep_reshuffle.rs index 552a94e..d206ab7 100644 --- a/tests/test_accept_deep_reshuffle.rs +++ b/tests/test_accept_deep_reshuffle.rs @@ -46,8 +46,8 @@ fn test_accept_deep_reshuffle(mut layer: LayerManager) -> Result<()> { layer.run(&["mv", &from_path, &to_path_str])?; } - //layer.run(&["status"])?; - layer.run(&["accept"])?; + //layer.run(&["status", "."])?; + layer.run(&["accept", "."])?; //let output = layer.run(&["ls", "-R", base.display().as_str()])?; //println!("{}", output.stdout); diff --git a/tests/test_diff.rs b/tests/test_diff.rs index 5babda1..3cc3307 100644 --- a/tests/test_diff.rs +++ b/tests/test_diff.rs @@ -10,7 +10,7 @@ fn test_diff_patterns(mut layer: LayerManager) -> Result<()> { layer.run(&["sh", "-c", "echo 'file_two' > file_two"])?; // diff for all files should show both changes - layer.run(&["diff"])?; + layer.run(&["diff", "."])?; assert!(layer.last_stdout.contains("file_one")); assert!(layer.last_stdout.contains("file_two")); @@ -53,7 +53,7 @@ fn test_diff_operations(mut layer: LayerManager) -> Result<()> { ])?; layer.run(&["mv", &moved_src, &moved_dst])?; - layer.run(&["diff"])?; + layer.run(&["diff", "."])?; assert!(layer.last_stdout.contains(&added)); assert!(layer.last_stdout.contains(&removed)); assert!(layer.last_stdout.contains(&modified)); diff --git a/tests/test_json.rs b/tests/test_json.rs index f998996..af2dfd4 100644 --- a/tests/test_json.rs +++ b/tests/test_json.rs @@ -31,7 +31,7 @@ fn test_json(mut layer: LayerManager) -> Result<()> { * out another way to exercise that code. */ #[rstest] fn test_json_diff(mut layer: LayerManager) -> Result<()> { - layer.xfail(&["--json", "diff"]); + layer.xfail(&["--json", "diff", "."]); assert!(layer.last_stdout.contains("\"status\": \"error\"")); Ok(()) } diff --git a/tests/test_layer_failures.rs b/tests/test_layer_failures.rs index d303746..2830b9d 100644 --- a/tests/test_layer_failures.rs +++ b/tests/test_layer_failures.rs @@ -90,7 +90,7 @@ fn test_rename_across_mount_points_failure( std::fs::create_dir_all(&test_file)?; layer.run(&["mv", test_file.as_str(), test_file2.as_str()])?; assert!(layer.exfail( - &["accept"], + &["accept", "."], "TEST_RENAME_ACROSS_MOUNT_POINTS_FAILURE", "1" )); @@ -102,11 +102,11 @@ fn test_rename_across_mount_points_failure( fn test_bad_staged_file(mut layer: LayerManager) -> Result<()> { let test_file = layer.test_filename("test-file"); layer.run(&["touch", test_file.as_str()])?; - assert!(layer.exfail(&["accept"], "TEST_NO_STAGED_FILE", "1")); + assert!(layer.exfail(&["accept", "."], "TEST_NO_STAGED_FILE", "1")); let test_file = layer.test_filename("test-file"); layer.run(&["touch", test_file.as_str()])?; - assert!(layer.exfail(&["accept"], "TEST_BAD_STAGED_FILE", "1")); + assert!(layer.exfail(&["accept", "."], "TEST_BAD_STAGED_FILE", "1")); assert!(!Path::new(test_file.as_str()).exists()); Ok(()) } @@ -116,11 +116,11 @@ fn test_bad_staged_file_remove(mut layer: LayerManager) -> Result<()> { let test_file = layer.test_filename("test-file"); std::fs::write(&test_file, "test")?; layer.run(&["rm", test_file.as_str()])?; - assert!(layer.exfail(&["accept"], "TEST_NO_STAGED_FILE", "1")); + assert!(layer.exfail(&["accept", "."], "TEST_NO_STAGED_FILE", "1")); let test_file = layer.test_filename("test-file"); layer.run(&["touch", test_file.as_str()])?; - assert!(layer.exfail(&["accept"], "TEST_BAD_STAGED_FILE", "1")); + assert!(layer.exfail(&["accept", "."], "TEST_BAD_STAGED_FILE", "1")); assert!(!Path::new(test_file.as_str()).exists()); Ok(()) } @@ -132,11 +132,11 @@ fn test_remove_underlying_dir_failure(mut layer: LayerManager) -> Result<()> { std::fs::create_dir_all(&test_dir)?; layer.run(&["mv", test_dir.as_str(), test_dir2.as_str()])?; std::fs::remove_dir(&test_dir)?; - assert!(layer.pass(&["status"])); + assert!(layer.pass(&["status", "."])); let last_stdout = layer.last_stdout.clone(); assert!(last_stdout.contains("Redirect path not found")); - assert!(layer.xfail(&["accept"])); + assert!(layer.xfail(&["accept", "."])); assert!(last_stdout.contains("Redirect path not found")); Ok(()) diff --git a/tests/test_misc.rs b/tests/test_misc.rs index 1b2b29c..f04ecc4 100644 --- a/tests/test_misc.rs +++ b/tests/test_misc.rs @@ -10,11 +10,11 @@ use serde_json::Value; #[rstest] fn test_program_runs_with_no_args(mut layer: LayerManager) -> Result<()> { layer.run(&["env"])?; - layer.run(&["status"])?; + layer.run(&["status", "."])?; layer.run(&["touch", "testfile"])?; - layer.run(&["status"])?; + layer.run(&["status", "."])?; layer.run(&["list"])?; - layer.run(&["diff"])?; + layer.run(&["diff", "."])?; layer.run(&[])?; // should launch bash, which should exit without an input terminal Ok(()) } @@ -214,7 +214,7 @@ fn exercise_large_xattr(mut layer: LayerManager) -> Result<()> { .status()?; //assert!(status.success()); - layer.run(&["status"])?; + layer.run(&["status", "."])?; Ok(()) } diff --git a/tests/test_reject.rs b/tests/test_reject.rs index 97ff81b..72f352a 100644 --- a/tests/test_reject.rs +++ b/tests/test_reject.rs @@ -98,9 +98,9 @@ fn test_reject_remove_filled_directory_with_opaque_directory( assert!(path.exists()); layer.run(&["mkdir", &dirname])?; layer.run(&["touch", path.join("file2").to_str().unwrap()])?; - layer.run(&["reject"])?; + layer.run(&["reject", "."])?; assert!(path.exists()); - layer.run(&["accept"])?; + layer.run(&["accept", "."])?; assert!(path.exists()); assert!(path.join("file").exists()); assert!(!path.join("file2").exists()); diff --git a/tests/test_status.rs b/tests/test_status.rs index f1e84ca..d23fa25 100644 --- a/tests/test_status.rs +++ b/tests/test_status.rs @@ -59,7 +59,7 @@ fn test_status(mut layer: LayerManager) -> Result<()> { fn test_status_outside(mut layer: LayerManager) -> Result<()> { let filename = "/tmp/test"; layer.run(&["touch", filename])?; - layer.run(&["status"])?; + layer.run(&["status", "."])?; println!("{}", layer.last_stdout); assert!( layer @@ -95,13 +95,13 @@ fn test_status_changed_attributes(mut layer: LayerManager) -> Result<()> { layer.run(&["touch", uid_file.as_str()])?; layer.run(&["touch", gid_file.as_str()])?; - assert!(layer.pass(&["status"])); + assert!(layer.pass(&["status", "."])); assert!(!layer.last_stderr.contains(&mode_file)); assert!(!layer.last_stderr.contains(&uid_file)); assert!(!layer.last_stderr.contains(&gid_file)); layer.run(&["chmod", "777", mode_file.as_str()])?; - assert!(layer.pass(&["status"])); + assert!(layer.pass(&["status", "."])); assert!(layer.last_stderr.contains(&mode_file)); assert!(!layer.last_stderr.contains(&uid_file)); assert!(!layer.last_stderr.contains(&gid_file)); @@ -114,7 +114,7 @@ fn test_status_changed_attributes(mut layer: LayerManager) -> Result<()> { .output()?; layer.run(&["chmod", "777", uid_file.as_str()])?; - assert!(layer.pass(&["status"])); + assert!(layer.pass(&["status", "."])); assert!(layer.last_stderr.contains(&mode_file)); assert!(layer.last_stderr.contains(&uid_file)); assert!(layer.last_stderr.contains(&gid_file)); From 03fec1af5a9be366d013f6f74ff10c7a362beea2 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 06:26:49 -0500 Subject: [PATCH 11/32] Fix review findings: / refusal only on layer start, plain-path binds, origin outside the layer, no real clean in tests --- src/config/resolve.rs | 73 +++++++++++++++++++++----------- src/layer/get_or_create.rs | 18 +++++++- src/layer/settings.rs | 41 ++++++++++++++---- tests/ai_test_cwd_bind.rs | 52 +++++++++++++++++++++++ tests/ai_test_layer_selection.rs | 5 ++- 5 files changed, 154 insertions(+), 35 deletions(-) diff --git a/src/config/resolve.rs b/src/config/resolve.rs index 918b904..1bcdb4b 100644 --- a/src/config/resolve.rs +++ b/src/config/resolve.rs @@ -1,7 +1,7 @@ use super::PartialConfig; use super::limits::{available_cpus, parse_cpus, parse_memory}; use crate::config::{BindMount, BindMountOptions, Network}; -use crate::layer::LayerSettings; +use crate::layer::LayerOrigin; use crate::util::{ can_access, can_mkdir, expand_tilde_path, find_mount_point, mkdir, }; @@ -20,6 +20,25 @@ use std::{ use super::cli::{Action, Args}; +/// A read-write bind of `path` onto itself. Unlike parse_bind_mount, ':' in +/// the path has no special meaning. +fn path_bind_mount(path: &Path) -> Result { + let canonical = path.canonicalize().context(format!( + "Failed to canonicalize source path: {}", + path.display() + ))?; + Ok(BindMount { + source: canonical.clone(), + target: canonical, + options: BindMountOptions::ReadWrite, + argument: path.display().to_string(), + }) +} + +fn path_bind_mounts>(paths: Vec

) -> Result> { + paths.iter().map(|p| path_bind_mount(p.as_ref())).collect() +} + /// Parses bind mount string and expands tildes /// Format: source[:target[:options]] fn parse_bind_mount(bind_mount: &str) -> Result { @@ -382,31 +401,38 @@ pub fn resolve_config(cli: Args) -> Result { let (created_in, bind_cwd) = resolve_origin(&layer_dir, &cwd, no_bind_cwd)?; sources.insert("created_in".into(), "layer settings or cwd".into()); sources.insert("bind_cwd".into(), "layer settings or no_bind_cwd".into()); + let mut path_layers: Vec> = vec![]; if bind_cwd { - bind_layers.insert(0, vec![created_in.display().to_string()]); + path_layers.insert(0, vec![path_bind_mount(&created_in)?]); } // LLM tool binds sit just above the default bind mounts if !no_default_llm_binds { - bind_layers.insert(0, get_llm_bind_mounts(&uid_gid_home.home)); + path_layers.insert( + 0, + path_bind_mounts(get_llm_bind_mounts(&uid_gid_home.home))?, + ); } // Default bind mounts, including audio, are the lowest precedence layer if !no_default_binds { let mut default_binds = get_default_bind_mounts(&net); default_binds.extend(get_audio_bind_mounts()); - bind_layers.insert(0, default_binds); + path_layers.insert(0, path_bind_mounts(default_binds)?); } // Resolve bind mounts layer by layer from lowest to highest precedence. // Conflicting mounts within a single layer are an error, while a mount in // a higher precedence layer overrides any mount with the same target in a // lower precedence layer. + let parsed_layers = bind_layers + .iter() + .map(|layer| layer.iter().map(|m| parse_bind_mount(m)).collect()) + .collect::>>>()?; let mut target_map: HashMap = HashMap::new(); - for layer in bind_layers { + for layer in path_layers.into_iter().chain(parsed_layers) { let mut layer_map: HashMap = HashMap::new(); for mount in layer { - let mount = parse_bind_mount(&mount)?; if let Some(existing) = layer_map.get(&mount.target) { if existing.source != mount.source || existing.options != mount.options @@ -511,30 +537,22 @@ fn get_default_bind_mounts(net: &Network) -> Vec { /// bound into the layer. An existing layer keeps the values recorded in its /// settings when it was created, so re-entering it from another directory, or /// without --no-bind-cwd, does not change its binds. A new layer uses `cwd`. +/// Binding / is refused when a layer starts, not here, so actions that don't +/// start a layer still work from /. pub fn resolve_origin( layer_dir: &Path, cwd: &Path, no_bind_cwd: bool, ) -> Result<(PathBuf, bool)> { - let settings_path = layer_dir.join("data").join("settings.json"); - if let Ok(settings) = LayerSettings::load_from_file(&settings_path) - && let (Some(created_in), Some(bind_cwd)) = - (settings.created_in, settings.bind_cwd) - { - return Ok((created_in, bind_cwd)); + if let Some(origin) = LayerOrigin::load(layer_dir) { + return Ok((origin.created_in, origin.bind_cwd)); } let created_in = cwd.canonicalize().context(format!( "Failed to canonicalize current directory {}", cwd.display() ))?; - let bind_cwd = !no_bind_cwd; - if bind_cwd && created_in == Path::new("/") { - return Err(anyhow::anyhow!( - "Refusing to bind / into the layer; run from a project directory or pass --no-bind-cwd" - )); - } - Ok((created_in, bind_cwd)) + Ok((created_in, !no_bind_cwd)) } /// Well-known AI tool config and state paths, relative to the home directory, @@ -999,15 +1017,12 @@ fn find_last_layer(storage_dir: &Path, cwd: &Path) -> Result { .flatten() .filter_map(|entry| { let path = entry.path(); - let settings = LayerSettings::load_from_file( - &path.join("data").join("settings.json"), - ) - .ok()?; + let origin = LayerOrigin::load(&path)?; let metadata = entry.metadata().ok()?; let created = metadata.created().or_else(|_| metadata.modified()).ok()?; Some(( - settings.created_in?, + origin.created_in, entry.file_name().to_string_lossy().to_string(), created, )) @@ -1112,6 +1127,16 @@ mod tests { home } + #[test] + fn path_bind_mount_keeps_colons() { + let home = fake_home("with:colon"); + let mount = path_bind_mount(&home).unwrap(); + assert_eq!(mount.source, home.canonicalize().unwrap()); + assert_eq!(mount.target, mount.source); + assert_eq!(mount.options, BindMountOptions::ReadWrite); + std::fs::remove_dir_all(&home).unwrap(); + } + #[test] fn llm_binds_skip_missing_paths() { let home = fake_home("missing"); diff --git a/src/layer/get_or_create.rs b/src/layer/get_or_create.rs index d2aa8f3..61fd6a6 100644 --- a/src/layer/get_or_create.rs +++ b/src/layer/get_or_create.rs @@ -1,7 +1,7 @@ use super::cgroup::remove_cgroup; use super::mount_overlays::MountHash; use crate::config::{BindMount, BindMountOptions, Config, Network}; -use crate::layer::Layer; +use crate::layer::{Layer, LayerOrigin}; #[cfg(feature = "coverage")] use crate::util::CLONE_FS; use crate::util::Lock; @@ -174,6 +174,12 @@ impl Layer { ), )?; + if config.bind_cwd && config.created_in == Path::new("/") { + return Err(anyhow!( + "Refusing to bind / into the layer; run from a project directory or pass --no-bind-cwd" + )); + } + let mut config = config.clone(); config.bind_mounts.push(BindMount { argument: "data".to_string(), @@ -212,6 +218,16 @@ impl Layer { } }; + /* Record where the layer was created the first time it starts. A + * restarted layer keeps its original origin. */ + if !LayerOrigin::path(&layer.base).exists() { + LayerOrigin { + created_in: config.created_in.clone(), + bind_cwd: config.bind_cwd, + } + .save(&layer.base)?; + } + Ok(layer) } diff --git a/src/layer/settings.rs b/src/layer/settings.rs index 3ee17e3..ee568f2 100644 --- a/src/layer/settings.rs +++ b/src/layer/settings.rs @@ -15,12 +15,39 @@ pub struct LayerSettings { pub cpus: Option, #[serde(default)] pub memory: Option, - /// Canonical directory the layer was created in - #[serde(default)] - pub created_in: Option, - /// Whether created_in is bound read-write into the layer - #[serde(default)] - pub bind_cwd: Option, +} + +/// Where a layer was created and whether that directory is bound into it. +/// This lives in the layer's base directory rather than in data/settings.json +/// because the data directory is bound read-write into the layer, so programs +/// in the layer could otherwise change which host directory is bound live. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct LayerOrigin { + pub created_in: PathBuf, + pub bind_cwd: bool, +} + +impl LayerOrigin { + pub fn path(layer_dir: &Path) -> PathBuf { + layer_dir.join("origin.json") + } + + /// Loads the origin recorded for the layer in `layer_dir`, if there is a + /// valid one + pub fn load(layer_dir: &Path) -> Option { + let json = std::fs::read_to_string(Self::path(layer_dir)).ok()?; + let origin: Self = serde_json::from_str(&json).ok()?; + origin.created_in.is_absolute().then_some(origin) + } + + pub fn save(&self, layer_dir: &Path) -> Result<()> { + let json = serde_json::to_string_pretty(self) + .context("Failed to serialize layer origin to JSON")?; + std::fs::write(Self::path(layer_dir), json).context(format!( + "Failed to write {}", + Self::path(layer_dir).display() + )) + } } impl LayerSettings { @@ -32,8 +59,6 @@ impl LayerSettings { bind_mounts: config.bind_mounts.clone(), cpus: config.cpus, memory: config.memory, - created_in: Some(config.created_in.clone()), - bind_cwd: Some(config.bind_cwd), } } diff --git a/tests/ai_test_cwd_bind.rs b/tests/ai_test_cwd_bind.rs index f695995..521a12d 100644 --- a/tests/ai_test_cwd_bind.rs +++ b/tests/ai_test_cwd_bind.rs @@ -142,3 +142,55 @@ fn ai_test_no_bind_cwd_persists(mut layer: LayerManager) -> Result<()> { assert!(!dir.join("still-layered").exists()); Ok(()) } + +/// Actions that never start a layer must work from / even though / can't be +/// bound. +#[rstest] +fn ai_test_root_non_creating_actions_ok(mut layer: LayerManager) -> Result<()> { + layer.set_bind_cwd(true); + layer.cwd = Some(PathBuf::from("/")); + assert!(layer.pass(&["list"])); + assert!(layer.pass(&["config", "name"])); + Ok(()) +} + +/// A project directory whose path contains ':' is bound as a plain path, not +/// parsed as source:target:options. +#[rstest] +fn ai_test_cwd_with_colon(mut layer: LayerManager) -> Result<()> { + let dir = std::env::current_dir()?.join(layer.test_filename("proj:v2")); + std::fs::create_dir_all(&dir)?; + layer.set_bind_cwd(true); + layer.cwd = Some(dir.clone()); + + layer.run(&["touch", "colon-file"])?; + assert!(dir.join("colon-file").exists()); + Ok(()) +} + +/// The layer's data directory is live inside the layer, so the recorded +/// origin must not be stored there: a program in the layer must not be able +/// to change which directory is bound on the next start. +#[rstest] +fn ai_test_origin_not_writable_from_layer( + mut layer: LayerManager, +) -> Result<()> { + let dir = project_dir(&layer)?; + layer.set_bind_cwd(true); + layer.cwd = Some(dir.clone()); + layer.run(&["--no-bind-cwd", "true"])?; + + let settings = layer.dir()?.join("data").join("settings.json"); + let script = format!( + "f={}; sed 's|\"bind_cwd\": false|\"bind_cwd\": true|; s|\"created_in\": \"[^\"]*\"|\"created_in\": \"/\"|' $f > $f.new && mv $f.new $f", + settings.display() + ); + layer.run(&["sh", "-c", &script])?; + layer.run(&["stop"])?; + + layer.run(&["config", "created_in"])?; + assert_eq!(layer.last_stdout.trim(), dir.display().to_string()); + layer.run(&["config", "bind_cwd"])?; + assert_eq!(layer.last_stdout.trim(), "false"); + Ok(()) +} diff --git a/tests/ai_test_layer_selection.rs b/tests/ai_test_layer_selection.rs index 04182e3..907aac6 100644 --- a/tests/ai_test_layer_selection.rs +++ b/tests/ai_test_layer_selection.rs @@ -176,12 +176,13 @@ fn ai_test_stop_delete_default_to_last(layer: LayerManager) -> Result<()> { } #[rstest] -fn ai_test_list_clean_sync_no_layer_ok(layer: LayerManager) -> Result<()> { +fn ai_test_list_config_sync_no_layer_ok(layer: LayerManager) -> Result<()> { let mut sel = Selection::new(layer)?; let empty = sel.dir("empty")?; assert!(sel.pass(&empty, &["list"])); - assert!(sel.pass(&empty, &["clean", "-y"])); + // `clean` is not run here: it would delete real stopped ephemeral layers in + // the shared storage directory. Its default selection is unit tested. assert!(sel.pass(&empty, &["config"])); // sync drops system caches, which may not be allowed inside containers; // it must not fail because there is no layer for this directory From 980a39ee101a20d8201a851dcfcee8fc0b8499f1 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 08:05:49 -0500 Subject: [PATCH 12/32] Keep the cwd bind on in layer selection tests The selection tests run from project directories under the system temp dir with --no-bind-cwd. When /tmp is a tmpfs, it is not part of the layer's overlay, so the project directory did not exist inside the layer and the layer failed to start with "failed to set CWD". Leave the cwd bind on, as it is for a user, and write the out-of-project file for the status check into the repository, which is always overlaid. --- tests/ai_test_layer_selection.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/tests/ai_test_layer_selection.rs b/tests/ai_test_layer_selection.rs index 907aac6..343a8e5 100644 --- a/tests/ai_test_layer_selection.rs +++ b/tests/ai_test_layer_selection.rs @@ -10,6 +10,10 @@ use std::path::{Path, PathBuf}; /// under the system temp dir, outside the repository, so layers that other /// tests create in the repository root never match --last. Layers created /// here are tracked and deleted on drop. +/// +/// The cwd bind is left on, as it is for a user. The temp dir is often a +/// tmpfs, which is not part of the layer's overlay, so without the bind the +/// project directory would not exist inside the layer. struct Selection { layer: LayerManager, storage: PathBuf, @@ -22,6 +26,7 @@ impl Selection { let mut layer = layer; // No --join, so the default selection applies layer.no_default_options = true; + layer.set_bind_cwd(true); let root = std::env::temp_dir() .join(format!("devlayer-coverage-sel-{}", rid())); std::fs::create_dir_all(&root)?; @@ -145,14 +150,18 @@ fn ai_test_last_nearest_ancestor_and_newest(layer: LayerManager) -> Result<()> { fn ai_test_actions_default_to_last(layer: LayerManager) -> Result<()> { let mut sel = Selection::new(layer)?; let dir = sel.dir("project")?; - let outside = sel.root.join("outside-file"); + // A file outside the bound project directory, in the repository, which + // is always part of the overlay (unlike a tmpfs temp dir). It only exists + // in the layer, which is deleted on drop. + let outside_name = format!("devlayer-coverage-outside-{}", rid()); + let outside = std::env::current_dir()?.join(&outside_name); let outside = outside.to_str().unwrap_or_default().to_string(); assert!(sel.pass(&dir, &["touch", &outside])); let name = sel.created()?.into_iter().next(); assert!(sel.pass(&dir, &["status", "/"])); - assert!(sel.layer.last_stdout.contains("outside-file")); + assert!(sel.layer.last_stdout.contains(&outside_name)); assert!(sel.pass(&dir, &["config", "name"])); assert_eq!(Some(sel.stdout()), name); From d3b0f77cf15fdce69bc18a56106e4729799ff699 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 09:46:24 -0500 Subject: [PATCH 13/32] Fix sandbox->layer rename slips: cgroup path in limits test, stale names in comments The internal rename pass turned the limits test's /sys/fs/cgroup/sandbox into /sys/fs/cgroup/layer, but the cgroup parent is devlayer, so the test never found the layer's cgroup. Also correct comments that named LAYER_IGNORED, LAYER_NO_DEFAULT_BINDS, .layer.toml, ~/.config/layer, /etc/layer.conf and /sys/fs/cgroup/layer. --- src/config/resolve.rs | 4 ++-- src/layer/cgroup.rs | 2 +- tests/ai_test_bind_mounts.rs | 2 +- tests/ai_test_config_impls.rs | 2 +- tests/ai_test_ignore_rules.rs | 6 +++--- tests/ai_test_resource_limits.rs | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/config/resolve.rs b/src/config/resolve.rs index 1bcdb4b..c08c98f 100644 --- a/src/config/resolve.rs +++ b/src/config/resolve.rs @@ -818,11 +818,11 @@ fn find_config_files() -> Result> { } } - // ~/.config/layer/config.toml + // ~/.config/devlayer/config.toml paths_to_check.push(uid_gid_home.home.join(".config/devlayer/config.conf")); paths_to_check.push(uid_gid_home.home.join(".config/devlayer/config.toml")); - // /etc/layer.conf + // /etc/devlayer.conf paths_to_check.push(PathBuf::from("/etc/devlayer.conf")); paths_to_check.push(PathBuf::from("/etc/devlayer.toml")); diff --git a/src/layer/cgroup.rs b/src/layer/cgroup.rs index f195fa2..34ec33f 100644 --- a/src/layer/cgroup.rs +++ b/src/layer/cgroup.rs @@ -1,7 +1,7 @@ //! cgroup v2 support for limiting the CPU and memory available to a layer. //! //! Layers with resource limits get a cgroup at -//! /sys/fs/cgroup/layer/-. The layer's PID 1 is started in that +//! /sys/fs/cgroup/devlayer/-. The layer's PID 1 is started in that //! cgroup, which also makes it the root of the layer's cgroup namespace, and //! every process that later joins the layer is moved into it. diff --git a/tests/ai_test_bind_mounts.rs b/tests/ai_test_bind_mounts.rs index d248e64..34e4ae1 100644 --- a/tests/ai_test_bind_mounts.rs +++ b/tests/ai_test_bind_mounts.rs @@ -147,7 +147,7 @@ fn test_no_default_binds_env(mut layer: LayerManager) -> Result<()> { assert!(layer.last_stdout.contains(&test1)); assert!(!layer.last_stdout.contains("/dev/fuse")); - // Test that LAYER_NO_DEFAULT_BINDS=false (or any other value) doesn't disable defaults + // Test that DEVLAYER_NO_DEFAULT_BINDS=false (or any other value) doesn't disable defaults layer.run_with_env( &["--no-config", "config"], "DEVLAYER_NO_DEFAULT_BINDS", diff --git a/tests/ai_test_config_impls.rs b/tests/ai_test_config_impls.rs index 3e33e1f..20c98b3 100644 --- a/tests/ai_test_config_impls.rs +++ b/tests/ai_test_config_impls.rs @@ -93,7 +93,7 @@ fn test_config_file_locations() -> Result<()> { layer.no_sudo = true; // Test that layer looks for config in the right places - // 1. .layer.toml in current directory + // 1. .devlayer.toml in current directory let test_dir = format!("generated-test-data/{}", layer.name); fs::create_dir_all(&test_dir)?; let local_config = format!("{}/.devlayer.toml", test_dir); diff --git a/tests/ai_test_ignore_rules.rs b/tests/ai_test_ignore_rules.rs index c09badb..1ec3630 100644 --- a/tests/ai_test_ignore_rules.rs +++ b/tests/ai_test_ignore_rules.rs @@ -648,7 +648,7 @@ config/*.data.bak Ok(()) } -/// Verify that the LAYER_IGNORED environment variable enables inclusion of +/// Verify that the DEVLAYER_IGNORED environment variable enables inclusion of /// ignored files even when the --ignored CLI flag is not provided. #[rstest] fn test_env_flag_includes_ignored(mut layer: LayerManager) -> Result<()> { @@ -696,7 +696,7 @@ fn test_env_flag_includes_ignored(mut layer: LayerManager) -> Result<()> { assert!(stdout.contains(ignored_file.to_str().unwrap())); assert!(stdout.contains(included_file.to_str().unwrap())); - // Invalid value for LAYER_IGNORED + // Invalid value for DEVLAYER_IGNORED layer.set_ignored(false); // Disable automatic --ignored let result = layer.run_with_env(&["status", &test_dir], "DEVLAYER_IGNORED", "cow"); @@ -706,7 +706,7 @@ fn test_env_flag_includes_ignored(mut layer: LayerManager) -> Result<()> { "Expected error for invalid DEVLAYER_IGNORED value" ); - // False value for LAYER_IGNORED + // False value for DEVLAYER_IGNORED layer.set_ignored(false); // Disable automatic --ignored layer.run_with_env(&["status", &test_dir], "DEVLAYER_IGNORED", "false")?; let stdout = layer.last_stdout.clone(); diff --git a/tests/ai_test_resource_limits.rs b/tests/ai_test_resource_limits.rs index a5051a4..c0ed372 100644 --- a/tests/ai_test_resource_limits.rs +++ b/tests/ai_test_resource_limits.rs @@ -41,7 +41,7 @@ fn limits_available(layer: &mut LayerManager) -> bool { /// Finds our layer's cgroup on the host, if it has one fn host_cgroup(layer: &LayerManager) -> Option { let suffix = format!("-{}", layer.name); - fs::read_dir("/sys/fs/cgroup/layer") + fs::read_dir("/sys/fs/cgroup/devlayer") .ok()? .filter_map(|entry| entry.ok()) .map(|entry| entry.path()) From 47ee3cfc57c91821f2e96f9e6e6d1753b597e4a5 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 11:24:24 -0500 Subject: [PATCH 14/32] Make tail the OOM killer's first choice in the memory limit test The devlayer command waits on its child inside the layer's cgroup, so when the cgroup ran out of memory the kernel sometimes killed devlayer instead of (or as well as) tail, and the test got no exit status. tail now raises its own oom_score_adj to 1000 so it is always picked first. --- tests/ai_test_resource_limits.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/ai_test_resource_limits.rs b/tests/ai_test_resource_limits.rs index c0ed372..eb4eb5f 100644 --- a/tests/ai_test_resource_limits.rs +++ b/tests/ai_test_resource_limits.rs @@ -262,13 +262,18 @@ fn ai_test_limits_memory_enforced(mut layer: LayerManager) -> Result<()> { layer.run(&["stop"])?; // tail has to buffer the whole newline-free input, which won't fit. - // memory.events is read in the same command so we see this cgroup's - // counters even if the OOM killer took down more than tail. + // The devlayer command waiting on the shell is in the cgroup too, so tail + // raises its own oom_score_adj to always be the OOM killer's first + // choice; otherwise the kernel may kill devlayer instead and we get no + // exit status. memory.events is read in the same command so we see this + // cgroup's counters. layer.run(&[ "--memory=32M", "sh", "-c", - "head -c 256M /dev/zero | tail > /dev/null; \ + "head -c 256M /dev/zero \ + | sh -c 'echo 1000 > /proc/self/oom_score_adj && exec tail' \ + > /dev/null; \ echo \"tail exited with $?\"; \ cat /sys/fs/cgroup/memory.events", ])?; From 8fa7f99431725ee615a63591c41293bf18c00ef2 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 14:25:20 -0500 Subject: [PATCH 15/32] Add layer auto-shutdown design --- .../2026-11-13-layer-auto-shutdown-design.md | 189 ++++++++++++++++++ 1 file changed, 189 insertions(+) create mode 100644 docs/superpowers/specs/2026-11-13-layer-auto-shutdown-design.md diff --git a/docs/superpowers/specs/2026-11-13-layer-auto-shutdown-design.md b/docs/superpowers/specs/2026-11-13-layer-auto-shutdown-design.md new file mode 100644 index 0000000..b2127e9 --- /dev/null +++ b/docs/superpowers/specs/2026-11-13-layer-auto-shutdown-design.md @@ -0,0 +1,189 @@ +# Layer auto-shutdown design + +## Intent + +Every bare `devlayer ` now creates a new layer, and every layer keeps +running (PID 1, overlay mounts, cgroup, pid file) until `devlayer stop` or a +reboot. Layers pile up. Separately, a layer's PID 1 never reaps processes, so +anything orphaned inside a layer (a background job whose shell exited) stays +`` until the layer is stopped. + +A layer should shut itself down once nothing is running in it any more, and +clean up after itself, so idle layers don't accumulate. + +## Goals + +- PID 1 reaps orphaned processes in its layer, so there are no zombies. +- When the last process in a layer exits (anything other than PID 1, not just + `devlayer` commands), the layer shuts down within about a second. +- Shutting down does what `devlayer stop` does today: overlay and bind mounts + are unmounted, the layer's cgroup (if it has one) is removed, and the pid + file is removed. +- The layer's changes are kept. `status`, `diff`, `accept`, `reject` work as + they do on any stopped layer, and running a command in it again + (`--last`, `--join`) restarts it as today. + +## Non-goals + +- Deleting layers (auto-clean of stopped layers) — a later iteration. +- An opt-out flag to keep idle layers running. +- Handling a command that joins a layer at the instant it shuts down. The + user ruled this out of scope: it is not a concern in practice. Taking the + existing layer lock during cleanup is enough; no retry logic. + +## Anti-goals + +- Killing anything still running. A layer with a background process left in + it (a dev server started with `&`, a tmux server, a daemon) stays up until + that process exits or the user runs `devlayer stop`. + +## Approaches + +1. **Host-side supervisor + PID 1 idle check (chosen).** A small root process + stays on the host as PID 1's parent. PID 1 reaps orphans and checks its own + `/proc` once a second; when only PID 1 is left it exits. The supervisor sees + that exit immediately (it is the parent) and does the cleanup. Covers + orphans that outlive every command, and cleans up even if the user's + terminal is killed. Cost: one idle process per running layer, up to ~1s + delay. +2. **The waiting `devlayer` command cleans up.** The `devlayer` process that + waits on the user's command keeps root and stops the layer when its command + exits and nothing else is running. Rejected: a background process that + outlives every command leaves the layer up forever (violates the goal), no + cleanup if that process is killed, and it leaves a root process inside the + layer's mount namespace. +3. **Lazy cleanup.** PID 1 exits when idle; the next `devlayer` invocation + unmounts layers whose PID 1 is gone. Rejected: mounts and cgroups linger + until the user happens to run `devlayer` again. + +## Design + +### Process structure + +Today `start_layer` (src/layer/get_or_create.rs) is called by the user's +`devlayer` process (call it the caller). It `clone3`s PID 1, writes the pid +file, waits on a pipe for PID 1 to report it is ready, and then goes on to +`exec` the user's command and wait on it. PID 1's parent is the caller, and +once the caller exits PID 1 is reparented to the host's init. + +New structure: + +- The caller forks a **supervisor** before `clone3`. The supervisor calls + `setsid` and does the `clone3` of PID 1, so it is PID 1's parent. +- *(Builder-check call)* The supervisor keeps stdin/stdout/stderr open until + PID 1 has reported ready or failed, so PID 1's setup errors still reach the + terminal (`tests/isolated_test_pivot_root_failure.rs` relies on that). Then + it closes them, as PID 1 does today, so the test harness and terminals + don't wait on it. +- *(Builder-check call)* `clone3` must set `exit_signal` to `SIGCHLD`. + `Clone3Args` leaves it at 0 today, and a plain `waitpid` never reports the + exit of a child that doesn't signal its parent. +- *(Builder-check call)* The supervisor sets all its uids and gids to root + (as PID 1 already does) so the user can't signal it, and ignores SIGHUP and + SIGINT. If it died, PID 1 would still exit when idle but the mounts would be + left behind. +- The caller still learns PID 1's pid and whether setup succeeded, and still + returns an error exactly as today when setup fails. How the pid and the + ready/failed byte get back to the caller (e.g. the existing pipe plus the + pid file, or a second pipe) is left to the builder. +- If setup fails, the supervisor exits without leaving anything running; the + caller's existing error path (removing the cgroup) still runs. +- The supervisor stays root, stays in the host mount namespace, and does + nothing but `waitpid` on PID 1. + +### PID 1 + +Replace the sleep-forever loop at the end of `setup_layer_and_sleep_forever`: + +- Every 1 second: + 1. Reap every exited child with `waitpid(-1, WNOHANG)` until none are left. + 2. List the numeric entries of `/proc` (PID 1's own procfs, which only shows + this layer's processes). If the only entry is `1`, exit with status 0. +- The first check happens 1 second after PID 1 reports ready. That gives the + caller time to join with the user's command; no other startup handling. +- The existing SIGTERM handler (exit with the signal number) stays. +- Coverage: keep dumping profraw as the current loop does. + +### Supervisor cleanup + +When `waitpid` reports PID 1 has exited (idle exit, `devlayer stop`, or +anything else): + +1. Take the layer lock. *(Builder-check call)* Open the existing lock file + without creating it: `Lock::layer` creates a missing one, and after + `devlayer delete` that would bring the deleted layer back in `list`. If the + lock file is gone, the layer was deleted (which already stopped and + unmounted it); just exit. +2. Remove the pid file if it still names this PID 1 (a restarted layer has + written a new pid; leave it alone). +3. Remove the layer's cgroup, but only if this layer created its own (the + `create_cgroup_or_share_outer` result was `Some`) and it still exists: + `Layer::cgroup_path()`. `remove_cgroup` retries for 5 seconds on any + error, including "not found", so check first. Note that + `running_cgroup()` can't be used here because it reads PID 1's + `/proc//cgroup`, which is gone. +4. Unmount the layer's mounts (`Layer::unmount`). +5. Exit. + +Every step must be harmless when `devlayer stop` already did it (the common +case for an explicit stop): no mounts, no pid file, no cgroup. The supervisor +has no stdout/stderr, so failures are ignored rather than reported. + +Skip steps 2–4 when the layer was restarted in the meantime: if, after taking +the lock, the pid file names a different, running PID 1, the supervisor must +not unmount that layer's mounts; it just exits. + +### What doesn't change + +- `devlayer stop` keeps its current behavior; the supervisor's cleanup after it + is a no-op. +- `get_running_layer_pid` and `list` keep using the pid file; a shut-down layer + shows as stopped. +- Nested layers work the same way (the supervisor runs inside the outer layer). + +## Constraints + +- The binary is setuid root; the supervisor runs as root on the host. It must + not run any user-supplied code or read user-controlled paths beyond what + `stop` already does. +- `fork` inherits the caller's flock fd for the layer lock. The caller's + `Lock` drop does an explicit unlock today, so the inherited fd doesn't keep + it locked, but the builder should close it in the supervisor anyway. +- Coverage instrumentation: the supervisor is a long-lived instrumented + process. Like PID 1 and the exec waiter, it must write its profraw to + `coverage/profraw/` via `__llvm_profile_set_filename` with a path that works + from its cwd (or an absolute one), and dump before exiting. +- Project rule: very high test coverage; new tests go in `tests/ai_test_*.rs`. + +## Testing + +New tests (in a new `tests/ai_test_auto_shutdown.rs`): + +- After `devlayer true`, the layer stops within a few seconds: the pid file + goes away, `list` shows it stopped, and no mounts under the layer dir remain. + Poll with a timeout rather than sleeping a fixed time. +- A layer with a background process left running (`sh -c 'sleep 30 &'`) is + still running after a few seconds; it stops once that process is killed. +- An orphan inside a running layer is reaped (no `Z` state process in the + layer). +- Changes survive shutdown: write a file, wait for shutdown, `status` shows it. +- With `--cpus`/`--memory`, the layer's cgroup is removed on shutdown. +- Rejoining a shut-down layer with `--join` restarts it. +- `devlayer stop` still works and the supervisor's cleanup afterwards doesn't + break anything (layer can be restarted and deleted). + +Existing tests that assume a layer stays running between two `devlayer` +invocations (e.g. limits tests that look up the cgroup after `true`, tests of +"running layer with different settings" errors, `list` running checks) will +become timing-dependent. They must keep the layer up explicitly, for example +with a test-fixture helper that starts a background `sleep` in the layer, rather +than relying on running within the 1-second window. + +## Left to the builder + +- How the supervisor passes PID 1's pid and the ready/failed status back to + the caller. +- The exact fixture helper for keeping a layer alive in tests, and which + existing tests need it (find them by running the suite). +- Whether to name the supervisor process (e.g. via `prctl(PR_SET_NAME)`) for + readability in `ps`. From 92464512d5916f01d8937825c6d16688657d0827 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 14:45:23 -0500 Subject: [PATCH 16/32] Add layer auto-shutdown plan --- .../plans/2026-11-13-layer-auto-shutdown.md | 209 ++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-13-layer-auto-shutdown.md diff --git a/docs/superpowers/plans/2026-11-13-layer-auto-shutdown.md b/docs/superpowers/plans/2026-11-13-layer-auto-shutdown.md new file mode 100644 index 0000000..5650f5e --- /dev/null +++ b/docs/superpowers/plans/2026-11-13-layer-auto-shutdown.md @@ -0,0 +1,209 @@ +# Layer Auto-Shutdown Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** A layer reaps its orphans and shuts itself down (unmount, cgroup, pid file) once nothing is running in it, keeping its changes. + +**Architecture:** The `devlayer` process that starts a layer forks a root supervisor that `clone3`s PID 1 and waits on it. PID 1 reaps orphans and exits when its `/proc` shows only itself. When PID 1 exits for any reason, the supervisor does `stop`'s cleanup under the layer lock. + +**Tech Stack:** Rust, nix, libc, clone3, cgroup v2, rstest integration tests. + +**Spec:** docs/superpowers/specs/2026-11-13-layer-auto-shutdown-design.md + +## Global Constraints + +- PID 1 idle check every 1 second; first check 1 second after PID 1 reports ready. +- PID 1 exits with status 0 when idle; the existing SIGTERM handler stays. +- Shutdown never kills a process; a layer with any process besides PID 1 stays up. +- Shutdown keeps the layer's data; it never deletes. +- No retry/race handling beyond taking the layer lock during cleanup. +- The supervisor runs as root (all uids/gids 0), ignores SIGHUP and SIGINT, has no output after PID 1 is ready, and ignores its own cleanup errors. +- The supervisor is forked before the caller joins the layer's cgroup and must never be in it (it would keep the cgroup busy). +- Coverage builds: every instrumented process that exits writes its profraw (see Task 1 step 3). +- New tests go in `tests/ai_test_*.rs`; layer names given in tests start with `devlayer-coverage`. + +## Review Focus + +1. A layer is restarted (`--join`) before the old supervisor runs its cleanup: the old supervisor must not unmount or remove the pid file of the new instance. +2. `devlayer delete` on a running layer: the supervisor wakes after the lock file is gone and must exit without recreating `.lock` (the layer must not reappear in `list`). +3. A layer with `--cpus`/`--memory`: the cgroup is removed on shutdown, and the supervisor isn't in the cgroup (rmdir would fail with EBUSY). +4. The user's terminal goes away (SIGHUP to the session) while a layer runs: the supervisor survives and still cleans up. +5. Nested layers (devlayer inside a layer): auto-shutdown and cleanup work the same. + +--- + +### Task 1: Supervisor process + +**Files:** +- Modify: `src/layer/get_or_create.rs` (`start_layer`, `get_or_create` error path) +- Create: `src/layer/supervisor.rs` (supervisor wait + cleanup), register in `src/layer/mod.rs` +- Modify: `src/util/lock_layer.rs` (open-existing variant) +- Test: `tests/ai_test_auto_shutdown.rs` + +**Interfaces:** +- Produces: `Lock::existing_layer(layers_storage_dir: &Path, layer_name: &str) -> Result>>` — `Ok(None)` when the lock file doesn't exist; never creates it. +- Produces: `fn supervise(layer: &Layer, pid1: Pid, own_cgroup: bool) -> !` in `src/layer/supervisor.rs`: waits on PID 1, runs cleanup, exits 0. +- Produces (tests): helpers in `tests/ai_test_auto_shutdown.rs`: `fn pid_file(layer: &LayerManager) -> Result` (`layer.dir()` + `.pid`), `fn layer_pid(layer: &LayerManager) -> Option`, `fn has_mounts(layer: &LayerManager) -> Result` (any `/proc/self/mountinfo` mount point under `layer.dir()`), `fn wait_until(timeout: Duration, f: impl FnMut() -> bool) -> bool` (polls every 50 ms), `fn ppid_of(pid: i32) -> Result` (`PPid:` line of `/proc//status`). + +- [ ] **Step 1: Write the failing tests** + +```rust +/// When PID 1 dies, the supervisor unmounts and removes the pid file +#[rstest] +fn ai_test_supervisor_cleans_up_after_pid1_exit(mut layer: LayerManager) -> Result<()> { + layer.run(&["true"])?; + let pid = layer_pid(&layer).expect("layer should be running"); + assert!(has_mounts(&layer)?); + Command::new("sudo").args(["kill", "-KILL", &pid.to_string()]).status()?; + assert!(wait_until(Duration::from_secs(5), || !pid_file(&layer).unwrap().exists())); + assert!(wait_until(Duration::from_secs(5), || !has_mounts(&layer).unwrap())); + Ok(()) +} + +/// The user can't signal the supervisor +#[rstest] +fn ai_test_supervisor_not_killable_by_user(mut layer: LayerManager) -> Result<()> { + layer.run(&["true"])?; + let pid = layer_pid(&layer).expect("layer should be running"); + let ppid = ppid_of(pid)?; // PPid: line of /proc//status + let status = Command::new("kill").args(["-TERM", &ppid.to_string()]).status()?; + assert!(!status.success()); + Ok(()) +} + +/// After an explicit stop, the supervisor's cleanup is harmless: the layer +/// restarts and deletes normally, and delete doesn't leave a lock file behind +#[rstest] +fn ai_test_supervisor_after_stop_and_delete(mut layer: LayerManager) -> Result<()> { + layer.run(&["true"])?; + layer.run(&["stop"])?; + layer.run(&["true"])?; + let lock = layer.dir()?.with_extension("lock"); + layer.run(&["delete", "-y"])?; + std::thread::sleep(Duration::from_secs(2)); + assert!(!lock.exists()); + layer.run(&["list"])?; + assert!(!layer.last_stdout.contains(&layer.name)); + Ok(()) +} +``` + +Note for the first test: until Task 2, PID 1 doesn't exit by itself, so the layer stays running between `true` and the kill. + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `TEST=ai_test_supervisor make quick-test` (or `cargo test --profile coverage --features coverage --test ai_test_auto_shutdown` with the coverage env from the Makefile) +Expected: `ai_test_supervisor_cleans_up_after_pid1_exit` FAILS (pid file and mounts remain); `ai_test_supervisor_not_killable_by_user` FAILS (PID 1's parent is the caller, already exited, so PPid is the host init or the kill hits a user-owned process — either way not the intended supervisor); `ai_test_supervisor_after_stop_and_delete` may already pass — keep it as a guard. + +- [ ] **Step 3: Implement** + +In `start_layer`: create the ready pipe, then `fork()`. The caller (parent) drops the write end, reads the ready byte as today, then reads PID 1's pid from the pid file (the supervisor writes it before PID 1 can report ready), and returns `Pid` or the existing `"Failed to setup layer"` error. The supervisor (child): +- `setsid()`; `setresuid(0,0,0)`/`setresgid(0,0,0)`; ignore SIGHUP and SIGINT; close the inherited layer-lock fd. +- `clone3` PID 1 with the existing args plus `exit_signal: libc::SIGCHLD as u64`; write the pid file; keep stdio open. +- Wait for PID 1's ready/failed byte on a second pipe from PID 1 (or forward the existing one); forward it to the caller; on failure exit 1. On success close stdin/stdout/stderr, then `supervise(...)`. + +`supervise`: `waitpid(pid1)`; then `Lock::existing_layer` — `None` → exit; if the pid file names a different PID that `get_running_layer_pid` reports running → exit; otherwise remove the pid file if it names `pid1`, remove `layer.cgroup_path()` with `remove_cgroup` only if `own_cgroup` and the path exists, `layer.unmount()`, exit 0 via `std::process::exit` (the profile runtime writes the supervisor's profraw at exit; with `LLVM_PROFILE_FILE` absolute this lands in `coverage/profraw/`; confirm a supervisor profraw appears after a test run, and if not, set the filename explicitly as `exec.rs` does). + +`own_cgroup` is `cgroup.is_some()` from `create_cgroup_or_share_outer` in `get_or_create`, passed into `start_layer`. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: same as step 2, plus `tests/isolated_test_pivot_root_failure.rs` and `tests/test_layer_failures.rs` (setup errors still reach stderr). +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add src tests/ai_test_auto_shutdown.rs +git commit -m "Supervise layer PID 1 and clean up when it exits" +``` + +### Task 2: PID 1 reaps orphans and exits when idle + +**Files:** +- Modify: `src/layer/get_or_create.rs` (end of `setup_layer_and_sleep_forever`; rename to `setup_layer_and_wait`) +- Modify: `tests/fixtures/fixture_layer.rs` (keep-alive helper) +- Modify: existing tests that need a layer to stay running between commands (found by running the suite; likely candidates: `ai_test_resource_limits.rs`, `ai_test_layer_settings.rs`, `test_list.rs`, `isolated_test_clean_running.rs`, `isolated_test_stop_*.rs`, `test_mount_unmount_kill.rs`, `ai_test_delete.rs`) +- Modify: `README.adoc` (layer lifetime: auto-shutdown, `stop` still available) +- Test: `tests/ai_test_auto_shutdown.rs` + +**Interfaces:** +- Consumes: Task 1's supervisor and test helpers. +- Produces: `LayerManager::hold(&mut self) -> Result<()>` — runs `sh -c "sleep 3600 >/dev/null 2>&1 &"` in the layer so it stays running until `stop`. + +- [ ] **Step 1: Write the failing tests** + +```rust +#[rstest] +fn ai_test_idle_layer_shuts_down(mut layer: LayerManager) -> Result<()> { + layer.run(&["touch", "/tmp/devlayer-coverage-idle-file"])?; + assert!(wait_until(Duration::from_secs(5), || !pid_file(&layer).unwrap().exists())); + assert!(!has_mounts(&layer)?); + layer.run(&["list"])?; // shows the layer as stopped + layer.run(&["status", "/tmp"])?; // changes survive + assert!(layer.last_stdout.contains("devlayer-coverage-idle-file")); + layer.run(&["true"])?; // rejoining restarts it + assert!(layer_pid(&layer).is_some()); + Ok(()) +} + +#[rstest] +fn ai_test_background_process_keeps_layer_up(mut layer: LayerManager) -> Result<()> { + layer.hold()?; + std::thread::sleep(Duration::from_secs(3)); + assert!(layer_pid(&layer).is_some()); + layer.run(&["pkill", "-f", "sleep 3600"])?; + assert!(wait_until(Duration::from_secs(5), || !pid_file(&layer).unwrap().exists())); + Ok(()) +} + +#[rstest] +fn ai_test_orphans_reaped(mut layer: LayerManager) -> Result<()> { + layer.hold()?; + // The shell exits right away, orphaning a short-lived child + layer.run(&["sh", "-c", "(sleep 0.2 &)"])?; + std::thread::sleep(Duration::from_secs(2)); + layer.run(&["sh", "-c", "grep -l '^State:.*Z' /proc/[0-9]*/status || true"])?; + assert_eq!(layer.last_stdout.trim(), ""); + Ok(()) +} + +#[rstest] +fn ai_test_idle_shutdown_removes_cgroup(mut layer: LayerManager) -> Result<()> { + // Skip like ai_test_resource_limits.rs's limits_available when cgroups + // can't be managed here + if !layer.pass(&["--cpus=1", "true"]) { return Ok(()); } + let cgroup = PathBuf::from("/sys/fs/cgroup/devlayer") + .join(format!("{}-{}", nix::unistd::getuid(), layer.name)); + assert!(wait_until(Duration::from_secs(5), || !cgroup.exists())); + Ok(()) +} +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `cargo test ... --test ai_test_auto_shutdown` (coverage env) +Expected: `ai_test_idle_layer_shuts_down`, `ai_test_idle_shutdown_removes_cgroup` FAIL (layer stays up); `ai_test_orphans_reaped` FAILS (a `Z` process is listed); `ai_test_background_process_keeps_layer_up` fails on its last assertion. + +- [ ] **Step 3: Implement** + +Replace PID 1's sleep loop: sleep 1 s, reap with `waitpid(Pid::from_raw(-1), Some(WaitPidFlag::WNOHANG))` until `StillAlive`/`ECHILD`, then if `/proc`'s numeric entries are exactly `["1"]`, dump coverage (as the current loop does) and `exit(0)`. Keep the periodic profraw dump. Add `LayerManager::hold`. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: same as step 2. +Expected: PASS. + +- [ ] **Step 5: Fix existing tests that relied on a layer staying up** + +Run the full suite (`make test` on a host; nested, compare per-file failures against a baseline run of the branch tip before this task). For each new failure caused by the layer shutting down between commands, call `layer.hold()?` after the layer's first command. Don't change any assertion. +Expected: no failures beyond the baseline. + +- [ ] **Step 6: Document and commit** + +README: in the section on layer lifetime/`stop`, say a layer stops by itself once nothing is running in it, keeps its changes, and restarts when a command runs in it again; `devlayer stop` stops it right away and kills what's running. + +```bash +git add src tests README.adoc +git commit -m "Reap orphans in layers and shut layers down when idle" +``` From 7ead605c4c3613f10eb32bfc068ed28f8798d989 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 16:20:21 -0500 Subject: [PATCH 17/32] Supervise layer PID 1 and clean up when it exits --- src/layer/get_or_create.rs | 90 ++++++++++++++++++++++--- src/layer/mod.rs | 1 + src/layer/supervisor.rs | 85 ++++++++++++++++++++++++ src/util/lock_layer.rs | 31 ++++++--- tests/ai_test_auto_shutdown.rs | 116 +++++++++++++++++++++++++++++++++ 5 files changed, 304 insertions(+), 19 deletions(-) create mode 100644 src/layer/supervisor.rs create mode 100644 tests/ai_test_auto_shutdown.rs diff --git a/src/layer/get_or_create.rs b/src/layer/get_or_create.rs index 61fd6a6..442faa5 100644 --- a/src/layer/get_or_create.rs +++ b/src/layer/get_or_create.rs @@ -1,5 +1,6 @@ use super::cgroup::remove_cgroup; use super::mount_overlays::MountHash; +use super::supervisor; use crate::config::{BindMount, BindMountOptions, Config, Network}; use crate::layer::{Layer, LayerOrigin}; #[cfg(feature = "coverage")] @@ -21,10 +22,14 @@ use nix::{ mount::MsFlags, mount::{MntFlags, umount2}, sys::stat::{Mode, SFlag, makedev, mknod}, - unistd::{Gid, Pid, Uid, close, pipe, pivot_root, setsid}, + sys::wait::waitpid, + unistd::{ + ForkResult, Gid, Pid, Uid, close, fork, pipe, pivot_root, setsid, + }, }; #[cfg(feature = "coverage")] use std::ffi::CString; +use std::io::Read; use std::os::{ fd::{AsRawFd, OwnedFd}, unix::fs::{MetadataExt, symlink}, @@ -234,6 +239,10 @@ impl Layer { /** * This launches a new process with new namespaces. The process will go to sleep * but stick around to allow future processes to be launched in the same namespaces. + * + * PID 1 is started by a supervisor process we fork first, which waits for + * PID 1 to exit and then cleans up after the layer. The supervisor reports + * back whether PID 1 is ready, followed by its pid. */ fn start_layer( &self, @@ -242,6 +251,67 @@ impl Layer { overlay_mounts: &Vec, cgroup: Option<&OwnedFd>, ) -> Result { + let (read_fd, write_fd) = + pipe().context("failed to create pipe for layer supervisor")?; + + match unsafe { fork() }.context("failed to fork layer supervisor")? { + ForkResult::Parent { child } => { + drop(write_fd); + let mut buffer = [0; 5]; + let ready = std::fs::File::from(read_fd) + .read_exact(&mut buffer) + .is_ok() + && buffer[0] == 0; + if !ready { + let _ = waitpid(child, None); + return Err(anyhow!("Failed to setup layer")); + } + let pid = i32::from_le_bytes([ + buffer[1], buffer[2], buffer[3], buffer[4], + ]); + Ok(Pid::from_raw(pid)) + } + ForkResult::Child => { + drop(read_fd); + let pid1 = self + .start_pid1(config, pid_file, overlay_mounts, cgroup) + .map_err(|e| { + error!("Failed to start layer: {:#}", e); + e + }); + let message = match pid1 { + Ok(pid) => { + let mut message = vec![0]; + message.extend(pid.as_raw().to_le_bytes()); + message + } + Err(_) => vec![1], + }; + let _ = nix::unistd::write(&write_fd, &message); + match pid1 { + Ok(pid) => { + supervisor::detach(); + supervisor::supervise(self, pid, cgroup.is_some()) + } + Err(_) => std::process::exit(1), + } + } + } + } + + /** + * Runs in the supervisor: starts PID 1, records its pid, and waits until + * it reports that the layer is set up. + */ + fn start_pid1( + &self, + config: &Config, + pid_file: &PathBuf, + overlay_mounts: &Vec, + cgroup: Option<&OwnedFd>, + ) -> Result { + supervisor::become_supervisor()?; + // create a pipe between ourselves and the main layer process so the main layer process can // let us know when it's done setting up the namespaces let (read_fd, write_fd) = @@ -263,6 +333,8 @@ impl Layer { // Starting in our cgroup also makes it the root of our cgroup namespace | cgroup.map_or(0, |_| CLONE_INTO_CGROUP), cgroup: cgroup.map_or(0, |fd| fd.as_raw_fd() as u64), + // Lets the supervisor waitpid() on PID 1 + exit_signal: libc::SIGCHLD as u64, ..Default::default() }; @@ -292,16 +364,16 @@ impl Layer { // Wait for the child process to finish mounting procfs and doing whatever // setup stuff it needs to do. Once done, it sends a byte over the pipe, that's // our signal that the namespaces are ready for use. - let mut buffer = [0; 1]; - nix::unistd::read(read_fd.as_raw_fd(), &mut buffer) - .context("failed to read from layer ready pipe")?; + let mut buffer = [1; 1]; + let _ = nix::unistd::read(read_fd.as_raw_fd(), &mut buffer); - if buffer[0] == 1 { + if buffer[0] != 0 { + // Wait for PID 1 to exit so it's out of the layer's cgroup + // before the caller removes it + let _ = waitpid(pid, None); return Err(anyhow!("Failed to setup layer")); } - drop(read_fd); - Ok(pid) } else { // We are the child process. We should never return from this branch. @@ -323,9 +395,7 @@ impl Layer { }); // If we're here, an error occurred and we'll exit - nix::unistd::write(&write_fd, &[1]) - .context("failed to write to layer ready pipe")?; - + let _ = nix::unistd::write(&write_fd, &[1]); std::process::exit(1); } } diff --git a/src/layer/mod.rs b/src/layer/mod.rs index 77f7df0..4b39097 100644 --- a/src/layer/mod.rs +++ b/src/layer/mod.rs @@ -8,6 +8,7 @@ mod layer_struct; pub mod mount_overlays; mod settings; mod stop; +mod supervisor; mod unmount; pub use layer_struct::*; diff --git a/src/layer/supervisor.rs b/src/layer/supervisor.rs new file mode 100644 index 0000000..59c49b7 --- /dev/null +++ b/src/layer/supervisor.rs @@ -0,0 +1,85 @@ +//! The supervisor is a small root process on the host that starts a layer's +//! PID 1 and waits for it to exit. When PID 1 exits, for whatever reason, the +//! supervisor cleans up after the layer the way `stop` does: it removes the +//! pid file and the layer's cgroup and unmounts the layer. + +use crate::layer::Layer; +use crate::layer::cgroup::remove_cgroup; +use crate::util::{Lock, get_layer_pid_path, get_running_layer_pid}; +use anyhow::{Context, Result}; +use log::trace; +use nix::sys::wait::waitpid; +use nix::unistd::{Gid, Pid, Uid, setresgid, setresuid, setsid}; +use std::os::fd::AsRawFd; +use std::path::Path; + +/// Detaches the current (freshly forked) process from the caller's session +/// and makes it fully root, so the user can't signal it and it survives the +/// user's terminal going away. +pub(super) fn become_supervisor() -> Result<()> { + setsid().context("failed to create a session for the layer supervisor")?; + setresuid(Uid::from_raw(0), Uid::from_raw(0), Uid::from_raw(0)) + .context("failed to set layer supervisor UIDs to root")?; + setresgid(Gid::from_raw(0), Gid::from_raw(0), Gid::from_raw(0)) + .context("failed to set layer supervisor GIDs to root")?; + unsafe { + libc::signal(libc::SIGHUP, libc::SIG_IGN); + libc::signal(libc::SIGINT, libc::SIG_IGN); + } + Ok(()) +} + +/// Points stdin, stdout and stderr at /dev/null and closes every other file +/// descriptor, so we don't keep the caller's terminal, pipes or layer lock +/// open while we wait, and don't hold the user's working directory busy. +pub(super) fn detach() { + if let Ok(null) = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open("/dev/null") + { + for fd in 0..=2 { + unsafe { libc::dup2(null.as_raw_fd(), fd) }; + } + } + unsafe { libc::syscall(libc::SYS_close_range, 3, u32::MAX, 0) }; + let _ = std::env::set_current_dir("/"); +} + +/// Waits for PID 1 to exit, cleans up after the layer, and exits. +/// `own_cgroup` is whether the layer created a cgroup of its own. +pub(super) fn supervise(layer: &Layer, pid1: Pid, own_cgroup: bool) -> ! { + trace!("Supervising layer '{}' with PID 1 {}", layer.name, pid1); + while let Err(nix::errno::Errno::EINTR) = waitpid(pid1, None) {} + let _ = cleanup(layer, pid1, own_cgroup); + std::process::exit(0); +} + +fn cleanup(layer: &Layer, pid1: Pid, own_cgroup: bool) -> Result<()> { + let storage_dir = layer.base.parent().unwrap_or(Path::new("/")); + + /* Without a lock file the layer was deleted, which already stopped and + * unmounted it. Opening it without creating it keeps it deleted. */ + let Some(_lock) = Lock::existing_layer(storage_dir, &layer.name)? else { + return Ok(()); + }; + + /* The layer was restarted, leave the new instance alone */ + if get_running_layer_pid(storage_dir, &layer.name).is_some() { + return Ok(()); + } + + let pid_file = get_layer_pid_path(storage_dir, &layer.name); + if std::fs::read_to_string(&pid_file) + .is_ok_and(|pid| pid.trim() == pid1.to_string()) + { + std::fs::remove_file(&pid_file)?; + } + + let cgroup = layer.cgroup_path(); + if own_cgroup && cgroup.exists() { + remove_cgroup(&cgroup); + } + + layer.unmount() +} diff --git a/src/util/lock_layer.rs b/src/util/lock_layer.rs index 416e69e..1ca075e 100644 --- a/src/util/lock_layer.rs +++ b/src/util/lock_layer.rs @@ -19,24 +19,37 @@ impl Lock { layer_name: &str, ) -> Result> { let lock_file = layers_storage_dir.join(format!("{}.lock", layer_name)); - trace!("Acquiring lock {}", lock_file.display()); - let file = match OpenOptions::new() + let file = OpenOptions::new() .create(true) .read(true) .write(true) .truncate(false) .open(&lock_file) - { - Ok(file) => file, - Err(e) => { - return Err(anyhow!( + .map_err(|e| { + anyhow!( "Failed to open lock file for layer {}: {}", layer_name, e - )); - } - }; + ) + })?; + Self::acquire(lock_file, file) + } + + /** Like `layer`, but returns None instead of creating the lock file + * when it can't be opened, e.g. because the layer was deleted. */ + pub fn existing_layer( + layers_storage_dir: &Path, + layer_name: &str, + ) -> Result>> { + let lock_file = layers_storage_dir.join(format!("{}.lock", layer_name)); + match OpenOptions::new().read(true).write(true).open(&lock_file) { + Ok(file) => Self::acquire(lock_file, file).map(Some), + Err(_) => Ok(None), + } + } + fn acquire(lock_file: PathBuf, file: File) -> Result> { + trace!("Acquiring lock {}", lock_file.display()); let lock = nix::fcntl::Flock::lock(file, nix::fcntl::FlockArg::LockExclusive) .map_err(|(_, e)| anyhow!("Failed to acquire lock: {}", e))?; diff --git a/tests/ai_test_auto_shutdown.rs b/tests/ai_test_auto_shutdown.rs new file mode 100644 index 0000000..fc5085c --- /dev/null +++ b/tests/ai_test_auto_shutdown.rs @@ -0,0 +1,116 @@ +mod fixtures; + +use anyhow::{Result, anyhow}; +use fixtures::*; +use rstest::*; +use std::path::PathBuf; +use std::process::Command; +use std::time::{Duration, Instant}; + +/// The layer's pid file, `/.pid` +fn pid_file(layer: &LayerManager) -> Result { + Ok(PathBuf::from(format!("{}.pid", layer.dir()?.display()))) +} + +/// PID 1 of the layer, if its pid file names a live process +fn layer_pid(layer: &LayerManager) -> Option { + let pid = std::fs::read_to_string(pid_file(layer).ok()?).ok()?; + let pid = pid.trim().parse::().ok()?; + PathBuf::from(format!("/proc/{}", pid)) + .exists() + .then_some(pid) +} + +/// Whether anything is mounted under the layer's directory +fn has_mounts(layer: &LayerManager) -> Result { + let dir = layer.dir()?; + let mountinfo = std::fs::read_to_string("/proc/self/mountinfo")?; + Ok(mountinfo.lines().any(|line| { + line.split_whitespace().nth(4).is_some_and(|mount_point| { + PathBuf::from(mount_point).starts_with(&dir) + }) + })) +} + +/// Polls `f` every 50 ms until it returns true or `timeout` passes +fn wait_until(timeout: Duration, mut f: impl FnMut() -> bool) -> bool { + let deadline = Instant::now() + timeout; + loop { + if f() { + return true; + } + if Instant::now() >= deadline { + return false; + } + std::thread::sleep(Duration::from_millis(50)); + } +} + +/// The parent pid of `pid` +fn ppid_of(pid: i32) -> Result { + let status = std::fs::read_to_string(format!("/proc/{}/status", pid))?; + status + .lines() + .find_map(|line| line.strip_prefix("PPid:")) + .ok_or_else(|| anyhow!("no PPid line for {}", pid))? + .trim() + .parse::() + .map_err(Into::into) +} + +/// When PID 1 dies, the supervisor unmounts the layer and removes its pid file +#[rstest] +fn ai_test_supervisor_cleans_up_after_pid1_exit( + mut layer: LayerManager, +) -> Result<()> { + layer.run(&["true"])?; + let pid = layer_pid(&layer).expect("layer should be running"); + assert!(has_mounts(&layer)?); + Command::new("sudo") + .args(["kill", "-KILL", &pid.to_string()]) + .status()?; + assert!(wait_until(Duration::from_secs(5), || { + !pid_file(&layer).unwrap().exists() + })); + assert!(wait_until(Duration::from_secs(5), || { + !has_mounts(&layer).unwrap() + })); + Ok(()) +} + +/// PID 1's parent is the devlayer supervisor, and the user can't signal it +#[rstest] +fn ai_test_supervisor_not_killable_by_user( + mut layer: LayerManager, +) -> Result<()> { + layer.run(&["true"])?; + let pid = layer_pid(&layer).expect("layer should be running"); + let ppid = ppid_of(pid)?; + let comm = std::fs::read_to_string(format!("/proc/{}/comm", ppid))?; + assert_eq!(comm.trim(), "devlayer"); + let status = Command::new("kill") + .args(["-TERM", &ppid.to_string()]) + .status()?; + assert!(!status.success()); + assert!(PathBuf::from(format!("/proc/{}", ppid)).exists()); + Ok(()) +} + +/// After an explicit stop, the supervisor's cleanup is harmless: the layer +/// restarts and deletes normally, and delete doesn't leave a lock file behind +#[rstest] +fn ai_test_supervisor_after_stop_and_delete( + mut layer: LayerManager, +) -> Result<()> { + layer.run(&["true"])?; + layer.run(&["stop"])?; + layer.run(&["true"])?; + assert!(layer_pid(&layer).is_some()); + let lock = PathBuf::from(format!("{}.lock", layer.dir()?.display())); + layer.run(&["delete", "-y"])?; + std::thread::sleep(Duration::from_secs(2)); + assert!(!lock.exists()); + layer.run(&["list"])?; + assert!(!layer.last_stdout.contains(&layer.name)); + Ok(()) +} From 96ff3efc948d67a52ca41327b749f70c9411a435 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 16:29:24 -0500 Subject: [PATCH 18/32] Reap orphans in layers and shut layers down when idle --- README.adoc | 10 +++- src/layer/get_or_create.rs | 85 +++++++++++++++++++++----------- tests/ai_test_auto_shutdown.rs | 78 +++++++++++++++++++++++++++-- tests/ai_test_delete.rs | 14 +++++- tests/ai_test_resource_limits.rs | 22 ++++++--- tests/fixtures/fixture_layer.rs | 17 +++++++ 6 files changed, 186 insertions(+), 40 deletions(-) diff --git a/README.adoc b/README.adoc index 8022ce3..f3f0123 100644 --- a/README.adoc +++ b/README.adoc @@ -151,7 +151,9 @@ change in the layer. Relative patterns are relative to your current directory. Synchronize changes that might have occurred in your host file system so that they are reflected in running layers. Note, this performs a system wide filesystem sync and flushes all caches. `stop [--all]`:: -Kill all processes in the layer and unmount the filesystems. Note this will not reject any changes +Kill all processes in the layer and unmount the filesystems. Note this will not reject any changes. +A layer also stops by itself once nothing is running in it any more; `stop` +is for stopping it right away, along with anything still running in it. `delete [PATTERNS]`:: Stop and delete all files associated with the layers matching the provided patterns. If no patterns are provided, deletes the default or --join'ed layer. @@ -300,6 +302,12 @@ The CLI argument parser will treat anything after the `[OPTIONS]` as either an action (listed above), or a command to run in the layer. Running a command will implicitly start the layer if it isn't running already. +A layer keeps running for as long as anything is running in it, including +processes left running in the background. About a second after the last +process in it exits, the layer stops by itself: its filesystems are unmounted, +but its changes are kept, so you can still `status`, `diff`, `accept` or +`reject` them, and running another command in the layer starts it again. + After the `[OPTIONS]`, provided you're not running an action, `devlayer` will execute whatever command you provide, along with all subsequent arguments, diff --git a/src/layer/get_or_create.rs b/src/layer/get_or_create.rs index 442faa5..2051ac5 100644 --- a/src/layer/get_or_create.rs +++ b/src/layer/get_or_create.rs @@ -22,7 +22,7 @@ use nix::{ mount::MsFlags, mount::{MntFlags, umount2}, sys::stat::{Mode, SFlag, makedev, mknod}, - sys::wait::waitpid, + sys::wait::{WaitPidFlag, WaitStatus, waitpid}, unistd::{ ForkResult, Gid, Pid, Uid, close, fork, pipe, pivot_root, setsid, }, @@ -384,11 +384,7 @@ impl Layer { // Normal operation is that this doesn't return. let _ = self - .setup_layer_and_sleep_forever( - config, - &write_fd, - overlay_mounts, - ) + .setup_layer_and_wait(config, &write_fd, overlay_mounts) .map_err(|e| { error!("Failed to setup layer: {}", e); e @@ -402,7 +398,7 @@ impl Layer { /* After forking via clone3, this is function gets called to finish setting up the layer. * namespaces. It should never return, if it does it's an error. */ - fn setup_layer_and_sleep_forever( + fn setup_layer_and_wait( &self, config: &Config, write_fd: &OwnedFd, @@ -1121,30 +1117,63 @@ impl Layer { libc::signal(libc::SIGTERM, exit as libc::sighandler_t); } - // sleep forever, this process hangs around only to host the namespaces so other processes - // can join in. - let mut count = 0; + /* Host the namespaces for as long as anything runs in the layer. + * Once a second, reap processes orphaned in the layer, and exit once + * we're the only process left, which has our supervisor clean up. */ + /* Write our coverage data now, as we may be killed rather than exit */ + #[cfg(feature = "coverage")] + let dump_coverage = || { + let _ = nix::unistd::chdir(&cwd); + unsafe { + __llvm_profile_set_filename( + CString::new( + format!( + "coverage/profraw/setup_layer-{}-{}-%m.profraw", + self.pid, + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() + ) + .as_str(), + ) + .unwrap() + .as_ptr(), + ); + __llvm_profile_dump(); + } + }; + #[cfg(feature = "coverage")] + dump_coverage(); + loop { - std::thread::sleep(std::time::Duration::from_millis(count)); - /* Cheap hack to fill out coverage */ - count += 1; - if count >= 2 { - count += 10000; - // Flush gcov coverage data before we spin forever + std::thread::sleep(std::time::Duration::from_secs(1)); + while !matches!( + waitpid(Pid::from_raw(-1), Some(WaitPidFlag::WNOHANG)), + Ok(WaitStatus::StillAlive) | Err(_) + ) {} + + if only_process_in_layer() { + trace!("Nothing is running in layer '{}', exiting", self.name); #[cfg(feature = "coverage")] - { - let _ = nix::unistd::chdir(&cwd); - - unsafe { - __llvm_profile_set_filename( - CString::new(format!("coverage/profraw/setup_layer-{}-{}-%m.profraw", self.pid, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs()).as_str(),) - .unwrap() - .as_ptr(), - ); - __llvm_profile_dump(); - } - } + dump_coverage(); + std::process::exit(0); } } } } + +/// Whether we (PID 1) are the only process in our pid namespace, going by +/// our layer's /proc +fn only_process_in_layer() -> bool { + std::fs::read_dir("/proc").is_ok_and(|entries| { + entries + .filter_map(Result::ok) + .map(|entry| entry.file_name()) + .filter(|name| { + name.to_str() + .is_some_and(|n| n.bytes().all(|b| b.is_ascii_digit())) + }) + .all(|name| name == "1") + }) +} diff --git a/tests/ai_test_auto_shutdown.rs b/tests/ai_test_auto_shutdown.rs index fc5085c..4658845 100644 --- a/tests/ai_test_auto_shutdown.rs +++ b/tests/ai_test_auto_shutdown.rs @@ -63,7 +63,7 @@ fn ppid_of(pid: i32) -> Result { fn ai_test_supervisor_cleans_up_after_pid1_exit( mut layer: LayerManager, ) -> Result<()> { - layer.run(&["true"])?; + layer.hold()?; let pid = layer_pid(&layer).expect("layer should be running"); assert!(has_mounts(&layer)?); Command::new("sudo") @@ -83,7 +83,7 @@ fn ai_test_supervisor_cleans_up_after_pid1_exit( fn ai_test_supervisor_not_killable_by_user( mut layer: LayerManager, ) -> Result<()> { - layer.run(&["true"])?; + layer.hold()?; let pid = layer_pid(&layer).expect("layer should be running"); let ppid = ppid_of(pid)?; let comm = std::fs::read_to_string(format!("/proc/{}/comm", ppid))?; @@ -104,7 +104,7 @@ fn ai_test_supervisor_after_stop_and_delete( ) -> Result<()> { layer.run(&["true"])?; layer.run(&["stop"])?; - layer.run(&["true"])?; + layer.hold()?; assert!(layer_pid(&layer).is_some()); let lock = PathBuf::from(format!("{}.lock", layer.dir()?.display())); layer.run(&["delete", "-y"])?; @@ -114,3 +114,75 @@ fn ai_test_supervisor_after_stop_and_delete( assert!(!layer.last_stdout.contains(&layer.name)); Ok(()) } + +/// Once its command exits, a layer shuts itself down, keeping its changes, +/// and running a command in it again restarts it +#[rstest] +fn ai_test_idle_layer_shuts_down(mut layer: LayerManager) -> Result<()> { + let name = format!("devlayer-coverage-idle-{}", rid()); + let file = std::env::current_dir()?.join(&name); + layer.run(&["touch", file.to_str().unwrap_or_default()])?; + assert!(wait_until(Duration::from_secs(5), || { + !pid_file(&layer).unwrap().exists() + })); + assert!(!has_mounts(&layer)?); + assert!(!file.exists()); + + layer.run(&["list"])?; + let stopped = layer.last_stdout.split("Stopped layers:").nth(1); + assert!(stopped.is_some_and(|stopped| stopped.contains(&layer.name))); + + layer.run(&["status", "/"])?; + assert!(layer.last_stdout.contains(&name)); + + layer.hold()?; + assert!(layer_pid(&layer).is_some()); + Ok(()) +} + +/// A process left running in a layer keeps it up until the process exits +#[rstest] +fn ai_test_background_process_keeps_layer_up( + mut layer: LayerManager, +) -> Result<()> { + layer.hold()?; + std::thread::sleep(Duration::from_secs(3)); + assert!(layer_pid(&layer).is_some()); + layer.run(&["pkill", "-f", "sleep 3600"])?; + assert!(wait_until(Duration::from_secs(5), || { + !pid_file(&layer).unwrap().exists() + })); + Ok(()) +} + +/// Processes orphaned inside a layer are reaped rather than left as zombies +#[rstest] +fn ai_test_orphans_reaped(mut layer: LayerManager) -> Result<()> { + layer.hold()?; + // The subshell exits right away, orphaning a short-lived child + layer.run(&["sh", "-c", "(sleep 0.2 &)"])?; + std::thread::sleep(Duration::from_secs(2)); + layer.run(&[ + "sh", + "-c", + "grep -l '^State:.*Z' /proc/[0-9]*/status || true", + ])?; + assert_eq!(layer.last_stdout.trim(), ""); + Ok(()) +} + +/// A layer with resource limits removes its cgroup when it shuts down +#[rstest] +fn ai_test_idle_shutdown_removes_cgroup(mut layer: LayerManager) -> Result<()> { + // Resource limits aren't available everywhere, e.g. inside another layer + if !layer.pass(&["--cpus=1", "true"]) { + return Ok(()); + } + let cgroup = PathBuf::from("/sys/fs/cgroup/devlayer").join(format!( + "{}-{}", + nix::unistd::getuid(), + layer.name + )); + assert!(wait_until(Duration::from_secs(5), || !cgroup.exists())); + Ok(()) +} diff --git a/tests/ai_test_delete.rs b/tests/ai_test_delete.rs index 6384616..114da3c 100644 --- a/tests/ai_test_delete.rs +++ b/tests/ai_test_delete.rs @@ -196,7 +196,12 @@ fn test_delete_modified_layer_n() -> Result<()> { let filename = layer.test_filename("test_file"); // Create and run a layer - layer.run(&["touch", &filename])?; + // Leave a process running so the layer stays up + layer.run(&[ + "sh", + "-c", + &format!("touch {} && (sleep 3600 >/dev/null 2>&1 &)", filename), + ])?; // Delete the stopped layer layer.run_with_stdin(&["delete", &name], "n\n")?; @@ -216,7 +221,12 @@ fn test_delete_modified_ignored_layer_n() -> Result<()> { let filename = layer.test_filename("test_file"); // Create and run a layer - layer.run(&["touch", &filename])?; + // Leave a process running so the layer stays up + layer.run(&[ + "sh", + "-c", + &format!("touch {} && (sleep 3600 >/dev/null 2>&1 &)", filename), + ])?; // Delete the stopped layer layer.set_ignored(false); diff --git a/tests/ai_test_resource_limits.rs b/tests/ai_test_resource_limits.rs index eb4eb5f..838d9a5 100644 --- a/tests/ai_test_resource_limits.rs +++ b/tests/ai_test_resource_limits.rs @@ -23,10 +23,11 @@ fn write_config( } /// Starts the layer with a CPU limit to find out if this machine lets us -/// manage cgroups. When it doesn't, e.g. because we're running inside a -/// container or another layer, we check that we fail with a helpful error. +/// manage cgroups, leaving it running. When it doesn't, e.g. because we're +/// running inside a container or another layer, we check that we fail with a +/// helpful error. fn limits_available(layer: &mut LayerManager) -> bool { - if layer.pass(&["--cpus=1", "true"]) { + if layer.hold_with(&["--cpus=1"]).is_ok() { return true; } assert!( @@ -218,6 +219,7 @@ fn ai_test_limits_applied(mut layer: LayerManager) -> Result<()> { assert_eq!(run(&mut layer, &["cat", "/proc/self/cgroup"])?, "0::/"); // Processes that join the running layer are in its cgroup too + layer.hold_with(&args)?; let cgroup = host_cgroup(&layer).expect("layer cgroup should exist"); let mut child = layer.run_in_background(&[args[0], args[1], "sleep", "30"])?; @@ -296,7 +298,7 @@ fn ai_test_limits_changed(mut layer: LayerManager) -> Result<()> { // Restart without config files, which may set limits of their own layer.run(&["stop"])?; - layer.run(&["--no-config", "--cpus=1", "true"])?; + layer.hold_with(&["--no-config", "--cpus=1"])?; // The layer is running with --cpus=1, so other limits are rejected assert!(layer.xfail(&["--no-config", "true"])); @@ -332,13 +334,21 @@ fn ai_test_limits_stale_cgroup(mut layer: LayerManager) -> Result<()> { return Ok(()); } - // Kill the layer without cleaning up, leaving an empty cgroup behind + // Kill the layer and its supervisor without cleaning up, leaving an + // empty cgroup behind let cgroup = host_cgroup(&layer).expect("layer cgroup should exist"); layer.run(&["config", "layer_dir"])?; let pid_file = format!("{}.pid", layer.last_stdout.trim()); let pid = fs::read_to_string(&pid_file)?; + let status = fs::read_to_string(format!("/proc/{}/status", pid.trim()))?; + let supervisor = status + .lines() + .find_map(|line| line.strip_prefix("PPid:")) + .unwrap_or_default() + .trim() + .to_string(); std::process::Command::new("sudo") - .args(["kill", "-9", pid.trim()]) + .args(["kill", "-9", &supervisor, pid.trim()]) .status()?; for _ in 0..100 { if fs::read_to_string(cgroup.join("cgroup.procs"))?.is_empty() { diff --git a/tests/fixtures/fixture_layer.rs b/tests/fixtures/fixture_layer.rs index 12b3733..6cf8089 100644 --- a/tests/fixtures/fixture_layer.rs +++ b/tests/fixtures/fixture_layer.rs @@ -359,6 +359,23 @@ impl LayerManager { } } + /// Leaves a process running in the layer so it doesn't shut itself down + /// once a command finishes. The layer then stays up until it's stopped. + #[allow(dead_code)] + pub fn hold(&mut self) -> Result<()> { + self.hold_with(&[]) + } + + /// Like `hold`, passing these options to devlayer, e.g. the resource + /// limits a layer was started with, which joining it requires + #[allow(dead_code)] + pub fn hold_with(&mut self, options: &[&str]) -> Result<()> { + let mut args = options.to_vec(); + args.extend(["sh", "-c", "sleep 3600 >/dev/null 2>&1 &"]); + self.run(&args)?; + Ok(()) + } + #[allow(dead_code)] pub fn run_in_background(&mut self, args: &[&str]) -> Result { let mut cmd = Command::new("sudo"); From 6e886edd69a63096f5b770b986d9e8c1b4eabe41 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Fri, 13 Nov 2026 16:48:57 -0500 Subject: [PATCH 19/32] Record PID 1's idle loop in coverage, cover supervisor cleanup paths, keep test layers up explicitly --- src/layer/get_or_create.rs | 4 +++ src/layer/supervisor.rs | 16 +++------ src/util/lock_layer.rs | 25 +++++++++++--- tests/ai_test_auto_shutdown.rs | 51 ++++++++++++++++++++++++++++ tests/ai_test_delete.rs | 2 +- tests/ai_test_resource_limits.rs | 10 +++++- tests/ai_test_sigterm.rs | 2 +- tests/isolated_test_clean_running.rs | 2 +- tests/test_mount_unmount_kill.rs | 14 ++++---- 9 files changed, 99 insertions(+), 27 deletions(-) diff --git a/src/layer/get_or_create.rs b/src/layer/get_or_create.rs index 2051ac5..3c60896 100644 --- a/src/layer/get_or_create.rs +++ b/src/layer/get_or_create.rs @@ -41,6 +41,7 @@ use uuid::Uuid; unsafe extern "C" { fn __llvm_profile_set_filename(filename: *const i8); fn __llvm_profile_dump(); + fn __llvm_profile_reset_counters(); } const TMPFS_SIZE: i32 = 64 * 1024 * 1024; // 64MB, because that's what docker does @@ -1141,6 +1142,9 @@ impl Layer { .as_ptr(), ); __llvm_profile_dump(); + // A later dump is skipped unless the counters are reset, + // after which it writes what ran since (merged by %m) + __llvm_profile_reset_counters(); } }; #[cfg(feature = "coverage")] diff --git a/src/layer/supervisor.rs b/src/layer/supervisor.rs index 59c49b7..3c70a7c 100644 --- a/src/layer/supervisor.rs +++ b/src/layer/supervisor.rs @@ -5,7 +5,7 @@ use crate::layer::Layer; use crate::layer::cgroup::remove_cgroup; -use crate::util::{Lock, get_layer_pid_path, get_running_layer_pid}; +use crate::util::{Lock, get_running_layer_pid}; use anyhow::{Context, Result}; use log::trace; use nix::sys::wait::waitpid; @@ -51,11 +51,11 @@ pub(super) fn detach() { pub(super) fn supervise(layer: &Layer, pid1: Pid, own_cgroup: bool) -> ! { trace!("Supervising layer '{}' with PID 1 {}", layer.name, pid1); while let Err(nix::errno::Errno::EINTR) = waitpid(pid1, None) {} - let _ = cleanup(layer, pid1, own_cgroup); + let _ = cleanup(layer, own_cgroup); std::process::exit(0); } -fn cleanup(layer: &Layer, pid1: Pid, own_cgroup: bool) -> Result<()> { +fn cleanup(layer: &Layer, own_cgroup: bool) -> Result<()> { let storage_dir = layer.base.parent().unwrap_or(Path::new("/")); /* Without a lock file the layer was deleted, which already stopped and @@ -64,18 +64,12 @@ fn cleanup(layer: &Layer, pid1: Pid, own_cgroup: bool) -> Result<()> { return Ok(()); }; - /* The layer was restarted, leave the new instance alone */ + /* If the pid file names a running PID 1, the layer was restarted, so + * leave the new instance alone. Otherwise this removes the pid file. */ if get_running_layer_pid(storage_dir, &layer.name).is_some() { return Ok(()); } - let pid_file = get_layer_pid_path(storage_dir, &layer.name); - if std::fs::read_to_string(&pid_file) - .is_ok_and(|pid| pid.trim() == pid1.to_string()) - { - std::fs::remove_file(&pid_file)?; - } - let cgroup = layer.cgroup_path(); if own_cgroup && cgroup.exists() { remove_cgroup(&cgroup); diff --git a/src/util/lock_layer.rs b/src/util/lock_layer.rs index 1ca075e..bf6b554 100644 --- a/src/util/lock_layer.rs +++ b/src/util/lock_layer.rs @@ -1,4 +1,5 @@ use std::fs::{File, OpenOptions}; +use std::os::unix::fs::MetadataExt; use std::path::{Path, PathBuf}; use log::trace; @@ -36,16 +37,30 @@ impl Lock { } /** Like `layer`, but returns None instead of creating the lock file - * when it can't be opened, e.g. because the layer was deleted. */ + * when it can't be opened, e.g. because the layer was deleted, or when + * it was deleted while we waited for the lock. */ pub fn existing_layer( layers_storage_dir: &Path, layer_name: &str, ) -> Result>> { let lock_file = layers_storage_dir.join(format!("{}.lock", layer_name)); - match OpenOptions::new().read(true).write(true).open(&lock_file) { - Ok(file) => Self::acquire(lock_file, file).map(Some), - Err(_) => Ok(None), - } + let file = OpenOptions::new().read(true).write(true).open(&lock_file); + let lock = file + .ok() + .map(|file| Self::acquire(lock_file, file)) + .transpose()?; + Ok(lock.filter(|lock| lock.is_current())) + } + + /// Whether our lock file is still the one at its path + fn is_current(&self) -> bool { + let ours = self.lock.metadata(); + let current = std::fs::metadata(&self.path); + ours.is_ok_and(|ours| { + current.is_ok_and(|current| { + ours.dev() == current.dev() && ours.ino() == current.ino() + }) + }) } fn acquire(lock_file: PathBuf, file: File) -> Result> { diff --git a/tests/ai_test_auto_shutdown.rs b/tests/ai_test_auto_shutdown.rs index 4658845..4f462d3 100644 --- a/tests/ai_test_auto_shutdown.rs +++ b/tests/ai_test_auto_shutdown.rs @@ -2,7 +2,9 @@ mod fixtures; use anyhow::{Result, anyhow}; use fixtures::*; +use nix::fcntl::{Flock, FlockArg}; use rstest::*; +use std::fs::File; use std::path::PathBuf; use std::process::Command; use std::time::{Duration, Instant}; @@ -186,3 +188,52 @@ fn ai_test_idle_shutdown_removes_cgroup(mut layer: LayerManager) -> Result<()> { assert!(wait_until(Duration::from_secs(5), || !cgroup.exists())); Ok(()) } + +/// When a layer was restarted by the time its old supervisor gets to clean +/// up, the supervisor leaves the new instance's pid file and mounts alone +#[rstest] +fn ai_test_supervisor_leaves_restarted_layer( + mut layer: LayerManager, +) -> Result<()> { + let mut other = LayerManager::new(); + layer.hold()?; + other.hold()?; + let pid = layer_pid(&layer).expect("layer should be running"); + let other_pid = layer_pid(&other).expect("other layer should be running"); + let pid_file = pid_file(&layer)?; + let lock_file = format!("{}.lock", layer.dir()?.display()); + + // Hold the layer lock so the supervisor waits to clean up, as it would + // while another devlayer restarts the layer + let lock = Flock::lock(File::open(&lock_file)?, FlockArg::LockExclusive) + .map_err(|(_, e)| e)?; + Command::new("sudo") + .args(["kill", "-KILL", &pid.to_string()]) + .status()?; + assert!(wait_until(Duration::from_secs(5), || { + !PathBuf::from(format!("/proc/{}", pid)).exists() + })); + // Restarting writes the new PID 1 to the pid file, a running layer's + // PID 1 stands in for it + Command::new("sudo") + .args([ + "sh", + "-c", + &format!("printf %s {} > {}", other_pid, pid_file.display()), + ]) + .status()?; + drop(lock); + + std::thread::sleep(Duration::from_secs(2)); + assert!(has_mounts(&layer)?); + assert_eq!( + std::fs::read_to_string(&pid_file)?.trim(), + other_pid.to_string() + ); + + // Don't let stopping this layer stop the other one + Command::new("sudo") + .args(["rm", &pid_file.to_string_lossy()]) + .status()?; + Ok(()) +} diff --git a/tests/ai_test_delete.rs b/tests/ai_test_delete.rs index 114da3c..1fe5658 100644 --- a/tests/ai_test_delete.rs +++ b/tests/ai_test_delete.rs @@ -276,7 +276,7 @@ fn test_delete_running_layer_by_name() -> Result<()> { let name = layer.name.clone(); // Create and run a layer - layer.run(&["true"])?; + layer.hold()?; // Accept the layer layer.run(&["accept", "."])?; diff --git a/tests/ai_test_resource_limits.rs b/tests/ai_test_resource_limits.rs index 838d9a5..bc2e181 100644 --- a/tests/ai_test_resource_limits.rs +++ b/tests/ai_test_resource_limits.rs @@ -467,9 +467,17 @@ fn ai_test_limits_no_swap_accounting(mut layer: LayerManager) -> Result<()> { // Only memory is limited (config files are skipped since they may limit // cpus too). Without swap accounting we can limit memory but not swap. + // The layer is left running, so the commands after the first one join + // the layer started without swap accounting let memory_only = ["--no-config", "--memory=64M", "cat"]; layer.run_with_env( - &[&memory_only[..], &["/sys/fs/cgroup/memory.max"]].concat(), + &[ + "--no-config", + "--memory=64M", + "sh", + "-c", + "cat /sys/fs/cgroup/memory.max; sleep 3600 >/dev/null 2>&1 &", + ], "TEST_NO_SWAP_ACCOUNTING", "1", )?; diff --git a/tests/ai_test_sigterm.rs b/tests/ai_test_sigterm.rs index 13af501..c553660 100644 --- a/tests/ai_test_sigterm.rs +++ b/tests/ai_test_sigterm.rs @@ -8,7 +8,7 @@ use std::time::{Duration, Instant}; #[rstest] fn ai_test_sigterm_stops_layer(mut layer: LayerManager) -> Result<()> { - layer.run(&["true"])?; + layer.hold()?; layer.run(&["config", "layer_dir"])?; let pid_file = format!("{}.pid", layer.last_stdout.trim()); diff --git a/tests/isolated_test_clean_running.rs b/tests/isolated_test_clean_running.rs index 006f61f..09e0b11 100644 --- a/tests/isolated_test_clean_running.rs +++ b/tests/isolated_test_clean_running.rs @@ -13,7 +13,7 @@ fn test_clean_deletes_running_test_layers() -> Result<()> { let mut layer = layer(); let name = layer.name.clone(); - layer.run(&["true"])?; + layer.hold()?; layer.run(&["list"])?; assert!(layer.last_stdout.contains("Running layers:")); assert!(layer.last_stdout.contains(&name)); diff --git a/tests/test_mount_unmount_kill.rs b/tests/test_mount_unmount_kill.rs index 274af76..fc2cc50 100644 --- a/tests/test_mount_unmount_kill.rs +++ b/tests/test_mount_unmount_kill.rs @@ -9,7 +9,7 @@ use std::path::Path; #[rstest] fn test_fail_to_read_mounts(mut layer: LayerManager) -> Result<()> { assert!(layer.exfail(&["env"], "TEST_SYSTEM_MOUNTS_NULL", "1")); - assert!(layer.pass(&["true"])); + layer.hold()?; assert!(layer.exfail(&["stop"], "TEST_SYSTEM_MOUNTS_NULL", "1")); assert!(layer.pass(&["stop"])); Ok(()) @@ -18,7 +18,7 @@ fn test_fail_to_read_mounts(mut layer: LayerManager) -> Result<()> { #[rstest] fn test_no_mounts_found(mut layer: LayerManager) -> Result<()> { assert!(layer.exfail(&["env"], "TEST_NO_MOUNTS_FOUND", "1")); - assert!(layer.pass(&["true"])); + layer.hold()?; assert!(layer.epass(&["stop"], "TEST_NO_MOUNTS_FOUND", "1")); assert!(layer.last_stderr.contains("No mounts found for layer")); Ok(()) @@ -26,7 +26,7 @@ fn test_no_mounts_found(mut layer: LayerManager) -> Result<()> { #[rstest] fn test_unmount_race(mut layer: LayerManager) -> Result<()> { - assert!(layer.pass(&["true"])); + layer.hold()?; assert!(layer.epass(&["stop"], "TEST_UNMOUNT_RACE", "1")); assert!(layer.last_stderr.contains("Failed to unmount")); Ok(()) @@ -37,22 +37,22 @@ fn test_kill_not_running(mut layer: LayerManager) -> Result<()> { assert!(layer.pass(&["stop"])); assert!(layer.last_stderr.contains("doesn't appear to be running")); - assert!(layer.pass(&["true"])); + layer.hold()?; assert!(layer.epass(&["stop"], "TEST_STOP_RACE", "1")); assert!(layer.last_stderr.contains("already gone")); - assert!(layer.pass(&["true"])); + layer.hold()?; assert!(layer.epass(&["stop"], "TEST_STOP_RACE2", "1")); assert!(layer.last_stderr.contains("Failed to kill process")); - assert!(layer.pass(&["true"])); + layer.hold()?; assert!(layer.epass(&["stop"], "TEST_STOP_RACE3", "1")); Ok(()) } #[rstest] fn test_kill_unmounts(mut layer: LayerManager) -> Result<()> { - assert!(layer.pass(&["true"])); + layer.hold()?; let mounts = get_mounts(&layer.dir()?); assert!(!mounts.is_empty()); From f485b29853da15f5691d2db91868507a07e88b5e Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Sat, 14 Nov 2026 15:09:37 -0500 Subject: [PATCH 20/32] clean out plans and specs --- .gitignore | 3 +- ...2026-11-13-devlayer-rename-and-defaults.md | 241 ----------------- .../plans/2026-11-13-layer-auto-shutdown.md | 209 --------------- ...-13-devlayer-rename-and-defaults-design.md | 245 ------------------ .../2026-11-13-layer-auto-shutdown-design.md | 189 -------------- 5 files changed, 2 insertions(+), 885 deletions(-) delete mode 100644 docs/superpowers/plans/2026-11-13-devlayer-rename-and-defaults.md delete mode 100644 docs/superpowers/plans/2026-11-13-layer-auto-shutdown.md delete mode 100644 docs/superpowers/specs/2026-11-13-devlayer-rename-and-defaults-design.md delete mode 100644 docs/superpowers/specs/2026-11-13-layer-auto-shutdown-design.md diff --git a/.gitignore b/.gitignore index 0e6b5fb..aa5b716 100644 --- a/.gitignore +++ b/.gitignore @@ -11,4 +11,5 @@ dev_devlayer.sh .aider* callgrind.out.* cachegrind.out.* -perf.data* \ No newline at end of file +perf.data* +superpowers/ diff --git a/docs/superpowers/plans/2026-11-13-devlayer-rename-and-defaults.md b/docs/superpowers/plans/2026-11-13-devlayer-rename-and-defaults.md deleted file mode 100644 index c630a33..0000000 --- a/docs/superpowers/plans/2026-11-13-devlayer-rename-and-defaults.md +++ /dev/null @@ -1,241 +0,0 @@ - -# devlayer Rename and New Defaults Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Rename the project from `sandbox` to `devlayer` (user-facing, then internal), then make the agent-friendly behavior the default: a new layer per run, the cwd bound live, host network, audio, and LLM tool binds; `--join` replaces `--name`; directory-aware `--last`. - -**Architecture:** Two no-behavior-change rename passes, then one task per behavior change. Layer selection moves from "always resolve `name`" to a `LayerSelection` that is chosen from the CLI, env, config and the action. The layer's directory and whether that directory was bound are stored in `settings.json`, and are reused on re-entry and on restart. - -**Tech Stack:** Rust (clap, serde/serde_json, toml, anyhow, rstest), OverlayFS, Linux namespaces, setuid binary; tests run under `sudo` via `make test` / `TEST=name make quick-test`. - -**Spec:** `docs/superpowers/specs/2026-11-13-devlayer-rename-and-defaults-design.md`. Read it before starting any task. - -## Global Constraints - -- Clean switchover: no fallback, alias or migration for any `sandbox` name, path, env var or config file. -- New names: binary `devlayer`; storage `~/.devlayer/`, fallback `/tmp/devlayer-`; env `DEVLAYER_*`; project config `.devlayer.conf` / `.devlayer.toml`; user config `~/.config/devlayer/config.(conf|toml)`; system config `/etc/devlayer.(conf|toml)`. -- Test layer name prefixes: `devlayer-coverage-*`, `devlayer-bind-empty-*`. New test files go in `tests/ai_test_*.rs` (per CLAUDE.md). -- The ephemeral layer name format stays `ephemeral_%Y-%m-%d_%H-%M-%S[.]`. -- Bind layer order (lowest to highest): system defaults + audio → LLM binds → cwd bind → config files → env → CLI. -- Every task ends with `cargo fmt`, `cargo clippy` clean, and the touched tests passing via `TEST= make quick-test`. Tasks 1, 2 and 9 also run the full `make test`. -- Coverage must stay at 100% (`make coverage-check`); any new `#[cfg(feature = "coverage")]` test hooks follow the existing `TEST_*` env-var pattern. - -## Review Focus - -1. **Running `devlayer` from a subdirectory of the directory where a layer was created, with `--last`.** The layer must be entered with its original directory bind, not fail with "bind mounts changed". Test: Task 7, `ai_test_cwd_bind_reenter_from_subdir`. -2. **`devlayer status` in a project dir right after an agent ran.** It must show changes outside the project (whole layer), not an empty list. Test: Task 9, `ai_test_status_default_whole_layer`. -3. **Bare `devlayer accept` / `reject`.** These must refuse with a hint, and must change nothing. Test: Task 9, `ai_test_accept_requires_pattern` (asserts the file is still in the layer afterwards). -4. **Two layers created in the same directory.** `--last` must pick the newer one; a layer created in a deeper directory must not be chosen when you stand in its parent. Test: Task 8, `ai_test_last_nearest_ancestor_and_newest`. -5. **A path in the LLM list that is missing on the host** (most users have only one or two agents). It must be skipped silently, not fail canonicalization. Test: Task 6, unit test `llm_binds_skip_missing_paths`. - ---- - -### Task 1: User-facing rename - -**Files:** -- Modify: `Cargo.toml` (package and `[[bin]]` name → `devlayer`; leave `[lib] name` for Task 2), `Cargo.lock` (regenerated by cargo) -- Modify: `src/config/resolve.rs` (storage dirs, `SANDBOX_*` env reads, `find_config_files` paths, default name text, error strings) -- Modify: `src/config/cli.rs` (`override_usage`, help text), `src/main.rs` and `src/actions/*.rs` (user-visible output strings and errors that say "sandbox") -- Modify: `src/actions/clean.rs:14` (test patterns → `devlayer-coverage-*`, `devlayer-bind-empty-*`), `src/util/mkdir.rs:78,104` (test dir names) -- Modify: `Makefile`, `packaging/*`, `vm-testing/**`, `README.adoc`, `CONTRIBUTING.adoc`, `RELEASE_CHECKLIST.md`, `CLAUDE.md`, `cspell.json`, `tests/README.md` -- Modify: `tests/fixtures/fixture_sandbox.rs` (`target/{debug,coverage}/devlayer`, name prefix `devlayer-coverage-test-`), and every `tests/*.rs` that hard-codes `sandbox-coverage`, `SANDBOX_*`, `.sandbox.toml`, `~/.sandboxes` or binary paths. - -**Interfaces:** -- Produces: binary `target/{debug,coverage}/devlayer`; env vars `DEVLAYER_LOG_LEVEL`, `DEVLAYER_NAME`, `DEVLAYER_STORAGE_DIR`, `DEVLAYER_NET`, `DEVLAYER_IGNORED`, `DEVLAYER_BIND`, `DEVLAYER_MASK`, `DEVLAYER_NO_DEFAULT_BINDS`, `DEVLAYER_AUDIO`, `DEVLAYER_CPUS`, `DEVLAYER_MEMORY` (later tasks rename or remove some of these). - -- [ ] **Step 1: Inventory.** Run `git grep -n -i sandbox -- ':!docs/superpowers'` and sort the hits into: user-visible (this task) or internal identifiers (Task 2). Internal means Rust type, function, module and variable names, plus the `[lib]` crate name and its `use sandbox::` imports. -- [ ] **Step 2: Apply the user-visible rename** using the table in the spec, Part 1. User-facing prose says "layer" where it said "sandbox" as a noun (e.g. "No layer by the name of 'x' found to delete."). The `/run/media/sandbox-coverage-testing` dir in the Makefile and in tests becomes `/run/media/devlayer-coverage-testing`. -- [ ] **Step 3: Build and check for leftovers.** - Run: `cargo build && git grep -n -i sandbox -- ':!docs/superpowers' ':!src' ':!tests'` - Expected: build OK; the grep shows no hits, or only historical text in a changelog if one exists. - Run: `git grep -n -E '"[^"]*[Ss]andbox[^"]*"' src` - Expected: hits only in identifiers or in `#[cfg(test)]` code that Task 2 renames, not in messages. -- [ ] **Step 4: Full test run.** - Run: `make test` - Expected: all non-ignored tests pass. -- [ ] **Step 5: Commit** — `git commit -am "Rename sandbox to devlayer (user-facing)"` - -### Task 2: Internal identifier rename pass - -**Files:** -- Rename: `src/sandbox/` → `src/layer/` (and the `mod sandbox` in `src/lib.rs`), `tests/fixtures/fixture_sandbox.rs` → `tests/fixtures/fixture_layer.rs` -- Modify: `Cargo.toml` `[lib] name = "devlayer"`; every `use sandbox::` → `use devlayer::` -- Modify: all of `src/**` and `tests/**` for the identifier renames below. - -**Interfaces:** -- Produces (later tasks use these names): - - `Sandbox` → `Layer`; `SandboxSettings` → `LayerSettings`; `SandboxLogger` → `DevlayerLogger`; `Lock::sandbox` → `Lock::layer` - - `resolve_sandbox_storage_dir` → `resolve_storage_dir`; `find_last_sandbox` → `find_last_layer`; `get_running_sandbox_pid` → `get_running_layer_pid`; `sandbox_name_completion` → `layer_name_completion`; other `sandbox_*` fns, variables and fields → `layer_*` - - `Config.sandbox_dir` → `Config.layer_dir`, and the `config` action key `sandbox_dir` → `layer_dir` - - Test fixture: `SandboxManager` → `LayerManager`; `#[fixture] fn sandbox()` → `#[fixture] fn layer()`; `get_sandbox_bin` → `get_devlayer_bin`; the field `sandbox_bin` → `devlayer_bin`; test params `mut sandbox: SandboxManager` → `mut layer: LayerManager` - -- [ ] **Step 1: Do the renames** (use `git mv` for files; IDE/LSP rename or careful `sed -i` with word boundaries for identifiers). -- [ ] **Step 2: Verify that no internal name is left.** - Run: `git grep -n -i sandbox -- ':!docs/superpowers'` - Expected: no hits. -- [ ] **Step 3: Build, lint, test.** - Run: `cargo build && cargo clippy && make test` - Expected: clean build, no clippy warnings, all tests pass. -- [ ] **Step 4: Commit** — `git commit -am "Rename internal sandbox identifiers to layer/devlayer"` - -### Task 3: `--join` replaces `--name` - -**Files:** -- Modify: `src/config/cli.rs` (remove `name`; add `join`), `src/config/structs.rs` (`PartialConfig.name` → `join`), `src/config/resolve.rs` (env `DEVLAYER_NAME` → `DEVLAYER_JOIN`, `merge_configs`, the mutual-exclusion check and its message) -- Modify: `tests/fixtures/fixture_layer.rs` (`--name=` → `--join=` in `dir`, `run_with_stdin`, `run_with_env`, `run_in_background`, and the `starts_with("--name")` checks), and every test that passes `--name` or sets `DEVLAYER_NAME` / `name =` in a config -- Modify: `README.adoc` (flag table / examples) -- Test: `tests/ai_test_join.rs` - -**Interfaces:** -- Produces: `Args.join: Option` (`#[arg(long, global = true, add = ArgValueCompleter::new(layer_name_completion), conflicts_with_all = &["new", "last"])]`); `PartialConfig.join: Option`; source key in `Config.sources` stays `"name"`, with the value `"cli --join"` / `"environment"` / ``. - -- [ ] **Step 1: Write failing tests** in `tests/ai_test_join.rs`: - - `ai_test_join_creates_then_reuses`: `--join= touch ` passes; `--join= test -f ` passes (same layer). - - `ai_test_name_flag_removed`: running with `--name=x true` fails (clap unknown argument). - - `ai_test_join_env_and_config`: `DEVLAYER_JOIN=` with `config name` prints ``; a temp config file `join = ""` passed via `--config` gives the same. - - `ai_test_join_conflicts_with_new_last`: `--join=x --new true` and `--join=x --last true` fail; `DEVLAYER_JOIN=x` plus `--new` fails with the message containing `"Cannot use --new or --last"`. -- [ ] **Step 2: Run them; expect failures.** `TEST=ai_test_join make quick-test` → FAIL (unknown `--join`). -- [ ] **Step 3: Implement** the rename in cli/structs/resolve and the fixture. -- [ ] **Step 4: Run.** `TEST=ai_test_join make quick-test` → PASS; then `make test` (the fixture change touches every test) → PASS. -- [ ] **Step 5: Commit** — `git commit -am "Replace --name with --join"` - -### Task 4: Host network by default - -**Files:** -- Modify: `src/config/resolve.rs` (`partial_config.net.unwrap_or(Network::Host)`), `src/config/cli.rs` (help text for `--net`: the default is host, use `--net=none` to disable) -- Modify: tests that assume no network by default (`tests/test_net.rs`, and any `config net` assertions expecting `none`) -- Modify: `README.adoc` -- Test: `tests/ai_test_net_default.rs` - -**Interfaces:** none new. - -- [ ] **Step 1: Write failing tests** in `tests/ai_test_net_default.rs`: `ai_test_net_defaults_to_host` (`--no-config config net` prints `host`, and `sources` shows `default`); `ai_test_net_none_disables` (`--net=none config net` prints `none`). -- [ ] **Step 2: Run** `TEST=ai_test_net_default make quick-test` → FAIL. -- [ ] **Step 3: Implement.** Update existing net tests so that tests which need no network pass `--net=none` explicitly. -- [ ] **Step 4: Run** `TEST=ai_test_net make quick-test` and `TEST=test_net make quick-test` → PASS. -- [ ] **Step 5: Commit** — `git commit -am "Default to host networking"` - -### Task 5: Audio becomes part of the default binds - -**Files:** -- Modify: `src/config/cli.rs` (remove `audio`), `src/config/structs.rs` (remove `audio` from `PartialConfig` and `Config`), `src/config/resolve.rs` (remove `DEVLAYER_AUDIO` env and merge; `get_audio_bind_mounts()` output is appended to the `get_default_bind_mounts` layer, only when `!no_default_binds`), `src/actions/config.rs` (drop the `audio` key), `src/layer/settings.rs` if it references audio -- Modify: `tests/ai_test_audio.rs` (rewrite for the new behavior), `README.adoc` -- Test: `tests/ai_test_audio.rs` - -**Interfaces:** none new. `--audio` and `audio=` no longer exist. - -- [ ] **Step 1: Rewrite tests** in `tests/ai_test_audio.rs`: `ai_test_audio_on_by_default` (with `XDG_RUNTIME_DIR` set to a temp dir containing a `pulse` dir, `config bind_mounts` lists `/pulse`); `ai_test_audio_off_with_no_default_binds` (same setup plus `--no-default-binds` → not listed); `ai_test_audio_flag_removed` (`--audio true` fails). -- [ ] **Step 2: Run** `TEST=ai_test_audio make quick-test` → FAIL. -- [ ] **Step 3: Implement.** -- [ ] **Step 4: Run** `TEST=ai_test_audio make quick-test` → PASS. -- [ ] **Step 5: Commit** — `git commit -am "Make audio binds part of the default binds"` - -### Task 6: Default LLM bind layer and `--no-default-llm-binds` - -**Files:** -- Modify: `src/config/resolve.rs`: add `const LLM_BIND_PATHS: &[&str]` and `fn get_llm_bind_mounts(home: &Path) -> Vec`; remove `.claude` / `.aider` / `.cursor` from `get_default_bind_mounts`; insert the LLM layer directly above the default layer, only when `!no_default_llm_binds` -- Modify: `src/config/cli.rs` (`no_default_llm_binds: bool`, help: "Disable default binds of well-known AI tool config (e.g. ~/.claude, ~/.codex)"), `src/config/structs.rs` (`PartialConfig.no_default_llm_binds: Option`, `Config.no_default_llm_binds: bool`), env `DEVLAYER_NO_DEFAULT_LLM_BINDS` (parse like `DEVLAYER_IGNORED`, returning an error on bad values rather than `expect`), `merge_configs`, `src/actions/config.rs` (key `no_default_llm_binds`) -- Modify: `README.adoc` (list the paths) -- Test: unit tests in `src/config/resolve.rs` `mod tests`; `tests/ai_test_llm_binds.rs` - -**Interfaces:** -- Produces: `get_llm_bind_mounts(home: &Path) -> Vec`. It returns absolute path strings, in `LLM_BIND_PATHS` order, for entries that exist under `home`. -- `LLM_BIND_PATHS` (relative to home, exact): `.claude`, `.claude.json`, `.codex`, `.pi`, `.gemini`, `.qwen`, `.aider`, `.cursor`, `.config/opencode`, `.local/share/opencode`, `.config/goose`, `.continue`, `.codeium`, `.config/github-copilot`, `.factory`, `.config/crush`, `.local/share/crush`. - -- [ ] **Step 1: Write failing unit tests:** - - `llm_binds_skip_missing_paths`: create a temp home with only `.codex/` and `.claude.json`; assert `get_llm_bind_mounts(home) == vec![home/.claude.json, home/.codex]`. - - `llm_binds_all_present`: create every entry; assert the length is 17 and the order matches `LLM_BIND_PATHS`. -- [ ] **Step 2: Write failing integration tests** in `tests/ai_test_llm_binds.rs`: `ai_test_llm_binds_default_on` (`config bind_mounts` contains `$HOME/.claude` when it exists; skip if it doesn't, the same way other tests skip on missing host features); `ai_test_no_default_llm_binds_flag`, `ai_test_no_default_llm_binds_env`, `ai_test_no_default_llm_binds_config` (each → not listed); `ai_test_llm_binds_independent_of_no_default_binds` (`--no-default-binds` still lists it). -- [ ] **Step 3: Run** `TEST=llm_binds make quick-test` → FAIL. -- [ ] **Step 4: Implement.** -- [ ] **Step 5: Run** `TEST=llm_binds make quick-test` and `TEST=bind make quick-test` → PASS (existing bind tests that expected `.claude` under the default binds must be updated to the new layer). -- [ ] **Step 6: Commit** — `git commit -am "Add default LLM tool binds and --no-default-llm-binds"` - -### Task 7: cwd bind by default, `--no-bind-cwd`, stored origin - -**Files:** -- Modify: `src/layer/settings.rs`: `LayerSettings` gains `#[serde(default)] created_in: Option` and `#[serde(default)] bind_cwd: Option`, filled from `Config` in `from_config` -- Modify: `src/config/structs.rs`: `Config` gains `created_in: PathBuf` and `bind_cwd: bool`; `PartialConfig.no_bind_cwd: Option` -- Modify: `src/config/cli.rs` (`no_bind_cwd: bool`, help: "Do not bind the current directory into the layer. By default it is bound read-write, so changes there go straight to the host."), env `DEVLAYER_NO_BIND_CWD`, `merge_configs`, `src/actions/config.rs` (keys `created_in`, `bind_cwd`) -- Modify: `src/config/resolve.rs`: after the layer name is known, call `resolve_origin` and push the cwd-bind layer between the LLM layer and the config layers -- Modify: `README.adoc`: document the cwd bind, `--no-bind-cwd`, and the known limitation from the spec (config files are discovered from the current cwd, so joining a layer from another project can load a different `.devlayer.toml`) -- Modify: `tests/fixtures/fixture_layer.rs`: add `pub bind_cwd: bool` (default `false`) and `set_bind_cwd(bool)`. When it is false, every run path (`run_with_env`, `run_with_stdin`, `run_in_background`, `dir`) adds `--no-bind-cwd`, unless `no_default_options` is set. This keeps existing overlay tests meaningful, because tests run from the repo root. -- Test: `tests/ai_test_cwd_bind.rs` - -**Interfaces:** -- Produces: `fn resolve_origin(layer_dir: &Path, cwd: &Path, no_bind_cwd: bool) -> Result<(PathBuf, bool)>`. It returns `(created_in, bind_cwd)`: - - if `layer_dir/settings.json` exists and has both fields → the stored values; - - otherwise → `(canonical cwd, !no_bind_cwd)`, and if `bind_cwd && cwd == "/"`, the error `"Refusing to bind / into the layer; run from a project directory or pass --no-bind-cwd"`. - - When `bind_cwd` is true, the cwd layer is `vec![created_in.display().to_string()]`. -- Task 8 consumes `LayerSettings.created_in`. - -- [ ] **Step 1: Write failing tests** in `tests/ai_test_cwd_bind.rs` (use `set_bind_cwd(true)` and a dir under `generated-test-data//`): - - `ai_test_cwd_bound_by_default`: `cd` into the temp dir, write a file inside the layer, then assert it exists on the host immediately (no accept) and `status /` doesn't list it. - - `ai_test_no_bind_cwd_flag_env_config`: with each of the three forms, the write stays in the layer (not on the host). - - `ai_test_refuse_root`: running from `/` without `--no-bind-cwd` fails with the message above; with `--no-bind-cwd` it passes. - - `ai_test_home_allowed`: running from `$HOME` with the cwd bind passes (`config bind_cwd` → `true`). - - `ai_test_cwd_bind_reenter_from_subdir`: start a background command in dir D (`run_in_background(["sleep","30"])`); from `D/sub`, `--join= config created_in` prints D, and `--join= true` passes (no "bind mounts changed"). - - `ai_test_restart_keeps_origin`: create in D, `stop`, re-run from `D/sub` → `config created_in` is still D. - - `ai_test_no_bind_cwd_persists`: create in D with `--no-bind-cwd`; re-enter without the flag → `config bind_cwd` is `false`. -- [ ] **Step 2: Run** `TEST=ai_test_cwd_bind make quick-test` → FAIL. -- [ ] **Step 3: Implement** settings fields, `resolve_origin`, the bind layer, the flag/env/config, and the fixture default. -- [ ] **Step 4: Run** `TEST=ai_test_cwd_bind make quick-test`, then `make test` (fixture change) → PASS. -- [ ] **Step 5: Commit** — `git commit -am "Bind the current directory by default; add --no-bind-cwd"` - -### Task 8: `--new` by default, directory-aware `--last`, per-action defaults - -**Files:** -- Modify: `src/config/resolve.rs`: replace the `if cli.new … else if cli.last …` block with `select_layer(...)`; rewrite `find_last_layer` to be directory-aware -- Modify: `src/config/cli.rs` (help for `--new`/`--last`/`--join` describing the defaults) -- Modify: `README.adoc` (usage section: a bare `devlayer`, `devlayer --last`, actions default to the last layer for this directory) -- Test: `tests/ai_test_layer_selection.rs`, plus updates to `tests/isolated_test_new_last.rs`, `tests/test_new_last.rs`, `tests/isolated_test_new.rs` - -**Interfaces:** -- Consumes: `LayerSettings::load_from_file`, `LayerSettings.created_in` (Task 7). -- Produces: - - `enum LayerSelection { New, Last, Join(String) }` - - `fn default_selection(action: Option<&Action>) -> LayerSelection` behaves like this: - - `None` → `New`; - - `Status`, `Diff`, `Accept`, `Reject` → `Last`; - - `Stop { all: false, patterns: None }` and `Delete { patterns: None|Some(empty) }` → `Last`; - - `Stop` with `all` or patterns, `Delete` with patterns, `List`, `Sync`, `Clean`, `Config` → `New` *without failing*. - - For `Config`, try `Last` first and fall back to `New` if nothing matches, so `devlayer config name` reports this directory's layer. - - Precedence: `--join`/`--new`/`--last` CLI > `DEVLAYER_JOIN` > config `join` > `default_selection`. - - `fn find_last_layer(storage_dir: &Path, cwd: &Path) -> Result`: for each ancestor `A` of canonical `cwd` (itself first, `/` last), collect the layers whose `settings.json` has `created_in == A`. At the first non-empty set, return the newest by dir creation time (`metadata.created()` falling back to `modified()`, as today). Layers without settings or without `created_in` are ignored. If nothing matches → `"No devlayer found for {cwd} or its parent directories; use --join or `devlayer list`"`. - - The existing `TEST_LAST_IS_EMPTY` coverage hook is kept. - -- [ ] **Step 1: Write failing tests** in `tests/ai_test_layer_selection.rs`. Use a fresh temp storage dir via `--storage-dir`/`DEVLAYER_STORAGE_DIR` so that layers from other tests don't interfere, and `no_default_options` where the fixture's `--join` must be suppressed; clean up created layers. - - `ai_test_bare_run_creates_new_each_time`: two bare `true` runs create two distinct `ephemeral_*` layers. - - `ai_test_last_nearest_ancestor_and_newest`: create L1 in D, L2 in D (later), L3 in `D/sub`. From D, `--last config name` → L2. From `D/sub/deeper` → L3. From the parent of D → error containing `"No devlayer found"`. - - `ai_test_actions_default_to_last`: create a layer in D that writes outside D; from D, `status /` without any selector shows that file, and `config name` equals that layer. - - `ai_test_stop_delete_default_to_last`: from D, bare `stop` stops D's latest layer; `delete -y` deletes it. - - `ai_test_list_clean_sync_no_layer_ok`: from a dir with no layers, `list`, `sync` and `clean -y` all pass and no new layer dir appears in storage. - - `ai_test_explicit_selector_wins`: from D, `--join= status` targets ``; `--new status` passes on an empty new layer. - - `ai_test_last_errors_without_layer`: `status` from a dir with no layers fails with `"No devlayer found"`. -- [ ] **Step 2: Run** `TEST=ai_test_layer_selection make quick-test` → FAIL. -- [ ] **Step 3: Implement** `LayerSelection`, `default_selection` and `find_last_layer`, wired through `resolve_config` (it already receives `cli.action`). -- [ ] **Step 4: Update** the existing `new_last` tests to the directory-aware semantics. Run `TEST=new_last make quick-test` and `TEST=ai_test_layer_selection make quick-test` → PASS. -- [ ] **Step 5: Commit** — `git commit -am "Default to a new layer; make --last directory-aware; actions default to --last"` - -### Task 9: Whole-layer `status`/`diff`; `accept`/`reject` need a pattern - -**Files:** -- Modify: `src/layer/changes/change_entries.rs` (`matching`: empty patterns → all entries; remove the cwd-prefix filter) -- Modify: `src/actions/accept.rs`, `src/actions/reject.rs`: at the start, if `patterns.is_empty()` → `Err("accept requires at least one pattern; use `devlayer accept /` to accept every change in the layer")` (the `reject` version says the same with "reject") -- Modify: `src/config/cli.rs` (help for Status/Diff/Accept/Reject), `README.adoc` -- Modify: existing tests that call bare `accept` (32), `reject` (1), `status` (18) or `diff` (17) and rely on the cwd scope. Change them to pass `.` (which matches the cwd subtree, as the old default did) — do not delete them. -- Test: `tests/ai_test_action_scope.rs` - -**Interfaces:** `ChangeEntries::matching(&self, cwd: &Path, patterns: &[String]) -> ChangeEntries` (unchanged signature). - -- [ ] **Step 1: Write failing tests** in `tests/ai_test_action_scope.rs`: - - `ai_test_status_default_whole_layer`: from `generated-test-data//a`, write a file in a sibling dir `../b/f`; bare `status` lists `b/f`. - - `ai_test_diff_default_whole_layer`: same, with `diff`. - - `ai_test_status_diff_patterns_still_filter`: `status ./nothing-here` lists nothing; `status ../b` lists it. - - `ai_test_accept_requires_pattern`: bare `accept` fails with `"requires at least one pattern"`, and the file still exists only in the layer (`status /` still lists it; the host path is missing). - - `ai_test_reject_requires_pattern`: same, for `reject`. -- [ ] **Step 2: Run** `TEST=ai_test_action_scope make quick-test` → FAIL. -- [ ] **Step 3: Implement** and update the existing bare-action tests. -- [ ] **Step 4: Full run.** `make test && make coverage-report && make coverage-check && make ready-for-commit-tests` → all pass, coverage 100%. -- [ ] **Step 5: Commit** — `git commit -am "Whole-layer status/diff by default; accept/reject require a pattern"` diff --git a/docs/superpowers/plans/2026-11-13-layer-auto-shutdown.md b/docs/superpowers/plans/2026-11-13-layer-auto-shutdown.md deleted file mode 100644 index 5650f5e..0000000 --- a/docs/superpowers/plans/2026-11-13-layer-auto-shutdown.md +++ /dev/null @@ -1,209 +0,0 @@ -# Layer Auto-Shutdown Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** A layer reaps its orphans and shuts itself down (unmount, cgroup, pid file) once nothing is running in it, keeping its changes. - -**Architecture:** The `devlayer` process that starts a layer forks a root supervisor that `clone3`s PID 1 and waits on it. PID 1 reaps orphans and exits when its `/proc` shows only itself. When PID 1 exits for any reason, the supervisor does `stop`'s cleanup under the layer lock. - -**Tech Stack:** Rust, nix, libc, clone3, cgroup v2, rstest integration tests. - -**Spec:** docs/superpowers/specs/2026-11-13-layer-auto-shutdown-design.md - -## Global Constraints - -- PID 1 idle check every 1 second; first check 1 second after PID 1 reports ready. -- PID 1 exits with status 0 when idle; the existing SIGTERM handler stays. -- Shutdown never kills a process; a layer with any process besides PID 1 stays up. -- Shutdown keeps the layer's data; it never deletes. -- No retry/race handling beyond taking the layer lock during cleanup. -- The supervisor runs as root (all uids/gids 0), ignores SIGHUP and SIGINT, has no output after PID 1 is ready, and ignores its own cleanup errors. -- The supervisor is forked before the caller joins the layer's cgroup and must never be in it (it would keep the cgroup busy). -- Coverage builds: every instrumented process that exits writes its profraw (see Task 1 step 3). -- New tests go in `tests/ai_test_*.rs`; layer names given in tests start with `devlayer-coverage`. - -## Review Focus - -1. A layer is restarted (`--join`) before the old supervisor runs its cleanup: the old supervisor must not unmount or remove the pid file of the new instance. -2. `devlayer delete` on a running layer: the supervisor wakes after the lock file is gone and must exit without recreating `.lock` (the layer must not reappear in `list`). -3. A layer with `--cpus`/`--memory`: the cgroup is removed on shutdown, and the supervisor isn't in the cgroup (rmdir would fail with EBUSY). -4. The user's terminal goes away (SIGHUP to the session) while a layer runs: the supervisor survives and still cleans up. -5. Nested layers (devlayer inside a layer): auto-shutdown and cleanup work the same. - ---- - -### Task 1: Supervisor process - -**Files:** -- Modify: `src/layer/get_or_create.rs` (`start_layer`, `get_or_create` error path) -- Create: `src/layer/supervisor.rs` (supervisor wait + cleanup), register in `src/layer/mod.rs` -- Modify: `src/util/lock_layer.rs` (open-existing variant) -- Test: `tests/ai_test_auto_shutdown.rs` - -**Interfaces:** -- Produces: `Lock::existing_layer(layers_storage_dir: &Path, layer_name: &str) -> Result>>` — `Ok(None)` when the lock file doesn't exist; never creates it. -- Produces: `fn supervise(layer: &Layer, pid1: Pid, own_cgroup: bool) -> !` in `src/layer/supervisor.rs`: waits on PID 1, runs cleanup, exits 0. -- Produces (tests): helpers in `tests/ai_test_auto_shutdown.rs`: `fn pid_file(layer: &LayerManager) -> Result` (`layer.dir()` + `.pid`), `fn layer_pid(layer: &LayerManager) -> Option`, `fn has_mounts(layer: &LayerManager) -> Result` (any `/proc/self/mountinfo` mount point under `layer.dir()`), `fn wait_until(timeout: Duration, f: impl FnMut() -> bool) -> bool` (polls every 50 ms), `fn ppid_of(pid: i32) -> Result` (`PPid:` line of `/proc//status`). - -- [ ] **Step 1: Write the failing tests** - -```rust -/// When PID 1 dies, the supervisor unmounts and removes the pid file -#[rstest] -fn ai_test_supervisor_cleans_up_after_pid1_exit(mut layer: LayerManager) -> Result<()> { - layer.run(&["true"])?; - let pid = layer_pid(&layer).expect("layer should be running"); - assert!(has_mounts(&layer)?); - Command::new("sudo").args(["kill", "-KILL", &pid.to_string()]).status()?; - assert!(wait_until(Duration::from_secs(5), || !pid_file(&layer).unwrap().exists())); - assert!(wait_until(Duration::from_secs(5), || !has_mounts(&layer).unwrap())); - Ok(()) -} - -/// The user can't signal the supervisor -#[rstest] -fn ai_test_supervisor_not_killable_by_user(mut layer: LayerManager) -> Result<()> { - layer.run(&["true"])?; - let pid = layer_pid(&layer).expect("layer should be running"); - let ppid = ppid_of(pid)?; // PPid: line of /proc//status - let status = Command::new("kill").args(["-TERM", &ppid.to_string()]).status()?; - assert!(!status.success()); - Ok(()) -} - -/// After an explicit stop, the supervisor's cleanup is harmless: the layer -/// restarts and deletes normally, and delete doesn't leave a lock file behind -#[rstest] -fn ai_test_supervisor_after_stop_and_delete(mut layer: LayerManager) -> Result<()> { - layer.run(&["true"])?; - layer.run(&["stop"])?; - layer.run(&["true"])?; - let lock = layer.dir()?.with_extension("lock"); - layer.run(&["delete", "-y"])?; - std::thread::sleep(Duration::from_secs(2)); - assert!(!lock.exists()); - layer.run(&["list"])?; - assert!(!layer.last_stdout.contains(&layer.name)); - Ok(()) -} -``` - -Note for the first test: until Task 2, PID 1 doesn't exit by itself, so the layer stays running between `true` and the kill. - -- [ ] **Step 2: Run tests to verify they fail** - -Run: `TEST=ai_test_supervisor make quick-test` (or `cargo test --profile coverage --features coverage --test ai_test_auto_shutdown` with the coverage env from the Makefile) -Expected: `ai_test_supervisor_cleans_up_after_pid1_exit` FAILS (pid file and mounts remain); `ai_test_supervisor_not_killable_by_user` FAILS (PID 1's parent is the caller, already exited, so PPid is the host init or the kill hits a user-owned process — either way not the intended supervisor); `ai_test_supervisor_after_stop_and_delete` may already pass — keep it as a guard. - -- [ ] **Step 3: Implement** - -In `start_layer`: create the ready pipe, then `fork()`. The caller (parent) drops the write end, reads the ready byte as today, then reads PID 1's pid from the pid file (the supervisor writes it before PID 1 can report ready), and returns `Pid` or the existing `"Failed to setup layer"` error. The supervisor (child): -- `setsid()`; `setresuid(0,0,0)`/`setresgid(0,0,0)`; ignore SIGHUP and SIGINT; close the inherited layer-lock fd. -- `clone3` PID 1 with the existing args plus `exit_signal: libc::SIGCHLD as u64`; write the pid file; keep stdio open. -- Wait for PID 1's ready/failed byte on a second pipe from PID 1 (or forward the existing one); forward it to the caller; on failure exit 1. On success close stdin/stdout/stderr, then `supervise(...)`. - -`supervise`: `waitpid(pid1)`; then `Lock::existing_layer` — `None` → exit; if the pid file names a different PID that `get_running_layer_pid` reports running → exit; otherwise remove the pid file if it names `pid1`, remove `layer.cgroup_path()` with `remove_cgroup` only if `own_cgroup` and the path exists, `layer.unmount()`, exit 0 via `std::process::exit` (the profile runtime writes the supervisor's profraw at exit; with `LLVM_PROFILE_FILE` absolute this lands in `coverage/profraw/`; confirm a supervisor profraw appears after a test run, and if not, set the filename explicitly as `exec.rs` does). - -`own_cgroup` is `cgroup.is_some()` from `create_cgroup_or_share_outer` in `get_or_create`, passed into `start_layer`. - -- [ ] **Step 4: Run tests to verify they pass** - -Run: same as step 2, plus `tests/isolated_test_pivot_root_failure.rs` and `tests/test_layer_failures.rs` (setup errors still reach stderr). -Expected: PASS. - -- [ ] **Step 5: Commit** - -```bash -git add src tests/ai_test_auto_shutdown.rs -git commit -m "Supervise layer PID 1 and clean up when it exits" -``` - -### Task 2: PID 1 reaps orphans and exits when idle - -**Files:** -- Modify: `src/layer/get_or_create.rs` (end of `setup_layer_and_sleep_forever`; rename to `setup_layer_and_wait`) -- Modify: `tests/fixtures/fixture_layer.rs` (keep-alive helper) -- Modify: existing tests that need a layer to stay running between commands (found by running the suite; likely candidates: `ai_test_resource_limits.rs`, `ai_test_layer_settings.rs`, `test_list.rs`, `isolated_test_clean_running.rs`, `isolated_test_stop_*.rs`, `test_mount_unmount_kill.rs`, `ai_test_delete.rs`) -- Modify: `README.adoc` (layer lifetime: auto-shutdown, `stop` still available) -- Test: `tests/ai_test_auto_shutdown.rs` - -**Interfaces:** -- Consumes: Task 1's supervisor and test helpers. -- Produces: `LayerManager::hold(&mut self) -> Result<()>` — runs `sh -c "sleep 3600 >/dev/null 2>&1 &"` in the layer so it stays running until `stop`. - -- [ ] **Step 1: Write the failing tests** - -```rust -#[rstest] -fn ai_test_idle_layer_shuts_down(mut layer: LayerManager) -> Result<()> { - layer.run(&["touch", "/tmp/devlayer-coverage-idle-file"])?; - assert!(wait_until(Duration::from_secs(5), || !pid_file(&layer).unwrap().exists())); - assert!(!has_mounts(&layer)?); - layer.run(&["list"])?; // shows the layer as stopped - layer.run(&["status", "/tmp"])?; // changes survive - assert!(layer.last_stdout.contains("devlayer-coverage-idle-file")); - layer.run(&["true"])?; // rejoining restarts it - assert!(layer_pid(&layer).is_some()); - Ok(()) -} - -#[rstest] -fn ai_test_background_process_keeps_layer_up(mut layer: LayerManager) -> Result<()> { - layer.hold()?; - std::thread::sleep(Duration::from_secs(3)); - assert!(layer_pid(&layer).is_some()); - layer.run(&["pkill", "-f", "sleep 3600"])?; - assert!(wait_until(Duration::from_secs(5), || !pid_file(&layer).unwrap().exists())); - Ok(()) -} - -#[rstest] -fn ai_test_orphans_reaped(mut layer: LayerManager) -> Result<()> { - layer.hold()?; - // The shell exits right away, orphaning a short-lived child - layer.run(&["sh", "-c", "(sleep 0.2 &)"])?; - std::thread::sleep(Duration::from_secs(2)); - layer.run(&["sh", "-c", "grep -l '^State:.*Z' /proc/[0-9]*/status || true"])?; - assert_eq!(layer.last_stdout.trim(), ""); - Ok(()) -} - -#[rstest] -fn ai_test_idle_shutdown_removes_cgroup(mut layer: LayerManager) -> Result<()> { - // Skip like ai_test_resource_limits.rs's limits_available when cgroups - // can't be managed here - if !layer.pass(&["--cpus=1", "true"]) { return Ok(()); } - let cgroup = PathBuf::from("/sys/fs/cgroup/devlayer") - .join(format!("{}-{}", nix::unistd::getuid(), layer.name)); - assert!(wait_until(Duration::from_secs(5), || !cgroup.exists())); - Ok(()) -} -``` - -- [ ] **Step 2: Run tests to verify they fail** - -Run: `cargo test ... --test ai_test_auto_shutdown` (coverage env) -Expected: `ai_test_idle_layer_shuts_down`, `ai_test_idle_shutdown_removes_cgroup` FAIL (layer stays up); `ai_test_orphans_reaped` FAILS (a `Z` process is listed); `ai_test_background_process_keeps_layer_up` fails on its last assertion. - -- [ ] **Step 3: Implement** - -Replace PID 1's sleep loop: sleep 1 s, reap with `waitpid(Pid::from_raw(-1), Some(WaitPidFlag::WNOHANG))` until `StillAlive`/`ECHILD`, then if `/proc`'s numeric entries are exactly `["1"]`, dump coverage (as the current loop does) and `exit(0)`. Keep the periodic profraw dump. Add `LayerManager::hold`. - -- [ ] **Step 4: Run tests to verify they pass** - -Run: same as step 2. -Expected: PASS. - -- [ ] **Step 5: Fix existing tests that relied on a layer staying up** - -Run the full suite (`make test` on a host; nested, compare per-file failures against a baseline run of the branch tip before this task). For each new failure caused by the layer shutting down between commands, call `layer.hold()?` after the layer's first command. Don't change any assertion. -Expected: no failures beyond the baseline. - -- [ ] **Step 6: Document and commit** - -README: in the section on layer lifetime/`stop`, say a layer stops by itself once nothing is running in it, keeps its changes, and restarts when a command runs in it again; `devlayer stop` stops it right away and kills what's running. - -```bash -git add src tests README.adoc -git commit -m "Reap orphans in layers and shut layers down when idle" -``` diff --git a/docs/superpowers/specs/2026-11-13-devlayer-rename-and-defaults-design.md b/docs/superpowers/specs/2026-11-13-devlayer-rename-and-defaults-design.md deleted file mode 100644 index 314d4ad..0000000 --- a/docs/superpowers/specs/2026-11-13-devlayer-rename-and-defaults-design.md +++ /dev/null @@ -1,245 +0,0 @@ -# Rename to devlayer and new defaults: design - -## Intent - -The tool is used mainly to run AI coding agents (Claude Code, Codex, pi, ...) -against a project. Today that takes a long config file and several flags: -`--new`, `--bind=.`, `--net=host`, `--audio`, plus a list of agent config -directories. The project is renamed to **devlayer**, and those choices become -the defaults. A bare `devlayer` in a project directory starts a fresh layer. -In that layer the project directory is live on the host, the network and -audio work, and the agent's own config/state is shared with the host. Changes -outside the project directory stay in the layer for review -(`status`/`diff`/`accept`/`reject`). - -## Goals - -1. Clean rename from `sandbox` to `devlayer` everywhere. -2. New defaults: a new layer per run, the current directory bound, host - network, audio on, and well-known LLM tool paths bound. -3. `--join ` replaces `--name`. -4. `--last` becomes directory-aware, and the actions that operate on one - layer default to it. - -## Non-goals - -- No fallback, compatibility or migration for `sandbox` names, paths, env - vars, config files or existing `~/.sandboxes` data. It is a clean - switchover. -- No automatic cleanup of the growing number of `ephemeral_*` layers. That - comes in a later iteration, and `devlayer clean` stays as it is. -- No GitHub repository rename or release work. - -## Anti-goals - -- Never run with `/` bound live by the default directory bind. -- Re-entering an existing layer from a subdirectory must not fail with - "bind mounts changed" just because the current directory differs. - -## Part 1: Rename (clean switchover) - -| Old | New | -|---|---| -| binary / crate / lib name `sandbox` | `devlayer` | -| `~/.sandboxes/`, fallback `/tmp/sandboxes-` | `~/.devlayer/`, fallback `/tmp/devlayer-` | -| `SANDBOX_*` env vars | `DEVLAYER_*` | -| `.sandbox.conf` / `.sandbox.toml` (cwd and parents) | `.devlayer.conf` / `.devlayer.toml` | -| `~/.config/sandbox/config.(conf\|toml)` | `~/.config/devlayer/config.(conf\|toml)` | -| `/etc/sandbox.(conf\|toml)` | `/etc/devlayer.(conf\|toml)` | -| test layer prefixes `sandbox-coverage-*`, `sandbox-bind-empty-*` | `devlayer-coverage-*`, `devlayer-bind-empty-*` | -| README, CONTRIBUTING, CLAUDE.md, RELEASE_CHECKLIST, Makefile, packaging, vm-testing, cspell, completions, user-facing messages | updated to "devlayer" / "layer" | - -User-visible text (help, errors, output, docs) must say devlayer. - -Internal Rust identifiers and modules (`Sandbox`, `SandboxSettings`, -`src/sandbox/`, `SandboxLogger`, `sandbox_*` functions and variables, test -fixture names such as `fixture_sandbox.rs`) are **also renamed** -(Sandbox → Layer / devlayer). This is done as a **separate pass**, in its -own commit(s), apart from the user-facing rename. - -Both rename passes land with no behavior change, before Part 2. - -## Part 2: New behavior - -### Choosing which layer to use - -The flags `--new`, `--last` and `--join ` are mutually exclusive (as -today). - -- **`--join `** works exactly like today's `--name`: it uses that - layer, and creates it if it does not exist. `--name` is removed. - - *(my call)* The config-file key `name` becomes `join`, and the env var - becomes `DEVLAYER_JOIN`. Either one acts like `--join` and overrides the - defaults below. Combining it with `--new`/`--last` is an error, as - today. -- **`--new`** creates a layer with an auto-generated `ephemeral_` - name (naming unchanged, so `clean` keeps working). -- **`--last`** is directory-aware: - - Each layer records the canonical directory it was created in, in its - `settings.json` (new field, e.g. `created_in`). The value is written when - the layer is created and kept unchanged when the layer is restarted. - - Resolution starts at the canonical cwd and walks up through its - ancestors to `/`. At the first directory that is the `created_in` of one - or more layers, it picks the newest of those (by creation time). Note: - `/` counts too, if a layer was created there with `--no-bind-cwd`. - - If no layer matches, it fails with an error that names the directory and - suggests `--join ` or `devlayer list`. - -**Defaults when no selection flag, `join` config or env var is given:** - -| Invocation | Default | -|---|---| -| no action (run a command or a shell) | `--new` | -| `status`, `diff`, `accept`, `reject` | `--last` | -| `stop` / `delete` with no patterns and no `--all` | `--last` | -| `list`, `sync`, `clean`, `config` | need no target. They must not fail or create anything when no layer exists for the cwd. | - -An explicit flag always wins, for example `devlayer --join foo status` or -`devlayer --last bash`. - -### Default scope of `status` / `diff` / `accept` / `reject` - -Today these actions, with no patterns, only consider changes under the cwd -(`ChangeEntries::matching` in `src/sandbox/changes/change_entries.rs`). The -cwd is now bound live, so its changes never reach the layer, and that default -would always be empty. - -- **`status` and `diff` with no patterns cover the whole layer** (the same as - `status /` today). Patterns work as they do today. -- **`accept` and `reject` require at least one pattern.** With no patterns - they fail with an error that suggests `devlayer accept /` (or `reject /`) - for everything. This protects against an accidental system-wide accept. - Pattern behavior is unchanged. - -Implementation note: today the name is resolved inside `resolve_config` -before `main` dispatches the action. The default now depends on the action, -so resolution has to know the action (or be deferred until it is known). - -### Directory bind (`--bind=.` by default) - -- By default the canonical current directory is bind-mounted read-write at - the same path. -- New flag **`--no-bind-cwd`**, with config key `no_bind_cwd` and env var - `DEVLAYER_NO_BIND_CWD`, turns it off. It is independent of - `--no-default-binds`. -- **Refuse to start** a new layer when the directory bind is on and the - canonical cwd is `/`. The error says to use `--no-bind-cwd`. `$HOME` is - allowed. -- **Re-entering an existing layer** (`--join` / `--last`, running or - stopped) *(my call)*: the layer's directory bind is fixed when the layer is - created. `settings.json` records both `created_in` and whether the - directory bind was on (e.g. `bind_cwd: bool`). On re-entry and on restart, - both values come from `settings.json`, and the current cwd and the - `--no-bind-cwd` flag are ignored for this bind. Results: - - Entering from a subdirectory or another directory does not change the - layer's bind set, so it does not trip the "bind mounts changed" check in - `SandboxSettings::validate_against_config`. - - A layer created at `/` with `--no-bind-cwd` never binds `/` later. - - Restarting a stopped layer (which rewrites `settings.json` in - `mount_overlays.rs`) must keep `created_in` and `bind_cwd`. - - Other binds (system, audio, LLM, config/env/CLI) are recomputed and - validated as they are today. -- *(my call, known limitation)* Config files are still found by walking up - from the current cwd, not from `created_in`. So `devlayer --join proj` - run from a different project can load a different `.devlayer.toml` and - fail validation. This is today's behavior with `--name`. Document it in - the README rather than restructure config loading. -- Precedence: the directory bind is a layer above the default and LLM binds - and below config/env/CLI binds. Explicit binds or masks on the same target - therefore override it. - -### Network - -- The default for `net` becomes `host`. `--net=none` (or `net="none"` in - config) disables networking. -- Consequence (intended, noted for the docs): the D-Bus/systemd default - binds that today depend on host networking are now present by default. - -### Audio - -- Audio binds (`/dev/snd`, `$XDG_RUNTIME_DIR/pipewire-0`, - `$XDG_RUNTIME_DIR/pulse`) become part of the default binds, so - `--no-default-binds` disables them. -- *(my call)* The `--audio` flag, the `audio` config key and - `DEVLAYER_AUDIO` are removed. - -### Default LLM binds - -- A new bind layer of well-known AI-tool paths. It is on by default and - disabled with **`--no-default-llm-binds`** (config key - `no_default_llm_binds`, env var `DEVLAYER_NO_DEFAULT_LLM_BINDS`). It is - independent of `--no-default-binds`. -- Each path is bound read-write at the same path, and **only if it exists** - on the host: - - `~/.claude`, `~/.claude.json` - - `~/.codex` - - `~/.pi` - - `~/.gemini` - - `~/.qwen` - - `~/.aider` *(moved here from the system defaults)* - - `~/.cursor` *(moved here from the system defaults)* - - `~/.config/opencode`, `~/.local/share/opencode` - - `~/.config/goose` - - `~/.continue` - - `~/.codeium` - - `~/.config/github-copilot` - - `~/.factory` - - `~/.config/crush`, `~/.local/share/crush` -- Personal binds (ssh keys, gh tokens, docker.sock, herdr) are **not** - defaults. They stay in the user's config. - -### Bind layer order (lowest to highest precedence) - -1. Default system binds (`/dev/fuse`, D-Bus/systemd when net=host) plus - audio. Skipped with `--no-default-binds`. -2. Default LLM binds. Skipped with `--no-default-llm-binds`. -3. Directory bind. Skipped with `--no-bind-cwd`. -4. Config file layers (as today). -5. Environment layer. -6. CLI layer. - -## Approaches considered - -1. **Rename first, then behavior changes, on this branch (chosen).** Each - diff is easy to review. The 116-file rename does not hide the logic - changes. -2. One combined change: less churn in test files, but much harder to - review and to bisect. -3. Keep the `sandbox` name with a `devlayer` alias, or migrate old data: - ruled out, because the user wants a clean switchover. - -For `created_in`: store it in the existing per-layer `settings.json` -(chosen), instead of a separate index file in the storage dir. An index -could get out of sync with layers that are deleted by hand, and -`settings.json` already exists per layer. - -## Testing - -- Follow CLAUDE.md: new tests go in `tests/ai_test_*.rs`. Explicit layer - names use the `devlayer-coverage` prefix. Keep line coverage at the - project's required level (`make coverage-check`). -- Existing tests that rely on the old defaults (no network, default name - `sandbox`, `--name`, `--audio`, `.claude`/`.aider`/`.cursor` in the system - defaults, cwd-scoped `status`/`diff`/`accept`/`reject` with no patterns) - must be updated to the new behavior. Do not delete them. -- New coverage is needed for: directory-aware `--last` (exact dir, ancestor - match, nearest ancestor wins, newest wins within a dir, no match → - error); defaults per action; `--no-bind-cwd`; refusing `/`; re-entering - from a subdirectory keeps the original directory bind; LLM binds only - when the path exists, and disabled by the flag; audio disabled by - `--no-default-binds`; `--join` create-or-use; `join` config/env; - whole-layer `status`/`diff` with no patterns; `accept`/`reject` with no - patterns → error; re-entering or restarting keeps `created_in`/`bind_cwd`. - -## Left to the builder - -- Exact wording of help text and errors. -- How to restructure name resolution so it knows the action. - -## Decided after review - -- Internal identifiers and modules are renamed, in a separate pass (see - Part 1). -- Test helpers (the fixture / layer manager in `tests/fixtures/`) are - updated for `--join` and the new defaults. diff --git a/docs/superpowers/specs/2026-11-13-layer-auto-shutdown-design.md b/docs/superpowers/specs/2026-11-13-layer-auto-shutdown-design.md deleted file mode 100644 index b2127e9..0000000 --- a/docs/superpowers/specs/2026-11-13-layer-auto-shutdown-design.md +++ /dev/null @@ -1,189 +0,0 @@ -# Layer auto-shutdown design - -## Intent - -Every bare `devlayer ` now creates a new layer, and every layer keeps -running (PID 1, overlay mounts, cgroup, pid file) until `devlayer stop` or a -reboot. Layers pile up. Separately, a layer's PID 1 never reaps processes, so -anything orphaned inside a layer (a background job whose shell exited) stays -`` until the layer is stopped. - -A layer should shut itself down once nothing is running in it any more, and -clean up after itself, so idle layers don't accumulate. - -## Goals - -- PID 1 reaps orphaned processes in its layer, so there are no zombies. -- When the last process in a layer exits (anything other than PID 1, not just - `devlayer` commands), the layer shuts down within about a second. -- Shutting down does what `devlayer stop` does today: overlay and bind mounts - are unmounted, the layer's cgroup (if it has one) is removed, and the pid - file is removed. -- The layer's changes are kept. `status`, `diff`, `accept`, `reject` work as - they do on any stopped layer, and running a command in it again - (`--last`, `--join`) restarts it as today. - -## Non-goals - -- Deleting layers (auto-clean of stopped layers) — a later iteration. -- An opt-out flag to keep idle layers running. -- Handling a command that joins a layer at the instant it shuts down. The - user ruled this out of scope: it is not a concern in practice. Taking the - existing layer lock during cleanup is enough; no retry logic. - -## Anti-goals - -- Killing anything still running. A layer with a background process left in - it (a dev server started with `&`, a tmux server, a daemon) stays up until - that process exits or the user runs `devlayer stop`. - -## Approaches - -1. **Host-side supervisor + PID 1 idle check (chosen).** A small root process - stays on the host as PID 1's parent. PID 1 reaps orphans and checks its own - `/proc` once a second; when only PID 1 is left it exits. The supervisor sees - that exit immediately (it is the parent) and does the cleanup. Covers - orphans that outlive every command, and cleans up even if the user's - terminal is killed. Cost: one idle process per running layer, up to ~1s - delay. -2. **The waiting `devlayer` command cleans up.** The `devlayer` process that - waits on the user's command keeps root and stops the layer when its command - exits and nothing else is running. Rejected: a background process that - outlives every command leaves the layer up forever (violates the goal), no - cleanup if that process is killed, and it leaves a root process inside the - layer's mount namespace. -3. **Lazy cleanup.** PID 1 exits when idle; the next `devlayer` invocation - unmounts layers whose PID 1 is gone. Rejected: mounts and cgroups linger - until the user happens to run `devlayer` again. - -## Design - -### Process structure - -Today `start_layer` (src/layer/get_or_create.rs) is called by the user's -`devlayer` process (call it the caller). It `clone3`s PID 1, writes the pid -file, waits on a pipe for PID 1 to report it is ready, and then goes on to -`exec` the user's command and wait on it. PID 1's parent is the caller, and -once the caller exits PID 1 is reparented to the host's init. - -New structure: - -- The caller forks a **supervisor** before `clone3`. The supervisor calls - `setsid` and does the `clone3` of PID 1, so it is PID 1's parent. -- *(Builder-check call)* The supervisor keeps stdin/stdout/stderr open until - PID 1 has reported ready or failed, so PID 1's setup errors still reach the - terminal (`tests/isolated_test_pivot_root_failure.rs` relies on that). Then - it closes them, as PID 1 does today, so the test harness and terminals - don't wait on it. -- *(Builder-check call)* `clone3` must set `exit_signal` to `SIGCHLD`. - `Clone3Args` leaves it at 0 today, and a plain `waitpid` never reports the - exit of a child that doesn't signal its parent. -- *(Builder-check call)* The supervisor sets all its uids and gids to root - (as PID 1 already does) so the user can't signal it, and ignores SIGHUP and - SIGINT. If it died, PID 1 would still exit when idle but the mounts would be - left behind. -- The caller still learns PID 1's pid and whether setup succeeded, and still - returns an error exactly as today when setup fails. How the pid and the - ready/failed byte get back to the caller (e.g. the existing pipe plus the - pid file, or a second pipe) is left to the builder. -- If setup fails, the supervisor exits without leaving anything running; the - caller's existing error path (removing the cgroup) still runs. -- The supervisor stays root, stays in the host mount namespace, and does - nothing but `waitpid` on PID 1. - -### PID 1 - -Replace the sleep-forever loop at the end of `setup_layer_and_sleep_forever`: - -- Every 1 second: - 1. Reap every exited child with `waitpid(-1, WNOHANG)` until none are left. - 2. List the numeric entries of `/proc` (PID 1's own procfs, which only shows - this layer's processes). If the only entry is `1`, exit with status 0. -- The first check happens 1 second after PID 1 reports ready. That gives the - caller time to join with the user's command; no other startup handling. -- The existing SIGTERM handler (exit with the signal number) stays. -- Coverage: keep dumping profraw as the current loop does. - -### Supervisor cleanup - -When `waitpid` reports PID 1 has exited (idle exit, `devlayer stop`, or -anything else): - -1. Take the layer lock. *(Builder-check call)* Open the existing lock file - without creating it: `Lock::layer` creates a missing one, and after - `devlayer delete` that would bring the deleted layer back in `list`. If the - lock file is gone, the layer was deleted (which already stopped and - unmounted it); just exit. -2. Remove the pid file if it still names this PID 1 (a restarted layer has - written a new pid; leave it alone). -3. Remove the layer's cgroup, but only if this layer created its own (the - `create_cgroup_or_share_outer` result was `Some`) and it still exists: - `Layer::cgroup_path()`. `remove_cgroup` retries for 5 seconds on any - error, including "not found", so check first. Note that - `running_cgroup()` can't be used here because it reads PID 1's - `/proc//cgroup`, which is gone. -4. Unmount the layer's mounts (`Layer::unmount`). -5. Exit. - -Every step must be harmless when `devlayer stop` already did it (the common -case for an explicit stop): no mounts, no pid file, no cgroup. The supervisor -has no stdout/stderr, so failures are ignored rather than reported. - -Skip steps 2–4 when the layer was restarted in the meantime: if, after taking -the lock, the pid file names a different, running PID 1, the supervisor must -not unmount that layer's mounts; it just exits. - -### What doesn't change - -- `devlayer stop` keeps its current behavior; the supervisor's cleanup after it - is a no-op. -- `get_running_layer_pid` and `list` keep using the pid file; a shut-down layer - shows as stopped. -- Nested layers work the same way (the supervisor runs inside the outer layer). - -## Constraints - -- The binary is setuid root; the supervisor runs as root on the host. It must - not run any user-supplied code or read user-controlled paths beyond what - `stop` already does. -- `fork` inherits the caller's flock fd for the layer lock. The caller's - `Lock` drop does an explicit unlock today, so the inherited fd doesn't keep - it locked, but the builder should close it in the supervisor anyway. -- Coverage instrumentation: the supervisor is a long-lived instrumented - process. Like PID 1 and the exec waiter, it must write its profraw to - `coverage/profraw/` via `__llvm_profile_set_filename` with a path that works - from its cwd (or an absolute one), and dump before exiting. -- Project rule: very high test coverage; new tests go in `tests/ai_test_*.rs`. - -## Testing - -New tests (in a new `tests/ai_test_auto_shutdown.rs`): - -- After `devlayer true`, the layer stops within a few seconds: the pid file - goes away, `list` shows it stopped, and no mounts under the layer dir remain. - Poll with a timeout rather than sleeping a fixed time. -- A layer with a background process left running (`sh -c 'sleep 30 &'`) is - still running after a few seconds; it stops once that process is killed. -- An orphan inside a running layer is reaped (no `Z` state process in the - layer). -- Changes survive shutdown: write a file, wait for shutdown, `status` shows it. -- With `--cpus`/`--memory`, the layer's cgroup is removed on shutdown. -- Rejoining a shut-down layer with `--join` restarts it. -- `devlayer stop` still works and the supervisor's cleanup afterwards doesn't - break anything (layer can be restarted and deleted). - -Existing tests that assume a layer stays running between two `devlayer` -invocations (e.g. limits tests that look up the cgroup after `true`, tests of -"running layer with different settings" errors, `list` running checks) will -become timing-dependent. They must keep the layer up explicitly, for example -with a test-fixture helper that starts a background `sleep` in the layer, rather -than relying on running within the 1-second window. - -## Left to the builder - -- How the supervisor passes PID 1's pid and the ready/failed status back to - the caller. -- The exact fixture helper for keeping a layer alive in tests, and which - existing tests need it (find them by running the suite). -- Whether to name the supervisor process (e.g. via `prctl(PR_SET_NAME)`) for - readability in `ps`. From dd68c4732026706721d8b0fec48d1d9acc58f0d4 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Sat, 14 Nov 2026 16:27:13 -0500 Subject: [PATCH 21/32] Give concurrent new launches their own layers, keep layers up while a command is starting in them --- src/config/resolve.rs | 41 +++++++-------- src/config/structs.rs | 3 ++ src/layer/exec.rs | 20 ++++++-- src/layer/get_or_create.rs | 90 ++++++++++++++++++++++++--------- src/layer/supervisor.rs | 54 +++++++++++++++----- src/main.rs | 4 +- src/util/lock_layer.rs | 64 ++++++++++++++++------- tests/ai_test_auto_shutdown.rs | 41 +++++++++++++++ tests/ai_test_concurrent_new.rs | 69 +++++++++++++++++++++++++ tests/ai_test_layer_settings.rs | 1 + 10 files changed, 304 insertions(+), 83 deletions(-) create mode 100644 tests/ai_test_concurrent_new.rs diff --git a/src/config/resolve.rs b/src/config/resolve.rs index c08c98f..7d4c643 100644 --- a/src/config/resolve.rs +++ b/src/config/resolve.rs @@ -236,13 +236,14 @@ pub fn resolve_config(cli: Args) -> Result { } else { (default_selection(cli.action.as_ref()), "") }; + let new_layer = selection == LayerSelection::New; let name = match selection { LayerSelection::Join(name) => name, - LayerSelection::New => generate_timestamp_name( - &partial_config.storage_dir, + LayerSelection::New => generate_timestamp_name(&resolve_storage_dir( + partial_config.storage_dir.clone(), uid_gid_home.uid, uid_gid_home.gid, - )?, + )?), LayerSelection::Last => find_last_layer( &resolve_storage_dir( partial_config.storage_dir.clone(), @@ -251,21 +252,15 @@ pub fn resolve_config(cli: Args) -> Result { )?, &cwd, )?, - LayerSelection::LastOrNew => match find_last_layer( - &resolve_storage_dir( + LayerSelection::LastOrNew => { + let storage_dir = resolve_storage_dir( partial_config.storage_dir.clone(), uid_gid_home.uid, uid_gid_home.gid, - )?, - &cwd, - ) { - Ok(name) => name, - Err(_) => generate_timestamp_name( - &partial_config.storage_dir, - uid_gid_home.uid, - uid_gid_home.gid, - )?, - }, + )?; + find_last_layer(&storage_dir, &cwd) + .unwrap_or_else(|_| generate_timestamp_name(&storage_dir)) + } }; if !explicit.is_empty() { sources.insert("name".into(), explicit.into()); @@ -462,6 +457,7 @@ pub fn resolve_config(cli: Args) -> Result { let config = Config { name, + new_layer, net, storage_dir, layer_dir, @@ -913,13 +909,9 @@ fn validate_config(config: &Config) -> Result<()> { Ok(()) } -fn generate_timestamp_name( - storage_dir: &Option, - uid: Uid, - gid: Gid, -) -> Result { - let storage_dir = resolve_storage_dir(storage_dir.clone(), uid, gid)?; - +/// Generates an `ephemeral_*` name for a new layer that isn't taken yet. +/// Generating it doesn't reserve it; `Layer::get_or_create` does that. +pub(crate) fn generate_timestamp_name(storage_dir: &Path) -> String { #[cfg(feature = "coverage")] let mut iter = 0; @@ -931,7 +923,7 @@ fn generate_timestamp_name( // Check if this name already exists let layer_path = storage_dir.join(&base_name); if !layer_path.exists() { - return Ok(base_name); + return base_name; } // If it exists, try with millisecond precision @@ -948,7 +940,7 @@ fn generate_timestamp_name( let layer_path_ms = storage_dir.join(&name_with_ms); if !layer_path_ms.exists() { - return Ok(name_with_ms); + return name_with_ms; } // If even that exists, sleep for a millisecond and try again @@ -1217,6 +1209,7 @@ mod tests { fn test_validate_config() { let mut config = Config { name: "test-layer".to_string(), + new_layer: false, storage_dir: PathBuf::from("/tmp/test"), layer_dir: PathBuf::from("/tmp/test"), upper_cwd: PathBuf::from("/tmp/test"), diff --git a/src/config/structs.rs b/src/config/structs.rs index a765b1d..4a2b79a 100644 --- a/src/config/structs.rs +++ b/src/config/structs.rs @@ -72,6 +72,9 @@ pub struct PartialConfig { pub struct Config { pub log_level: log::LevelFilter, pub name: String, + /// Whether a new layer was asked for, with `name` generated for it, + /// rather than a layer to join + pub new_layer: bool, pub storage_dir: PathBuf, pub layer_dir: PathBuf, pub upper_cwd: PathBuf, diff --git a/src/layer/exec.rs b/src/layer/exec.rs index cb9cf8e..b67341a 100644 --- a/src/layer/exec.rs +++ b/src/layer/exec.rs @@ -1,6 +1,6 @@ #![allow(static_mut_refs)] use crate::layer::Layer; -use crate::util::drop_privileges; +use crate::util::{Lock, drop_privileges}; use anyhow::{Context, Result, anyhow}; use libc::syscall; use log::trace; @@ -20,9 +20,10 @@ unsafe extern "C" { impl Layer { /** * Exec within the provided layer. This function never returns on - * success. + * success. `lock` is the layer lock, which keeps PID 1 from shutting the + * layer down until our command is running in it. */ - pub fn exec(&self, command: &[String]) -> Result<()> { + pub fn exec(&self, command: &[String], lock: Box) -> Result<()> { let cwd = std::env::current_dir() .context(format!("failed to get current directory"))?; @@ -120,8 +121,21 @@ impl Layer { ); } + /* Stands in for a command that's slow to start, e.g. on a loaded + * machine */ + #[cfg(feature = "coverage")] + if let Some(ms) = std::env::var("TEST_DELAY_FORK") + .ok() + .and_then(|ms| ms.parse().ok()) + { + std::thread::sleep(std::time::Duration::from_millis(ms)); + } + /* We need to fork to properly enter the PID namespace */ let result = unsafe { fork() }.context(format!("failed to fork"))?; + /* Our command is in the layer's PID namespace now, where PID 1 sees + * it */ + drop(lock); match result { ForkResult::Parent { child } => { /* Parent process */ diff --git a/src/layer/get_or_create.rs b/src/layer/get_or_create.rs index 3c60896..3c74e82 100644 --- a/src/layer/get_or_create.rs +++ b/src/layer/get_or_create.rs @@ -1,11 +1,11 @@ use super::cgroup::remove_cgroup; use super::mount_overlays::MountHash; use super::supervisor; +use crate::config::resolve::generate_timestamp_name; use crate::config::{BindMount, BindMountOptions, Config, Network}; use crate::layer::{Layer, LayerOrigin}; #[cfg(feature = "coverage")] use crate::util::CLONE_FS; -use crate::util::Lock; use crate::util::get_layer_pid_path; use crate::util::get_running_layer_pid; use crate::util::{ @@ -13,6 +13,7 @@ use crate::util::{ CLONE_NEWNS, CLONE_NEWPID, CLONE_NEWUTS, Clone3Args, check_path_for_mount_option_compatibility, clone3, mkdir, mount, }; +use crate::util::{Lock, SharedLock}; use anyhow::Context; use anyhow::{Result, anyhow}; use log::{error, trace}; @@ -105,21 +106,42 @@ impl Layer { Ok((None, lock)) } - pub fn get_or_create(config: &Config, uid: Uid, gid: Gid) -> Result { + /** + * Returns the layer, starting it if it isn't running, along with the + * layer lock, which is held until the caller drops it. + */ + pub fn get_or_create( + config: &Config, + uid: Uid, + gid: Gid, + ) -> Result<(Layer, Box)> { let storage_dir = &config.storage_dir; - let layer_name = &config.name; /* Ensure that the storage directory exists */ mkdir(storage_dir, uid, gid).context(format!( "failed to create storage directory: {}", storage_dir.display() ))?; - /* First lock so we don't have multiple processes trying to get_or_create at the same time */ - let lock = Lock::layer(storage_dir, layer_name) - .context(format!("failed to lock layer: {}", layer_name))?; + /* First lock so we don't have multiple processes trying to + * get_or_create at the same time. A name generated for a new layer + * is ours once we hold its lock and no layer by that name exists, + * since we create the layer's directory before letting go of the + * lock. If one does exist, another launch generated the same name + * first, so we generate another. */ + let mut layer_name = config.name.clone(); + let lock = loop { + let lock = Lock::layer(storage_dir, &layer_name) + .context(format!("failed to lock layer: {}", layer_name))?; + if !config.new_layer || !storage_dir.join(&layer_name).exists() { + break lock; + } + trace!("Layer '{}' was created meanwhile", layer_name); + layer_name = generate_timestamp_name(storage_dir); + }; + let layer_name = &layer_name; /* If we have an existing layer, return it */ - let (layer, _lock) = + let (layer, lock) = Layer::get(storage_dir, layer_name, uid, gid, Some(lock))?; if let Some(layer) = layer { @@ -158,7 +180,7 @@ impl Layer { } } } - return Ok(layer); + return Ok((layer, lock)); } /* @@ -234,7 +256,7 @@ impl Layer { .save(&layer.base)?; } - Ok(layer) + Ok((layer, lock)) } /** @@ -280,8 +302,8 @@ impl Layer { error!("Failed to start layer: {:#}", e); e }); - let message = match pid1 { - Ok(pid) => { + let message = match &pid1 { + Ok((pid, _)) => { let mut message = vec![0]; message.extend(pid.as_raw().to_le_bytes()); message @@ -290,9 +312,9 @@ impl Layer { }; let _ = nix::unistd::write(&write_fd, &message); match pid1 { - Ok(pid) => { - supervisor::detach(); - supervisor::supervise(self, pid, cgroup.is_some()) + Ok((pid, lock)) => { + supervisor::detach(&lock); + supervisor::supervise(self, pid, cgroup.is_some(), lock) } Err(_) => std::process::exit(1), } @@ -302,7 +324,8 @@ impl Layer { /** * Runs in the supervisor: starts PID 1, records its pid, and waits until - * it reports that the layer is set up. + * it reports that the layer is set up. Returns PID 1's pid and the + * handle on the layer lock that we share with it. */ fn start_pid1( &self, @@ -310,9 +333,11 @@ impl Layer { pid_file: &PathBuf, overlay_mounts: &Vec, cgroup: Option<&OwnedFd>, - ) -> Result { + ) -> Result<(Pid, SharedLock)> { supervisor::become_supervisor()?; + let lock = SharedLock::open(&config.storage_dir, &self.name)?; + // create a pipe between ourselves and the main layer process so the main layer process can // let us know when it's done setting up the namespaces let (read_fd, write_fd) = @@ -375,7 +400,7 @@ impl Layer { return Err(anyhow!("Failed to setup layer")); } - Ok(pid) + Ok((pid, lock)) } else { // We are the child process. We should never return from this branch. @@ -385,7 +410,7 @@ impl Layer { // Normal operation is that this doesn't return. let _ = self - .setup_layer_and_wait(config, &write_fd, overlay_mounts) + .setup_layer_and_wait(config, &write_fd, overlay_mounts, &lock) .map_err(|e| { error!("Failed to setup layer: {}", e); e @@ -404,9 +429,17 @@ impl Layer { config: &Config, write_fd: &OwnedFd, mounts: &Vec, + lock: &SharedLock, ) -> Result<()> { trace!("Setting up layer root process"); + /* Of the file descriptors we inherited, keep only stdio, the pipe to + * our supervisor and our handle on the layer lock. Notably not the + * caller's lock on the layer: if the caller died holding it, the + * lock would stay held for as long as we keep it open, and nothing + * could get at the layer, nor could we shut it down. */ + supervisor::close_fds_except(&[write_fd.as_raw_fd(), lock.as_raw_fd()]); + /* Normalize credentials and dumpable state for pidfd-based setns(). * * When another process uses pidfd_open + setns() to join our @@ -1120,7 +1153,10 @@ impl Layer { /* Host the namespaces for as long as anything runs in the layer. * Once a second, reap processes orphaned in the layer, and exit once - * we're the only process left, which has our supervisor clean up. */ + * we're the only process left, which has our supervisor clean up. + * A command starting in the layer holds the layer lock until it's + * running in our pid namespace, so we only look while holding the + * lock, and exit holding it. */ /* Write our coverage data now, as we may be killed rather than exit */ #[cfg(feature = "coverage")] let dump_coverage = || { @@ -1157,11 +1193,17 @@ impl Layer { Ok(WaitStatus::StillAlive) | Err(_) ) {} - if only_process_in_layer() { - trace!("Nothing is running in layer '{}', exiting", self.name); - #[cfg(feature = "coverage")] - dump_coverage(); - std::process::exit(0); + if lock.try_lock() { + if only_process_in_layer() { + trace!( + "Nothing is running in layer '{}', exiting", + self.name + ); + #[cfg(feature = "coverage")] + dump_coverage(); + std::process::exit(0); + } + lock.unlock(); } } } diff --git a/src/layer/supervisor.rs b/src/layer/supervisor.rs index 3c70a7c..98ed0ce 100644 --- a/src/layer/supervisor.rs +++ b/src/layer/supervisor.rs @@ -2,15 +2,21 @@ //! PID 1 and waits for it to exit. When PID 1 exits, for whatever reason, the //! supervisor cleans up after the layer the way `stop` does: it removes the //! pid file and the layer's cgroup and unmounts the layer. +//! +//! The supervisor and PID 1 share a handle on the layer lock. PID 1 only +//! shuts the layer down while holding the lock, so it can't shut down while +//! a command is starting in the layer, and it exits still holding it. The +//! supervisor keeps holding it until it has cleaned up, so nothing can join +//! or restart the layer in the meantime. use crate::layer::Layer; use crate::layer::cgroup::remove_cgroup; -use crate::util::{Lock, get_running_layer_pid}; +use crate::util::{SharedLock, get_running_layer_pid}; use anyhow::{Context, Result}; use log::trace; use nix::sys::wait::waitpid; use nix::unistd::{Gid, Pid, Uid, setresgid, setresuid, setsid}; -use std::os::fd::AsRawFd; +use std::os::fd::{AsRawFd, RawFd}; use std::path::Path; /// Detaches the current (freshly forked) process from the caller's session @@ -30,9 +36,10 @@ pub(super) fn become_supervisor() -> Result<()> { } /// Points stdin, stdout and stderr at /dev/null and closes every other file -/// descriptor, so we don't keep the caller's terminal, pipes or layer lock -/// open while we wait, and don't hold the user's working directory busy. -pub(super) fn detach() { +/// descriptor but our handle on the layer lock, so we don't keep the +/// caller's terminal, pipes or lock on the layer open while we wait, and +/// don't hold the user's working directory busy. +pub(super) fn detach(lock: &SharedLock) { if let Ok(null) = std::fs::OpenOptions::new() .read(true) .write(true) @@ -42,25 +49,46 @@ pub(super) fn detach() { unsafe { libc::dup2(null.as_raw_fd(), fd) }; } } - unsafe { libc::syscall(libc::SYS_close_range, 3, u32::MAX, 0) }; + close_fds_except(&[lock.as_raw_fd()]); let _ = std::env::set_current_dir("/"); } +/// Closes every file descriptor from 3 up, except those in `keep` +pub(super) fn close_fds_except(keep: &[RawFd]) { + let mut keep: Vec = keep.iter().map(|&fd| fd as u32).collect(); + keep.sort_unstable(); + let mut first = 3; + for fd in keep { + if fd > first { + unsafe { libc::syscall(libc::SYS_close_range, first, fd - 1, 0) }; + } + first = first.max(fd + 1); + } + unsafe { libc::syscall(libc::SYS_close_range, first, u32::MAX, 0) }; +} + /// Waits for PID 1 to exit, cleans up after the layer, and exits. -/// `own_cgroup` is whether the layer created a cgroup of its own. -pub(super) fn supervise(layer: &Layer, pid1: Pid, own_cgroup: bool) -> ! { +/// `own_cgroup` is whether the layer created a cgroup of its own, and `lock` +/// is the handle on the layer lock we share with PID 1. +pub(super) fn supervise( + layer: &Layer, + pid1: Pid, + own_cgroup: bool, + lock: SharedLock, +) -> ! { trace!("Supervising layer '{}' with PID 1 {}", layer.name, pid1); while let Err(nix::errno::Errno::EINTR) = waitpid(pid1, None) {} - let _ = cleanup(layer, own_cgroup); + let _ = cleanup(layer, own_cgroup, lock); std::process::exit(0); } -fn cleanup(layer: &Layer, own_cgroup: bool) -> Result<()> { +fn cleanup(layer: &Layer, own_cgroup: bool, lock: SharedLock) -> Result<()> { let storage_dir = layer.base.parent().unwrap_or(Path::new("/")); - /* Without a lock file the layer was deleted, which already stopped and - * unmounted it. Opening it without creating it keeps it deleted. */ - let Some(_lock) = Lock::existing_layer(storage_dir, &layer.name)? else { + /* When PID 1 shut the layer down, it left us holding the lock already. + * Without a lock file the layer was deleted, which already stopped and + * unmounted it. */ + let Some(_lock) = lock.lock()? else { return Ok(()); }; diff --git a/src/main.rs b/src/main.rs index 0c3f63b..0564c96 100644 --- a/src/main.rs +++ b/src/main.rs @@ -181,10 +181,10 @@ pub fn main() -> Result<()> { None => vec![std::env::var("SHELL").unwrap_or("sh".to_string())], }; - let layer = + let (layer, lock) = Layer::get_or_create(&config, uid_gid_home.uid, uid_gid_home.gid) .context("Getting or creating layer")?; // On success, we never actually return from this call - layer.exec(&layered_command) + layer.exec(&layered_command, lock) } diff --git a/src/util/lock_layer.rs b/src/util/lock_layer.rs index bf6b554..ab0344c 100644 --- a/src/util/lock_layer.rs +++ b/src/util/lock_layer.rs @@ -1,11 +1,12 @@ use std::fs::{File, OpenOptions}; +use std::os::fd::{AsRawFd, RawFd}; use std::os::unix::fs::MetadataExt; use std::path::{Path, PathBuf}; use log::trace; use nix::fcntl::Flock; -use anyhow::{Result, anyhow}; +use anyhow::{Context, Result, anyhow}; pub struct Lock { path: PathBuf, @@ -36,22 +37,6 @@ impl Lock { Self::acquire(lock_file, file) } - /** Like `layer`, but returns None instead of creating the lock file - * when it can't be opened, e.g. because the layer was deleted, or when - * it was deleted while we waited for the lock. */ - pub fn existing_layer( - layers_storage_dir: &Path, - layer_name: &str, - ) -> Result>> { - let lock_file = layers_storage_dir.join(format!("{}.lock", layer_name)); - let file = OpenOptions::new().read(true).write(true).open(&lock_file); - let lock = file - .ok() - .map(|file| Self::acquire(lock_file, file)) - .transpose()?; - Ok(lock.filter(|lock| lock.is_current())) - } - /// Whether our lock file is still the one at its path fn is_current(&self) -> bool { let ours = self.lock.metadata(); @@ -82,3 +67,48 @@ impl Drop for Lock { trace!("Unlocking lock {}", self.path.display()); } } + +/// A handle on an existing layer lock file that isn't locked yet. Forked +/// processes share the handle, and with it the lock: once one of them takes +/// it, it's held until one of them unlocks it, or all of them have closed +/// the handle. +pub struct SharedLock { + path: PathBuf, + file: File, +} + +impl SharedLock { + pub fn open( + layers_storage_dir: &Path, + layer_name: &str, + ) -> Result { + let path = layers_storage_dir.join(format!("{}.lock", layer_name)); + let file = File::open(&path).context("Failed to open layer lock")?; + Ok(SharedLock { path, file }) + } + + /// Takes the lock unless someone else holds it, returning whether we did + pub fn try_lock(&self) -> bool { + unsafe { + libc::flock(self.file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) + == 0 + } + } + + pub fn unlock(&self) { + unsafe { libc::flock(self.file.as_raw_fd(), libc::LOCK_UN) }; + } + + /// Waits for the lock, unless we hold it already. Returns None when the + /// lock file has been deleted or replaced, i.e. the layer was deleted. + pub fn lock(self) -> Result>> { + let lock = Lock::acquire(self.path, self.file)?; + Ok(Some(lock).filter(|lock| lock.is_current())) + } +} + +impl AsRawFd for SharedLock { + fn as_raw_fd(&self) -> RawFd { + self.file.as_raw_fd() + } +} diff --git a/tests/ai_test_auto_shutdown.rs b/tests/ai_test_auto_shutdown.rs index 4f462d3..8721ca2 100644 --- a/tests/ai_test_auto_shutdown.rs +++ b/tests/ai_test_auto_shutdown.rs @@ -237,3 +237,44 @@ fn ai_test_supervisor_leaves_restarted_layer( .status()?; Ok(()) } + +/// A command that's slow to start in a new layer still runs: the layer +/// doesn't shut down for lack of anything running in it while the command +/// is on its way +#[rstest] +fn ai_test_layer_waits_for_starting_command( + mut layer: LayerManager, +) -> Result<()> { + // By then PID 1 has looked for anything running in the layer + layer.run_with_env( + &["sh", "-c", "echo started"], + "TEST_DELAY_FORK", + "1500", + )?; + assert_eq!(layer.last_stdout.trim(), "started"); + Ok(()) +} + +/// A launch killed before its command starts doesn't keep the layer from +/// shutting down +#[rstest] +fn ai_test_killed_launch_lets_layer_shut_down( + layer: LayerManager, +) -> Result<()> { + let pid_file = pid_file(&layer)?; + // The setuid binary rather than sudo, so we kill the launch itself + let mut launch = Command::new(format!("{}-setuid", layer.devlayer_bin)) + .args([ + &format!("--join={}", layer.name), + "--no-config", + "--no-bind-cwd", + "true", + ]) + .env("TEST_DELAY_FORK", "60000") + .spawn()?; + assert!(wait_until(Duration::from_secs(5), || pid_file.exists())); + launch.kill()?; + launch.wait()?; + assert!(wait_until(Duration::from_secs(5), || !pid_file.exists())); + Ok(()) +} diff --git a/tests/ai_test_concurrent_new.rs b/tests/ai_test_concurrent_new.rs new file mode 100644 index 0000000..7c2dbc9 --- /dev/null +++ b/tests/ai_test_concurrent_new.rs @@ -0,0 +1,69 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use std::collections::BTreeSet; +use std::process::{Command, Stdio}; + +/// Commands launched at the same moment, each in a new layer, generate the +/// same timestamp name, yet each still gets a layer of its own +#[test] +fn ai_test_concurrent_new_launches_get_own_layers() -> Result<()> { + let bin = get_devlayer_bin(); + let launches = (0..8) + .map(|_| { + Command::new("sudo") + .args([ + "-E", + &bin, + "--no-config", + "--no-bind-cwd", + "--new", + "sh", + "-c", + "echo $DEVLAYER", + ]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + }) + .collect::>>()?; + let outputs = launches + .into_iter() + .map(|launch| launch.wait_with_output()) + .collect::>>()?; + let names: Vec = outputs + .iter() + .map(|output| { + String::from_utf8_lossy(&output.stdout).trim().to_string() + }) + .collect(); + + // Deletes the layers when dropped + let _layers: Vec = names + .iter() + .filter(|name| !name.is_empty()) + .collect::>() + .into_iter() + .map(|name| { + let mut layer = LayerManager::new(); + layer.name = name.clone(); + layer + }) + .collect(); + + for output in &outputs { + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + } + assert_eq!( + names.iter().collect::>().len(), + names.len(), + "launches shared layers: {:?}", + names + ); + Ok(()) +} diff --git a/tests/ai_test_layer_settings.rs b/tests/ai_test_layer_settings.rs index bacb099..3b5baf4 100644 --- a/tests/ai_test_layer_settings.rs +++ b/tests/ai_test_layer_settings.rs @@ -18,6 +18,7 @@ fn create_test_config() -> ::devlayer::config::Config { ::devlayer::config::Config { log_level: log::LevelFilter::Info, name: "test_layer".to_string(), + new_layer: false, storage_dir: PathBuf::from("/tmp/test_storage"), layer_dir: PathBuf::from("/tmp/test_layer"), upper_cwd: PathBuf::from("/tmp/test_upper"), From 998644ef71b9a2f13e0f5e8d493fc89de444a9ea Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Sat, 14 Nov 2026 16:41:05 -0500 Subject: [PATCH 22/32] Add CI spelling exceptions, report output when the audio bind test fails --- cspell.json | 7 +++++++ tests/ai_test_audio.rs | 6 +++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/cspell.json b/cspell.json index 986aca1..b6a52e1 100644 --- a/cspell.json +++ b/cspell.json @@ -31,6 +31,7 @@ "CLOEXEC", "cmdline", "codegen", + "codeium", "codespell", "cpus", "CREAT", @@ -44,6 +45,7 @@ "eaccess", "EAGAIN", "egid", + "EINTR", "EINVAL", "elif", "ELOOP", @@ -117,6 +119,7 @@ "IXON", "kcore", "keygen", + "killable", "kmod", "lchown", "lflag", @@ -134,6 +137,7 @@ "mknod", "mkpart", "mman", + "mountinfo", "mqueue", "netcat", "netlink", @@ -168,7 +172,9 @@ "pidfd", "pipewire", "PKGBUILD", + "pkill", "powercap", + "ppid", "prctl", "procs", "profdata", @@ -224,6 +230,7 @@ "SIGTSTP", "splitn", "subsec", + "subshell", "syscall", "sysconfig", "sysfs", diff --git a/tests/ai_test_audio.rs b/tests/ai_test_audio.rs index 8fa57b1..2725c6e 100644 --- a/tests/ai_test_audio.rs +++ b/tests/ai_test_audio.rs @@ -43,7 +43,11 @@ fn ai_test_audio_on_by_default(mut layer: LayerManager) -> Result<()> { assert!( layer .last_stdout - .contains(&format!("{}/pulse", xdg.display())) + .contains(&format!("{}/pulse", xdg.display())), + "{}/pulse not bound\nstdout: {}\nstderr: {}", + xdg.display(), + layer.last_stdout, + layer.last_stderr ); Ok(()) } From 91b30638f224f83b06e94f7c2e8e1855554c51c6 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Sat, 14 Nov 2026 16:45:26 -0500 Subject: [PATCH 23/32] Run coverage on Ubuntu 24.04, whose sudo honors -E --- .github/workflows/coverage.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 3803c92..c9b35ed 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -21,7 +21,10 @@ env: jobs: run-coverage: - runs-on: ubuntu-latest + # The tests run devlayer with `sudo -E`. Ubuntu 26.04's sudo-rs + # ignores -E, so test environment variables (TEST_* hooks, + # LLVM_PROFILE_FILE) wouldn't reach devlayer. + runs-on: ubuntu-24.04 timeout-minutes: 10 steps: From 40752c02e03c386abb83bef2e73e7b8816d5a092 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Sat, 14 Nov 2026 17:13:54 -0500 Subject: [PATCH 24/32] Refuse to bind the home directory into a layer unless asked for with --bind --- src/config/resolve.rs | 11 +++++++ src/config/structs.rs | 3 ++ src/layer/get_or_create.rs | 5 ++++ tests/ai_test_home_bind.rs | 52 +++++++++++++++++++++++++++++++++ tests/ai_test_layer_settings.rs | 1 + 5 files changed, 72 insertions(+) create mode 100644 tests/ai_test_home_bind.rs diff --git a/src/config/resolve.rs b/src/config/resolve.rs index 7d4c643..760967b 100644 --- a/src/config/resolve.rs +++ b/src/config/resolve.rs @@ -424,6 +424,15 @@ pub fn resolve_config(cli: Args) -> Result { .iter() .map(|layer| layer.iter().map(|m| parse_bind_mount(m)).collect()) .collect::>>>()?; + + // Binding the home directory takes asking for it, e.g. with --bind=. + let cwd_bind_is_home = bind_cwd + && uid_gid_home.home.canonicalize().ok().as_ref() == Some(&created_in) + && !parsed_layers.iter().flatten().any(|mount| { + mount.target == created_in + && mount.options != BindMountOptions::Mask + }); + let mut target_map: HashMap = HashMap::new(); for layer in path_layers.into_iter().chain(parsed_layers) { let mut layer_map: HashMap = HashMap::new(); @@ -471,6 +480,7 @@ pub fn resolve_config(cli: Args) -> Result { no_default_llm_binds, created_in, bind_cwd, + cwd_bind_is_home, cpus, memory, config_files, @@ -1223,6 +1233,7 @@ mod tests { no_default_llm_binds: false, created_in: PathBuf::from("/tmp"), bind_cwd: false, + cwd_bind_is_home: false, cpus: None, memory: None, config_files: vec![], diff --git a/src/config/structs.rs b/src/config/structs.rs index 4a2b79a..ad40654 100644 --- a/src/config/structs.rs +++ b/src/config/structs.rs @@ -89,6 +89,9 @@ pub struct Config { pub created_in: PathBuf, /// Whether created_in is bound read-write into the layer pub bind_cwd: bool, + /// Whether that would bind the home directory without a bind of it + /// being asked for, which starting the layer refuses + pub cwd_bind_is_home: bool, /// Number of CPUs the layer may use, None for unlimited pub cpus: Option, /// Bytes of memory the layer may use, None for unlimited diff --git a/src/layer/get_or_create.rs b/src/layer/get_or_create.rs index 3c74e82..23f935b 100644 --- a/src/layer/get_or_create.rs +++ b/src/layer/get_or_create.rs @@ -207,6 +207,11 @@ impl Layer { "Refusing to bind / into the layer; run from a project directory or pass --no-bind-cwd" )); } + if config.cwd_bind_is_home { + return Err(anyhow!( + "Refusing to bind your home directory into the layer, where anything run could change all of it; run from a project directory, pass --no-bind-cwd, or pass --bind=. to bind it anyway" + )); + } let mut config = config.clone(); config.bind_mounts.push(BindMount { diff --git a/tests/ai_test_home_bind.rs b/tests/ai_test_home_bind.rs new file mode 100644 index 0000000..34efbe0 --- /dev/null +++ b/tests/ai_test_home_bind.rs @@ -0,0 +1,52 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use rstest::*; +use std::path::PathBuf; + +/// A layer manager that runs from the home directory with the cwd bind on, +/// as a user starting devlayer from `~` would +fn from_home(mut layer: LayerManager) -> Result { + layer.set_bind_cwd(true); + layer.cwd = Some(PathBuf::from(std::env::var("HOME")?)); + Ok(layer) +} + +/// Starting a layer from the home directory doesn't bind all of it +#[rstest] +fn ai_test_home_not_bound_by_default(layer: LayerManager) -> Result<()> { + let mut layer = from_home(layer)?; + assert!(layer.xfail(&["true"])); + assert!( + layer + .last_stderr + .contains("Refusing to bind your home directory"), + "{}", + layer.last_stderr + ); + Ok(()) +} + +/// Asking for the home directory with --bind=. binds it anyway +#[rstest] +fn ai_test_home_bound_when_asked(layer: LayerManager) -> Result<()> { + let mut layer = from_home(layer)?; + // Lists the mounts in the layer at the home directory + layer.run(&[ + "--bind=.", + "sh", + "-c", + "awk -v home=\"$HOME\" '$5 == home' /proc/self/mountinfo", + ])?; + assert!(!layer.last_stdout.trim().is_empty(), "home isn't bound"); + Ok(()) +} + +/// Without the cwd bind, starting a layer from the home directory is fine +#[rstest] +fn ai_test_home_without_cwd_bind(layer: LayerManager) -> Result<()> { + let mut layer = from_home(layer)?; + assert!(layer.pass(&["--no-bind-cwd", "true"])); + Ok(()) +} diff --git a/tests/ai_test_layer_settings.rs b/tests/ai_test_layer_settings.rs index 3b5baf4..febeec7 100644 --- a/tests/ai_test_layer_settings.rs +++ b/tests/ai_test_layer_settings.rs @@ -31,6 +31,7 @@ fn create_test_config() -> ::devlayer::config::Config { no_default_llm_binds: false, created_in: PathBuf::from("/tmp"), bind_cwd: false, + cwd_bind_is_home: false, cpus: None, memory: None, config_files: Vec::new(), From f438e972ef6d99ceb0b2d7dd43f998313ef56381 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Sat, 14 Nov 2026 17:27:58 -0500 Subject: [PATCH 25/32] Share lock, pid and data bind path helpers, exit safely on SIGTERM, tidy comments --- src/actions/stop.rs | 14 ++++-------- src/layer/delete.rs | 4 +--- src/layer/exec.rs | 2 ++ src/layer/exists.rs | 9 +++----- src/layer/get_or_create.rs | 47 ++++++++++++++++++++------------------ src/layer/layer_struct.rs | 15 +++++++++--- src/layer/stop.rs | 4 ++-- src/util/lock_layer.rs | 13 ++++++++--- 8 files changed, 59 insertions(+), 49 deletions(-) diff --git a/src/actions/stop.rs b/src/actions/stop.rs index 9610a37..ce6418c 100644 --- a/src/actions/stop.rs +++ b/src/actions/stop.rs @@ -5,6 +5,7 @@ use log::{trace, warn}; use nix::unistd::{Gid, Uid}; use crate::layer::Layer; +use crate::util::{get_layer_lock_path, get_layer_pid_path}; use anyhow::Result; pub fn stop( @@ -49,16 +50,9 @@ pub fn stop_all( let layer_name = filename.to_string_lossy()[..filename.len() - 5].to_string(); - let lock_file = - format!("{}/{}.lock", layers_storage_dir.display(), layer_name); - let pid_file = - format!("{}/{}.pid", layers_storage_dir.display(), layer_name); - let storage_dir = - format!("{}/{}", layers_storage_dir.display(), layer_name); - - if !Path::new(&lock_file).exists() - || !Path::new(&pid_file).exists() - || !Path::new(&storage_dir).exists() + if !get_layer_lock_path(layers_storage_dir, &layer_name).exists() + || !get_layer_pid_path(layers_storage_dir, &layer_name).exists() + || !layers_storage_dir.join(&layer_name).exists() { continue; } diff --git a/src/layer/delete.rs b/src/layer/delete.rs index 2b77a9b..3177d76 100644 --- a/src/layer/delete.rs +++ b/src/layer/delete.rs @@ -1,5 +1,3 @@ -use std::path::PathBuf; - use crate::{actions::rmdir_recursive, layer::Layer}; use anyhow::{Context, Result}; use log::{debug, trace}; @@ -16,7 +14,7 @@ impl Layer { debug!("Layer directory does not exist: {}", self.base.display()); } - let lock_file = PathBuf::from(format!("{}.lock", self.base.display())); + let lock_file = self.lock_path(); trace!("Cleaning up lock file: {}", lock_file.display()); std::fs::remove_file(&lock_file).context(format!( "failed to remove lock file {}", diff --git a/src/layer/exec.rs b/src/layer/exec.rs index b67341a..c713b6b 100644 --- a/src/layer/exec.rs +++ b/src/layer/exec.rs @@ -27,6 +27,8 @@ impl Layer { let cwd = std::env::current_dir() .context(format!("failed to get current directory"))?; + /* With host networking, PID 1 is in the host's network namespace, so + * CLONE_NEWNET just joins that */ let ns_flags = libc::CLONE_NEWNS | libc::CLONE_NEWPID | libc::CLONE_NEWIPC diff --git a/src/layer/exists.rs b/src/layer/exists.rs index cc05fe5..afabcbb 100644 --- a/src/layer/exists.rs +++ b/src/layer/exists.rs @@ -1,12 +1,9 @@ -use std::path::PathBuf; - use crate::layer::Layer; impl Layer { pub fn exists(&self) -> bool { - let pid_file = PathBuf::from(format!("{}.pid", self.base.display())); - let lock_file = PathBuf::from(format!("{}.lock", self.base.display())); - - self.base.exists() || pid_file.exists() || lock_file.exists() + self.base.exists() + || self.pid_path().exists() + || self.lock_path().exists() } } diff --git a/src/layer/get_or_create.rs b/src/layer/get_or_create.rs index 23f935b..ac79098 100644 --- a/src/layer/get_or_create.rs +++ b/src/layer/get_or_create.rs @@ -75,6 +75,16 @@ impl Layer { } } + /// The bind mount of the layer's data directory, which every layer has + fn data_bind_mount(&self) -> BindMount { + BindMount { + argument: "data".to_string(), + source: self.data_storage_dir.clone(), + target: self.data_storage_dir.clone(), + options: BindMountOptions::ReadWrite, + } + } + pub fn get( layers_storage_dir: &Path, layer_name: &str, @@ -158,12 +168,9 @@ impl Layer { // Create a config that includes the implicit data bind mount for validation let mut validation_config = config.clone(); - validation_config.bind_mounts.push(BindMount { - argument: "data".to_string(), - source: layer.data_storage_dir.clone(), - target: layer.data_storage_dir.clone(), - options: BindMountOptions::ReadWrite, - }); + validation_config + .bind_mounts + .push(layer.data_bind_mount()); // Validate settings compatibility existing_settings.validate_against_config( @@ -214,12 +221,7 @@ impl Layer { } let mut config = config.clone(); - config.bind_mounts.push(BindMount { - argument: "data".to_string(), - source: layer.data_storage_dir.clone(), - target: layer.data_storage_dir.clone(), - options: BindMountOptions::ReadWrite, - }); + config.bind_mounts.push(layer.data_bind_mount()); /* Create a cgroup to enforce any resource limits. We do this first * so we fail before mounting anything if limits aren't available. */ @@ -1148,20 +1150,15 @@ impl Layer { close(std::io::stdin().as_raw_fd()) .context(format!("failed to close stdin"))?; - /* Exit on SIGTERM, with the signal number as our exit status. libc's - * exit has the C calling convention a signal handler needs, which - * std::process::exit doesn't. */ - let exit: unsafe extern "C" fn(libc::c_int) -> ! = libc::exit; + /* Exit on SIGTERM, with the signal number as our exit status. Unlike + * exit, _exit is safe to call from a signal handler, and it has the C + * calling convention a handler needs, which std::process::exit + * doesn't. */ + let exit: unsafe extern "C" fn(libc::c_int) -> ! = libc::_exit; unsafe { libc::signal(libc::SIGTERM, exit as libc::sighandler_t); } - /* Host the namespaces for as long as anything runs in the layer. - * Once a second, reap processes orphaned in the layer, and exit once - * we're the only process left, which has our supervisor clean up. - * A command starting in the layer holds the layer lock until it's - * running in our pid namespace, so we only look while holding the - * lock, and exit holding it. */ /* Write our coverage data now, as we may be killed rather than exit */ #[cfg(feature = "coverage")] let dump_coverage = || { @@ -1191,6 +1188,12 @@ impl Layer { #[cfg(feature = "coverage")] dump_coverage(); + /* Host the namespaces for as long as anything runs in the layer. + * Once a second, reap processes orphaned in the layer, and exit once + * we're the only process left, which has our supervisor clean up. + * A command starting in the layer holds the layer lock until it's + * running in our pid namespace, so we only look while holding the + * lock, and exit holding it. */ loop { std::thread::sleep(std::time::Duration::from_secs(1)); while !matches!( diff --git a/src/layer/layer_struct.rs b/src/layer/layer_struct.rs index a43ed14..d7b7e98 100644 --- a/src/layer/layer_struct.rs +++ b/src/layer/layer_struct.rs @@ -10,11 +10,20 @@ pub struct Layer { pub upper_base: PathBuf, pub overlay_base: PathBuf, pub data_storage_dir: PathBuf, // storage dir for layer data and nested layers - //pub root_suffix: String, - //pub root_work: PathBuf, - //pub root_upper: PathBuf, pub root_overlay: PathBuf, pub pid: Pid, pub uid: Uid, pub gid: Gid, } + +impl Layer { + /// The pid file naming the layer's PID 1, next to the layer's directory + pub fn pid_path(&self) -> PathBuf { + PathBuf::from(format!("{}.pid", self.base.display())) + } + + /// The layer's lock file, next to the layer's directory + pub fn lock_path(&self) -> PathBuf { + PathBuf::from(format!("{}.lock", self.base.display())) + } +} diff --git a/src/layer/stop.rs b/src/layer/stop.rs index 9166568..fd2faf1 100644 --- a/src/layer/stop.rs +++ b/src/layer/stop.rs @@ -3,7 +3,7 @@ use crate::layer::cgroup::remove_cgroup; use anyhow::{Context, Result}; use log::trace; use nix::{fcntl::readlink, unistd::Pid}; -use std::path::{Path, PathBuf}; +use std::path::Path; impl Layer { pub fn stop(&self) -> Result<()> { @@ -144,7 +144,7 @@ impl Layer { } } - let pid_file = PathBuf::from(format!("{}.pid", self.base.display())); + let pid_file = self.pid_path(); trace!("Cleaning up PID file: {}", pid_file.display()); if pid_file.exists() { std::fs::remove_file(&pid_file).context(format!( diff --git a/src/util/lock_layer.rs b/src/util/lock_layer.rs index ab0344c..2dc4604 100644 --- a/src/util/lock_layer.rs +++ b/src/util/lock_layer.rs @@ -14,13 +14,20 @@ pub struct Lock { lock: Flock, } +pub fn get_layer_lock_path( + layers_storage_dir: &Path, + layer_name: &str, +) -> PathBuf { + layers_storage_dir.join(format!("{}.lock", layer_name)) +} + impl Lock { - /** Acquire a lock on the layer storage directory. */ + /** Acquire the lock on a layer, creating its lock file if needed. */ pub fn layer( layers_storage_dir: &Path, layer_name: &str, ) -> Result> { - let lock_file = layers_storage_dir.join(format!("{}.lock", layer_name)); + let lock_file = get_layer_lock_path(layers_storage_dir, layer_name); let file = OpenOptions::new() .create(true) .read(true) @@ -82,7 +89,7 @@ impl SharedLock { layers_storage_dir: &Path, layer_name: &str, ) -> Result { - let path = layers_storage_dir.join(format!("{}.lock", layer_name)); + let path = get_layer_lock_path(layers_storage_dir, layer_name); let file = File::open(&path).context("Failed to open layer lock")?; Ok(SharedLock { path, file }) } From 39768e144b313777e8f8b98fa78191458dd09e1c Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Sat, 14 Nov 2026 17:37:39 -0500 Subject: [PATCH 26/32] Doc update --- README.adoc | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/README.adoc b/README.adoc index f3f0123..ce95575 100644 --- a/README.adoc +++ b/README.adoc @@ -19,8 +19,9 @@ ifndef::env-github,env-vscode[] == Name devlayer - endif::[] -A tool for creating lightweight containerized views of your computer for safely -running semi-trusted programs and selectively managing their output. +A Linux tool for creating lightweight containerized views, similar to sandboxes, +to better control what agents have access to, and to allow them to make either immediate or +copy-on-write changes to specified locations. == Description @@ -28,7 +29,8 @@ The `devlayer` tool creates lightweight containerized copy-on-write views of you computer with optional network access. Its primary purpose is to run semi-trusted programs—such as AI agents, app images, or shell installers—in an environment that mirrors your host computer, while preventing them from -modifying your system. It can also be useful during development and testing for +modifying your system in undesired ways, but still letting them make changes in working +directories. It can also be useful during development and testing for doing things like testing migrations or file reorganizations as it lets you run your code, examine the changes, reject the changes and try again rapidly. @@ -43,23 +45,18 @@ making it practical to create new layers for each task you need to perform. Please note: The use of the term `semi-trusted` is meant to distinguish code that may do things you don't want it to do, but isn't actively malicious in a -sophisticated way. While the privilege escalations, data exfiltration, and other -ways of escaping the layer would absolutely be considered a bug, it is not -advised to run actively malicious code within a layer as there are not many -layers to protect your host system from the malicious code, and it is easy for -the code to detect it is running in a layer and potentially act accordingly. -You should be using other more isolated environments for that sort of research. - +sophisticated way. For real security needs, always use at least a virtual +machine if not a physically separate computer for your needs. ifdef::env-github,env-vscode[] == Installation To build and install from source simply run `make install`. -Arch Linux users can install the `devlayer-bin` package from the AUR. +// Arch Linux users can install the `devlayer-bin` package from the AUR. For most other Linux distributions there are applicable binary packages available from -the releases page: https://github.com/anoek/sandbox/releases +the releases page: https://github.com/anoek/devlayer/releases Binaries are provided for x86_64 and arm64, but it should compile and work on any architecture linux and rust supports. @@ -392,7 +389,7 @@ the same target within a single source are an error. Despite our test suite achieving a high degree of code coverage, this is still a fairly new project so please expect well covered bugs, security issues, and rough edges. Please report any issues you run into to the issue tracker: -https://github.com/anoek/sandbox/issues +https://github.com/anoek/devlayer/issues === Changing files in both the host system and the layer From 827ad5fa522ffef456b48b0d40c059e5e6866b98 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Sat, 14 Nov 2026 17:49:18 -0500 Subject: [PATCH 27/32] Don't follow symlinks in the storage directory, only trust a pid file naming the layer's own PID 1 --- cspell.json | 1 + src/actions/list.rs | 25 ++----- src/layer/get_or_create.rs | 25 ++++--- src/layer/settings.rs | 5 +- src/util/get_running_layer_pid.rs | 105 ++++++++++++++++++++---------- src/util/lock_layer.rs | 11 +++- src/util/mod.rs | 2 + src/util/no_follow.rs | 20 ++++++ tests/ai_test_auto_shutdown.rs | 12 ++-- tests/ai_test_pid_file_trust.rs | 60 +++++++++++++++++ tests/ai_test_resource_limits.rs | 3 +- tests/ai_test_sigterm.rs | 7 +- tests/ai_test_storage_symlinks.rs | 40 ++++++++++++ tests/test_layer_failures.rs | 6 +- tests/test_list.rs | 11 +++- 15 files changed, 251 insertions(+), 82 deletions(-) create mode 100644 src/util/no_follow.rs create mode 100644 tests/ai_test_pid_file_trust.rs create mode 100644 tests/ai_test_storage_symlinks.rs diff --git a/cspell.json b/cspell.json index b6a52e1..72bbc01 100644 --- a/cspell.json +++ b/cspell.json @@ -192,6 +192,7 @@ "resgid", "resolv", "resuid", + "rfind", "rgid", "rmdirs", "rstest", diff --git a/src/actions/list.rs b/src/actions/list.rs index 3dcced9..a9019d9 100644 --- a/src/actions/list.rs +++ b/src/actions/list.rs @@ -2,13 +2,12 @@ use anyhow::Result; use colored::*; use fast_glob::glob_match; use log::trace; -use nix::{sys::signal::kill, unistd::Pid}; use serde_json::Value; use std::path::Path; use crate::{ outln, - util::{get_layer_pid_path, set_json_output}, + util::{get_running_layer_pid, set_json_output}, }; pub fn list(layers_storage_dir: &Path, patterns: &[String]) -> Result<()> { @@ -72,24 +71,10 @@ pub fn get_layers( .iter() .any(|pattern| glob_match(pattern, &layer_name)) { - let pid_file = - get_layer_pid_path(layers_storage_dir, &layer_name); - if pid_file.exists() { - let pid = std::fs::read_to_string(pid_file)?; - - match pid.parse::() { - Ok(pid) => { - let pid = Pid::from_raw(pid); - if kill(pid, None).is_ok() { - running_layers.push(layer_name); - } else { - stopped_layers.push(layer_name); - } - } - Err(_) => { - stopped_layers.push(layer_name); - } - } + if get_running_layer_pid(layers_storage_dir, &layer_name) + .is_some() + { + running_layers.push(layer_name); } else { stopped_layers.push(layer_name); } diff --git a/src/layer/get_or_create.rs b/src/layer/get_or_create.rs index ac79098..18f0da7 100644 --- a/src/layer/get_or_create.rs +++ b/src/layer/get_or_create.rs @@ -7,13 +7,13 @@ use crate::layer::{Layer, LayerOrigin}; #[cfg(feature = "coverage")] use crate::util::CLONE_FS; use crate::util::get_layer_pid_path; -use crate::util::get_running_layer_pid; use crate::util::{ CLONE_INTO_CGROUP, CLONE_NEWCGROUP, CLONE_NEWIPC, CLONE_NEWNET, CLONE_NEWNS, CLONE_NEWPID, CLONE_NEWUTS, Clone3Args, check_path_for_mount_option_compatibility, clone3, mkdir, mount, }; -use crate::util::{Lock, SharedLock}; +use crate::util::{Lock, SharedLock, write_no_follow}; +use crate::util::{get_running_layer_pid, layer_pid_file_contents}; use anyhow::Context; use anyhow::{Result, anyhow}; use log::{error, trace}; @@ -22,6 +22,7 @@ use nix::sys::stat::fchmodat; use nix::{ mount::MsFlags, mount::{MntFlags, umount2}, + sys::signal::Signal, sys::stat::{Mode, SFlag, makedev, mknod}, sys::wait::{WaitPidFlag, WaitStatus, waitpid}, unistd::{ @@ -277,7 +278,7 @@ impl Layer { fn start_layer( &self, config: &Config, - pid_file: &PathBuf, + pid_file: &Path, overlay_mounts: &Vec, cgroup: Option<&OwnedFd>, ) -> Result { @@ -337,7 +338,7 @@ impl Layer { fn start_pid1( &self, config: &Config, - pid_file: &PathBuf, + pid_file: &Path, overlay_mounts: &Vec, cgroup: Option<&OwnedFd>, ) -> Result<(Pid, SharedLock)> { @@ -388,11 +389,17 @@ impl Layer { // We are the parent process drop(write_fd); - // write pid to pid file - std::fs::write(pid_file, pid.to_string()).context(format!( - "failed to write pid to pid file: {}", - pid_file.display() - ))?; + // write pid to pid file, or else don't leave PID 1 behind + if let Err(e) = + write_no_follow(pid_file, layer_pid_file_contents(pid)) + { + let _ = nix::sys::signal::kill(pid, Signal::SIGKILL); + let _ = waitpid(pid, None); + return Err(e).context(format!( + "failed to write pid to pid file: {}", + pid_file.display() + )); + } // Wait for the child process to finish mounting procfs and doing whatever // setup stuff it needs to do. Once done, it sends a byte over the pipe, that's diff --git a/src/layer/settings.rs b/src/layer/settings.rs index ee568f2..6efdc97 100644 --- a/src/layer/settings.rs +++ b/src/layer/settings.rs @@ -1,5 +1,6 @@ use crate::config::{BindMount, Config}; use crate::layer::mount_overlays::MountHash; +use crate::util::write_no_follow; use anyhow::{Context, Result, anyhow}; use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; @@ -43,7 +44,7 @@ impl LayerOrigin { pub fn save(&self, layer_dir: &Path) -> Result<()> { let json = serde_json::to_string_pretty(self) .context("Failed to serialize layer origin to JSON")?; - std::fs::write(Self::path(layer_dir), json).context(format!( + write_no_follow(&Self::path(layer_dir), json).context(format!( "Failed to write {}", Self::path(layer_dir).display() )) @@ -78,7 +79,7 @@ impl LayerSettings { pub fn save_to_file(&self, path: &Path) -> Result<()> { let settings_json = serde_json::to_string_pretty(self) .context("Failed to serialize layer settings to JSON")?; - std::fs::write(path, settings_json).context(format!( + write_no_follow(path, settings_json).context(format!( "Failed to write settings.json to {}", path.display() ))?; diff --git a/src/util/get_running_layer_pid.rs b/src/util/get_running_layer_pid.rs index fa38785..f44e478 100644 --- a/src/util/get_running_layer_pid.rs +++ b/src/util/get_running_layer_pid.rs @@ -1,54 +1,89 @@ -use nix::{sys::signal::kill, unistd::Pid}; +use nix::unistd::Pid; use std::path::Path; use std::path::PathBuf; use log::trace; /** - * Get the PID of a running layer. + * Get the PID 1 of a running layer, from its pid file. * - * Returns None if the layer is not running. + * The pid file is only trusted while it names PID 1 of a pid namespace + * below ours that started when the pid file says it did. A stale pid file, + * e.g. after a reboot, may name an unrelated process, which we must not + * kill everything alongside of or run commands next to. + * + * Returns None, removing the pid file, if the layer is not running. */ pub fn get_running_layer_pid( layers_storage_dir: &Path, layer_name: &str, ) -> Option { - let layers_storage_dir = &PathBuf::from(layers_storage_dir); let pid_file = get_layer_pid_path(layers_storage_dir, layer_name); - if pid_file.exists() { - match std::fs::read_to_string(&pid_file) - .ok() - .and_then(|pid_str| pid_str.parse::().ok()) - .map(Pid::from_raw) - .filter(|&pid| kill(pid, None).is_ok()) - .and_then(|pid| { - trace!( - "Existing layer '{}' found with PID: {}", - layer_name, pid - ); - - std::fs::read_to_string(format!("/proc/{}/stat", pid.as_raw())) - .ok() - .map(|status| (pid, status)) - }) - .and_then(|(pid, status)| { - let components: Vec<&str> = status.split_whitespace().collect(); - components - .get(2) - .filter(|&status| *status != "Z" && *status != "T") - .map(|_| pid) - }) { - Some(pid) => return Some(pid), - None => { - trace!( - "Invalid PID file or layer was not in a good state, cleaning up" - ); - std::fs::remove_file(&pid_file).ok(); - } + if !pid_file.exists() { + return None; + } + + let pid = std::fs::read_to_string(&pid_file) + .ok() + .and_then(|contents| { + let mut fields = contents.split_whitespace(); + let pid = Pid::from_raw(fields.next()?.parse().ok()?); + let start_time = fields.next()?.parse::().ok()?; + let (state, started) = process_state_and_start_time(pid)?; + (started == start_time + && state != "Z" + && state != "T" + && is_namespace_init(pid)) + .then_some(pid) + }); + + match pid { + Some(pid) => { + trace!("Existing layer '{}' found with PID: {}", layer_name, pid); + } + None => { + trace!( + "Layer '{}' isn't running, removing its pid file", + layer_name + ); + std::fs::remove_file(&pid_file).ok(); } } + pid +} + +/// What to write to the pid file of a layer whose PID 1 is `pid` +pub fn layer_pid_file_contents(pid: Pid) -> String { + let start_time = process_state_and_start_time(pid).map_or(0, |(_, t)| t); + format!("{} {}", pid, start_time) +} - None +/// The state (e.g. "R", "Z") and start time, in clock ticks since boot, of +/// process `pid` +fn process_state_and_start_time(pid: Pid) -> Option<(String, u64)> { + let stat = std::fs::read_to_string(format!("/proc/{}/stat", pid)).ok()?; + // The command name is in parentheses and may contain anything + let fields: Vec<&str> = stat + .get(stat.rfind(')')? + 1..)? + .split_whitespace() + .collect(); + // Fields 3 (state) and 22 (starttime) of proc_pid_stat(5) + Some((fields.first()?.to_string(), fields.get(19)?.parse().ok()?)) +} + +/// Whether `pid` is PID 1 of a pid namespace below ours +fn is_namespace_init(pid: Pid) -> bool { + std::fs::read_to_string(format!("/proc/{}/status", pid)).is_ok_and( + |status| { + status.lines().any(|line| { + let ids: Vec<&str> = line + .strip_prefix("NSpid:") + .map(|ids| ids.split_whitespace().collect()) + .unwrap_or_default(); + ids.len() > 1 && ids.last() == Some(&"1") + }) + }, + ) } pub fn get_layer_pid_path( diff --git a/src/util/lock_layer.rs b/src/util/lock_layer.rs index 2dc4604..624b2f2 100644 --- a/src/util/lock_layer.rs +++ b/src/util/lock_layer.rs @@ -1,6 +1,6 @@ use std::fs::{File, OpenOptions}; use std::os::fd::{AsRawFd, RawFd}; -use std::os::unix::fs::MetadataExt; +use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; use std::path::{Path, PathBuf}; use log::trace; @@ -33,6 +33,7 @@ impl Lock { .read(true) .write(true) .truncate(false) + .custom_flags(libc::O_NOFOLLOW) .open(&lock_file) .map_err(|e| { anyhow!( @@ -47,7 +48,7 @@ impl Lock { /// Whether our lock file is still the one at its path fn is_current(&self) -> bool { let ours = self.lock.metadata(); - let current = std::fs::metadata(&self.path); + let current = std::fs::symlink_metadata(&self.path); ours.is_ok_and(|ours| { current.is_ok_and(|current| { ours.dev() == current.dev() && ours.ino() == current.ino() @@ -90,7 +91,11 @@ impl SharedLock { layer_name: &str, ) -> Result { let path = get_layer_lock_path(layers_storage_dir, layer_name); - let file = File::open(&path).context("Failed to open layer lock")?; + let file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW) + .open(&path) + .context("Failed to open layer lock")?; Ok(SharedLock { path, file }) } diff --git a/src/util/mod.rs b/src/util/mod.rs index 0adeb47..a63bd5e 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -8,6 +8,7 @@ mod lock_layer; mod mkdir; mod mount; mod mounts; +mod no_follow; mod output; mod resolve_uid_gid_home; mod sync_and_drop_caches; @@ -22,6 +23,7 @@ pub use lock_layer::*; pub use mkdir::*; pub use mount::*; pub use mounts::*; +pub use no_follow::*; pub use output::*; pub use resolve_uid_gid_home::*; pub use sync_and_drop_caches::*; diff --git a/src/util/no_follow.rs b/src/util/no_follow.rs new file mode 100644 index 0000000..161d3e7 --- /dev/null +++ b/src/util/no_follow.rs @@ -0,0 +1,20 @@ +use std::fs::OpenOptions; +use std::io::Write; +use std::os::unix::fs::OpenOptionsExt; +use std::path::Path; + +/// Writes `contents` to `path`, replacing what's there, but fails rather +/// than follow a symlink at `path`. For files we write as root in +/// directories the user owns. +pub fn write_no_follow( + path: &Path, + contents: impl AsRef<[u8]>, +) -> std::io::Result<()> { + OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .custom_flags(libc::O_NOFOLLOW) + .open(path)? + .write_all(contents.as_ref()) +} diff --git a/tests/ai_test_auto_shutdown.rs b/tests/ai_test_auto_shutdown.rs index 8721ca2..aaae19b 100644 --- a/tests/ai_test_auto_shutdown.rs +++ b/tests/ai_test_auto_shutdown.rs @@ -17,7 +17,7 @@ fn pid_file(layer: &LayerManager) -> Result { /// PID 1 of the layer, if its pid file names a live process fn layer_pid(layer: &LayerManager) -> Option { let pid = std::fs::read_to_string(pid_file(layer).ok()?).ok()?; - let pid = pid.trim().parse::().ok()?; + let pid = pid.split_whitespace().next()?.parse::().ok()?; PathBuf::from(format!("/proc/{}", pid)) .exists() .then_some(pid) @@ -199,7 +199,8 @@ fn ai_test_supervisor_leaves_restarted_layer( layer.hold()?; other.hold()?; let pid = layer_pid(&layer).expect("layer should be running"); - let other_pid = layer_pid(&other).expect("other layer should be running"); + assert!(layer_pid(&other).is_some(), "other layer should be running"); + let other_pid_file = std::fs::read_to_string(pid_file(&other)?)?; let pid_file = pid_file(&layer)?; let lock_file = format!("{}.lock", layer.dir()?.display()); @@ -219,17 +220,14 @@ fn ai_test_supervisor_leaves_restarted_layer( .args([ "sh", "-c", - &format!("printf %s {} > {}", other_pid, pid_file.display()), + &format!("printf %s '{}' > {}", other_pid_file, pid_file.display()), ]) .status()?; drop(lock); std::thread::sleep(Duration::from_secs(2)); assert!(has_mounts(&layer)?); - assert_eq!( - std::fs::read_to_string(&pid_file)?.trim(), - other_pid.to_string() - ); + assert_eq!(std::fs::read_to_string(&pid_file)?, other_pid_file); // Don't let stopping this layer stop the other one Command::new("sudo") diff --git a/tests/ai_test_pid_file_trust.rs b/tests/ai_test_pid_file_trust.rs new file mode 100644 index 0000000..f02e2cf --- /dev/null +++ b/tests/ai_test_pid_file_trust.rs @@ -0,0 +1,60 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use rstest::*; +use std::path::PathBuf; +use std::process::Command; + +/// Writes `contents` to the layer's pid file, as a stale or mistaken pid +/// file would have them +fn write_pid_file(layer: &LayerManager, contents: &str) -> Result<()> { + let pid_file = format!("{}.pid", layer.dir()?.display()); + std::fs::write(PathBuf::from(pid_file), contents)?; + Ok(()) +} + +/// A pid file naming a process outside of any layer, as a stale one can +/// after a reboot, doesn't get a command run in that process's namespaces +#[rstest] +fn ai_test_pid_file_naming_host_process(mut layer: LayerManager) -> Result<()> { + let mut sleep = Command::new("sleep").arg("30").spawn()?; + layer.run(&["true"])?; + layer.run(&["stop"])?; + write_pid_file(&layer, &sleep.id().to_string())?; + + layer.run(&["readlink", "/proc/self/ns/mnt"])?; + let host_ns = std::fs::read_link("/proc/self/ns/mnt")?; + let result = layer.last_stdout.trim() != host_ns.to_string_lossy(); + let sleep_alive = sleep.try_wait()?.is_none(); + sleep.kill()?; + sleep.wait()?; + assert!(result, "the command ran outside of a layer"); + assert!(sleep_alive); + Ok(()) +} + +/// A pid file naming a layer's PID 1 but recording a different start time +/// names a process that has since exited, so the layer isn't running +#[rstest] +fn ai_test_pid_file_with_wrong_start_time( + mut layer: LayerManager, +) -> Result<()> { + let mut other = LayerManager::new(); + other.hold()?; + let other_pid_file = format!("{}.pid", other.dir()?.display()); + let contents = std::fs::read_to_string(other_pid_file)?; + let other_pid = contents.split_whitespace().next().unwrap_or_default(); + + layer.run(&["true"])?; + layer.run(&["stop"])?; + write_pid_file(&layer, &format!("{} 1", other_pid))?; + layer.run(&["list"])?; + let stopped = layer.last_stdout.split("Stopped layers:").nth(1); + assert!( + stopped.is_some_and(|stopped| stopped.contains(&layer.name)), + "{}", + layer.last_stdout + ); + Ok(()) +} diff --git a/tests/ai_test_resource_limits.rs b/tests/ai_test_resource_limits.rs index bc2e181..5e3dae2 100644 --- a/tests/ai_test_resource_limits.rs +++ b/tests/ai_test_resource_limits.rs @@ -340,7 +340,8 @@ fn ai_test_limits_stale_cgroup(mut layer: LayerManager) -> Result<()> { layer.run(&["config", "layer_dir"])?; let pid_file = format!("{}.pid", layer.last_stdout.trim()); let pid = fs::read_to_string(&pid_file)?; - let status = fs::read_to_string(format!("/proc/{}/status", pid.trim()))?; + let pid = pid.split_whitespace().next().unwrap_or_default(); + let status = fs::read_to_string(format!("/proc/{}/status", pid))?; let supervisor = status .lines() .find_map(|line| line.strip_prefix("PPid:")) diff --git a/tests/ai_test_sigterm.rs b/tests/ai_test_sigterm.rs index c553660..ae2cb96 100644 --- a/tests/ai_test_sigterm.rs +++ b/tests/ai_test_sigterm.rs @@ -12,7 +12,12 @@ fn ai_test_sigterm_stops_layer(mut layer: LayerManager) -> Result<()> { layer.run(&["config", "layer_dir"])?; let pid_file = format!("{}.pid", layer.last_stdout.trim()); - let pid = std::fs::read_to_string(&pid_file)?.trim().to_string(); + let pid = std::fs::read_to_string(&pid_file)?; + let pid = pid + .split_whitespace() + .next() + .unwrap_or_default() + .to_string(); let proc_dir = format!("/proc/{}", pid); assert!(Path::new(&proc_dir).exists()); diff --git a/tests/ai_test_storage_symlinks.rs b/tests/ai_test_storage_symlinks.rs new file mode 100644 index 0000000..b8eb8f1 --- /dev/null +++ b/tests/ai_test_storage_symlinks.rs @@ -0,0 +1,40 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use rstest::*; + +/// Root doesn't follow a symlink where it writes one of a layer's files in +/// the storage directory, which the user owns. `file` is relative to the +/// storage directory, with `{}` standing for the layer's name. +#[rstest] +#[case("{}.lock")] +#[case("{}.pid")] +#[case("{}/data/settings.json")] +#[case("{}/origin.json")] +fn ai_test_storage_symlinks_not_followed( + mut layer: LayerManager, + #[case] file: &str, +) -> Result<()> { + let layer_dir = layer.dir()?; + let link = layer_dir + .parent() + .expect("layer dir has a parent") + .join(file.replace("{}", &layer.name)); + if let Some(dir) = link.parent() { + std::fs::create_dir_all(dir)?; + } + let target = + std::env::current_dir()?.join(layer.test_filename("symlink-target")); + std::os::unix::fs::symlink(&target, &link)?; + + assert!(layer.xfail(&["true"])); + assert!( + !target.exists(), + "followed {} to {}", + file, + target.display() + ); + std::fs::remove_file(&link)?; + Ok(()) +} diff --git a/tests/test_layer_failures.rs b/tests/test_layer_failures.rs index 2830b9d..c20a015 100644 --- a/tests/test_layer_failures.rs +++ b/tests/test_layer_failures.rs @@ -43,7 +43,11 @@ fn test_recover_from_bad_pid_file() -> Result<()> { let pid_file = std::fs::File::open(&pid_file_name)?; let pid_file_content = std::io::read_to_string(pid_file)?; println!("pid_file: {} contains {}", pid_file_name, pid_file_content); - assert!(pid_file_content.parse::().is_ok()); + let pid = pid_file_content + .split_whitespace() + .next() + .unwrap_or_default(); + assert!(pid.parse::().is_ok()); Ok(()) } diff --git a/tests/test_list.rs b/tests/test_list.rs index 3930d89..1cbe12d 100644 --- a/tests/test_list.rs +++ b/tests/test_list.rs @@ -1,6 +1,6 @@ mod fixtures; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use anyhow::Result; use fixtures::*; @@ -67,8 +67,9 @@ fn test_list_ignore_bad_pid_file(mut layer: LayerManager) -> Result<()> { assert!(layer.run(&["list"]).is_ok()); // still expected to be listed assert!(layer.all_stdout.contains("coverage_test_bad_pid_file")); + // and listing it cleans up the bad pid file + assert!(!Path::new(&pid_file_name).exists()); - std::fs::remove_file(&pid_file_name)?; std::fs::remove_file(&lock_file_name)?; Ok(()) @@ -97,7 +98,11 @@ fn test_list_stale_pid_file(mut layer: LayerManager) -> Result<()> { let pid_file = std::fs::File::open(&pid_file_name)?; let pid_file_content = std::io::read_to_string(pid_file)?; println!("pid_file_content: {}", pid_file_content); - assert!(pid_file_content.parse::().is_ok()); + let pid = pid_file_content + .split_whitespace() + .next() + .unwrap_or_default(); + assert!(pid.parse::().is_ok()); assert!(layer.run(&["list", &layer.name.clone()]).is_ok()); eprintln!(">>>> {} <<<<", layer.last_stdout); From 9794feba6e89a87d468eeca1e21b153af966268b Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Sat, 14 Nov 2026 17:53:35 -0500 Subject: [PATCH 28/32] Pass test environment to sudo explicitly, so tests work with sudo-rs; run coverage on ubuntu-latest again --- .github/workflows/coverage.yml | 5 +-- tests/ai_test_bind_mounts.rs | 22 +++++----- tests/ai_test_concurrent_new.rs | 25 +++++------ tests/ai_test_ignore_rules.rs | 23 +++++----- tests/fixtures/fixture_layer.rs | 78 +++++++++++++++++++++------------ tests/test_misc.rs | 38 ++++++++-------- 6 files changed, 102 insertions(+), 89 deletions(-) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index c9b35ed..3803c92 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -21,10 +21,7 @@ env: jobs: run-coverage: - # The tests run devlayer with `sudo -E`. Ubuntu 26.04's sudo-rs - # ignores -E, so test environment variables (TEST_* hooks, - # LLVM_PROFILE_FILE) wouldn't reach devlayer. - runs-on: ubuntu-24.04 + runs-on: ubuntu-latest timeout-minutes: 10 steps: diff --git a/tests/ai_test_bind_mounts.rs b/tests/ai_test_bind_mounts.rs index 34e4ae1..16f8389 100644 --- a/tests/ai_test_bind_mounts.rs +++ b/tests/ai_test_bind_mounts.rs @@ -502,17 +502,17 @@ fn test_bind_mount_empty_destination_with_sudo() -> Result<()> { fs::create_dir_all(&tmp)?; // Run directly with sudo to ensure proper handling of bind mount paths - let output = std::process::Command::new("sudo") - .arg("-E") - .arg(env!("CARGO_BIN_EXE_devlayer")) - .arg("--join") - .arg(&unique_name) - .arg("--bind") - .arg(format!("{}:", tmp)) // Empty destination after colon - .arg("--") - .arg("echo") - .arg("test") - .output()?; + let output = as_root( + std::process::Command::new(env!("CARGO_BIN_EXE_devlayer")) + .arg("--join") + .arg(&unique_name) + .arg("--bind") + .arg(format!("{}:", tmp)) // Empty destination after colon + .arg("--") + .arg("echo") + .arg("test"), + ) + .output()?; assert!( output.status.success(), diff --git a/tests/ai_test_concurrent_new.rs b/tests/ai_test_concurrent_new.rs index 7c2dbc9..61d8629 100644 --- a/tests/ai_test_concurrent_new.rs +++ b/tests/ai_test_concurrent_new.rs @@ -12,20 +12,17 @@ fn ai_test_concurrent_new_launches_get_own_layers() -> Result<()> { let bin = get_devlayer_bin(); let launches = (0..8) .map(|_| { - Command::new("sudo") - .args([ - "-E", - &bin, - "--no-config", - "--no-bind-cwd", - "--new", - "sh", - "-c", - "echo $DEVLAYER", - ]) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() + as_root(Command::new(&bin).args([ + "--no-config", + "--no-bind-cwd", + "--new", + "sh", + "-c", + "echo $DEVLAYER", + ])) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() }) .collect::>>()?; let outputs = launches diff --git a/tests/ai_test_ignore_rules.rs b/tests/ai_test_ignore_rules.rs index 1ec3630..e303e53 100644 --- a/tests/ai_test_ignore_rules.rs +++ b/tests/ai_test_ignore_rules.rs @@ -718,17 +718,18 @@ fn test_env_flag_includes_ignored(mut layer: LayerManager) -> Result<()> { // This one needs to stay as Command::new because we need to pass --ignored directly // and test that it overrides the env var layer.set_ignored(false); // Disable automatic --ignored - let output = Command::new("sudo") - .env("DEVLAYER_IGNORED", "false") - .args(["-E", &layer.devlayer_bin]) - .args([ - "-v", - "--ignored", - &format!("--join={}", &layer.name), - "status", - &test_dir, - ]) - .output()?; + let output = as_root( + Command::new(&layer.devlayer_bin) + .env("DEVLAYER_IGNORED", "false") + .args([ + "-v", + "--ignored", + &format!("--join={}", &layer.name), + "status", + &test_dir, + ]), + ) + .output()?; assert!(output.status.success()); // Both files should be reported because cli takes precedence over env var let stdout = String::from_utf8_lossy(&output.stdout); diff --git a/tests/fixtures/fixture_layer.rs b/tests/fixtures/fixture_layer.rs index 6cf8089..98092f1 100644 --- a/tests/fixtures/fixture_layer.rs +++ b/tests/fixtures/fixture_layer.rs @@ -2,6 +2,8 @@ use anyhow::Result; use log::{error, warn}; use rand::Rng; use rstest::*; +use std::collections::BTreeMap; +use std::ffi::OsString; use std::path::Path; use std::process::Child; use std::{path::PathBuf, process::Command}; @@ -56,6 +58,37 @@ pub fn get_devlayer_bin() -> String { absolute_path.to_string_lossy().to_string() } +/// A command that runs `cmd` as root with sudo, with our environment and +/// the variables set on `cmd`, as `sudo -E` would. sudo-rs, the default sudo +/// on Ubuntu 26.04, ignores -E, so the variables are passed through `env`. +pub fn as_root(cmd: &Command) -> Command { + let mut vars: BTreeMap = std::env::vars_os().collect(); + let mut sudo = Command::new("sudo"); + sudo.arg("env"); + for (key, value) in cmd.get_envs() { + match value { + Some(value) => { + vars.insert(key.to_os_string(), value.to_os_string()); + } + None => { + vars.remove(key); + sudo.arg("-u").arg(key); + } + } + } + for (key, value) in vars { + let mut var = key; + var.push("="); + var.push(value); + sudo.arg(var); + } + sudo.arg(cmd.get_program()).args(cmd.get_args()); + if let Some(dir) = cmd.get_current_dir() { + sudo.current_dir(dir); + } + sudo +} + pub struct LayerManager { pub name: String, pub last_stdout: String, @@ -122,6 +155,11 @@ impl LayerManager { } } + /// `cmd` run as root, unless no_sudo is set + fn privileged(&self, cmd: Command) -> Command { + if self.no_sudo { cmd } else { as_root(&cmd) } + } + /// Applies the configured working directory to a command. A relative /// LLVM_PROFILE_FILE is made absolute so coverage data from commands run /// elsewhere still lands in this repository. @@ -151,17 +189,13 @@ impl LayerManager { #[allow(dead_code)] pub fn dir(&self) -> Result { - let mut cmd = Command::new("sudo"); - cmd.args(["-E", &self.devlayer_bin]); - - if self.no_sudo { - cmd = Command::new(&self.devlayer_bin); - } + let mut cmd = Command::new(&self.devlayer_bin); cmd.args([format!("--join={}", &self.name)]); self.add_no_bind_cwd(&mut cmd, &[]); cmd.args(["config", "layer_dir"]); self.apply_cwd(&mut cmd); + let mut cmd = self.privileged(cmd); let output = cmd.output()?; let base = String::from_utf8_lossy(&output.stdout).to_string(); let base = base.trim(); @@ -197,12 +231,7 @@ impl LayerManager { use std::io::Write; use std::process::Stdio; - let mut cmd = Command::new("sudo"); - cmd.args(["-E", &self.devlayer_bin]); - - if self.no_sudo { - cmd = Command::new(&self.devlayer_bin); - } + let mut cmd = Command::new(&self.devlayer_bin); if !self.no_default_options && !args.iter().any(|arg| { @@ -226,11 +255,6 @@ impl LayerManager { self.add_no_bind_cwd(&mut cmd, args); cmd.args(args); - // Set up stdin - cmd.stdin(Stdio::piped()); - cmd.stdout(Stdio::piped()); - cmd.stderr(Stdio::piped()); - println!( "Running command with stdin: {} {}", cmd.get_program().to_string_lossy(), @@ -241,6 +265,10 @@ impl LayerManager { ); self.apply_cwd(&mut cmd); + let mut cmd = self.privileged(cmd); + cmd.stdin(Stdio::piped()); + cmd.stdout(Stdio::piped()); + cmd.stderr(Stdio::piped()); let mut child = cmd .spawn() .map_err(|e| anyhow::anyhow!("Failed to spawn command: {:?}", e))?; @@ -288,16 +316,11 @@ impl LayerManager { env_key: &str, env_value: &str, ) -> Result { - let mut cmd = Command::new("sudo"); + let mut cmd = Command::new(&self.devlayer_bin); if !env_key.is_empty() { println!("Setting env var: {}={}", env_key, env_value); cmd.env(env_key, env_value); } - cmd.args(["-E", &self.devlayer_bin]); - - if self.no_sudo { - cmd = Command::new(&self.devlayer_bin); - } if !self.no_default_options && !args.iter().any(|arg| { @@ -327,6 +350,7 @@ impl LayerManager { .join(" ") ); self.apply_cwd(&mut cmd); + let mut cmd = self.privileged(cmd); match cmd.output() { Ok(output) => { self.last_stdout = @@ -378,12 +402,7 @@ impl LayerManager { #[allow(dead_code)] pub fn run_in_background(&mut self, args: &[&str]) -> Result { - let mut cmd = Command::new("sudo"); - cmd.args(["-E", &self.devlayer_bin]); - - if self.no_sudo { - cmd = Command::new(&self.devlayer_bin); - } + let mut cmd = Command::new(&self.devlayer_bin); if !self.no_default_options { cmd.args([format!("--join={}", &self.name)]); @@ -401,6 +420,7 @@ impl LayerManager { ); self.apply_cwd(&mut cmd); + let mut cmd = self.privileged(cmd); Ok(cmd.spawn()?) } diff --git a/tests/test_misc.rs b/tests/test_misc.rs index f04ecc4..dd0685f 100644 --- a/tests/test_misc.rs +++ b/tests/test_misc.rs @@ -23,9 +23,10 @@ fn test_program_runs_with_no_args(mut layer: LayerManager) -> Result<()> { fn test_weird_sudo_env_variables(layer: LayerManager) -> Result<()> { let devlayer_bin = layer.devlayer_bin.clone(); - let mut cmd = Command::new("sudo"); - cmd.args(["-E", "SUDO_UID=nan", &devlayer_bin]); + let mut cmd = Command::new(&devlayer_bin); + cmd.env("SUDO_UID", "nan"); cmd.args([format!("--join={}", &layer.name)]); + let mut cmd = as_root(&cmd); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); assert!( @@ -33,9 +34,10 @@ fn test_weird_sudo_env_variables(layer: LayerManager) -> Result<()> { .contains("Failed to parse SUDO_UID") ); - let mut cmd = Command::new("sudo"); - cmd.args(["-E", "SUDO_GID=nan", &devlayer_bin]); + let mut cmd = Command::new(&devlayer_bin); + cmd.env("SUDO_GID", "nan"); cmd.args([format!("--join={}", &layer.name)]); + let mut cmd = as_root(&cmd); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); assert!( @@ -43,9 +45,10 @@ fn test_weird_sudo_env_variables(layer: LayerManager) -> Result<()> { .contains("Failed to parse SUDO_GID") ); - let mut cmd = Command::new("sudo"); - cmd.args(["-E", "SUDO_HOME=", &devlayer_bin]); + let mut cmd = Command::new(&devlayer_bin); + cmd.env("SUDO_HOME", ""); cmd.args([format!("--join={}", &layer.name)]); + let mut cmd = as_root(&cmd); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); assert!( @@ -53,9 +56,10 @@ fn test_weird_sudo_env_variables(layer: LayerManager) -> Result<()> { .contains("Home directory is not absolute") ); - let mut cmd = Command::new("sudo"); - cmd.args(["-E", "SUDO_HOME=~/foobar", &devlayer_bin]); + let mut cmd = Command::new(&devlayer_bin); + cmd.env("SUDO_HOME", "~/foobar"); cmd.args([format!("--join={}", &layer.name)]); + let mut cmd = as_root(&cmd); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); @@ -64,9 +68,10 @@ fn test_weird_sudo_env_variables(layer: LayerManager) -> Result<()> { .contains("Home directory is not absolute") ); - let mut cmd = Command::new("sudo"); - cmd.args(["-E", "SUDO_HOME=/invalid-home-directory", &devlayer_bin]); + let mut cmd = Command::new(&devlayer_bin); + cmd.env("SUDO_HOME", "/invalid-home-directory"); cmd.args([format!("--join={}", &layer.name)]); + let mut cmd = as_root(&cmd); let output = cmd.output()?; assert!(output.status.code().unwrap() != 0); @@ -88,18 +93,11 @@ fn test_weird_sudo_env_variables(layer: LayerManager) -> Result<()> { absolute_dir_with_spaces.display() ); - let mut cmd = Command::new("sudo"); - cmd.args([ - "-E", - format!( - "DEVLAYER_STORAGE_DIR={}", - absolute_dir_with_spaces.display() - ) - .as_str(), - &devlayer_bin, - ]); + let mut cmd = Command::new(&devlayer_bin); + cmd.env("DEVLAYER_STORAGE_DIR", &absolute_dir_with_spaces); cmd.args([format!("--join={}", &layer.name)]); cmd.args(["true"]); + let mut cmd = as_root(&cmd); println!("cmd: {:?}", cmd); let output = cmd.output()?; println!("output: {}", String::from_utf8_lossy(&output.stdout)); From bdced3de6bca27616c52569cfa30ba4092ed36bd Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Sat, 14 Nov 2026 17:58:29 -0500 Subject: [PATCH 29/32] Wait for the supervisor to unmount in the idle shutdown test --- tests/ai_test_auto_shutdown.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/ai_test_auto_shutdown.rs b/tests/ai_test_auto_shutdown.rs index aaae19b..68d70ee 100644 --- a/tests/ai_test_auto_shutdown.rs +++ b/tests/ai_test_auto_shutdown.rs @@ -127,7 +127,10 @@ fn ai_test_idle_layer_shuts_down(mut layer: LayerManager) -> Result<()> { assert!(wait_until(Duration::from_secs(5), || { !pid_file(&layer).unwrap().exists() })); - assert!(!has_mounts(&layer)?); + // The supervisor removes the pid file before it unmounts the layer + assert!(wait_until(Duration::from_secs(5), || { + !has_mounts(&layer).unwrap() + })); assert!(!file.exists()); layer.run(&["list"])?; From 28e67cca8b416affe2986a9c71ee21d6e1ea3bf3 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Sat, 14 Nov 2026 21:17:16 -0500 Subject: [PATCH 30/32] Simplify config resolution and layer start, fix review findings - Resolve the storage dir once; record the layer name's source per branch - Store a single LayerOrigin in Config; skip loading it for new layers, so a concurrent launch's origin isn't picked up - Only remove an unparseable pid file while holding the layer lock, so list can't remove one that is being written - Share pid/lock path helpers between Layer and util - Pass only PID 1's pid from the supervisor; drop redundant setresuid/gid - config: report bind_cwd's real source, drop the no_bind_cwd key - Check accept/reject patterns before choosing the layer - Parse true/false env vars in one loop; bad values error, empty ignored - Make LLVM_PROFILE_FILE absolute in the Makefile, so the supervisor's coverage data lands in coverage/profraw - Fix flaky ai_test_limits_applied; share pid file helpers in the fixture --- Makefile | 10 +- src/actions/accept.rs | 6 - src/actions/config.rs | 7 +- src/actions/reject.rs | 6 - src/config/resolve.rs | 264 ++++++++++++++---------------- src/config/structs.rs | 7 +- src/layer/cgroup.rs | 2 +- src/layer/get_or_create.rs | 107 ++++-------- src/layer/layer_struct.rs | 7 +- src/layer/supervisor.rs | 14 +- src/main.rs | 1 + src/util/get_running_layer_pid.rs | 48 +++--- tests/ai_test_action_scope.rs | 23 +++ tests/ai_test_auto_shutdown.rs | 34 +--- tests/ai_test_cwd_bind.rs | 69 ++++---- tests/ai_test_env_bools.rs | 28 ++++ tests/ai_test_home_bind.rs | 18 +- tests/ai_test_layer_selection.rs | 3 +- tests/ai_test_layer_settings.rs | 6 +- tests/ai_test_pid_file_trust.rs | 8 +- tests/ai_test_resource_limits.rs | 21 +-- tests/ai_test_sigterm.rs | 9 +- tests/fixtures/fixture_layer.rs | 48 ++++-- tests/test_list.rs | 5 +- 24 files changed, 377 insertions(+), 374 deletions(-) create mode 100644 tests/ai_test_env_bools.rs diff --git a/Makefile b/Makefile index 0268234..90d1c3b 100644 --- a/Makefile +++ b/Makefile @@ -16,7 +16,7 @@ build-debug-with-setuid: build sudo chmod u+s target/debug/devlayer-setuid build-coverage-binary: - CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage' LLVM_PROFILE_FILE="coverage/profraw/cargo-test-%p-%m.profraw" cargo build --profile coverage --features coverage + CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage' LLVM_PROFILE_FILE="$(CURDIR)/coverage/profraw/cargo-test-%p-%m.profraw" cargo build --profile coverage --features coverage rm -f target/coverage/devlayer-setuid cp target/coverage/devlayer target/coverage/devlayer-setuid sudo chown root:root target/coverage/devlayer-setuid @@ -83,7 +83,7 @@ test: build-coverage-binary sudo rm --one-file-system -Rf coverage mkdir -p coverage/profraw sudo mkdir -p /run/media/devlayer-coverage-testing - RUST_BACKTRACE=1 CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage' LLVM_PROFILE_FILE="coverage/profraw/cargo-test-%p-%m.profraw" cargo test --profile coverage --features coverage -- --test-threads=1 + RUST_BACKTRACE=1 CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage' LLVM_PROFILE_FILE="$(CURDIR)/coverage/profraw/cargo-test-%p-%m.profraw" cargo test --profile coverage --features coverage -- --test-threads=1 coverage coverage-report: test update-coverage-report-and-show-json @@ -96,8 +96,8 @@ test-with-stop-all: build-coverage-binary @echo "### Running all tests including --ignored tests" sudo rm --one-file-system -Rf coverage mkdir -p coverage/profraw - RUST_BACKTRACE=1 CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage' LLVM_PROFILE_FILE="coverage/profraw/cargo-test-%p-%m.profraw" cargo test --profile coverage --features coverage -- --test-threads=1 - RUST_BACKTRACE=1 CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage' LLVM_PROFILE_FILE="coverage/profraw/cargo-test-%p-%m.profraw" cargo test --profile coverage --features coverage -- --test-threads=1 --ignored + RUST_BACKTRACE=1 CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage' LLVM_PROFILE_FILE="$(CURDIR)/coverage/profraw/cargo-test-%p-%m.profraw" cargo test --profile coverage --features coverage -- --test-threads=1 + RUST_BACKTRACE=1 CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage' LLVM_PROFILE_FILE="$(CURDIR)/coverage/profraw/cargo-test-%p-%m.profraw" cargo test --profile coverage --features coverage -- --test-threads=1 --ignored coverage-with-stop-all: test-with-stop-all update-coverage-report-and-show-json @@ -114,7 +114,7 @@ update-coverage-report: TEST ?= test_accept quick-test: build-coverage-binary # test_accept - RUST_BACKTRACE=1 CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage' LLVM_PROFILE_FILE="coverage/profraw/cargo-test-%p-%m.profraw" cargo test --profile coverage --features coverage -- --test-threads=1 \ + RUST_BACKTRACE=1 CARGO_INCREMENTAL=0 RUSTFLAGS='-Cinstrument-coverage' LLVM_PROFILE_FILE="$(CURDIR)/coverage/profraw/cargo-test-%p-%m.profraw" cargo test --profile coverage --features coverage -- --test-threads=1 \ $(TEST) make update-coverage-report diff --git a/src/actions/accept.rs b/src/actions/accept.rs index bd2b711..0251d0d 100644 --- a/src/actions/accept.rs +++ b/src/actions/accept.rs @@ -122,12 +122,6 @@ pub fn accept( ) -> Result<()> { trace!("Accepting changes from layer {}", layer.name); - if patterns.is_empty() { - return Err(anyhow::anyhow!( - "accept requires at least one pattern; use `devlayer accept /` to accept every change in the layer" - )); - } - let cwd = std::env::current_dir()?; let all_changes = layer.changes(config)?; diff --git a/src/actions/config.rs b/src/actions/config.rs index 63ad2fb..6b8d9af 100644 --- a/src/actions/config.rs +++ b/src/actions/config.rs @@ -17,7 +17,6 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { "mask", "no_default_binds", "no_default_llm_binds", - "no_bind_cwd", "bind_cwd", "created_in", "cpus", @@ -52,8 +51,7 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { let no_default_binds_str = format!("{}", config.no_default_binds); let no_default_llm_binds_str = format!("{}", config.no_default_llm_binds); - let bind_cwd_str = format!("{}", config.bind_cwd); - let no_bind_cwd_str = format!("{}", !config.bind_cwd); + let bind_cwd_str = format!("{}", config.origin.bind_cwd); let cpus_str = config .cpus .map_or("unlimited".to_string(), |cpus| cpus.to_string()); @@ -93,10 +91,9 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { ("no_default_llm_binds", no_default_llm_binds_str.as_str()) } "bind_cwd" => ("bind_cwd", bind_cwd_str.as_str()), - "no_bind_cwd" => ("no_bind_cwd", no_bind_cwd_str.as_str()), "created_in" => ( "created_in", - config.created_in.to_str().unwrap_or(""), + config.origin.created_in.to_str().unwrap_or(""), ), "cpus" => ("cpus", cpus_str.as_str()), "memory" => ("memory", memory_str.as_str()), diff --git a/src/actions/reject.rs b/src/actions/reject.rs index b7ce90d..46d3db8 100644 --- a/src/actions/reject.rs +++ b/src/actions/reject.rs @@ -14,12 +14,6 @@ pub fn reject( ) -> Result<()> { trace!("Rejecting changes from layer {}", layer.name); - if patterns.is_empty() { - return Err(anyhow::anyhow!( - "reject requires at least one pattern; use `devlayer reject /` to reject every change in the layer" - )); - } - let cwd = std::env::current_dir()?; let changes = layer.changes(config)?; diff --git a/src/config/resolve.rs b/src/config/resolve.rs index 760967b..a5929e1 100644 --- a/src/config/resolve.rs +++ b/src/config/resolve.rs @@ -132,18 +132,6 @@ pub fn resolve_config(cli: Args) -> Result { } } - if let Ok(ignored_env) = env::var("DEVLAYER_IGNORED") { - if let Ok(ignored_val) = bool::from_str(&ignored_env) { - partial_config.ignored = Some(ignored_val); - sources.insert("ignored".into(), "environment".into()); - } else { - return Err(anyhow::anyhow!( - "Invalid value for DEVLAYER_IGNORED: {}", - ignored_env - )); - } - } - // Bind mounts and masks from environment variables form a single layer let mut env_bind_layer = vec![]; if let Ok(bind_mounts_env) = env::var("DEVLAYER_BIND") { @@ -174,30 +162,31 @@ pub fn resolve_config(cli: Args) -> Result { } bind_layers.push(env_bind_layer); - if let Ok(no_default_binds_env) = env::var("DEVLAYER_NO_DEFAULT_BINDS") { - let no_default_binds_val = bool::from_str(&no_default_binds_env) - .expect("Invalid value for DEVLAYER_NO_DEFAULT_BINDS"); - partial_config.no_default_binds = Some(no_default_binds_val); - sources.insert("no_default_binds".into(), "environment".into()); - } - - if let Ok(value) = env::var("DEVLAYER_NO_DEFAULT_LLM_BINDS") { - let value = bool::from_str(&value).map_err(|_| { - anyhow::anyhow!( - "Invalid value for DEVLAYER_NO_DEFAULT_LLM_BINDS: {}", - value - ) - })?; - partial_config.no_default_llm_binds = Some(value); - sources.insert("no_default_llm_binds".into(), "environment".into()); - } - - if let Ok(value) = env::var("DEVLAYER_NO_BIND_CWD") { - let value = bool::from_str(&value).map_err(|_| { - anyhow::anyhow!("Invalid value for DEVLAYER_NO_BIND_CWD: {}", value) - })?; - partial_config.no_bind_cwd = Some(value); - sources.insert("no_bind_cwd".into(), "environment".into()); + for (var, key, field) in [ + ("DEVLAYER_IGNORED", "ignored", &mut partial_config.ignored), + ( + "DEVLAYER_NO_DEFAULT_BINDS", + "no_default_binds", + &mut partial_config.no_default_binds, + ), + ( + "DEVLAYER_NO_DEFAULT_LLM_BINDS", + "no_default_llm_binds", + &mut partial_config.no_default_llm_binds, + ), + ( + "DEVLAYER_NO_BIND_CWD", + "no_bind_cwd", + &mut partial_config.no_bind_cwd, + ), + ] { + if let Some(value) = env::var(var).ok().filter(|v| !v.is_empty()) { + let value = bool::from_str(&value).map_err(|_| { + anyhow::anyhow!("Invalid value for {}: {}", var, value) + })?; + *field = Some(value); + sources.insert(key.into(), "environment".into()); + } } for (var, key, field) in [ @@ -216,55 +205,45 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("log_level".into(), "cli".into()); } - // Set storage_dir first if provided via CLI, as it's needed for --new and --last + // Resolve storage_dir first, as choosing the layer needs it if let Some(storage_dir) = cli.storage_dir { partial_config.storage_dir = Some(storage_dir); sources.insert("storage_dir".into(), "cli".into()); } + let storage_dir = resolve_storage_dir( + partial_config.storage_dir, + uid_gid_home.uid, + uid_gid_home.gid, + )?; + if !sources.contains_key("storage_dir") { + sources.insert("storage_dir".into(), "default".into()); + } // Choose the layer. Explicit --new/--last/--join win, then a join from // the environment or a config file, then the default for the action. let cwd = std::env::current_dir()?; - let (selection, explicit) = if cli.new { - (LayerSelection::New, "cli --new") + let selection = if cli.new { + sources.insert("name".into(), "cli --new".into()); + LayerSelection::New } else if cli.last { - (LayerSelection::Last, "cli --last") - } else if let Some(name) = cli.join.clone() { - (LayerSelection::Join(name), "cli --join") - } else if let Some(name) = partial_config.join.take() { - (LayerSelection::Join(name), "") + sources.insert("name".into(), "cli --last".into()); + LayerSelection::Last + } else if let Some(name) = cli.join { + sources.insert("name".into(), "cli --join".into()); + LayerSelection::Join(name) + } else if let Some(name) = partial_config.join { + LayerSelection::Join(name) } else { - (default_selection(cli.action.as_ref()), "") + default_selection(cli.action.as_ref()) }; let new_layer = selection == LayerSelection::New; let name = match selection { LayerSelection::Join(name) => name, - LayerSelection::New => generate_timestamp_name(&resolve_storage_dir( - partial_config.storage_dir.clone(), - uid_gid_home.uid, - uid_gid_home.gid, - )?), - LayerSelection::Last => find_last_layer( - &resolve_storage_dir( - partial_config.storage_dir.clone(), - uid_gid_home.uid, - uid_gid_home.gid, - )?, - &cwd, - )?, - LayerSelection::LastOrNew => { - let storage_dir = resolve_storage_dir( - partial_config.storage_dir.clone(), - uid_gid_home.uid, - uid_gid_home.gid, - )?; - find_last_layer(&storage_dir, &cwd) - .unwrap_or_else(|_| generate_timestamp_name(&storage_dir)) - } + LayerSelection::New => generate_timestamp_name(&storage_dir), + LayerSelection::Last => find_last_layer(&storage_dir, &cwd)?, + LayerSelection::LastOrNew => find_last_layer(&storage_dir, &cwd) + .unwrap_or_else(|_| generate_timestamp_name(&storage_dir)), }; - if !explicit.is_empty() { - sources.insert("name".into(), explicit.into()); - } if let Some(net) = cli.net { partial_config.net = Some(net); @@ -361,15 +340,6 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("memory".into(), "default".into()); } - let storage_dir = resolve_storage_dir( - partial_config.storage_dir, - uid_gid_home.uid, - uid_gid_home.gid, - )?; - if !sources.contains_key("storage_dir") { - sources.insert("storage_dir".into(), "default".into()); - } - let layer_dir = storage_dir.join(name.clone()); if !sources.contains_key("layer_dir") { sources.insert("layer_dir".into(), "derived from storage_dir".into()); @@ -392,28 +362,54 @@ pub fn resolve_config(cli: Args) -> Result { .join(cwd.strip_prefix(&mp)?); sources.insert("overlay_cwd".into(), "derived from storage_dir".into()); - // The directory the layer was created in is bound just above the LLM binds - let (created_in, bind_cwd) = resolve_origin(&layer_dir, &cwd, no_bind_cwd)?; - sources.insert("created_in".into(), "layer settings or cwd".into()); - sources.insert("bind_cwd".into(), "layer settings or no_bind_cwd".into()); - let mut path_layers: Vec> = vec![]; - if bind_cwd { - path_layers.insert(0, vec![path_bind_mount(&created_in)?]); - } - - // LLM tool binds sit just above the default bind mounts - if !no_default_llm_binds { - path_layers.insert( - 0, - path_bind_mounts(get_llm_bind_mounts(&uid_gid_home.home))?, - ); - } + // Where a layer was created and whether that directory is bound are + // recorded when it's created, so entering it from another directory, or + // without --no-bind-cwd, doesn't change its binds. A new layer's name was + // free when it was generated, so an origin recorded under it belongs to a + // concurrent launch that took the name first. Binding / is refused when a + // layer starts, not here, so actions that don't start one work from /. + let recorded = if new_layer { + None + } else { + LayerOrigin::load(&layer_dir) + }; + let origin = match recorded { + Some(origin) => { + let path = LayerOrigin::path(&layer_dir).display().to_string(); + sources.insert("created_in".into(), path.clone()); + sources.insert("bind_cwd".into(), path); + origin + } + None => { + let no_bind_cwd_source = + sources.get("no_bind_cwd").cloned().unwrap_or_default(); + sources.insert("created_in".into(), "cwd".into()); + sources.insert("bind_cwd".into(), no_bind_cwd_source); + LayerOrigin { + created_in: cwd.canonicalize().context(format!( + "Failed to canonicalize current directory {}", + cwd.display() + ))?, + bind_cwd: !no_bind_cwd, + } + } + }; - // Default bind mounts, including audio, are the lowest precedence layer + // Below the config file, environment and CLI bind layers, from lowest to + // highest precedence: the default bind mounts including audio, the LLM + // tool binds, and the directory the layer was created in + let mut path_layers: Vec> = vec![]; if !no_default_binds { let mut default_binds = get_default_bind_mounts(&net); default_binds.extend(get_audio_bind_mounts()); - path_layers.insert(0, path_bind_mounts(default_binds)?); + path_layers.push(path_bind_mounts(default_binds)?); + } + if !no_default_llm_binds { + path_layers + .push(path_bind_mounts(get_llm_bind_mounts(&uid_gid_home.home))?); + } + if origin.bind_cwd { + path_layers.push(vec![path_bind_mount(&origin.created_in)?]); } // Resolve bind mounts layer by layer from lowest to highest precedence. @@ -426,10 +422,11 @@ pub fn resolve_config(cli: Args) -> Result { .collect::>>>()?; // Binding the home directory takes asking for it, e.g. with --bind=. - let cwd_bind_is_home = bind_cwd - && uid_gid_home.home.canonicalize().ok().as_ref() == Some(&created_in) + let cwd_bind_is_home = origin.bind_cwd + && uid_gid_home.home.canonicalize().ok().as_ref() + == Some(&origin.created_in) && !parsed_layers.iter().flatten().any(|mount| { - mount.target == created_in + mount.target == origin.created_in && mount.options != BindMountOptions::Mask }); @@ -478,8 +475,7 @@ pub fn resolve_config(cli: Args) -> Result { bind_mounts, no_default_binds, no_default_llm_binds, - created_in, - bind_cwd, + origin, cwd_bind_is_home, cpus, memory, @@ -539,31 +535,9 @@ fn get_default_bind_mounts(net: &Network) -> Vec { default_binds } -/// Returns the directory a layer was created in and whether that directory is -/// bound into the layer. An existing layer keeps the values recorded in its -/// settings when it was created, so re-entering it from another directory, or -/// without --no-bind-cwd, does not change its binds. A new layer uses `cwd`. -/// Binding / is refused when a layer starts, not here, so actions that don't -/// start a layer still work from /. -pub fn resolve_origin( - layer_dir: &Path, - cwd: &Path, - no_bind_cwd: bool, -) -> Result<(PathBuf, bool)> { - if let Some(origin) = LayerOrigin::load(layer_dir) { - return Ok((origin.created_in, origin.bind_cwd)); - } - - let created_in = cwd.canonicalize().context(format!( - "Failed to canonicalize current directory {}", - cwd.display() - ))?; - Ok((created_in, !no_bind_cwd)) -} - /// Well-known AI tool config and state paths, relative to the home directory, /// that are bound into layers by default unless --no-default-llm-binds is set -pub const LLM_BIND_PATHS: &[&str] = &[ +const LLM_BIND_PATHS: &[&str] = &[ ".claude", ".claude.json", ".codex", @@ -584,12 +558,11 @@ pub const LLM_BIND_PATHS: &[&str] = &[ ]; /// Returns the LLM_BIND_PATHS that exist under `home`, as absolute paths -fn get_llm_bind_mounts(home: &Path) -> Vec { +fn get_llm_bind_mounts(home: &Path) -> Vec { LLM_BIND_PATHS .iter() .map(|path| home.join(path)) .filter(|path| path.exists()) - .map(|path| path.display().to_string()) .collect() } @@ -965,7 +938,7 @@ pub(crate) fn generate_timestamp_name(storage_dir: &Path) -> String { /// How the layer to use is chosen #[derive(Debug, Clone, PartialEq)] -pub enum LayerSelection { +enum LayerSelection { /// A new layer with a generated `ephemeral_*` name New, /// The newest layer created in the cwd, or else in its nearest ancestor @@ -980,7 +953,7 @@ pub enum LayerSelection { /// The layer selection used when no --new, --last or --join is given and no /// join is set in the environment or a config file -pub fn default_selection(action: Option<&Action>) -> LayerSelection { +fn default_selection(action: Option<&Action>) -> LayerSelection { match action { None => LayerSelection::New, Some( @@ -1003,6 +976,22 @@ pub fn default_selection(action: Option<&Action>) -> LayerSelection { } } +/// Fails if the action is accept or reject without a pattern. Checked before +/// the layer is chosen, so the hint is given even where there's no layer. +pub fn require_patterns(action: Option<&Action>) -> Result<()> { + let (name, patterns) = match action { + Some(Action::Accept { patterns }) => ("accept", patterns), + Some(Action::Reject { patterns }) => ("reject", patterns), + _ => return Ok(()), + }; + if patterns.as_ref().is_none_or(|p| p.is_empty()) { + return Err(anyhow::anyhow!( + "{name} requires at least one pattern; use `devlayer {name} /` to {name} every change in the layer" + )); + } + Ok(()) +} + /// Finds the newest layer created in `cwd`, or else in the nearest ancestor /// of `cwd` that has layers. Layers without a recorded creation directory are /// ignored. @@ -1147,10 +1136,7 @@ mod tests { assert_eq!( get_llm_bind_mounts(&home), - vec![ - home.join(".claude.json").display().to_string(), - home.join(".codex").display().to_string(), - ] + vec![home.join(".claude.json"), home.join(".codex")] ); std::fs::remove_dir_all(&home).unwrap(); } @@ -1164,10 +1150,8 @@ mod tests { let binds = get_llm_bind_mounts(&home); assert_eq!(binds.len(), 17); - let expected: Vec = LLM_BIND_PATHS - .iter() - .map(|p| home.join(p).display().to_string()) - .collect(); + let expected: Vec = + LLM_BIND_PATHS.iter().map(|p| home.join(p)).collect(); assert_eq!(binds, expected); std::fs::remove_dir_all(&home).unwrap(); } @@ -1231,8 +1215,10 @@ mod tests { bind_mounts: vec![], no_default_binds: false, no_default_llm_binds: false, - created_in: PathBuf::from("/tmp"), - bind_cwd: false, + origin: LayerOrigin { + created_in: PathBuf::from("/tmp"), + bind_cwd: false, + }, cwd_bind_is_home: false, cpus: None, memory: None, diff --git a/src/config/structs.rs b/src/config/structs.rs index ad40654..2f4d1c6 100644 --- a/src/config/structs.rs +++ b/src/config/structs.rs @@ -1,5 +1,6 @@ use super::impls::deserialize_level_filter; use super::limits::deserialize_number_or_string; +use crate::layer::LayerOrigin; use anyhow::Result; use serde::{Deserialize, Serialize}; use std::{collections::HashMap, path::PathBuf}; @@ -85,10 +86,8 @@ pub struct Config { pub bind_mounts: Vec, pub no_default_binds: bool, pub no_default_llm_binds: bool, - /// Canonical directory the layer was created in - pub created_in: PathBuf, - /// Whether created_in is bound read-write into the layer - pub bind_cwd: bool, + /// Where the layer was created and whether that directory is bound + pub origin: LayerOrigin, /// Whether that would bind the home directory without a bind of it /// being asked for, which starting the layer refuses pub cwd_bind_is_home: bool, diff --git a/src/layer/cgroup.rs b/src/layer/cgroup.rs index 34ec33f..b0added 100644 --- a/src/layer/cgroup.rs +++ b/src/layer/cgroup.rs @@ -192,7 +192,7 @@ impl Layer { /// Removes a cgroup once the processes in it have exited, waiting a little /// while for that. Layer processes have already been killed by this point. -/// The only other processes in the cgroup are the `layer` commands waiting +/// The only other processes in the cgroup are the `devlayer` commands waiting /// on them, which exit by themselves once their child is gone, so they get to /// report its exit status instead of being killed too. pub(crate) fn remove_cgroup(path: &Path) { diff --git a/src/layer/get_or_create.rs b/src/layer/get_or_create.rs index 18f0da7..3c2de6a 100644 --- a/src/layer/get_or_create.rs +++ b/src/layer/get_or_create.rs @@ -3,17 +3,16 @@ use super::mount_overlays::MountHash; use super::supervisor; use crate::config::resolve::generate_timestamp_name; use crate::config::{BindMount, BindMountOptions, Config, Network}; -use crate::layer::{Layer, LayerOrigin}; +use crate::layer::Layer; #[cfg(feature = "coverage")] use crate::util::CLONE_FS; -use crate::util::get_layer_pid_path; use crate::util::{ CLONE_INTO_CGROUP, CLONE_NEWCGROUP, CLONE_NEWIPC, CLONE_NEWNET, CLONE_NEWNS, CLONE_NEWPID, CLONE_NEWUTS, Clone3Args, check_path_for_mount_option_compatibility, clone3, mkdir, mount, }; use crate::util::{Lock, SharedLock, write_no_follow}; -use crate::util::{get_running_layer_pid, layer_pid_file_contents}; +use crate::util::{get_running_layer_pid_or_remove, layer_pid_file_contents}; use anyhow::Context; use anyhow::{Result, anyhow}; use log::{error, trace}; @@ -64,6 +63,7 @@ impl Layer { Layer { name: layer_name.to_string(), + storage_dir: layers_storage_dir.to_path_buf(), base: layer_base_dir.clone(), work_base: work_base.clone(), upper_base: upper_base.clone(), @@ -106,8 +106,11 @@ impl Layer { } /* If we have an existing layer, return it */ - if let Some(pid) = get_running_layer_pid(layers_storage_dir, layer_name) - { + if let Some(pid) = get_running_layer_pid_or_remove( + &lock, + layers_storage_dir, + layer_name, + ) { let mut layer = Layer::from_location(layers_storage_dir, layer_name, uid, gid); layer.pid = pid; @@ -210,7 +213,8 @@ impl Layer { ), )?; - if config.bind_cwd && config.created_in == Path::new("/") { + if config.origin.bind_cwd && config.origin.created_in == Path::new("/") + { return Err(anyhow!( "Refusing to bind / into the layer; run from a project directory or pass --no-bind-cwd" )); @@ -235,12 +239,7 @@ impl Layer { .and_then(|overlay_mounts| { /* Create PID 1 for our layer */ layer - .start_layer( - &config, - &get_layer_pid_path(storage_dir, layer_name), - &overlay_mounts, - cgroup.as_ref(), - ) + .start_layer(&config, &overlay_mounts, cgroup.as_ref()) .map_err(|e| anyhow!("Failed to start layer: {}", e)) }); @@ -254,15 +253,9 @@ impl Layer { } }; - /* Record where the layer was created the first time it starts. A - * restarted layer keeps its original origin. */ - if !LayerOrigin::path(&layer.base).exists() { - LayerOrigin { - created_in: config.created_in.clone(), - bind_cwd: config.bind_cwd, - } - .save(&layer.base)?; - } + /* Record where the layer was created. A restarted layer was given + * the origin recorded when it was first started. */ + config.origin.save(&layer.base)?; Ok((layer, lock)) } @@ -272,13 +265,13 @@ impl Layer { * but stick around to allow future processes to be launched in the same namespaces. * * PID 1 is started by a supervisor process we fork first, which waits for - * PID 1 to exit and then cleans up after the layer. The supervisor reports - * back whether PID 1 is ready, followed by its pid. + * PID 1 to exit and then cleans up after the layer. The supervisor sends + * us PID 1's pid once PID 1 is ready, or exits without sending anything + * if PID 1 fails to start. */ fn start_layer( &self, config: &Config, - pid_file: &Path, overlay_mounts: &Vec, cgroup: Option<&OwnedFd>, ) -> Result { @@ -288,43 +281,28 @@ impl Layer { match unsafe { fork() }.context("failed to fork layer supervisor")? { ForkResult::Parent { child } => { drop(write_fd); - let mut buffer = [0; 5]; - let ready = std::fs::File::from(read_fd) - .read_exact(&mut buffer) - .is_ok() - && buffer[0] == 0; - if !ready { + let mut pid = [0; 4]; + if std::fs::File::from(read_fd).read_exact(&mut pid).is_err() { let _ = waitpid(child, None); return Err(anyhow!("Failed to setup layer")); } - let pid = i32::from_le_bytes([ - buffer[1], buffer[2], buffer[3], buffer[4], - ]); - Ok(Pid::from_raw(pid)) + Ok(Pid::from_raw(i32::from_le_bytes(pid))) } ForkResult::Child => { drop(read_fd); - let pid1 = self - .start_pid1(config, pid_file, overlay_mounts, cgroup) - .map_err(|e| { - error!("Failed to start layer: {:#}", e); - e - }); - let message = match &pid1 { - Ok((pid, _)) => { - let mut message = vec![0]; - message.extend(pid.as_raw().to_le_bytes()); - message - } - Err(_) => vec![1], - }; - let _ = nix::unistd::write(&write_fd, &message); - match pid1 { + match self.start_pid1(config, overlay_mounts, cgroup) { Ok((pid, lock)) => { + let _ = nix::unistd::write( + &write_fd, + &pid.as_raw().to_le_bytes(), + ); supervisor::detach(&lock); supervisor::supervise(self, pid, cgroup.is_some(), lock) } - Err(_) => std::process::exit(1), + Err(e) => { + error!("Failed to start layer: {:#}", e); + std::process::exit(1) + } } } } @@ -338,7 +316,6 @@ impl Layer { fn start_pid1( &self, config: &Config, - pid_file: &Path, overlay_mounts: &Vec, cgroup: Option<&OwnedFd>, ) -> Result<(Pid, SharedLock)> { @@ -390,8 +367,9 @@ impl Layer { drop(write_fd); // write pid to pid file, or else don't leave PID 1 behind + let pid_file = self.pid_path(); if let Err(e) = - write_no_follow(pid_file, layer_pid_file_contents(pid)) + write_no_follow(&pid_file, layer_pid_file_contents(pid)) { let _ = nix::sys::signal::kill(pid, Signal::SIGKILL); let _ = waitpid(pid, None); @@ -454,7 +432,7 @@ impl Layer { * could get at the layer, nor could we shut it down. */ supervisor::close_fds_except(&[write_fd.as_raw_fd(), lock.as_raw_fd()]); - /* Normalize credentials and dumpable state for pidfd-based setns(). + /* Restore our dumpable state for pidfd-based setns(). * * When another process uses pidfd_open + setns() to join our * namespaces, the kernel's ptrace_may_access() check verifies: @@ -462,23 +440,10 @@ impl Layer { * and gid/egid/sgid, or the caller has CAP_SYS_PTRACE. * 2. Our dumpable flag == SUID_DUMP_USER (1). * - * When launched via a setuid binary, we inherit ruid!=0 from the - * caller and dumpable=suid_dumpable (typically 2). Both cause - * ptrace_may_access to fail when CAP_SYS_PTRACE is unavailable. - * - * Fix: set all UIDs/GIDs to root and restore dumpable to 1. */ - nix::unistd::setresuid( - Uid::from_raw(0), - Uid::from_raw(0), - Uid::from_raw(0), - ) - .context("failed to normalize layer PID 1 UIDs to root")?; - nix::unistd::setresgid( - Gid::from_raw(0), - Gid::from_raw(0), - Gid::from_raw(0), - ) - .context("failed to normalize layer PID 1 GIDs to root")?; + * Our supervisor already set all its UIDs/GIDs to root, which we + * inherited, but changing them left dumpable at suid_dumpable + * (typically 2), which fails check 2 when CAP_SYS_PTRACE is + * unavailable. */ unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 1); } diff --git a/src/layer/layer_struct.rs b/src/layer/layer_struct.rs index d7b7e98..1e43ff9 100644 --- a/src/layer/layer_struct.rs +++ b/src/layer/layer_struct.rs @@ -1,3 +1,4 @@ +use crate::util::{get_layer_lock_path, get_layer_pid_path}; use nix::unistd::Gid; use nix::unistd::Pid; use nix::unistd::Uid; @@ -5,6 +6,8 @@ use std::path::PathBuf; pub struct Layer { pub name: String, + /// The storage directory the layer is in + pub storage_dir: PathBuf, pub base: PathBuf, pub work_base: PathBuf, pub upper_base: PathBuf, @@ -19,11 +22,11 @@ pub struct Layer { impl Layer { /// The pid file naming the layer's PID 1, next to the layer's directory pub fn pid_path(&self) -> PathBuf { - PathBuf::from(format!("{}.pid", self.base.display())) + get_layer_pid_path(&self.storage_dir, &self.name) } /// The layer's lock file, next to the layer's directory pub fn lock_path(&self) -> PathBuf { - PathBuf::from(format!("{}.lock", self.base.display())) + get_layer_lock_path(&self.storage_dir, &self.name) } } diff --git a/src/layer/supervisor.rs b/src/layer/supervisor.rs index 98ed0ce..a57228e 100644 --- a/src/layer/supervisor.rs +++ b/src/layer/supervisor.rs @@ -11,17 +11,17 @@ use crate::layer::Layer; use crate::layer::cgroup::remove_cgroup; -use crate::util::{SharedLock, get_running_layer_pid}; +use crate::util::{SharedLock, get_running_layer_pid_or_remove}; use anyhow::{Context, Result}; use log::trace; use nix::sys::wait::waitpid; use nix::unistd::{Gid, Pid, Uid, setresgid, setresuid, setsid}; use std::os::fd::{AsRawFd, RawFd}; -use std::path::Path; /// Detaches the current (freshly forked) process from the caller's session /// and makes it fully root, so the user can't signal it and it survives the -/// user's terminal going away. +/// user's terminal going away. PID 1, which we start, inherits being fully +/// root, which joining the layer with pidfd setns() requires. pub(super) fn become_supervisor() -> Result<()> { setsid().context("failed to create a session for the layer supervisor")?; setresuid(Uid::from_raw(0), Uid::from_raw(0), Uid::from_raw(0)) @@ -83,18 +83,18 @@ pub(super) fn supervise( } fn cleanup(layer: &Layer, own_cgroup: bool, lock: SharedLock) -> Result<()> { - let storage_dir = layer.base.parent().unwrap_or(Path::new("/")); - /* When PID 1 shut the layer down, it left us holding the lock already. * Without a lock file the layer was deleted, which already stopped and * unmounted it. */ - let Some(_lock) = lock.lock()? else { + let Some(lock) = lock.lock()? else { return Ok(()); }; /* If the pid file names a running PID 1, the layer was restarted, so * leave the new instance alone. Otherwise this removes the pid file. */ - if get_running_layer_pid(storage_dir, &layer.name).is_some() { + if get_running_layer_pid_or_remove(&lock, &layer.storage_dir, &layer.name) + .is_some() + { return Ok(()); } diff --git a/src/main.rs b/src/main.rs index 0564c96..080afd7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -50,6 +50,7 @@ pub fn main() -> Result<()> { logger.set_level(log::LevelFilter::Info); }; + config::resolve::require_patterns(cli.action.as_ref())?; let config = resolve_config(cli.clone()).context("Resolving config")?; let uid_gid_home = resolve_uid_gid_home().context("Resolving uid/gid/home")?; diff --git a/src/util/get_running_layer_pid.rs b/src/util/get_running_layer_pid.rs index f44e478..44cf54b 100644 --- a/src/util/get_running_layer_pid.rs +++ b/src/util/get_running_layer_pid.rs @@ -4,6 +4,8 @@ use std::path::PathBuf; use log::trace; +use super::Lock; + /** * Get the PID 1 of a running layer, from its pid file. * @@ -12,42 +14,50 @@ use log::trace; * e.g. after a reboot, may name an unrelated process, which we must not * kill everything alongside of or run commands next to. * - * Returns None, removing the pid file, if the layer is not running. + * Returns None if the layer is not running. Without the layer lock, a pid + * file that's being written may read as not running. */ pub fn get_running_layer_pid( layers_storage_dir: &Path, layer_name: &str, ) -> Option { let pid_file = get_layer_pid_path(layers_storage_dir, layer_name); - if !pid_file.exists() { - return None; - } - - let pid = std::fs::read_to_string(&pid_file) - .ok() - .and_then(|contents| { - let mut fields = contents.split_whitespace(); - let pid = Pid::from_raw(fields.next()?.parse().ok()?); - let start_time = fields.next()?.parse::().ok()?; - let (state, started) = process_state_and_start_time(pid)?; - (started == start_time - && state != "Z" - && state != "T" - && is_namespace_init(pid)) - .then_some(pid) - }); + let contents = std::fs::read_to_string(pid_file).ok()?; + let mut fields = contents.split_whitespace(); + let pid = Pid::from_raw(fields.next()?.parse().ok()?); + let start_time = fields.next()?.parse::().ok()?; + let (state, started) = process_state_and_start_time(pid)?; + (started == start_time + && state != "Z" + && state != "T" + && is_namespace_init(pid)) + .then_some(pid) +} +/** + * Like get_running_layer_pid, but removes the pid file if the layer is not + * running. Only safe while holding the layer's `_lock`, as otherwise the + * pid file may be one that's still being written. + */ +pub fn get_running_layer_pid_or_remove( + _lock: &Lock, + layers_storage_dir: &Path, + layer_name: &str, +) -> Option { + let pid = get_running_layer_pid(layers_storage_dir, layer_name); + let pid_file = get_layer_pid_path(layers_storage_dir, layer_name); match pid { Some(pid) => { trace!("Existing layer '{}' found with PID: {}", layer_name, pid); } - None => { + None if pid_file.exists() => { trace!( "Layer '{}' isn't running, removing its pid file", layer_name ); std::fs::remove_file(&pid_file).ok(); } + None => {} } pid } diff --git a/tests/ai_test_action_scope.rs b/tests/ai_test_action_scope.rs index 1dbf8fe..8c5845c 100644 --- a/tests/ai_test_action_scope.rs +++ b/tests/ai_test_action_scope.rs @@ -90,3 +90,26 @@ fn ai_test_reject_requires_pattern(mut layer: LayerManager) -> Result<()> { assert!(layer.last_stdout.contains("scope-reject-file")); Ok(()) } + +/// Without a pattern, accept and reject say how to accept or reject +/// everything, even from a directory that has no layer to default to +#[rstest] +fn ai_test_pattern_hint_without_layer(mut layer: LayerManager) -> Result<()> { + let dir = std::env::temp_dir().join(format!("devlayer-coverage-{}", rid())); + std::fs::create_dir_all(&dir)?; + // No --join, so --last would apply + layer.no_default_options = true; + layer.cwd = Some(dir.clone()); + for action in ["accept", "reject"] { + assert!(layer.xfail(&[action])); + assert!( + layer + .last_stderr + .contains(&format!("use `devlayer {} /`", action)), + "{}", + layer.last_stderr + ); + } + std::fs::remove_dir_all(&dir)?; + Ok(()) +} diff --git a/tests/ai_test_auto_shutdown.rs b/tests/ai_test_auto_shutdown.rs index 68d70ee..cc6a949 100644 --- a/tests/ai_test_auto_shutdown.rs +++ b/tests/ai_test_auto_shutdown.rs @@ -1,6 +1,6 @@ mod fixtures; -use anyhow::{Result, anyhow}; +use anyhow::Result; use fixtures::*; use nix::fcntl::{Flock, FlockArg}; use rstest::*; @@ -9,15 +9,9 @@ use std::path::PathBuf; use std::process::Command; use std::time::{Duration, Instant}; -/// The layer's pid file, `/.pid` -fn pid_file(layer: &LayerManager) -> Result { - Ok(PathBuf::from(format!("{}.pid", layer.dir()?.display()))) -} - /// PID 1 of the layer, if its pid file names a live process fn layer_pid(layer: &LayerManager) -> Option { - let pid = std::fs::read_to_string(pid_file(layer).ok()?).ok()?; - let pid = pid.split_whitespace().next()?.parse::().ok()?; + let pid = layer.pid1().ok()?; PathBuf::from(format!("/proc/{}", pid)) .exists() .then_some(pid) @@ -48,18 +42,6 @@ fn wait_until(timeout: Duration, mut f: impl FnMut() -> bool) -> bool { } } -/// The parent pid of `pid` -fn ppid_of(pid: i32) -> Result { - let status = std::fs::read_to_string(format!("/proc/{}/status", pid))?; - status - .lines() - .find_map(|line| line.strip_prefix("PPid:")) - .ok_or_else(|| anyhow!("no PPid line for {}", pid))? - .trim() - .parse::() - .map_err(Into::into) -} - /// When PID 1 dies, the supervisor unmounts the layer and removes its pid file #[rstest] fn ai_test_supervisor_cleans_up_after_pid1_exit( @@ -72,7 +54,7 @@ fn ai_test_supervisor_cleans_up_after_pid1_exit( .args(["kill", "-KILL", &pid.to_string()]) .status()?; assert!(wait_until(Duration::from_secs(5), || { - !pid_file(&layer).unwrap().exists() + !layer.pid_file().unwrap().exists() })); assert!(wait_until(Duration::from_secs(5), || { !has_mounts(&layer).unwrap() @@ -125,7 +107,7 @@ fn ai_test_idle_layer_shuts_down(mut layer: LayerManager) -> Result<()> { let file = std::env::current_dir()?.join(&name); layer.run(&["touch", file.to_str().unwrap_or_default()])?; assert!(wait_until(Duration::from_secs(5), || { - !pid_file(&layer).unwrap().exists() + !layer.pid_file().unwrap().exists() })); // The supervisor removes the pid file before it unmounts the layer assert!(wait_until(Duration::from_secs(5), || { @@ -155,7 +137,7 @@ fn ai_test_background_process_keeps_layer_up( assert!(layer_pid(&layer).is_some()); layer.run(&["pkill", "-f", "sleep 3600"])?; assert!(wait_until(Duration::from_secs(5), || { - !pid_file(&layer).unwrap().exists() + !layer.pid_file().unwrap().exists() })); Ok(()) } @@ -203,8 +185,8 @@ fn ai_test_supervisor_leaves_restarted_layer( other.hold()?; let pid = layer_pid(&layer).expect("layer should be running"); assert!(layer_pid(&other).is_some(), "other layer should be running"); - let other_pid_file = std::fs::read_to_string(pid_file(&other)?)?; - let pid_file = pid_file(&layer)?; + let other_pid_file = std::fs::read_to_string(other.pid_file()?)?; + let pid_file = layer.pid_file()?; let lock_file = format!("{}.lock", layer.dir()?.display()); // Hold the layer lock so the supervisor waits to clean up, as it would @@ -262,7 +244,7 @@ fn ai_test_layer_waits_for_starting_command( fn ai_test_killed_launch_lets_layer_shut_down( layer: LayerManager, ) -> Result<()> { - let pid_file = pid_file(&layer)?; + let pid_file = layer.pid_file()?; // The setuid binary rather than sudo, so we kill the launch itself let mut launch = Command::new(format!("{}-setuid", layer.devlayer_bin)) .args([ diff --git a/tests/ai_test_cwd_bind.rs b/tests/ai_test_cwd_bind.rs index 521a12d..c39a838 100644 --- a/tests/ai_test_cwd_bind.rs +++ b/tests/ai_test_cwd_bind.rs @@ -16,16 +16,14 @@ fn project_dir(layer: &LayerManager) -> Result { /// default (on) fn layer_in(dir: &Path) -> LayerManager { let mut layer = LayerManager::new(); - layer.set_bind_cwd(true); - layer.cwd = Some(dir.to_path_buf()); + layer.bind_cwd_in(dir); layer } #[rstest] fn ai_test_cwd_bound_by_default(mut layer: LayerManager) -> Result<()> { let dir = project_dir(&layer)?; - layer.set_bind_cwd(true); - layer.cwd = Some(dir.clone()); + layer.bind_cwd_in(&dir); layer.run(&["touch", "cwd-bound-file"])?; @@ -63,8 +61,7 @@ fn ai_test_no_bind_cwd_flag_env_config(layer: LayerManager) -> Result<()> { #[rstest] fn ai_test_refuse_root(mut layer: LayerManager) -> Result<()> { - layer.set_bind_cwd(true); - layer.cwd = Some(PathBuf::from("/")); + layer.bind_cwd_in(Path::new("/")); assert!(layer.xfail(&["true"])); assert!(layer.last_stderr.contains( @@ -79,27 +76,10 @@ fn ai_test_refuse_root(mut layer: LayerManager) -> Result<()> { Ok(()) } -#[rstest] -fn ai_test_home_allowed(mut layer: LayerManager) -> Result<()> { - let home = PathBuf::from(std::env::var("HOME")?); - layer.set_bind_cwd(true); - layer.cwd = Some(home.clone()); - - layer.run(&["config", "bind_cwd"])?; - assert_eq!(layer.last_stdout.trim(), "true"); - layer.run(&["config", "created_in"])?; - assert_eq!( - layer.last_stdout.trim(), - home.canonicalize()?.display().to_string() - ); - Ok(()) -} - #[rstest] fn ai_test_cwd_bind_reenter_from_subdir(mut layer: LayerManager) -> Result<()> { let dir = project_dir(&layer)?; - layer.set_bind_cwd(true); - layer.cwd = Some(dir.clone()); + layer.bind_cwd_in(&dir); layer.run(&["true"])?; // Entering the running layer from a subdirectory keeps the original bind @@ -114,8 +94,7 @@ fn ai_test_cwd_bind_reenter_from_subdir(mut layer: LayerManager) -> Result<()> { #[rstest] fn ai_test_restart_keeps_origin(mut layer: LayerManager) -> Result<()> { let dir = project_dir(&layer)?; - layer.set_bind_cwd(true); - layer.cwd = Some(dir.clone()); + layer.bind_cwd_in(&dir); layer.run(&["true"])?; layer.run(&["stop"])?; @@ -131,8 +110,7 @@ fn ai_test_restart_keeps_origin(mut layer: LayerManager) -> Result<()> { #[rstest] fn ai_test_no_bind_cwd_persists(mut layer: LayerManager) -> Result<()> { let dir = project_dir(&layer)?; - layer.set_bind_cwd(true); - layer.cwd = Some(dir.clone()); + layer.bind_cwd_in(&dir); layer.run(&["--no-bind-cwd", "true"])?; // Re-entering without the flag keeps the layer's original choice @@ -147,8 +125,7 @@ fn ai_test_no_bind_cwd_persists(mut layer: LayerManager) -> Result<()> { /// bound. #[rstest] fn ai_test_root_non_creating_actions_ok(mut layer: LayerManager) -> Result<()> { - layer.set_bind_cwd(true); - layer.cwd = Some(PathBuf::from("/")); + layer.bind_cwd_in(Path::new("/")); assert!(layer.pass(&["list"])); assert!(layer.pass(&["config", "name"])); Ok(()) @@ -160,8 +137,7 @@ fn ai_test_root_non_creating_actions_ok(mut layer: LayerManager) -> Result<()> { fn ai_test_cwd_with_colon(mut layer: LayerManager) -> Result<()> { let dir = std::env::current_dir()?.join(layer.test_filename("proj:v2")); std::fs::create_dir_all(&dir)?; - layer.set_bind_cwd(true); - layer.cwd = Some(dir.clone()); + layer.bind_cwd_in(&dir); layer.run(&["touch", "colon-file"])?; assert!(dir.join("colon-file").exists()); @@ -176,8 +152,7 @@ fn ai_test_origin_not_writable_from_layer( mut layer: LayerManager, ) -> Result<()> { let dir = project_dir(&layer)?; - layer.set_bind_cwd(true); - layer.cwd = Some(dir.clone()); + layer.bind_cwd_in(&dir); layer.run(&["--no-bind-cwd", "true"])?; let settings = layer.dir()?.join("data").join("settings.json"); @@ -194,3 +169,29 @@ fn ai_test_origin_not_writable_from_layer( assert_eq!(layer.last_stdout.trim(), "false"); Ok(()) } + +/// `config` reports where bind_cwd comes from: the setting for a layer +/// that doesn't exist yet, and the recorded origin once it does +#[rstest] +fn ai_test_bind_cwd_source(mut layer: LayerManager) -> Result<()> { + let dir = project_dir(&layer)?; + layer.bind_cwd_in(&dir); + layer.run(&["--no-bind-cwd", "config", "bind_cwd"])?; + assert!( + layer.last_stderr.contains("bind_cwd=false set from cli"), + "{}", + layer.last_stderr + ); + + layer.run(&["true"])?; + layer.run(&["--no-bind-cwd", "config", "bind_cwd"])?; + let origin = layer.dir()?.join("origin.json"); + assert!( + layer + .last_stderr + .contains(&format!("bind_cwd=true set from {}", origin.display())), + "{}", + layer.last_stderr + ); + Ok(()) +} diff --git a/tests/ai_test_env_bools.rs b/tests/ai_test_env_bools.rs new file mode 100644 index 0000000..6903016 --- /dev/null +++ b/tests/ai_test_env_bools.rs @@ -0,0 +1,28 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use rstest::*; + +/// A true/false environment variable with any other value is an error, and +/// an empty one is ignored like other empty environment variables +#[rstest] +#[case("DEVLAYER_IGNORED")] +#[case("DEVLAYER_NO_DEFAULT_BINDS")] +#[case("DEVLAYER_NO_DEFAULT_LLM_BINDS")] +#[case("DEVLAYER_NO_BIND_CWD")] +fn ai_test_env_bool_values( + mut layer: LayerManager, + #[case] var: &str, +) -> Result<()> { + assert!(layer.exfail(&["config", "name"], var, "cow")); + assert!( + layer + .last_stderr + .contains(&format!("Invalid value for {}: cow", var)), + "{}", + layer.last_stderr + ); + assert!(layer.epass(&["config", "name"], var, "")); + Ok(()) +} diff --git a/tests/ai_test_home_bind.rs b/tests/ai_test_home_bind.rs index 34efbe0..148af73 100644 --- a/tests/ai_test_home_bind.rs +++ b/tests/ai_test_home_bind.rs @@ -3,13 +3,12 @@ mod fixtures; use anyhow::Result; use fixtures::*; use rstest::*; -use std::path::PathBuf; +use std::path::Path; /// A layer manager that runs from the home directory with the cwd bind on, /// as a user starting devlayer from `~` would fn from_home(mut layer: LayerManager) -> Result { - layer.set_bind_cwd(true); - layer.cwd = Some(PathBuf::from(std::env::var("HOME")?)); + layer.bind_cwd_in(Path::new(&std::env::var("HOME")?)); Ok(layer) } @@ -50,3 +49,16 @@ fn ai_test_home_without_cwd_bind(layer: LayerManager) -> Result<()> { assert!(layer.pass(&["--no-bind-cwd", "true"])); Ok(()) } + +/// `config`, which doesn't start a layer, reports that a layer created in +/// the home directory would bind it +#[rstest] +fn ai_test_home_config_reports_cwd_bind(layer: LayerManager) -> Result<()> { + let mut layer = from_home(layer)?; + layer.run(&["config", "bind_cwd"])?; + assert_eq!(layer.last_stdout.trim(), "true"); + layer.run(&["config", "created_in"])?; + let home = Path::new(&std::env::var("HOME")?).canonicalize()?; + assert_eq!(layer.last_stdout.trim(), home.display().to_string()); + Ok(()) +} diff --git a/tests/ai_test_layer_selection.rs b/tests/ai_test_layer_selection.rs index 343a8e5..602e980 100644 --- a/tests/ai_test_layer_selection.rs +++ b/tests/ai_test_layer_selection.rs @@ -26,11 +26,10 @@ impl Selection { let mut layer = layer; // No --join, so the default selection applies layer.no_default_options = true; - layer.set_bind_cwd(true); let root = std::env::temp_dir() .join(format!("devlayer-coverage-sel-{}", rid())); std::fs::create_dir_all(&root)?; - layer.cwd = Some(root.clone()); + layer.bind_cwd_in(&root); layer.run(&["--new", "config", "storage_dir"])?; let storage = PathBuf::from(layer.last_stdout.trim()); let mut sel = Self { diff --git a/tests/ai_test_layer_settings.rs b/tests/ai_test_layer_settings.rs index febeec7..49f0abd 100644 --- a/tests/ai_test_layer_settings.rs +++ b/tests/ai_test_layer_settings.rs @@ -29,8 +29,10 @@ fn create_test_config() -> ::devlayer::config::Config { bind_mounts: Vec::new(), no_default_binds: false, no_default_llm_binds: false, - created_in: PathBuf::from("/tmp"), - bind_cwd: false, + origin: ::devlayer::layer::LayerOrigin { + created_in: PathBuf::from("/tmp"), + bind_cwd: false, + }, cwd_bind_is_home: false, cpus: None, memory: None, diff --git a/tests/ai_test_pid_file_trust.rs b/tests/ai_test_pid_file_trust.rs index f02e2cf..8bce811 100644 --- a/tests/ai_test_pid_file_trust.rs +++ b/tests/ai_test_pid_file_trust.rs @@ -3,14 +3,12 @@ mod fixtures; use anyhow::Result; use fixtures::*; use rstest::*; -use std::path::PathBuf; use std::process::Command; /// Writes `contents` to the layer's pid file, as a stale or mistaken pid /// file would have them fn write_pid_file(layer: &LayerManager, contents: &str) -> Result<()> { - let pid_file = format!("{}.pid", layer.dir()?.display()); - std::fs::write(PathBuf::from(pid_file), contents)?; + std::fs::write(layer.pid_file()?, contents)?; Ok(()) } @@ -42,9 +40,7 @@ fn ai_test_pid_file_with_wrong_start_time( ) -> Result<()> { let mut other = LayerManager::new(); other.hold()?; - let other_pid_file = format!("{}.pid", other.dir()?.display()); - let contents = std::fs::read_to_string(other_pid_file)?; - let other_pid = contents.split_whitespace().next().unwrap_or_default(); + let other_pid = other.pid1()?; layer.run(&["true"])?; layer.run(&["stop"])?; diff --git a/tests/ai_test_resource_limits.rs b/tests/ai_test_resource_limits.rs index 5e3dae2..7eacbc0 100644 --- a/tests/ai_test_resource_limits.rs +++ b/tests/ai_test_resource_limits.rs @@ -221,12 +221,14 @@ fn ai_test_limits_applied(mut layer: LayerManager) -> Result<()> { // Processes that join the running layer are in its cgroup too layer.hold_with(&args)?; let cgroup = host_cgroup(&layer).expect("layer cgroup should exist"); + let procs = cgroup.join("cgroup.procs"); + // PID 1 and the process holding the layer up + let held = fs::read_to_string(&procs)?.lines().count(); let mut child = layer.run_in_background(&[args[0], args[1], "sleep", "30"])?; let mut joined = false; for _ in 0..100 { - let procs = fs::read_to_string(cgroup.join("cgroup.procs"))?; - if procs.lines().count() > 1 { + if fs::read_to_string(&procs)?.lines().count() > held { joined = true; break; } @@ -337,19 +339,10 @@ fn ai_test_limits_stale_cgroup(mut layer: LayerManager) -> Result<()> { // Kill the layer and its supervisor without cleaning up, leaving an // empty cgroup behind let cgroup = host_cgroup(&layer).expect("layer cgroup should exist"); - layer.run(&["config", "layer_dir"])?; - let pid_file = format!("{}.pid", layer.last_stdout.trim()); - let pid = fs::read_to_string(&pid_file)?; - let pid = pid.split_whitespace().next().unwrap_or_default(); - let status = fs::read_to_string(format!("/proc/{}/status", pid))?; - let supervisor = status - .lines() - .find_map(|line| line.strip_prefix("PPid:")) - .unwrap_or_default() - .trim() - .to_string(); + let pid = layer.pid1()?; + let supervisor = ppid_of(pid)?; std::process::Command::new("sudo") - .args(["kill", "-9", &supervisor, pid.trim()]) + .args(["kill", "-9", &supervisor.to_string(), &pid.to_string()]) .status()?; for _ in 0..100 { if fs::read_to_string(cgroup.join("cgroup.procs"))?.is_empty() { diff --git a/tests/ai_test_sigterm.rs b/tests/ai_test_sigterm.rs index ae2cb96..842e1f6 100644 --- a/tests/ai_test_sigterm.rs +++ b/tests/ai_test_sigterm.rs @@ -10,14 +10,7 @@ use std::time::{Duration, Instant}; fn ai_test_sigterm_stops_layer(mut layer: LayerManager) -> Result<()> { layer.hold()?; - layer.run(&["config", "layer_dir"])?; - let pid_file = format!("{}.pid", layer.last_stdout.trim()); - let pid = std::fs::read_to_string(&pid_file)?; - let pid = pid - .split_whitespace() - .next() - .unwrap_or_default() - .to_string(); + let pid = layer.pid1()?.to_string(); let proc_dir = format!("/proc/{}", pid); assert!(Path::new(&proc_dir).exists()); diff --git a/tests/fixtures/fixture_layer.rs b/tests/fixtures/fixture_layer.rs index 98092f1..6b5db19 100644 --- a/tests/fixtures/fixture_layer.rs +++ b/tests/fixtures/fixture_layer.rs @@ -89,6 +89,19 @@ pub fn as_root(cmd: &Command) -> Command { sudo } +/// The parent pid of `pid` +#[allow(dead_code)] +pub fn ppid_of(pid: i32) -> Result { + let status = std::fs::read_to_string(format!("/proc/{}/status", pid))?; + status + .lines() + .find_map(|line| line.strip_prefix("PPid:")) + .ok_or_else(|| anyhow::anyhow!("no PPid line for {}", pid))? + .trim() + .parse::() + .map_err(Into::into) +} + pub struct LayerManager { pub name: String, pub last_stdout: String, @@ -141,10 +154,12 @@ impl LayerManager { } } - /* Controls whether --no-bind-cwd is automatically added to commands */ + /// Runs commands from `dir` with the cwd bind on, as a user starting + /// devlayer in `dir` would #[allow(dead_code)] - pub fn set_bind_cwd(&mut self, bind_cwd: bool) { - self.bind_cwd = bind_cwd; + pub fn bind_cwd_in(&mut self, dir: &Path) { + self.bind_cwd = true; + self.cwd = Some(dir.to_path_buf()); } /// Adds --no-bind-cwd unless the test opted in to the cwd bind or passes @@ -160,18 +175,10 @@ impl LayerManager { if self.no_sudo { cmd } else { as_root(&cmd) } } - /// Applies the configured working directory to a command. A relative - /// LLVM_PROFILE_FILE is made absolute so coverage data from commands run - /// elsewhere still lands in this repository. + /// Applies the configured working directory to a command fn apply_cwd(&self, cmd: &mut Command) { if let Some(cwd) = &self.cwd { cmd.current_dir(cwd); - if let (Ok(profile), Ok(here)) = - (std::env::var("LLVM_PROFILE_FILE"), std::env::current_dir()) - && Path::new(&profile).is_relative() - { - cmd.env("LLVM_PROFILE_FILE", here.join(profile)); - } } } @@ -202,6 +209,23 @@ impl LayerManager { Ok(PathBuf::from(base)) } + /// The pid file naming the layer's PID 1, next to the layer's directory + #[allow(dead_code)] + pub fn pid_file(&self) -> Result { + Ok(PathBuf::from(format!("{}.pid", self.dir()?.display()))) + } + + /// The layer's PID 1, as its pid file records it + #[allow(dead_code)] + pub fn pid1(&self) -> Result { + let contents = std::fs::read_to_string(self.pid_file()?)?; + Ok(contents + .split_whitespace() + .next() + .unwrap_or_default() + .parse()?) + } + #[allow(dead_code)] pub fn test_filename(&self, prefix: &str) -> String { format!( diff --git a/tests/test_list.rs b/tests/test_list.rs index 1cbe12d..d2b6d09 100644 --- a/tests/test_list.rs +++ b/tests/test_list.rs @@ -67,8 +67,9 @@ fn test_list_ignore_bad_pid_file(mut layer: LayerManager) -> Result<()> { assert!(layer.run(&["list"]).is_ok()); // still expected to be listed assert!(layer.all_stdout.contains("coverage_test_bad_pid_file")); - // and listing it cleans up the bad pid file - assert!(!Path::new(&pid_file_name).exists()); + // but listing doesn't hold the layer lock, so it leaves the pid file + // alone, as it might be one that's being written + assert!(Path::new(&pid_file_name).exists()); std::fs::remove_file(&lock_file_name)?; From 341861e217fff90e92bd6225ab14acfb618bccf5 Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Sat, 14 Nov 2026 23:05:52 -0500 Subject: [PATCH 31/32] Make head an OOM victim before devlayer in the memory limit test After tail is OOM-killed, head can still be writing to the pipe before tail's memory is freed, which triggers a second OOM kill. With head at the default oom_score_adj, that second kill took the waiting devlayer command, so the test got no exit status (about 1 in 40 runs under load). --- tests/ai_test_resource_limits.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/ai_test_resource_limits.rs b/tests/ai_test_resource_limits.rs index 7eacbc0..8caabcd 100644 --- a/tests/ai_test_resource_limits.rs +++ b/tests/ai_test_resource_limits.rs @@ -269,13 +269,16 @@ fn ai_test_limits_memory_enforced(mut layer: LayerManager) -> Result<()> { // The devlayer command waiting on the shell is in the cgroup too, so tail // raises its own oom_score_adj to always be the OOM killer's first // choice; otherwise the kernel may kill devlayer instead and we get no - // exit status. memory.events is read in the same command so we see this - // cgroup's counters. + // exit status. head does too: it can still be writing to the pipe after + // tail is killed but before tail's memory is freed, which can trigger a + // second OOM kill. memory.events is read in the same command so we see + // this cgroup's counters. layer.run(&[ "--memory=32M", "sh", "-c", - "head -c 256M /dev/zero \ + "sh -c 'echo 1000 > /proc/self/oom_score_adj \ + && exec head -c 256M /dev/zero' \ | sh -c 'echo 1000 > /proc/self/oom_score_adj && exec tail' \ > /dev/null; \ echo \"tail exited with $?\"; \ From edd71ec5adf716660d071d8c255a22e665e8e75a Mon Sep 17 00:00:00 2001 From: Akita Noek Date: Sun, 15 Nov 2026 06:56:44 -0500 Subject: [PATCH 32/32] Name the mount point when lstat of a scanned mount fails --- src/layer/mount_overlays.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/layer/mount_overlays.rs b/src/layer/mount_overlays.rs index 8d2e5fd..a447241 100644 --- a/src/layer/mount_overlays.rs +++ b/src/layer/mount_overlays.rs @@ -40,7 +40,8 @@ impl Layer { let dir = &mount_entry.dir; // Get the uid/gid of the source directory - let source_stat = nix::sys::stat::lstat(dir.as_str())?; + let source_stat = nix::sys::stat::lstat(dir.as_str()) + .context(format!("lstat {}", dir))?; let source_uid = Uid::from_raw(source_stat.st_uid); let source_gid = Gid::from_raw(source_stat.st_gid);