summaryrefslogtreecommitdiff
path: root/internal/namespace
AgeCommit message (Collapse)Author
3 daysrefactor: implement dependency injection and enable parallel testingJames O'Doherty
This commit refactors the core system operations to use a manager-based dependency injection pattern, eliminating global state and resolving data races in the test suite. Architecture: - Introduced NetworkManager and NetworkOps interface in internal/network to abstract netlink calls. - Introduced MountOps and FileSystem interfaces in internal/namespace to abstract mount and filesystem operations. - Introduced TunnelManager in internal/wireguard to coordinate tunnel lifecycle using the new abstractions. - Updated internal/cli and internal/manager to use these managers. Testing: - Restored t.Parallel() to unit tests in internal/network and internal/wireguard. - Implemented setupParallelEnv and an enhanced mockFS in wireguard_unit_test.go to ensure complete test isolation. - Added bootstrap_test.go to verify launcher preparation logic in internal/namespace without requiring syscall.Exec. - Resolved data races in internal/network tests. CLI: - Added support for -h, --help, and -help flags for the main command. Verification: - Passed all tests (unit, integration, E2E). - Verified zero data races with 'go test -race'. - Passed golangci-lint and go vet.
11 daysrefactor: remove dependency on ip CLI tool and abstract network logicJames O'Doherty
Eliminate the external dependency on the `ip` (iproute2) command-line tool by centralizing network configuration and diagnostics within a new `internal/network` package using the `netlink` library. Changes: - Introduced `internal/network` package to handle network interface listing and configuration. - Replaced `exec.Command("ip", "link")` in `internal/namespace.VerifyIsolation` with `network.ListInterfaces()`. - Improved `VerifyIsolation` to explicitly ensure only the loopback interface is present in a fresh network namespace. - Moved interface and routing configuration logic from `internal/wireguard` to `internal/network`. - Removed unnecessary `os/exec` imports from network-related files. This change increases the tool's portability by removing the requirement for `iproute2` to be installed in the target environment.
11 daysrefactor: decouple namespace operations and improve test coverageJames O'Doherty
- Introduce `namespace.Ops` interface to decouple `Manager` from system-level namespace operations, enabling easier unit testing via mocks. - Add unit tests for `internal/paths` to verify path resolution logic across different environment configurations. - Implement `EnsureBinary` helper in E2E tests to gracefully skip tests when `WG_WRAP_BIN` is not set, allowing `go test ./...` to pass in non-build environments. - Apply project-wide formatting and fix linting issues.
11 daysrefactor: simplify architecture and improve documentationJames O'Doherty
- Extract orchestration logic from `internal/cli` into a new `internal/manager` package for better composability. - Migrate technical implementation details from README.md to package-level godoc strings. - Rewrite README.md to be more user-centric, focusing on quick start and usage. - Add comprehensive documentation for exported structs and fields across the project. - Verify all changes with `go fmt`, `go vet`, `golangci-lint`, and full E2E test suite.
12 daysclean up debugging prints and silence successful execution outputJames O'Doherty
- Remove leftover DEBUG prints from CLI and wireguard internal packages. - Silence stdout during successful command wrapping to ensure only the wrapped command's output is visible. - Redirect all warnings and internal errors to stderr. - Implement a verbose mode via `WG_WRAP_VERBOSE=1` to enable tunnel status messages. - Update E2E tests to use verbose mode for verification of tunnel lifecycle events. - Fix errcheck linting issue in wireguard.go and apply go fmt.
12 daysfix: resolve resource leaks and improve namespace lifecycle managementJames O'Doherty
- Fix DNS resolver leaks by creating temporary resolv.conf files within the profile's runtime directory and ensuring robust cleanup. - Fix isolation block directory leaks by explicitly removing the block directory during namespace unpinning. - Improve namespace lifecycle management: - Register processes before joining an active namespace to prevent race conditions in reference counting. - Update `IsLastProcess` and corresponding tests to reflect the unregister-then-check cleanup flow. - Improve test reliability and correctness: - Convert `TestAppRun_ProfileDirInjection` to use separate binary execution, preventing process replacement and ensuring `t.TempDir()` cleanup. - Replace hardcoded test configuration paths with `t.TempDir()` in `mount_leak_test.go`. - Implement `SetEnvOverrides` helper for cleaner environment variable management in E2E tests. - Improve E2E lifecycle tests with better environment handling and output redirection.
2026-05-29refactor: rename module to git.theodohertyfamily.com/wg-wrap and apply ↵James O'Doherty
public domain license - Update go.mod and all internal imports to reflect the new module path - Add LICENSE file with the Unlicense (public domain dedication) - Increase timeouts in e2e lifecycle tests to prevent flaky failures - Verify all tests, linting, and formatting pass with the new module name
2026-05-29feat: harden bootstrap and optimize network data pathJames O'Doherty
- Security: Eliminate namespace escape risk by removing `HostBind` and enforcing `FDBind` using pre-opened host socket FDs. - Security: Replace unsafe `atoi` with `strtol` and strict validation in the C launcher to prevent malformed PID joins. - Stability: Fix PID wraparound by storing session timestamps in PID files to detect recycled PIDs. - Stability: Resolve DNS mount leaks by implementing proper unmounting of `/etc/resolv.conf` during tunnel shutdown. - Performance: Optimize `FDBind` throughput by implementing batch packet processing in the receive loop. - Deployment: Implement `memfd_create` for the C launcher to support `noexec` temporary directories and reduce disk I/O. - Maintenance: Replace external `ip` CLI dependency with native `netlink` library for robust network configuration. - Quality: Fix all `golangci-lint` errors and replace remaining panics with explicit error handling.
2026-05-29refactor: improve resource management and cleanup patternsJames O'Doherty
- Simplify namespace bootstrapping by introducing `prepareLauncher` helper - Implement a cleanup stack in `StartTunnel` to ensure orderly resource release on error - Streamline temporary file and mount lifecycles in `ConfigureResolvConf` and `BlockHostServices` - Ensure `Tunnel.Close()` also closes the underlying TUN device - Reduce redundant manual cleanup calls using defer-based error handling
2026-05-29feat: implement robust namespace lifecycle and resilience suiteJames O'Doherty
- Replace marker-file pinning with kernel bind-mount anchors for reliable namespace persistence. - Implement atomic "last-man-out" cleanup sequence using ProfileLock, preventing namespace leaks and race conditions. - Add comprehensive resilience test suite covering: - Crash recovery from stale runtime state. - Host network change stability. - Configuration hot-swap session persistence. - Resource exhaustion and high-churn lifecycle stress. - Align documentation and test expectations with rootless session-based persistence. - Fix argument integrity and isolation leaks. - Ensure 100% pass rate for all E2E and integration tests.
2026-05-29Refactor rootless namespace joining to use C launcherJames O'Doherty
Fix an architectural shortfall where concurrent sessions failed to share the target network and mount namespaces. Because the Go runtime is multi-threaded, calling unix.Setns with CLONE_NEWNS from Go always returned EINVAL, silently forcing concurrent runs to fall back to bootstrapping separate isolated namespaces and separate WireGuard connections. This commit resolves the issue by extending the embedded single-threaded C launcher to handle namespace joining, and introducing a host-to-isolated path propagation pattern: 1. Launcher setns Support: The C launcher now checks for WG_WRAP_JOIN_PID in the environment. If present, it joins the User, Mount, and Network namespaces of the active PID in single-threaded mode before executing the Go binary. 2. BootstrapJoin Integration: Implemented namespace.BootstrapJoin to transition joining sessions via the launcher. 3. Path Preservation: Export WG_WRAP_HOST_RUNTIME_BASE_DIR from the host to ensure the isolated instance maps the profile and PID directories to the exact same location. 4. Redundant Tunnel Bypass: Detect joined sessions via WG_WRAP_JOINED=1 in the CLI and bypass starting a duplicate WireGuard tunnel on the occupied tun0. 5. Testing: Added tests/e2e/sharing_test.go to assert namespace ID equality, which now passes successfully. 6. Git Tracking: Fixed .gitignore overmatch to stop ignoring cmd/wg-wrap/.
2026-05-29security, refactor: resolve critical namespace escapes, path traversal, ↵James O'Doherty
concurrency races, and resource leaks This commit addresses several security vulnerabilities, undefined behaviors, race conditions, and resource leaks across the application: 1. Path Traversal & Arbitrary File/Directory Actions: - Implemented `IsValidProfileName` in `internal/cli/cli.go` to restrict profile names to alphanumeric characters, dashes, and underscores. - Applied validation to all CLI paths (`--profile`, `import`, `configure`, `delete`, `stop`) to prevent directory traversal and unauthorized directory or file creations/deletions. - Added `TestIsValidProfileName` in `internal/cli/cli_test.go`. 2. Network Namespace Escape via Compromised Thread recycling: - Fixed `HostBind.Open` in `internal/wireguard/wireguard.go` to panic immediately instead of returning an error if restoring the isolated namespace fails. This prevents Go from returning the compromised thread (still in host namespace) to the runtime pool. 3. Concurrency Race Conditions & Thread Migration: - Added `runtime.LockOSThread()` in `JoinExistingNamespace` (`internal/namespace/pinning.go`) to ensure the goroutine stays on the modified namespace thread before executing the command. - Implemented profile locking using advisory file locks (`unix.Flock`) on a `.lock` file in the user's runtime directory (with platform stubs in `internal/namespace/lock_linux.go` and `internal/namespace/lock_stub.go`). - Integrated locking during `App.Run` and `App.ExecuteCommand`, releasing the lock right before spawning the wrapped process. 4. File Descriptor Leaks on Bootstrap Failures: - Refactored `Bootstrap()` in `internal/namespace/namespace.go` to use named return values and a deferred cleanup loop that closes `execFd`, `hostNetFd`, and the duplicated `hostSocketFd` if `syscall.Exec` fails. - Added an explicit `conn.Close()` on the original socket connection after duplication. 5. Glibc Undefined Behavior / Crash on argc == 0: - Corrected `internal/namespace/launcher_src/launcher.c` to not reference `argv[0]` when `argc < 1`. Recompiled `internal/namespace/launcher.bin`. 6. DNS Fallback Usability & Import Safety: - Added validation in `ExecuteCommand` to issue a warning when falling back to `1.1.1.1` if the configuration does not route all traffic (`0.0.0.0/0` or `::/0`). - Prevented silent overwrites in `handleProfileImport` if the destination profile already exists, and added a corresponding unit test verifying failure.
2026-05-29refactor: optimize file cleanups, propagate exit codes, and fix MakefileJames O'Doherty
- Unlink the temporary bootstrap launcher binary immediately after opening a read-only descriptor to it, then execute via `/proc/self/fd/<fd>` to ensure zero-disk footprint on execution. - Unlink temporary `/tmp/resolvconf*` files immediately after successful bind-mounting over `/etc/resolv.conf`. - Prune parent ephemeral profile directories when unpinning a namespace, leaving zero directories behind once empty. - Propagate the exact exit status of the wrapped command to the host process using `errors.As` and `*exec.ExitError` instead of defaulting to exit code 1. - Added E2E automated test `TestExitCodePropagation` to verify exit status delivery. - Added the `$(BINARY)` target to `.PHONY` in the Makefile to delegate dependency tracking to Go's compiler cache, ensuring modified Go files are rebuilt during `make test`.
2026-05-29feat: implement userspace wireguard data-path and unprivileged host fd-passingJames O'Doherty
- Implement complete rootless network namespace bootstrap via C launcher using unshare(CLONE_NEWUSER | CLONE_NEWNS | CLONE_NEWNET). - Resolve unprivileged network isolation blackhole via host-socket preservation (FD passing): open client UDP sockets on the host pre-isolation, clear O_CLOEXEC, and ingest them via custom `FDBind` inside the sandbox. - Implement isolated routing table automation over `tun0` (addresses, MTU, default routes). - Implement persistent, multi-process namespace sharing and joining using reference-counted PID files and the setns system call. - Write robust, self-contained E2E data plane test suites in `tests/e2e/e2e_test.go` using a mock UDP listener. - Update project documentation (`README.md` and `AGENTS.md`) to reflect completed milestones. - Ensure 100% test passing rate and zero lint/staticcheck warnings.
2026-05-22refactor: unify path management and complete profile management systemJames O'Doherty
- Create internal/paths package for unified config and runtime directory resolution - Implement robust WireGuard config parsing in pkg/wgconf - Implement profile management subcommands: list, import, configure, delete, stop - Fix namespace pinning path collisions (separating .ns files from pids directories) - Implement and verify namespace unpinning logic - Fix linting errors and improve error handling across the project
2026-05-22Fix PID lifecycle race and improve CLI routing for diagnostic commandsJames O'Doherty
2026-05-22Refactor lifecycle to support XDG_RUNTIME_DIR and fix binary pathing in E2E ↵James O'Doherty
tests
2026-05-22Implement automatic namespace lifecycle cleanup with last-man-out reference ↵James O'Doherty
counting
2026-05-22Security hardening: prevent shell injection and null-byte crashes, implement ↵James O'Doherty
8-bit clean argument fuzzing and portable E2E binary discovery
2026-05-22feat: add argument verification diagnostic and secure temp files for launcherJames O'Doherty
2026-05-22docs: update README and AGENTS.md to reflect embedded launcher architectureJames O'Doherty
2026-05-22feat: implement rootless network isolation bootstrap and C launcherJames O'Doherty
2026-05-22Implement platform compatibility stubs and update AGENTS.mdJames O'Doherty
2026-05-22Refactor CLI for testability and implement hermetic config path injectionJames O'Doherty
2026-05-22Scaffold wg-wrap project structure and toolchainJames O'Doherty