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..aa5b716 100644 --- a/.gitignore +++ b/.gitignore @@ -7,8 +7,9 @@ /dist /build -dev_sandbox.sh +dev_devlayer.sh .aider* callgrind.out.* cachegrind.out.* -perf.data* \ No newline at end of file +perf.data* +superpowers/ diff --git a/CLAUDE.md b/CLAUDE.md index c297805..30e7796 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 LayerManager, 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..13dd8d8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,15 +1,15 @@ [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] -name = "sandbox" +name = "devlayer" path = "src/lib.rs" [lints.rust] diff --git a/Makefile b/Makefile index c507c48..90d1c3b 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 + 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 + 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,8 +82,8 @@ 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 - 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 + sudo mkdir -p /run/media/devlayer-coverage-testing + 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 @@ -91,13 +91,13 @@ 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 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 @@ -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..ce95575 100644 --- a/README.adoc +++ b/README.adoc @@ -4,62 +4,59 @@ // 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. +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 -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 -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. 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 -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. -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 `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 +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. @@ -72,41 +69,52 @@ 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 new layer. The current directory is live, the rest +of your system is layered. ``` - sandbox + devlayer ``` -Try that trendy web based install script in a sandbox first +Hop back into the last layer you started in this directory ``` - curl -s https://trustmebro.sh | sandbox sh + devlayer --last +``` + +Try that trendy web based install script in a layer first +``` + curl -s https://trustmebro.sh | devlayer sh ``` Let AIs run wild in YOLO mode without too much risk ``` - sandbox --net=host aider + devlayer aider +``` + +Check what files were modified outside the current directory +``` + devlayer status ``` -Check what files were modified +Accept changes to your shell config, copying them from the layer to the host +system ``` - sandbox status + devlayer accept ~/.bashrc ``` -Accept changes to all the python files in the current directory, copying -them from the sandbox to the host system. +Accept every change in the layer ``` - sandbox accept '*.py' + devlayer accept / ``` -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 +123,40 @@ 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 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`:: -Show changes in the sandbox relative to the current changes +`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 changes in the sandbox. This works relative to your current working directory only, and changes outside of your working directory are ignored. +`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 changes in the sandbox. This works relative to your current working directory only, and changes outside of your working directory are ignored. +`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 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. +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 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 --join'ed 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) @@ -151,87 +167,116 @@ 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 sandbox, defaults to "sandbox". Executables run within the same sandbox -name will be run in the same container. +`--join=`:: +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 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 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 sandbox. This is useful for quickly returning to -the last sandbox you were working in. Cannot be used with --name 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 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 -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. + +`--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 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 - 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=../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 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. - -`--audio`:: -Allow audio inside the sandbox 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 -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 -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. + +`--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 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 +293,45 @@ 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. + +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, `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 to join (like --join) + join="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 +339,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 +362,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_JOIN="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" ``` @@ -338,45 +389,45 @@ 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 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..72bbc01 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", @@ -186,6 +192,7 @@ "resgid", "resolv", "resuid", + "rfind", "rgid", "rmdirs", "rstest", @@ -194,10 +201,10 @@ "rustlib", "rustsec", "rustup", - "sandboxd", - "sandboxed", - "sandboxing", - "sandboxnet", + "devlayer", + "herdr", + "opencode", + "qwen", "sched", "serde", "setegid", @@ -224,6 +231,7 @@ "SIGTSTP", "splitn", "subsec", + "subshell", "syscall", "sysconfig", "sysfs", 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..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 sandbox {}", 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 5215981..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] = - &["sandbox-coverage-*", "sandbox-bind-empty-*"]; +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 sandboxes to clean"); + 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) @@ -41,13 +38,13 @@ 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(()); } - 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..6b8d9af 100644 --- a/src/actions/config.rs +++ b/src/actions/config.rs @@ -16,11 +16,13 @@ pub fn config(config: &Config, keys: Option>) -> Result<()> { "bind", "mask", "no_default_binds", - "audio", + "no_default_llm_binds", + "bind_cwd", + "created_in", "cpus", "memory", "storage_dir", - "sandbox_dir", + "layer_dir", "upper_cwd", "overlay_cwd", "ignored", @@ -48,7 +50,8 @@ 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 no_default_llm_binds_str = format!("{}", config.no_default_llm_binds); + let bind_cwd_str = format!("{}", config.origin.bind_cwd); let cpus_str = config .cpus .map_or("unlimited".to_string(), |cpus| cpus.to_string()); @@ -68,10 +71,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("")) } @@ -85,7 +87,14 @@ 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()), + "no_default_llm_binds" => { + ("no_default_llm_binds", no_default_llm_binds_str.as_str()) + } + "bind_cwd" => ("bind_cwd", bind_cwd_str.as_str()), + "created_in" => ( + "created_in", + config.origin.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/actions/delete.rs b/src/actions/delete.rs index ecabaa1..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 sandboxes"); + 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,74 +86,73 @@ 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 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(()); } - 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 sandboxes will be deleted:"); - for (list, stopped) in - [(running_sandboxes, false), (stopped_sandboxes, true)] + outln!("The following layers will be deleted:"); + 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 ); @@ -174,7 +173,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(); @@ -186,40 +185,35 @@ 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 sandbox: {}", 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 sandbox: {}", 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 sandbox: {}", e); + outln!("Error deleting layer: {}", e); errors.push(Value::String(e.to_string())); } } } } - outln!("{} sandboxes 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 d83986a..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 sandbox {}", 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 983f59c..a9019d9 100644 --- a/src/actions/list.rs +++ b/src/actions/list.rs @@ -2,65 +2,60 @@ 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_sandbox_pid_path, set_json_output}, + util::{get_running_layer_pid, set_json_output}, }; -pub fn list(sandboxes_storage_dir: &Path, patterns: &[String]) -> Result<()> { - trace!("Listing sandboxes"); +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() { - outln!("Running sandboxes:"); - for sandbox in &running_sandboxes { - outln!("{}", sandbox); + if !running_layers.is_empty() { + outln!("Running layers:"); + 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() { - outln!("{}", "Stopped sandboxes:".dimmed()); - for sandbox in &stopped_sandboxes { - outln!("{}", sandbox.dimmed()); + if !stopped_layers.is_empty() { + outln!("{}", "Stopped layers:".dimmed()); + for layer in &stopped_layers { + outln!("{}", layer.dimmed()); } } set_json_output( - "running_sandboxes", - &Value::Array( - running_sandboxes.into_iter().map(Value::String).collect(), - ), + "running_layers", + &Value::Array(running_layers.into_iter().map(Value::String).collect()), ); set_json_output( - "stopped_sandboxes", - &Value::Array( - stopped_sandboxes.into_iter().map(Value::String).collect(), - ), + "stopped_layers", + &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,41 +63,27 @@ 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); - 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_sandboxes.push(sandbox_name); - } else { - stopped_sandboxes.push(sandbox_name); - } - } - Err(_) => { - stopped_sandboxes.push(sandbox_name); - } - } + if get_running_layer_pid(layers_storage_dir, &layer_name) + .is_some() + { + running_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 d921ec8..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 sandbox {}", 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 9dafa71..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 sandbox {}", 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 71f5955..ce6418c 100644 --- a/src/actions/stop.rs +++ b/src/actions/stop.rs @@ -4,49 +4,42 @@ use fast_glob::glob_match; use log::{trace, warn}; use nix::unistd::{Gid, Uid}; -use crate::sandbox::Sandbox; +use crate::layer::Layer; +use crate::util::{get_layer_lock_path, get_layer_pid_path}; 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 sandbox {}", 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 sandboxes 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() @@ -54,25 +47,12 @@ 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 storage_dir = - format!("{}/{}", sandboxes_storage_dir.display(), sandbox_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; } @@ -81,13 +61,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 sandbox {}: {}", sandbox_name, e); + warn!("Failed to kill layer {}: {}", layer_name, e); } } } diff --git a/src/config/cli.rs b/src/config/cli.rs index 602d590..a1252d6 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,24 +23,28 @@ pub struct Args { )] pub log_level: Option, - /// Name of the sandbox, defaults to "sandbox" - #[arg(long, global = true, value_hint = clap::ValueHint::Other, add = ArgValueCompleter::new(sandbox_name_completion), conflicts_with_all = &["new", "last"])] - pub name: Option, + /// 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 sandbox with an auto-generated timestamp name - #[arg(long, global = true, conflicts_with_all = &["name", "last"])] + /// 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 sandbox - #[arg(long, global = true, conflicts_with_all = &["name", "new"])] + /// 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, - /// 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, - /// 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, @@ -51,7 +55,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( @@ -72,18 +76,23 @@ 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. + /// 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 audio: bool, + pub no_default_llm_binds: bool, - /// Limit how many CPUs the sandbox can use. Fractional values such as 1.5 + /// 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 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 +102,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, @@ -128,18 +137,18 @@ pub struct Args { pub action: Option, /*********************/ - /* Sandboxed Command */ + /* Layered 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>, + pub layered_command: Option>, } #[derive(clap::Subcommand, Clone, Debug)] @@ -152,69 +161,71 @@ 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 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 sandbox 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 sandbox + /// 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 sandbox + /// 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>, }, /// 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)] @@ -222,7 +233,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 +256,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/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..a5929e1 100644 --- a/src/config/resolve.rs +++ b/src/config/resolve.rs @@ -1,10 +1,11 @@ use super::PartialConfig; use super::limits::{available_cpus, parse_cpus, parse_memory}; use crate::config::{BindMount, BindMountOptions, Network}; +use crate::layer::LayerOrigin; 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; @@ -17,7 +18,26 @@ use std::{ path::{Path, PathBuf}, }; -use super::cli::Args; +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]] @@ -69,16 +89,16 @@ 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.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" )); } // 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 +107,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_JOIN") { if !name.is_empty() { - partial_config.name = Some(name); + partial_config.join = 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,21 +132,9 @@ pub fn resolve_config(cli: Args) -> Result { } } - if let Ok(ignored_env) = env::var("SANDBOX_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: {}", - 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("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 +147,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 +162,36 @@ 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") { - let no_default_binds_val = bool::from_str(&no_default_binds_env) - .expect("Invalid value for SANDBOX_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_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: {}", - audio_env - )); + 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 [ - ("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); @@ -189,35 +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()); + } - // 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.name = Some(name); + // 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 = if cli.new { sources.insert("name".into(), "cli --new".into()); + LayerSelection::New } else if cli.last { - // Find the most recently created sandbox - let name = find_last_sandbox( - &partial_config.storage_dir, - uid_gid_home.uid, - uid_gid_home.gid, - )?; - partial_config.name = 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()); - } + 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()) + }; + let new_layer = selection == LayerSelection::New; + let name = match selection { + LayerSelection::Join(name) => name, + 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 let Some(net) = cli.net { partial_config.net = Some(net); @@ -234,9 +260,14 @@ 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 cli.no_default_llm_binds { + partial_config.no_default_llm_binds = Some(true); + 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 { @@ -261,12 +292,11 @@ 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()); if !sources.contains_key("name") { 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()); } @@ -281,9 +311,15 @@ 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 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 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 @@ -304,21 +340,11 @@ pub fn resolve_config(cli: Args) -> Result { sources.insert("memory".into(), "default".into()); } - let storage_dir = resolve_sandbox_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 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()?; let mp = find_mount_point(cwd.clone())?; let hash = data_encoding::BASE32_NOPAD.encode(mp.to_string_lossy().as_bytes()); @@ -336,26 +362,78 @@ 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()); - } + // 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 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 { - bind_layers.insert(0, get_default_bind_mounts(&net, &uid_gid_home)); + let mut default_binds = get_default_bind_mounts(&net); + default_binds.extend(get_audio_bind_mounts()); + 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. // 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::>>>()?; + + // Binding the home directory takes asking for it, e.g. with --bind=. + 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 == origin.created_in + && mount.options != BindMountOptions::Mask + }); + 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 @@ -385,9 +463,10 @@ pub fn resolve_config(cli: Args) -> Result { let config = Config { name, + new_layer, net, storage_dir, - sandbox_dir, + layer_dir, upper_cwd, overlay_cwd, log_level: partial_config.log_level.unwrap_or(log::LevelFilter::Info), @@ -395,7 +474,9 @@ pub fn resolve_config(cli: Args) -> Result { sources, bind_mounts, no_default_binds, - audio, + no_default_llm_binds, + origin, + cwd_bind_is_home, cpus, memory, config_files, @@ -404,15 +485,12 @@ 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) } -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 @@ -454,23 +532,40 @@ 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 +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()) + .collect() +} + fn get_audio_bind_mounts() -> Vec { let mut audio_binds = Vec::new(); @@ -495,7 +590,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, @@ -518,8 +613,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 +790,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")); + // ~/.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/sandbox.conf - paths_to_check.push(PathBuf::from("/etc/sandbox.conf")); - paths_to_check.push(PathBuf::from("/etc/sandbox.toml")); + // /etc/devlayer.conf + 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(); @@ -740,8 +835,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 { @@ -760,9 +855,13 @@ 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(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(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); @@ -787,20 +886,15 @@ 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(()) } -fn generate_timestamp_name( - storage_dir: &Option, - uid: Uid, - gid: Gid, -) -> Result { - let storage_dir = - resolve_sandbox_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; @@ -810,9 +904,9 @@ 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() { - return Ok(base_name); + let layer_path = storage_dir.join(&base_name); + if !layer_path.exists() { + return base_name; } // If it exists, try with millisecond precision @@ -827,9 +921,9 @@ fn generate_timestamp_name( name_with_ms }; - let sandbox_path_ms = storage_dir.join(&name_with_ms); - if !sandbox_path_ms.exists() { - return Ok(name_with_ms); + let layer_path_ms = storage_dir.join(&name_with_ms); + if !layer_path_ms.exists() { + return name_with_ms; } // If even that exists, sleep for a millisecond and try again @@ -842,56 +936,111 @@ fn generate_timestamp_name( } } -fn find_last_sandbox( - storage_dir: &Option, - uid: Uid, - gid: Gid, -) -> Result { - let storage_dir = - 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: {:?}", - storage_dir - ))?; - - let mut sandboxes: 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)] +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 sandbox 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 +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 sandbox")?; - sandboxes.push((name, created)); + LayerSelection::Last } + Some(Action::Config { .. }) => LayerSelection::LastOrNew, + Some(_) => LayerSelection::New, } +} + +/// 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. +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 origin = LayerOrigin::load(&path)?; + let metadata = entry.metadata().ok()?; + let created = + metadata.created().or_else(|_| metadata.modified()).ok()?; + Some(( + origin.created_in, + entry.file_name().to_string_lossy().to_string(), + created, + )) + }) + .collect(); #[cfg(feature = "coverage")] - let mut sandboxes = 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 { - sandboxes + layers }; - if sandboxes.is_empty() { - return Err(anyhow::anyhow!("No sandboxes found")); - } - - // Sort by creation time (newest first) - sandboxes.sort_by(|a, b| b.1.cmp(&a.1)); - - Ok(sandboxes[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)] @@ -905,17 +1054,111 @@ 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!( + "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 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"); + 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"), home.join(".codex")] + ); + 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)).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 { @@ -923,7 +1166,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 { @@ -935,7 +1178,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 @@ -944,7 +1187,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() @@ -952,16 +1195,17 @@ 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"))); } #[test] fn test_validate_config() { let mut config = Config { - name: "test-sandbox".to_string(), + name: "test-layer".to_string(), + new_layer: false, 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, @@ -970,19 +1214,24 @@ mod tests { log_level: LevelFilter::Info, bind_mounts: vec![], no_default_binds: false, - audio: false, + no_default_llm_binds: false, + origin: LayerOrigin { + created_in: PathBuf::from("/tmp"), + bind_cwd: false, + }, + cwd_bind_is_home: false, cpus: None, memory: None, 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 +1287,7 @@ mod tests { let override_config = PartialConfig { log_level: Some(LevelFilter::Debug), - name: Some("test-sandbox".to_string()), + join: Some("test-layer".to_string()), storage_dir: Some("/tmp/test".to_string()), net: Some(Network::Host), ignored: Some(true), @@ -1048,7 +1297,8 @@ mod tests { ]), mask: Some(vec!["/tmp/test3".to_string()]), no_default_binds: Some(true), - audio: Some(true), + no_default_llm_binds: Some(true), + no_bind_cwd: Some(true), cpus: Some("-2".to_string()), memory: Some("4G".to_string()), }; @@ -1070,13 +1320,18 @@ 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.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)); - assert_eq!(base.audio, 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!(base.no_bind_cwd, 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 94b2223..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}; @@ -53,14 +54,15 @@ 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, pub bind: Option>, pub mask: Option>, pub no_default_binds: Option, - pub audio: 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)] @@ -71,8 +73,11 @@ 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 sandbox_dir: PathBuf, + pub layer_dir: PathBuf, pub upper_cwd: PathBuf, pub overlay_cwd: PathBuf, pub net: Network, @@ -80,10 +85,15 @@ pub struct Config { pub ignored: bool, pub bind_mounts: Vec, pub no_default_binds: bool, - pub audio: bool, - /// Number of CPUs the sandbox may use, None for unlimited + pub no_default_llm_binds: 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, + /// 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 80% rename from src/sandbox/cgroup.rs rename to src/layer/cgroup.rs index 3907076..b0added 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/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. 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,9 +16,9 @@ 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("sandbox"); + let parent = String::from("devlayer"); // Lets tests start from a parent cgroup that doesn't exist yet #[cfg(feature = "coverage")] @@ -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,16 +51,16 @@ 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); }; 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) @@ -111,11 +111,11 @@ 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 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() ))?; } @@ -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 `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) { @@ -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/changes/change_entries.rs b/src/layer/changes/change_entries.rs similarity index 97% rename from src/sandbox/changes/change_entries.rs rename to src/layer/changes/change_entries.rs index 966f5ed..df09345 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. @@ -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/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 57% rename from src/sandbox/delete.rs rename to src/layer/delete.rs index 2f8cd1b..3177d76 100644 --- a/src/sandbox/delete.rs +++ b/src/layer/delete.rs @@ -1,22 +1,20 @@ -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 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())); + 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/sandbox/exec.rs b/src/layer/exec.rs similarity index 83% rename from src/sandbox/exec.rs rename to src/layer/exec.rs index 688dcde..c713b6b 100644 --- a/src/sandbox/exec.rs +++ b/src/layer/exec.rs @@ -1,6 +1,6 @@ #![allow(static_mut_refs)] -use crate::sandbox::Sandbox; -use crate::util::drop_privileges; +use crate::layer::Layer; +use crate::util::{Lock, drop_privileges}; use anyhow::{Context, Result, anyhow}; use libc::syscall; use log::trace; @@ -17,15 +17,18 @@ 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 - * success. + * Exec within the provided layer. This function never returns on + * 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"))?; + /* 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 @@ -34,16 +37,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,25 +85,25 @@ 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!( - "Failed to join sandbox namespaces: {}", + "Failed to join layer namespaces: {}", nix::errno::Errno::last() )); } - // 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()))?; @@ -113,15 +116,28 @@ 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(), ); } + /* 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/exists.rs b/src/layer/exists.rs new file mode 100644 index 0000000..afabcbb --- /dev/null +++ b/src/layer/exists.rs @@ -0,0 +1,9 @@ +use crate::layer::Layer; + +impl Layer { + pub fn exists(&self) -> bool { + self.base.exists() + || self.pid_path().exists() + || self.lock_path().exists() + } +} diff --git a/src/sandbox/get_or_create.rs b/src/layer/get_or_create.rs similarity index 71% rename from src/sandbox/get_or_create.rs rename to src/layer/get_or_create.rs index 683cba0..3c2de6a 100644 --- a/src/sandbox/get_or_create.rs +++ b/src/layer/get_or_create.rs @@ -1,17 +1,18 @@ 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::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::{ 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_or_remove, layer_pid_file_contents}; use anyhow::Context; use anyhow::{Result, anyhow}; use log::{error, trace}; @@ -20,11 +21,16 @@ use nix::sys::stat::fchmodat; use nix::{ mount::MsFlags, mount::{MntFlags, umount2}, + sys::signal::Signal, sys::stat::{Mode, SFlag, makedev, mknod}, - unistd::{Gid, Pid, Uid, close, pipe, pivot_root, setsid}, + sys::wait::{WaitPidFlag, WaitStatus, 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}, @@ -36,27 +42,29 @@ 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 -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(), + storage_dir: layers_storage_dir.to_path_buf(), + base: layer_base_dir.clone(), work_base: work_base.clone(), upper_base: upper_base.clone(), overlay_base: overlay_base.clone(), @@ -68,83 +76,105 @@ impl Sandbox { } } + /// 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( - 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 sandbox: {}", 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) - { - let mut sandbox = Sandbox::from_location( - sandboxes_storage_dir, - sandbox_name, - uid, - gid, - ); - sandbox.pid = pid; - return Ok((Some(sandbox), lock)); + /* If we have an existing layer, return it */ + 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; + return Ok((Some(layer), lock)); } Ok((None, lock)) } + /** + * 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 { + ) -> Result<(Layer, Box)> { let storage_dir = &config.storage_dir; - let sandbox_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::sandbox(storage_dir, sandbox_name) - .context(format!("failed to lock sandbox: {}", sandbox_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 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(), - options: BindMountOptions::ReadWrite, - }); + validation_config + .bind_mounts + .push(layer.data_bind_mount()); // Validate settings compatibility existing_settings.validate_against_config( @@ -154,26 +184,25 @@ 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 )); } } } - return Ok(sandbox); + return Ok((layer, lock)); } /* - * 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 sandbox '{}': {}", - sandbox_name, - sandbox.base.display() + "Creating new layer '{}': {}", + layer_name, + layer.base.display() ); /* Sanity check our storage path*/ @@ -184,62 +213,120 @@ impl Sandbox { ), )?; + 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" + )); + } + 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 { - argument: "data".to_string(), - source: sandbox.data_storage_dir.clone(), - target: sandbox.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. */ - let cgroup = sandbox.create_cgroup_or_share_outer(&config)?; + let cgroup = layer.create_cgroup_or_share_outer(&config)?; - trace!("Mounting sandbox"); - let started = sandbox + trace!("Mounting layer"); + let started = layer .mount_overlays(&config) - .context(format!("failed to mount sandbox: {}", sandbox_name)) + .context(format!("failed to mount layer: {}", layer_name)) .and_then(|overlay_mounts| { - /* Create PID 1 for our sandbox */ - sandbox - .start_sandbox( - &config, - &get_sandbox_pid_path(storage_dir, sandbox_name), - &overlay_mounts, - cgroup.as_ref(), - ) - .map_err(|e| anyhow!("Failed to start sandbox: {}", e)) + /* Create PID 1 for our layer */ + layer + .start_layer(&config, &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) + /* 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)) } /** * 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 sends + * us PID 1's pid once PID 1 is ready, or exits without sending anything + * if PID 1 fails to start. */ - 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 + 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 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")); + } + Ok(Pid::from_raw(i32::from_le_bytes(pid))) + } + ForkResult::Child => { + drop(read_fd); + 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(e) => { + error!("Failed to start layer: {:#}", e); + 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. Returns PID 1's pid and the + * handle on the layer lock that we share with it. + */ + fn start_pid1( + &self, + config: &Config, + overlay_mounts: &Vec, + cgroup: Option<&OwnedFd>, + ) -> 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) = - pipe().context("failed to create pipe for sandbox")?; + pipe().context("failed to create pipe for layer")?; let clone_args = Clone3Args { flags: CLONE_NEWNS @@ -257,12 +344,14 @@ impl Sandbox { // 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() }; #[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 @@ -270,33 +359,40 @@ 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 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 + let pid_file = self.pid_path(); + 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 // 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")?; - - if buffer[0] == 1 { - return Err(anyhow!("Failed to setup sandbox")); + let mut buffer = [1; 1]; + let _ = nix::unistd::read(read_fd.as_raw_fd(), &mut buffer); + + 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) + Ok((pid, lock)) } else { // We are the child process. We should never return from this branch. @@ -306,35 +402,37 @@ impl Sandbox { // Normal operation is that this doesn't return. let _ = self - .setup_sandbox_and_sleep_forever( - config, - &write_fd, - overlay_mounts, - ) + .setup_layer_and_wait(config, &write_fd, overlay_mounts, &lock) .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")?; - + let _ = nix::unistd::write(&write_fd, &[1]); std::process::exit(1); } } - /* 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_wait( &self, config: &Config, write_fd: &OwnedFd, mounts: &Vec, + lock: &SharedLock, ) -> Result<()> { - trace!("Setting up sandbox root process"); + trace!("Setting up layer root process"); - /* Normalize credentials and dumpable state for pidfd-based setns(). + /* 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()]); + + /* 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: @@ -342,23 +440,10 @@ impl Sandbox { * 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 sandbox 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")?; + * 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); } @@ -810,7 +895,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,14 +1104,14 @@ 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 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. */ @@ -1037,38 +1122,84 @@ impl Sandbox { 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); } - // sleep forever, this process hangs around only to host the namespaces so other processes - // can join in. - let mut count = 0; - 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 - #[cfg(feature = "coverage")] - { - let _ = nix::unistd::chdir(&cwd); - - 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(),) + /* 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_ptr(), - ); - __llvm_profile_dump(); - } + .as_secs() + ) + .as_str(), + ) + .unwrap() + .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")] + 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!( + waitpid(Pid::from_raw(-1), Some(WaitPidFlag::WNOHANG)), + Ok(WaitStatus::StillAlive) | Err(_) + ) {} + + 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(); } } } } + +/// 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/src/layer/layer_struct.rs b/src/layer/layer_struct.rs new file mode 100644 index 0000000..1e43ff9 --- /dev/null +++ b/src/layer/layer_struct.rs @@ -0,0 +1,32 @@ +use crate::util::{get_layer_lock_path, get_layer_pid_path}; +use nix::unistd::Gid; +use nix::unistd::Pid; +use nix::unistd::Uid; +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, + pub overlay_base: PathBuf, + pub data_storage_dir: PathBuf, // storage dir for layer data and nested layers + 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 { + 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 { + get_layer_lock_path(&self.storage_dir, &self.name) + } +} diff --git a/src/sandbox/mod.rs b/src/layer/mod.rs similarity index 74% rename from src/sandbox/mod.rs rename to src/layer/mod.rs index 3f7a76e..4b39097 100644 --- a/src/sandbox/mod.rs +++ b/src/layer/mod.rs @@ -4,11 +4,12 @@ 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 supervisor; 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 90% rename from src/sandbox/mount_overlays.rs rename to src/layer/mount_overlays.rs index bab6d59..a447241 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,12 +22,12 @@ pub struct MountHash { pub dir: String, } -impl Sandbox { +impl Layer { pub fn mount_overlays(&self, config: &Config) -> Result> { 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)?; @@ -40,7 +40,8 @@ impl Sandbox { 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); @@ -105,11 +106,11 @@ 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 sandbox settings")?; + .context("Failed to save layer settings")?; Ok(result_mounts) } @@ -119,14 +120,15 @@ 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"); + // 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() { 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) + let parent_settings = LayerSettings::load_from_file(&settings_json) .context(format!( "Failed to read parent settings.json from {}", settings_json.display() @@ -169,7 +171,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 != "/" @@ -198,7 +200,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/layer/settings.rs similarity index 74% rename from src/sandbox/settings.rs rename to src/layer/settings.rs index e68b414..6efdc97 100644 --- a/src/sandbox/settings.rs +++ b/src/layer/settings.rs @@ -1,23 +1,57 @@ use crate::config::{BindMount, Config}; -use crate::sandbox::mount_overlays::MountHash; +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; +use std::path::{Path, PathBuf}; #[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 { +/// 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")?; + write_no_follow(&Self::path(layer_dir), json).context(format!( + "Failed to write {}", + Self::path(layer_dir).display() + )) + } +} + +impl LayerSettings { pub fn from_config(config: &Config, mounts: &[MountHash]) -> Self { Self { version: env!("CARGO_PKG_VERSION").to_string(), @@ -44,8 +78,8 @@ 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")?; - std::fs::write(path, settings_json).context(format!( + .context("Failed to serialize layer settings to JSON")?; + write_no_follow(path, settings_json).context(format!( "Failed to write settings.json to {}", path.display() ))?; @@ -63,7 +97,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) } @@ -77,7 +111,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 +121,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 +158,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 +195,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/layer/stop.rs similarity index 79% rename from src/sandbox/stop.rs rename to src/layer/stop.rs index 9e25a40..fd2faf1 100644 --- a/src/sandbox/stop.rs +++ b/src/layer/stop.rs @@ -1,18 +1,18 @@ -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}; +use std::path::Path; -impl Sandbox { +impl Layer { 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 @@ -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!("sandbox_ns_str: {}", sandbox_ns_str); - let sandbox_ns_path = Path::new(&sandbox_ns_str); - trace!("sandbox_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() { - trace!("Sandbox process {} already gone", pid); + 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!("sandbox_ns: {}", ns.to_string_lossy()); + 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")] @@ -106,13 +106,13 @@ impl Sandbox { trace!("command: {}", command); trace!( - "[{}] Killing {} in sandbox '{}'", + "[{}] Killing {} in layer '{}'", process_pid, command, self.name ); #[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, @@ -144,7 +144,7 @@ impl Sandbox { } } - 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/layer/supervisor.rs b/src/layer/supervisor.rs new file mode 100644 index 0000000..a57228e --- /dev/null +++ b/src/layer/supervisor.rs @@ -0,0 +1,107 @@ +//! 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. +//! +//! 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::{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}; + +/// 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. 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)) + .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 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) + .open("/dev/null") + { + for fd in 0..=2 { + unsafe { libc::dup2(null.as_raw_fd(), fd) }; + } + } + 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, 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, lock); + std::process::exit(0); +} + +fn cleanup(layer: &Layer, own_cgroup: bool, lock: SharedLock) -> Result<()> { + /* 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(()); + }; + + /* 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_or_remove(&lock, &layer.storage_dir, &layer.name) + .is_some() + { + return Ok(()); + } + + let cgroup = layer.cgroup_path(); + if own_cgroup && cgroup.exists() { + remove_cgroup(&cgroup); + } + + layer.unmount() +} diff --git a/src/sandbox/unmount.rs b/src/layer/unmount.rs similarity index 90% rename from src/sandbox/unmount.rs rename to src/layer/unmount.rs index 57e6fb4..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)); @@ -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/lib.rs b/src/lib.rs index c80c090..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; \ No newline at end of file +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 39da15e..080afd7 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(); @@ -50,12 +50,13 @@ 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")?; // 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)?; @@ -74,15 +75,15 @@ 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" )); } // 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 +95,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 +175,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) - .context("Getting or creating sandbox")?; + 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 - sandbox.exec(&sandboxed_command) + layer.exec(&layered_command, lock) } diff --git a/src/sandbox/exists.rs b/src/sandbox/exists.rs deleted file mode 100644 index b96bad7..0000000 --- a/src/sandbox/exists.rs +++ /dev/null @@ -1,12 +0,0 @@ -use std::path::PathBuf; - -use crate::sandbox::Sandbox; - -impl Sandbox { - 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() - } -} diff --git a/src/sandbox/sandbox_struct.rs b/src/sandbox/sandbox_struct.rs deleted file mode 100644 index 3350cec..0000000 --- a/src/sandbox/sandbox_struct.rs +++ /dev/null @@ -1,20 +0,0 @@ -use nix::unistd::Gid; -use nix::unistd::Pid; -use nix::unistd::Uid; -use std::path::PathBuf; - -pub struct Sandbox { - 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 root_suffix: String, - //pub root_work: PathBuf, - //pub root_upper: PathBuf, - pub root_overlay: PathBuf, - pub pid: Pid, - pub uid: Uid, - pub gid: Gid, -} 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_layer_pid.rs b/src/util/get_running_layer_pid.rs new file mode 100644 index 0000000..44cf54b --- /dev/null +++ b/src/util/get_running_layer_pid.rs @@ -0,0 +1,104 @@ +use nix::unistd::Pid; +use std::path::Path; +use std::path::PathBuf; + +use log::trace; + +use super::Lock; + +/** + * Get the PID 1 of a running layer, from its pid file. + * + * 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 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); + 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 if pid_file.exists() => { + trace!( + "Layer '{}' isn't running, removing its pid file", + layer_name + ); + std::fs::remove_file(&pid_file).ok(); + } + None => {} + } + 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) +} + +/// 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( + layers_storage_dir: &Path, + layer_name: &str, +) -> PathBuf { + layers_storage_dir.join(format!("{}.pid", layer_name)) +} diff --git a/src/util/get_running_sandbox_pid.rs b/src/util/get_running_sandbox_pid.rs deleted file mode 100644 index 166f4f5..0000000 --- a/src/util/get_running_sandbox_pid.rs +++ /dev/null @@ -1,59 +0,0 @@ -use nix::{sys::signal::kill, unistd::Pid}; -use std::path::Path; -use std::path::PathBuf; - -use log::trace; - -/** - * Get the PID of a running sandbox. - * - * Returns None if the sandbox is not running. - */ -pub fn get_running_sandbox_pid( - sandboxes_storage_dir: &Path, - sandbox_name: &str, -) -> Option { - let sandboxes_storage_dir = &PathBuf::from(sandboxes_storage_dir); - let pid_file = get_sandbox_pid_path(sandboxes_storage_dir, sandbox_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 sandbox '{}' found with PID: {}", - sandbox_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 sandbox was not in a good state, cleaning up" - ); - std::fs::remove_file(&pid_file).ok(); - } - } - } - - None -} - -pub fn get_sandbox_pid_path( - sandboxes_storage_dir: &Path, - sandbox_name: &str, -) -> PathBuf { - sandboxes_storage_dir.join(format!("{}.pid", sandbox_name)) -} diff --git a/src/util/lock_layer.rs b/src/util/lock_layer.rs new file mode 100644 index 0000000..624b2f2 --- /dev/null +++ b/src/util/lock_layer.rs @@ -0,0 +1,126 @@ +use std::fs::{File, OpenOptions}; +use std::os::fd::{AsRawFd, RawFd}; +use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; +use std::path::{Path, PathBuf}; + +use log::trace; +use nix::fcntl::Flock; + +use anyhow::{Context, Result, anyhow}; + +pub struct Lock { + path: PathBuf, + #[allow(dead_code)] + 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 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 = get_layer_lock_path(layers_storage_dir, layer_name); + let file = OpenOptions::new() + .create(true) + .read(true) + .write(true) + .truncate(false) + .custom_flags(libc::O_NOFOLLOW) + .open(&lock_file) + .map_err(|e| { + anyhow!( + "Failed to open lock file for layer {}: {}", + layer_name, + e + ) + })?; + Self::acquire(lock_file, file) + } + + /// 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::symlink_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> { + 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))?; + + trace!("Acquired lock {}", lock_file.display()); + Ok(Box::new(Lock { + path: lock_file, + lock, + })) + } +} + +impl Drop for Lock { + fn drop(&mut self) { + 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 = get_layer_lock_path(layers_storage_dir, layer_name); + let file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW) + .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/src/util/lock_sandbox.rs b/src/util/lock_sandbox.rs deleted file mode 100644 index 133e823..0000000 --- a/src/util/lock_sandbox.rs +++ /dev/null @@ -1,57 +0,0 @@ -use std::fs::{File, OpenOptions}; -use std::path::{Path, PathBuf}; - -use log::trace; -use nix::fcntl::Flock; - -use anyhow::{Result, anyhow}; - -pub struct Lock { - path: PathBuf, - #[allow(dead_code)] - lock: Flock, -} - -impl Lock { - /** Acquire a lock on the sandbox storage directory. */ - pub fn sandbox( - sandboxes_storage_dir: &Path, - sandbox_name: &str, - ) -> Result> { - let lock_file = - sandboxes_storage_dir.join(format!("{}.lock", sandbox_name)); - trace!("Acquiring lock {}", lock_file.display()); - let file = match OpenOptions::new() - .create(true) - .read(true) - .write(true) - .truncate(false) - .open(&lock_file) - { - Ok(file) => file, - Err(e) => { - return Err(anyhow!( - "Failed to open lock file for sandbox {}: {}", - sandbox_name, - e - )); - } - }; - - let lock = - nix::fcntl::Flock::lock(file, nix::fcntl::FlockArg::LockExclusive) - .map_err(|(_, e)| anyhow!("Failed to acquire lock: {}", e))?; - - trace!("Acquired lock {}", lock_file.display()); - Ok(Box::new(Lock { - path: lock_file, - lock, - })) - } -} - -impl Drop for Lock { - fn drop(&mut self) { - trace!("Unlocking lock {}", self.path.display()); - } -} 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/src/util/mod.rs b/src/util/mod.rs index 2a34c57..a63bd5e 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -3,11 +3,12 @@ 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; +mod no_follow; mod output; mod resolve_uid_gid_home; mod sync_and_drop_caches; @@ -17,11 +18,12 @@ 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::*; +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/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_cli_flags.rs b/tests/ai_cli_flags.rs index b92bd13..6f27c18 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(&["--join", &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(&["--join", &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(&["--join", &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(&["--join", &name, "--log-level=debug", "config"])); + assert!(layer.last_stdout.contains("log_level=DEBUG")); - assert!(sandbox.pass(&["--name", &name, "--json", "config"])); + assert!(layer.pass(&["--join", &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(&["--join", &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", "--join", "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(&["--join", &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(&["--join", &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(&["--join", &name, "config", "--log-level=debug"])); + assert!(layer.last_stdout.contains("log_level=DEBUG")); - assert!(sandbox.pass(&["--name", &name, "config", "--json"])); + assert!(layer.pass(&["--join", &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(&["--join", &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(&["--join", "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", "--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"); @@ -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"])); - // Should show defaults when no config is loaded - assert!(sandbox.last_stdout.contains("net=none")); + assert!(layer.pass(&["--no-config", "config"])); + // Should show defaults (host network) when no config is loaded + assert!(layer.last_stdout.contains("net=host")); - 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=host")); // 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..2369010 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_action_scope.rs b/tests/ai_test_action_scope.rs new file mode 100644 index 0000000..8c5845c --- /dev/null +++ b/tests/ai_test_action_scope.rs @@ -0,0 +1,115 @@ +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(()) +} + +/// 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_audio.rs b/tests/ai_test_audio.rs index 49dd986..2725c6e 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 sandbox, 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,142 +24,78 @@ fn host_audio_paths() -> Vec { paths } -/// Writes a config file with the given contents and returns its path -fn write_config( - sandbox: &SandboxManager, - prefix: &str, - contents: &str, -) -> Result { - let path = format!("{}.toml", sandbox.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 sandbox: SandboxManager, -) -> Result<()> { - sandbox.run(&["--no-config", "config", "audio"])?; - assert_eq!(sandbox.last_stdout.trim(), "false"); - - sandbox.run(&["--no-config", "config", "bind"])?; - for path in host_audio_paths() { - assert!(!sandbox.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"); - - sandbox.run(&["--no-config", "--audio", "config", "bind"])?; - for path in host_audio_paths() { - assert!(sandbox.last_stdout.contains(&path)); - } - - Ok(()) -} - -#[rstest] -fn ai_test_audio_env(mut sandbox: SandboxManager) -> Result<()> { - sandbox.run_with_env( - &["--no-config", "config", "audio"], - "SANDBOX_AUDIO", - "true", - )?; - assert_eq!(sandbox.last_stdout.trim(), "true"); - - sandbox.run_with_env( - &["--no-config", "config", "audio"], - "SANDBOX_AUDIO", - "false", +fn ai_test_audio_on_by_default(mut layer: LayerManager) -> Result<()> { + let xdg = fake_runtime_dir(&layer)?; + layer.run_with_env( + &["--no-config", "config", "bind"], + "XDG_RUNTIME_DIR", + xdg.to_str().unwrap_or_default(), )?; - assert_eq!(sandbox.last_stdout.trim(), "false"); - - assert!(sandbox.exfail( - &["--no-config", "config", "audio"], - "SANDBOX_AUDIO", - "yes" - )); assert!( - sandbox - .last_stderr - .contains("Invalid value for SANDBOX_AUDIO") + layer + .last_stdout + .contains(&format!("{}/pulse", xdg.display())), + "{}/pulse not bound\nstdout: {}\nstderr: {}", + xdg.display(), + layer.last_stdout, + layer.last_stderr ); - Ok(()) } #[rstest] -fn ai_test_audio_config_file(mut sandbox: SandboxManager) -> Result<()> { - let config = write_config(&sandbox, "audio", "audio = true")?; - - sandbox.run(&["--config", &config, "config", "audio"])?; - assert_eq!(sandbox.last_stdout.trim(), "true"); - - // The environment takes precedence over config files - sandbox.run_with_env( - &["--config", &config, "config", "audio"], - "SANDBOX_AUDIO", - "false", +fn ai_test_audio_off_with_no_default_binds( + mut layer: LayerManager, +) -> Result<()> { + let xdg = fake_runtime_dir(&layer)?; + layer.run_with_env( + &["--no-config", "--no-default-binds", "config", "bind"], + "XDG_RUNTIME_DIR", + xdg.to_str().unwrap_or_default(), )?; - assert_eq!(sandbox.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 sandbox: SandboxManager, -) -> Result<()> { - sandbox.run(&[ - "--no-config", - "--no-default-binds", - "--audio", - "config", - "bind", - ])?; - assert!(!sandbox.last_stdout.contains("/dev/fuse")); - for path in host_audio_paths() { - assert!(sandbox.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(()) } #[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 - // 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!(sandbox.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"])?; - - for path in &paths { - assert!(sandbox.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 // 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", "-c", "%u %a", @@ -168,30 +104,42 @@ 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) ); } } + // 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(()) } #[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( - &["--no-config", "--audio", "config", "bind"], + layer.run_with_env( + &["--no-config", "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_auto_shutdown.rs b/tests/ai_test_auto_shutdown.rs new file mode 100644 index 0000000..cc6a949 --- /dev/null +++ b/tests/ai_test_auto_shutdown.rs @@ -0,0 +1,263 @@ +mod fixtures; + +use anyhow::Result; +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}; + +/// PID 1 of the layer, if its pid file names a live process +fn layer_pid(layer: &LayerManager) -> Option { + let pid = layer.pid1().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)); + } +} + +/// 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.hold()?; + 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), || { + !layer.pid_file().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.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))?; + 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.hold()?; + 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(()) +} + +/// 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), || { + !layer.pid_file().unwrap().exists() + })); + // 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"])?; + 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), || { + !layer.pid_file().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(()) +} + +/// 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"); + assert!(layer_pid(&other).is_some(), "other layer should be running"); + 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 + // 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_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)?, other_pid_file); + + // Don't let stopping this layer stop the other one + Command::new("sudo") + .args(["rm", &pid_file.to_string_lossy()]) + .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 = 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([ + &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_bind_mount_validation.rs b/tests/ai_test_bind_mount_validation.rs index e187cc2..c017552 100644 --- a/tests/ai_test_bind_mount_validation.rs +++ b/tests/ai_test_bind_mount_validation.rs @@ -6,73 +6,82 @@ 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"])?; - + let _output1 = + 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!(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!("{}{}", layer.last_stderr, layer.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 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"])?; - + let _output1 = + 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"])?; - + let _output2 = + 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!(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..16f8389 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"], - "SANDBOX_BIND", + "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"], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{}:{}", test1, mapped1), )?; assert!( - sandbox + layer .last_stdout .contains(&format!("{}:{}", test1, mapped1)) ); @@ -91,129 +87,150 @@ 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", + "--no-default-llm-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( - &["--no-config", "config"], - "SANDBOX_NO_DEFAULT_BINDS", + layer.run_with_env( + &["--no-default-llm-binds", "--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"], - "SANDBOX_NO_DEFAULT_BINDS", + "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 DEVLAYER_NO_DEFAULT_BINDS=false (or any other value) doesn't disable defaults + layer.run_with_env( &["--no-config", "config"], - "SANDBOX_NO_DEFAULT_BINDS", + "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( - &["--no-default-binds", "--no-config", "config"], - "SANDBOX_BIND", + layer.run_with_env( + &[ + "--no-default-binds", + "--no-default-llm-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( - &["--no-default-binds", "--no-config", "config"], - "SANDBOX_BIND", + layer.run_with_env( + &[ + "--no-default-binds", + "--no-default-llm-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"], - "SANDBOX_BIND", + "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( - &["--no-default-binds", "--no-config", "config"], - "SANDBOX_BIND", + layer.run_with_env( + &[ + "--no-default-binds", + "--no-default-llm-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 +242,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( - &["--no-default-binds", "config"], - "SANDBOX_BIND", + layer.run_with_env( + &["--no-default-binds", "--no-default-llm-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( - &["--no-default-binds", "config"], - "SANDBOX_BIND", + layer.run_with_env( + &["--no-default-binds", "--no-default-llm-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 +280,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 +290,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 +312,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 +321,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 +339,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,14 +347,14 @@ 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", "--", "touch", &format!("{}/new_file.txt", env_ro), ], - "SANDBOX_BIND", + "DEVLAYER_BIND", &format!("{}:{}:ro", test_dir_str, env_ro), ); @@ -349,38 +366,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"], - "SANDBOX_BIND", + "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 +403,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 +412,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 +460,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,16 +468,16 @@ 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!("sandbox-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(&[ - "--name", + // Run a command that will definitely create a new layer and process bind mounts + assert!(layer.pass(&[ + "--join", &test_name, "--bind", &format!("{}:", tmp), @@ -474,7 +487,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(()) } @@ -482,24 +495,24 @@ 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); 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_sandbox")) - .arg("--name") - .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(), @@ -513,14 +526,14 @@ 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 - let config_file = format!("{}/.sandbox.toml", work_dir); + let config_file = format!("{}/.devlayer.toml", work_dir); fs::write( &config_file, r#" @@ -529,12 +542,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,12 +560,12 @@ 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 config_dir = PathBuf::from(&test_dir).join(".config/sandbox"); + 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 +587,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 941f3c9..b4d858c 100644 --- a/tests/ai_test_bind_precedence.rs +++ b/tests/ai_test_bind_precedence.rs @@ -6,35 +6,36 @@ 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", + "--no-default-llm-binds", "--config", &low, "--config", @@ -42,10 +43,11 @@ 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", + "--no-default-llm-binds", "--config", &high, "--config", @@ -53,29 +55,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,48 +87,50 @@ 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", + "--no-default-llm-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", + "--no-default-llm-binds", "--config", &low, "--config", @@ -135,10 +139,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,24 +151,29 @@ 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( - &["--no-default-binds", "--config", &config, "config", "bind"], - "SANDBOX_BIND", + layer.run_with_env( + &[ + "--no-default-binds", + "--no-default-llm-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( - &["--no-default-binds", "config"], - "SANDBOX_BIND", + assert!(layer.exfail( + &["--no-default-binds", "--no-default-llm-binds", "config"], + "DEVLAYER_BIND", &format!("{dir},{dir}::ro"), )); @@ -173,15 +182,16 @@ 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", + "--no-default-llm-binds", "--config", &config, "--bind", @@ -189,14 +199,15 @@ 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); + assert_eq!(layer.last_stdout.trim(), dir); // A CLI mask overrides a bind from a config file - sandbox.run(&[ + layer.run(&[ "--no-default-binds", + "--no-default-llm-binds", "--config", &config, "--mask", @@ -205,10 +216,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 +228,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 02f6f77..071c7c2 100644 --- a/tests/ai_test_builtin_ignore_patterns.rs +++ b/tests/ai_test_builtin_ignore_patterns.rs @@ -5,50 +5,50 @@ 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/sandbox-builtin-test && echo 'test' > /tmp/sandbox-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!( - 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,21 +62,21 @@ fn test_builtin_ignore_patterns_tmp(mut sandbox: SandboxManager) -> Result<()> { ); // Clean up - sandbox.run(&["sh", "-c", "rm -rf /tmp/sandbox-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,42 +84,38 @@ 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", - "echo 'hidden' > ~/.sandbox-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!( - 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 ); @@ -132,35 +128,35 @@ fn test_builtin_ignore_patterns_home_dotfiles( ); // Clean up - sandbox.run(&[ + layer.run(&[ "sh", "-c", - "rm -rf ~/.sandbox-builtin-test ~/.sandbox-builtin-hidden-file", + "rm -rf ~/.layer-builtin-test ~/.layer-builtin-hidden-file", ])?; Ok(()) } #[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 11dac51..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/sandbox") + layer.test_filename("nested/storage/path/for/layer") ); - sandbox.epass(&["true"], "SANDBOX_STORAGE_DIR", &nested_storage); - sandbox.epass( + layer.epass(&["true"], "DEVLAYER_STORAGE_DIR", &nested_storage); + layer.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); + 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 2f9c6d9..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,17 +72,17 @@ 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(); 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 +98,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.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 sandboxes will be deleted") - ); - assert!(env.sandbox.last_stdout.contains(&old_stopped)); - assert!( - env.sandbox - .last_stdout - .contains("Delete operation cancelled") + .contains("The following layers will be deleted") ); + 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 sandboxes to clean.")); + assert!(env.layer.last_stdout.contains("No layers to clean.")); Ok(()) } diff --git a/tests/ai_test_concurrent_new.rs b/tests/ai_test_concurrent_new.rs new file mode 100644 index 0000000..61d8629 --- /dev/null +++ b/tests/ai_test_concurrent_new.rs @@ -0,0 +1,66 @@ +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(|_| { + 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 + .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_config_impls.rs b/tests/ai_test_config_impls.rs index e98f861..20c98b3 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,13 +34,13 @@ 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!("{}/.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); @@ -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,33 +89,33 @@ 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. .devlayer.toml in current directory + let test_dir = format!("generated-test-data/{}", layer.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 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"), - "Should pick up local .sandbox.toml config" + layer.last_stdout.contains("TRACE"), + "Should pick up local .devlayer.toml config" ); } // 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 a704e18..92dc92e 100644 --- a/tests/ai_test_config_option.rs +++ b/tests/ai_test_config_option.rs @@ -8,11 +8,11 @@ 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 - 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"); @@ -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 95142a1..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; @@ -9,135 +9,169 @@ use rstest::*; use std::fs; #[rstest] -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"); +fn test_get_or_create_with_corrupted_settings( + mut layer: LayerManager, +) -> Result<()> { + // First, create a working layer + let _output = layer.run(&["echo", "initial setup"])?; + + // 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 - assert!(settings_file.exists(), "Settings file should exist after initial sandbox creation at {}", settings_file.display()); - + + // Verify the layer was created and settings file exists + 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"]); - + // because the existing layer has corrupted settings + let success = layer.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(); - + let error_output = layer.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<()> { - // 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"); +fn test_get_or_create_with_unreadable_settings( + mut layer: LayerManager, +) -> Result<()> { + // First, create a working layer + let _output = layer.run(&["echo", "initial setup"])?; + + // 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 - assert!(settings_file.exists(), "Settings file should exist after initial sandbox creation"); - + + // Verify the layer was created and settings file exists + 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"]); - + let success = layer.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(); - + let error_output = layer.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<()> { - // 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"); +fn test_get_or_create_with_directory_as_settings_file( + mut layer: LayerManager, +) -> Result<()> { + // First, create a working layer + let _output = layer.run(&["echo", "initial setup"])?; + + // 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 - assert!(settings_file.exists(), "Settings file should exist after initial sandbox creation"); - + + // Verify the layer was created and settings file exists + 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"]); - + let success = layer.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(); - + let error_output = layer.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_cwd_bind.rs b/tests/ai_test_cwd_bind.rs new file mode 100644 index 0000000..c39a838 --- /dev/null +++ b/tests/ai_test_cwd_bind.rs @@ -0,0 +1,197 @@ +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.bind_cwd_in(dir); + layer +} + +#[rstest] +fn ai_test_cwd_bound_by_default(mut layer: LayerManager) -> Result<()> { + let dir = project_dir(&layer)?; + layer.bind_cwd_in(&dir); + + 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.bind_cwd_in(Path::new("/")); + + 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"])); + + // 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(()) +} + +#[rstest] +fn ai_test_cwd_bind_reenter_from_subdir(mut layer: LayerManager) -> Result<()> { + let dir = project_dir(&layer)?; + layer.bind_cwd_in(&dir); + 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.bind_cwd_in(&dir); + 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.bind_cwd_in(&dir); + 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(()) +} + +/// 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.bind_cwd_in(Path::new("/")); + 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.bind_cwd_in(&dir); + + 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.bind_cwd_in(&dir); + 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(()) +} + +/// `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_delete.rs b/tests/ai_test_delete.rs index 32a79ec..1fe5658 100644 --- a/tests/ai_test_delete.rs +++ b/tests/ai_test_delete.rs @@ -6,391 +6,401 @@ 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 sandboxes 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 - // For now it will show "No default sandbox found" - sandbox.run_with_stdin(&["delete"], "n\n")?; + // 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" + layer.run_with_stdin(&["delete"], "n\n")?; assert!( - sandbox + layer .last_stdout - .contains("The following sandboxes will be deleted") + .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 sandbox" - sandbox.run(&["delete", "-y"])?; + // is checked twice with contradictory logic, so it currently shows "No default layer" + 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 sandboxes 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 sandbox 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!("sandbox-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(); + let base_name = format!("devlayer-coverage-test-del-status-{}", rid()); + 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 sandboxes 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!("sandbox-coverage-test-delete-{}", rid()); - sandbox2.name = format!("sandbox-coverage-test-delete-{}", rid()); - sandbox3.name = format!("sandbox-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", "sandbox-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 sandbox:")) + .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-sandbox"])?; - assert!(sandbox.last_stdout.contains("No sandboxes 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 sandboxes 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 + // 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")?; + 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 + // 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); + 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 sandboxes 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 sandbox")); +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.hold()?; - // 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 sandboxes 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 sandboxes 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!("sandbox-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(); + let base_name = format!("devlayer-coverage-test-del-stopped-{}", rid()); + 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 sandboxes 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!("sandbox-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(); + let base_name = format!("devlayer-coverage-test-del-mixed-{}", rid()); + 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 sandboxes 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 +415,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 sandboxes 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 sandboxes 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 +551,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 sandboxes 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..8447785 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_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_error_paths.rs b/tests/ai_test_error_paths.rs index 1b3ddd6..8d0ddbd 100644 --- a/tests/ai_test_error_paths.rs +++ b/tests/ai_test_error_paths.rs @@ -9,75 +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; - let storage_dir = format!("--storage-dir=/proc/sandbox-coverage-{}", rid()); - assert!(sandbox.xfail(&["--new", &storage_dir, "config", "name"])); + // --join the fixture normally adds. + layer.no_default_options = true; + let storage_dir = + format!("--storage-dir=/proc/devlayer-coverage-{}", rid()); + 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_home_bind.rs b/tests/ai_test_home_bind.rs new file mode 100644 index 0000000..148af73 --- /dev/null +++ b/tests/ai_test_home_bind.rs @@ -0,0 +1,64 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use rstest::*; +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.bind_cwd_in(Path::new(&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(()) +} + +/// `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_ignore_rules.rs b/tests/ai_test_ignore_rules.rs index 3453fbb..e303e53 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 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 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,91 +675,92 @@ 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], "SANDBOX_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 DEVLAYER_IGNORED + layer.set_ignored(false); // Disable automatic --ignored let result = - sandbox.run_with_env(&["status", &test_dir], "SANDBOX_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 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")?; - let stdout = sandbox.last_stdout.clone(); - sandbox.set_ignored(true); // Reset back + // 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(); + 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 - let output = Command::new("sudo") - .env("SANDBOX_IGNORED", "false") - .args(["-E", &sandbox.sandbox_bin]) - .args([ - "-v", - "--ignored", - &format!("--name={}", &sandbox.name), - "status", - &test_dir, - ]) - .output()?; + layer.set_ignored(false); // Disable automatic --ignored + 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); 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))); @@ -769,20 +768,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#" @@ -820,7 +819,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!( @@ -831,7 +830,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() ])?; @@ -860,11 +859,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 { @@ -886,20 +885,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 @@ -910,7 +909,7 @@ README.md Build/ "#; let gitignore_path = Path::new(&test_dir).join(".gitignore"); - sandbox.run(&[ + layer.run(&[ "sh", "-c", &format!( @@ -920,7 +919,7 @@ Build/ ), ])?; - sandbox.run(&[ + layer.run(&[ "mkdir", "-p", Path::new(&test_dir).join("Build").to_str().unwrap(), @@ -942,11 +941,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_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/ai_test_layer_selection.rs b/tests/ai_test_layer_selection.rs new file mode 100644 index 0000000..602e980 --- /dev/null +++ b/tests/ai_test_layer_selection.rs @@ -0,0 +1,229 @@ +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. +/// +/// 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, + 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.bind_cwd_in(&root); + 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")?; + // 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_name)); + + 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_config_sync_no_layer_ok(layer: LayerManager) -> Result<()> { + let mut sel = Selection::new(layer)?; + let empty = sel.dir("empty")?; + + assert!(sel.pass(&empty, &["list"])); + // `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 + 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/ai_test_sandbox_settings.rs b/tests/ai_test_layer_settings.rs similarity index 85% rename from tests/ai_test_sandbox_settings.rs rename to tests/ai_test_layer_settings.rs index 005f948..49f0abd 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,18 @@ 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_sandbox".to_string(), + name: "test_layer".to_string(), + new_layer: false, storage_dir: PathBuf::from("/tmp/test_storage"), - sandbox_dir: PathBuf::from("/tmp/test_sandbox"), + layer_dir: PathBuf::from("/tmp/test_layer"), upper_cwd: PathBuf::from("/tmp/test_upper"), overlay_cwd: PathBuf::from("/tmp/test_overlay"), net: Network::None, @@ -27,7 +28,12 @@ fn create_test_config() -> ::sandbox::config::Config { ignored: false, bind_mounts: Vec::new(), no_default_binds: false, - audio: false, + no_default_llm_binds: false, + origin: ::devlayer::layer::LayerOrigin { + created_in: PathBuf::from("/tmp"), + bind_cwd: false, + }, + cwd_bind_is_home: false, cpus: None, memory: None, config_files: Vec::new(), @@ -38,7 +44,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"), @@ -52,7 +58,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); @@ -65,49 +71,49 @@ 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, &[]); - + 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(); 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(()) } #[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)); let mut config = create_test_config(); config.net = Network::None; - + let bind_mount = BindMount { source: PathBuf::from("/test/source"), target: PathBuf::from("/test/target"), @@ -127,19 +133,19 @@ 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)?; - + // Verify file was created and contains valid JSON assert!(settings_path.exists()); let file_content = fs::read_to_string(&settings_path)?; 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); assert_eq!(loaded_settings.mounts.len(), 2); @@ -152,48 +158,48 @@ 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); - + + let result = LayerSettings::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(()) } #[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(); assert!(error_msg.contains("Failed to parse settings.json")); - + Ok(()) } #[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"); - + 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 +207,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"), @@ -215,8 +221,8 @@ 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); assert!(result.is_ok()); @@ -228,26 +234,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); - + let settings = LayerSettings::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 +264,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(), @@ -267,22 +276,26 @@ 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 { 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 +303,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); - + let settings = LayerSettings::from_config(&config, &original_mounts); + // Add another mount let new_mounts = vec![ MountHash { @@ -309,9 +322,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 +337,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, &[]); - + + let settings = LayerSettings::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 +377,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, &[]); - + + let settings = LayerSettings::from_config(&original_config, &[]); + // Add another bind mount let bind2 = BindMount { source: PathBuf::from("/source2"), @@ -381,12 +396,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 +414,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, &[]); - + + 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(); 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 +452,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 = + LayerSettings::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/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(()) +} 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/ai_test_pid_file_trust.rs b/tests/ai_test_pid_file_trust.rs new file mode 100644 index 0000000..8bce811 --- /dev/null +++ b/tests/ai_test_pid_file_trust.rs @@ -0,0 +1,56 @@ +mod fixtures; + +use anyhow::Result; +use fixtures::*; +use rstest::*; +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<()> { + std::fs::write(layer.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 = other.pid1()?; + + 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 4a38b75..8caabcd 100644 --- a/tests/ai_test_resource_limits.rs +++ b/tests/ai_test_resource_limits.rs @@ -13,35 +13,36 @@ 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 -/// 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"]) { +/// Starts the layer with a CPU limit to find out if this machine lets us +/// 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.hold_with(&["--cpus=1"]).is_ok() { 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); - fs::read_dir("/sys/fs/cgroup/sandbox") +/// 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/devlayer") .ok()? .filter_map(|entry| entry.ok()) .map(|entry| entry.path()) @@ -53,137 +54,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(), - "SANDBOX_CPUS", + "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(), - "SANDBOX_MEMORY", + "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(), - "SANDBOX_CPUS", + "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"], - "SANDBOX_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"], - "SANDBOX_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,89 +191,100 @@ 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::/"); - - // Processes that join the running sandbox are in its cgroup too - let cgroup = host_cgroup(&sandbox).expect("sandbox cgroup should exist"); + 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 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 = - 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"))?; - if procs.lines().count() > 1 { + if fs::read_to_string(&procs)?.lines().count() > held { joined = true; break; } 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"])?; + // 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(&[ + // 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. 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 | tail > /dev/null; \ + "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 $?\"; \ 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,56 +296,56 @@ 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.hold_with(&["--no-config", "--cpus=1"])?; - // 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("sandbox 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)?; + // Kill the layer and its supervisor without cleaning up, leaving an + // empty cgroup behind + let cgroup = host_cgroup(&layer).expect("layer cgroup should exist"); + let pid = layer.pid1()?; + let supervisor = ppid_of(pid)?; std::process::Command::new("sudo") - .args(["kill", "-9", 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() { @@ -346,26 +356,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 +383,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 sandbox")); - 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 +456,79 @@ 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. + // 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"]; - sandbox.run_with_env( - &[&memory_only[..], &["/sys/fs/cgroup/memory.max"]].concat(), + layer.run_with_env( + &[ + "--no-config", + "--memory=64M", + "sh", + "-c", + "cat /sys/fs/cgroup/memory.max; sleep 3600 >/dev/null 2>&1 &", + ], "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("sandbox 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 +539,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 +552,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"], - "SANDBOX_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 +601,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( - "shares the limits of the sandbox it's running in (cpus=2 memory=unlimited)" + 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( - "shares the limits of the sandbox it's running in (cpus=unlimited memory=unlimited)" + 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("sandbox 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 0705ad5..f37b855 100644 --- a/tests/ai_test_run_media_mount.rs +++ b/tests/ai_test_run_media_mount.rs @@ -5,36 +5,36 @@ 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 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(&[ + let success = layer.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: {}", - sandbox.last_stderr + "Failed to bind mount to /run/media/devlayer-coverage-testing: {}", + 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..842e1f6 100644 --- a/tests/ai_test_sigterm.rs +++ b/tests/ai_test_sigterm.rs @@ -7,16 +7,14 @@ 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.hold()?; - sandbox.run(&["config", "sandbox_dir"])?; - let pid_file = format!("{}.pid", sandbox.last_stdout.trim()); - let pid = std::fs::read_to_string(&pid_file)?.trim().to_string(); + let pid = layer.pid1()?.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 +25,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/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/fixtures/fixture_sandbox.rs b/tests/fixtures/fixture_layer.rs similarity index 67% rename from tests/fixtures/fixture_sandbox.rs rename to tests/fixtures/fixture_layer.rs index ca9bd74..6b5db19 100644 --- a/tests/fixtures/fixture_sandbox.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}; @@ -17,7 +19,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") @@ -40,13 +42,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); @@ -56,7 +58,51 @@ pub fn get_sandbox_bin() -> String { absolute_path.to_string_lossy().to_string() } -pub struct SandboxManager { +/// 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 +} + +/// 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, pub last_stderr: String, @@ -64,15 +110,20 @@ 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 + /// 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 SandboxManager { +impl LayerManager { 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( @@ -95,13 +146,43 @@ 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 + bind_cwd: false, + cwd: None, + } + } + + /// Runs commands from `dir` with the cwd bind on, as a user starting + /// devlayer in `dir` would + #[allow(dead_code)] + 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 + /// 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"]); + } + } + + /// `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 + fn apply_cwd(&self, cmd: &mut Command) { + if let Some(cwd) = &self.cwd { + cmd.current_dir(cwd); } } - /* 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; @@ -115,21 +196,36 @@ impl SandboxManager { #[allow(dead_code)] pub fn dir(&self) -> Result { - let mut cmd = Command::new("sudo"); - cmd.args(["-E", &self.sandbox_bin]); + let mut cmd = Command::new(&self.devlayer_bin); - if self.no_sudo { - cmd = Command::new(&self.sandbox_bin); - } - - cmd.args([format!("--name={}", &self.name)]); - cmd.args(["config", "sandbox_dir"]); + 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(); 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!( @@ -159,12 +255,7 @@ impl SandboxManager { use std::io::Write; use std::process::Stdio; - let mut cmd = Command::new("sudo"); - cmd.args(["-E", &self.sandbox_bin]); - - if self.no_sudo { - cmd = Command::new(&self.sandbox_bin); - } + let mut cmd = Command::new(&self.devlayer_bin); if !self.no_default_options && !args.iter().any(|arg| { @@ -181,17 +272,13 @@ impl SandboxManager { 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)]); } + 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(), @@ -201,6 +288,11 @@ impl SandboxManager { .join(" ") ); + 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))?; @@ -248,16 +340,11 @@ impl SandboxManager { 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.sandbox_bin]); - - if self.no_sudo { - cmd = Command::new(&self.sandbox_bin); - } if !self.no_default_options && !args.iter().any(|arg| { @@ -272,10 +359,11 @@ impl SandboxManager { } 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)]); } + self.add_no_bind_cwd(&mut cmd, args); cmd.args(args); println!( "Running command: {} {}", @@ -285,6 +373,8 @@ impl SandboxManager { .collect::>() .join(" ") ); + self.apply_cwd(&mut cmd); + let mut cmd = self.privileged(cmd); match cmd.output() { Ok(output) => { self.last_stdout = @@ -317,18 +407,31 @@ impl SandboxManager { } } + /// 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 run_in_background(&mut self, args: &[&str]) -> Result { - let mut cmd = Command::new("sudo"); - cmd.args(["-E", &self.sandbox_bin]); + pub fn hold(&mut self) -> Result<()> { + self.hold_with(&[]) + } - if self.no_sudo { - cmd = Command::new(&self.sandbox_bin); - } + /// 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(&self.devlayer_bin); if !self.no_default_options { - cmd.args([format!("--name={}", &self.name)]); + cmd.args([format!("--join={}", &self.name)]); } + self.add_no_bind_cwd(&mut cmd, args); cmd.args(args); println!( @@ -340,6 +443,8 @@ impl SandboxManager { .join(" ") ); + self.apply_cwd(&mut cmd); + let mut cmd = self.privileged(cmd); Ok(cmd.spawn()?) } @@ -394,14 +499,15 @@ 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; self.ignored = true; + self.cwd = None; 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; @@ -421,11 +527,11 @@ 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 sandbox: {}", e); + warn!("Failed to delete layer: {}", e); warn!("last_stderr: {}", self.last_stderr); warn!("last_stdout: {}", self.last_stdout); } @@ -437,6 +543,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 b5e0621..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<()> { - let dest_host_dir = "/delete-me-this-is-a-sandbox-coverage-test-dir-for-rename-across-mount"; - let dir_to_move = sandbox.test_filename("dir_to_move"); +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 = 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 ec98ce6..0862aa4 100644 --- a/tests/isolated_test_accept_root.rs +++ b/tests/isolated_test_accept_root.rs @@ -9,10 +9,10 @@ use std::{path::Path, process::Command}; * and tests are run in parallel per file. */ #[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"; +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"; Command::new("sudo").arg("mkdir").arg(dirname).output()?; Command::new("sudo").arg("touch").arg(&filename).output()?; Command::new("sudo") @@ -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 a49e5f6..09e0b11 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 sandboxes"] -fn test_clean_deletes_running_test_sandboxes() -> Result<()> { - let mut sandbox = sandbox(); - let name = sandbox.name.clone(); +#[ignore = "Ignoring as this will delete old non test ephemeral layers"] +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 sandboxes:")); - assert!(sandbox.last_stdout.contains(&name)); + layer.hold()?; + 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 39c65e7..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", - "sandbox-coverage-new-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!("sandbox.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 a08cff7..7881480 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 sandboxes"] +#[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,8 +26,8 @@ fn test_stop_all() -> Result<()> { let lines: Vec<&str> = ps_output .lines() .filter(|line| { - // excluding --name excludes the sandbox 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 { @@ -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 @@ -48,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()); @@ -59,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()?; @@ -67,11 +65,11 @@ 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()); - 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 54d42b0..e3a3611 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 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"])?; - 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 "sandbox" 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"])?; + /* Despite bad state that the above "devlayer" is in, the following is expected to work. */ + 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 { @@ -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,12 +54,12 @@ 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); - assert!(sandbox1.pass(&["stop", "--all"])); + assert!(layer1.pass(&["stop", "--all"])); c1.wait()?; let ps = Command::new("ps").arg("aux").output()?; @@ -67,17 +67,17 @@ 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()); - 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..83e288c 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 { @@ -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,12 +38,12 @@ 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); - 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()?; @@ -51,13 +51,13 @@ 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); - 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..8f13822 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 { @@ -20,7 +20,7 @@ fn test_stop_stop_children(mut sandbox: SandboxManager) -> 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,13 +34,13 @@ fn test_stop_stop_children(mut sandbox: SandboxManager) -> 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); // kill them - assert!(sandbox.pass(&["stop"])); + assert!(layer.pass(&["stop"])); // wait for that to happen c1.wait()?; @@ -52,7 +52,7 @@ fn test_stop_stop_children(mut sandbox: SandboxManager) -> 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_sync.rs b/tests/isolated_test_sync.rs index 69da3a6..f3ce559 100644 --- a/tests/isolated_test_sync.rs +++ b/tests/isolated_test_sync.rs @@ -6,26 +6,26 @@ 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 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"); + 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 std::fs::remove_file(upper_dir.join(&t)).context(format!( @@ -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..9ded799 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,44 +63,43 @@ 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( - &["accept"], + 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..7253b57 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..d206ab7 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 1ff0a0b..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], - "SANDBOX_MASK", + "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], - "SANDBOX_MASK", + "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], - "SANDBOX_BIND", + "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], - "SANDBOX_BIND", + "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], - "SANDBOX_BIND", + "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"], - "SANDBOX_MASK", + "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 1bc01e2..e87195a 100644 --- a/tests/test_cli.rs +++ b/tests/test_cli.rs @@ -5,120 +5,120 @@ 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/sandbox", "config"])); - assert!(sandbox.last_stdout.contains("storage_dir=/tmp/sandbox")); - - assert!(sandbox.pass(&["--storage-dir=/tmp/sandbox", "config"])); - assert!(sandbox.last_stdout.contains("storage_dir=/tmp/sandbox")); +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(&["--join", "test-cli", "config"])); + assert!(layer.last_stdout.contains("name=test-cli")); + assert!(layer.pass(&["--join=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=sandbox")); - assert!(sandbox.last_stdout.contains("net=none")); + layer.no_default_options = true; + assert!(layer.pass(&["--no-config", "config"])); + assert!(layer.last_stdout.contains("name=devlayer")); + assert!(layer.last_stdout.contains("net=host")); // 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" + join = "parent" log_level = "trace" - storage_dir = "/tmp/sandbox1" + 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/sandbox2" + storage_dir = "/tmp/layer2" bind = [".cargo"] "#; - let _ = std::fs::remove_file(".sandbox.toml"); - let _ = std::fs::remove_file("../.sandbox.conf"); - - std::fs::write("../.sandbox.conf", parent_config)?; - sandbox.no_default_options = true; - assert!(sandbox.epass(&["config"], "SANDBOX_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(".cargo")); - - std::fs::write(".sandbox.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")); - - std::fs::remove_file(".sandbox.toml")?; - std::fs::remove_file("../.sandbox.conf")?; + let _ = std::fs::remove_file(".devlayer.toml"); + let _ = std::fs::remove_file("../.devlayer.conf"); + + std::fs::write("../.devlayer.conf", parent_config)?; + 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)?; + 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")?; 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.last_stdout.contains("net=host")); - assert!(sandbox.epass(&["config"], "SANDBOX_NET", "none")); - assert!(sandbox.last_stdout.contains("net=none")); - assert!(sandbox.exfail(&["config"], "SANDBOX_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"], "SANDBOX_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"], "SANDBOX_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"], "SANDBOX_NAME", "")); - assert!(sandbox.epass(&["config"], "SANDBOX_NAME", "test-cli-with-env")); + assert!(layer.epass(&["config"], "DEVLAYER_JOIN", "")); + assert!(layer.epass(&["config"], "DEVLAYER_JOIN", "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!(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..3cc3307 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..af2dfd4 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..c20a015 --- /dev/null +++ b/tests/test_layer_failures.rs @@ -0,0 +1,147 @@ +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); + let pid = pid_file_content + .split_whitespace() + .next() + .unwrap_or_default(); + assert!(pid.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 665520d..d2b6d09 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::*; @@ -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_sandbox_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,29 +64,31 @@ 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")); + // 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(&pid_file_name)?; std::fs::remove_file(&lock_file_name)?; Ok(()) } #[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 @@ -97,14 +99,18 @@ fn test_list_stale_pid_file(mut sandbox: SandboxManager) -> 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()); - - assert!(sandbox.run(&["list", &sandbox.name.clone()]).is_ok()); - eprintln!(">>>> {} <<<<", sandbox.last_stdout); - eprintln!(">>>> {} <<<<", sandbox.last_stderr); + 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); + 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 3548f8e..dd0685f 100644 --- a/tests/test_misc.rs +++ b/tests/test_misc.rs @@ -8,24 +8,25 @@ 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)]); + 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(sandbox: SandboxManager) -> Result<()> { .contains("Failed to parse SUDO_UID") ); - let mut cmd = Command::new("sudo"); - cmd.args(["-E", "SUDO_GID=nan", &sandbox_bin]); - cmd.args([format!("--name={}", &sandbox.name)]); + 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(sandbox: SandboxManager) -> Result<()> { .contains("Failed to parse SUDO_GID") ); - let mut cmd = Command::new("sudo"); - cmd.args(["-E", "SUDO_HOME=", &sandbox_bin]); - cmd.args([format!("--name={}", &sandbox.name)]); + 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(sandbox: SandboxManager) -> Result<()> { .contains("Home directory is not absolute") ); - let mut cmd = Command::new("sudo"); - cmd.args(["-E", "SUDO_HOME=~/foobar", &sandbox_bin]); - cmd.args([format!("--name={}", &sandbox.name)]); + 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(sandbox: SandboxManager) -> Result<()> { .contains("Home directory is not absolute") ); - let mut cmd = Command::new("sudo"); - cmd.args(["-E", "SUDO_HOME=/invalid-home-directory", &sandbox_bin]); - cmd.args([format!("--name={}", &sandbox.name)]); + 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,15 +93,11 @@ fn test_weird_sudo_env_variables(sandbox: SandboxManager) -> Result<()> { absolute_dir_with_spaces.display() ); - let mut cmd = Command::new("sudo"); - cmd.args([ - "-E", - format!("SANDBOX_STORAGE_DIR={}", absolute_dir_with_spaces.display()) - .as_str(), - &sandbox_bin, - ]); - cmd.args([format!("--name={}", &sandbox.name)]); + 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)); @@ -117,14 +118,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!("--join={}", &layer.name)]); cmd.args(["whoami"]); let setuid_output = cmd.output()?; @@ -134,49 +135,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_sandbox_env_variable_is_set(mut sandbox: SandboxManager) -> Result<()> { - let output = sandbox.run(&["sh", "-c", "echo -n $SANDBOX"])?; - 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(()) } @@ -186,11 +187,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(); @@ -211,21 +212,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 069f3ca..fc2cc50 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")); + layer.hold()?; + 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 sandbox")); +fn test_no_mounts_found(mut layer: LayerManager) -> Result<()> { + assert!(layer.exfail(&["env"], "TEST_NO_MOUNTS_FOUND", "1")); + layer.hold()?; + 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<()> { + layer.hold()?; + 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")); + layer.hold()?; + 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")); + layer.hold()?; + 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")); + layer.hold()?; + 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<()> { + layer.hold()?; - 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 4243b42..9dcebaf 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"], "SANDBOX_NAME", "foo")); - assert!(sandbox.exfail(&["--last", "ls"], "SANDBOX_NAME", "foo")); + assert!(layer.xfail(&["--new", "--last", "ls"])); + 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(()) } #[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 sandboxes found")); + assert!(layer.exfail(&["--last", "-v", "true"], "TEST_LAST_IS_EMPTY", "1")); + assert!(layer.last_stderr.contains("No devlayer 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..72f352a 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 77e6d17..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 sandbox")); - 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 sandbox 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..d23fa25 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(()) } 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' <