diff --git a/.github/workflows/installer-ci.yml b/.github/workflows/installer-ci.yml index 1aaa5e74..6a7de5ec 100644 --- a/.github/workflows/installer-ci.yml +++ b/.github/workflows/installer-ci.yml @@ -123,6 +123,31 @@ jobs: run: go test -race -v ./... working-directory: installer + privilege-test: + name: Installer Privilege Regression + needs: build + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: installer/go.mod + - uses: arduino/setup-task@v2 + with: + repo-token: ${{ github.token }} + - name: Install privilege test dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends sudo expect passwd util-linux + - name: Test installer privileges on the disposable Ubuntu runner + run: task test:privilege + working-directory: installer + env: + INSTALLER_PRIVILEGE_TEST_DISPOSABLE: '1' + e2e-test: name: E2E Tests needs: build @@ -385,7 +410,7 @@ jobs: ci-status: name: Installer CI Status if: always() - needs: [changes, build, test, e2e-test] + needs: [changes, build, test, privilege-test, e2e-test] runs-on: ubuntu-latest steps: - name: Check job results @@ -393,11 +418,14 @@ jobs: echo "changes: ${{ needs.changes.result }}" echo "build: ${{ needs.build.result }}" echo "test: ${{ needs.test.result }}" + echo "privilege-test: ${{ needs.privilege-test.result }}" echo "e2e-test: ${{ needs.e2e-test.result }}" if [[ "${{ needs.changes.result }}" == "failure" || \ "${{ needs.build.result }}" == "failure" || \ "${{ needs.test.result }}" == "failure" || \ + "${{ needs.privilege-test.result }}" == "failure" || \ + "${{ needs.privilege-test.result }}" == "cancelled" || \ "${{ needs.e2e-test.result }}" == "failure" ]]; then echo "One or more jobs failed" exit 1 diff --git a/.opencode/agents/cheapest-go-worker.md b/.opencode/agents/cheapest-go-worker.md index 6ca8993d..fa24ec85 100644 --- a/.opencode/agents/cheapest-go-worker.md +++ b/.opencode/agents/cheapest-go-worker.md @@ -2,8 +2,7 @@ name: cheapest-go-worker description: "Use this project-local worker for Go implementation tasks assigned to the cheapest model tier. It is intended for straightforward Go/config changes with clear acceptance criteria." mode: subagent -model: openai/gpt-5.5 -reasoningEffort: low +model: openai/gpt-6-luna#high permission: edit: allow bash: allow @@ -19,7 +18,7 @@ permission: building-go-binaries: allow --- -You are a project-local Go implementation worker running at the cheapest tier with low reasoning effort. +You are a project-local Go implementation worker running at the cheapest tier with high reasoning effort. Load these skills immediately before working: `managing-chezmoi`, `writing-go-code`, `writing-go-tests`, `testing-go-code`, `linting-go-code`, and `building-go-binaries`. diff --git a/.opencode/agents/mid-tier-go-worker.md b/.opencode/agents/mid-tier-go-worker.md index 67626e1e..d192c98f 100644 --- a/.opencode/agents/mid-tier-go-worker.md +++ b/.opencode/agents/mid-tier-go-worker.md @@ -2,8 +2,7 @@ name: mid-tier-go-worker description: "Use this project-local worker for Go implementation tasks assigned to the mid-tier model. It is intended for Go changes with moderate integration, edge cases, or coordination risk." mode: subagent -model: openai/gpt-5.5 -reasoningEffort: medium +model: openai/gpt-6.1-terra#medium permission: edit: allow bash: allow diff --git a/.opencode/agents/most-capable-go-worker.md b/.opencode/agents/most-capable-go-worker.md index 86b41075..d79d43cd 100644 --- a/.opencode/agents/most-capable-go-worker.md +++ b/.opencode/agents/most-capable-go-worker.md @@ -2,8 +2,7 @@ name: most-capable-go-worker description: "Use this project-local worker for Go implementation tasks assigned to the most capable model tier. It is intended for complex Go work requiring broad reasoning or high correctness confidence." mode: subagent -model: openai/gpt-5.5 -reasoningEffort: xhigh +model: openai/gpt-6.1-sol#medium permission: edit: allow bash: allow diff --git a/installer/.gitignore b/installer/.gitignore index eb1dafb6..8aac57b6 100755 --- a/installer/.gitignore +++ b/installer/.gitignore @@ -51,6 +51,10 @@ # Expect scripts !test-interactive-gpg.exp +# Shared privilege integration checks +!tests/privilege/*.sh +!tests/privilege/*.exp + # Agent rules !AGENTS.md !CLAUDE.md diff --git a/installer/AGENTS.md b/installer/AGENTS.md index 99ac84c8..3dafef63 100644 --- a/installer/AGENTS.md +++ b/installer/AGENTS.md @@ -40,6 +40,7 @@ installer/ │ └── httpclient/ # HTTP client interface ├── cli/ # Interactive UI components ├── internal/config/ # Embedded YAML configs +├── tests/privilege/ # Shared real-sudo integration test scripts ├── Taskfile.yml # Task runner commands └── .goreleaser.yaml # Release configuration ``` @@ -91,11 +92,16 @@ OS-level operations (user management, environment, program queries, permissions) ### Privilege Escalator (utils/privilege/) -Smart privilege escalation (prefers sudo, falls back to doas): +Privilege escalation selects commands without probing authentication: root runs +the command directly; a non-root user uses installed `sudo` in preference to +installed `doas`; and a non-root user with neither tool receives an actionable +error. Authentication occurs when the selected command runs. In particular, +`sudo` may prompt through the terminal; the installer does not read or store the +password. ```go -escalatedCmd, escalatedArgs, err := escalator.EscalateCommand("apt-get", []string{"install", "git"}) -isRoot := escalator.IsRunningAsRoot() +escalated, err := escalator.EscalateCommand("apt-get", []string{"install", "git"}) +isRoot, err := escalator.IsRunningAsRoot() ``` ## Development Commands @@ -110,6 +116,32 @@ isRoot := escalator.IsRunningAsRoot() | `task cov` | Generate coverage report | | `task bench` | Run benchmarks | | `task sloc` | Print lines of code stats | +| `task test:privilege:build` | Cross-compile the Linux privilege test binary | +| `task test:privilege` | Run the real-sudo privilege checks on disposable Ubuntu or Debian | + +## Privilege Integration Tests + +The privilege integration test checks real authentication during APT setup +and shell setup, each with a cold sudo cache and either the correct password or +a rejected password. It uses the default progress display. + +The shared test logic is in `tests/privilege/`. It creates a separate +password-required user and a temporary root-owned workspace, drives the real +password prompt through a terminal, and records calls to real `apt`, `tee`, and +`usermod`. The checks use an offline local package and per-command APT source +options, so they do not change the machine's configured APT sources. The shell +check uses a unique temporary shell symlink and does not remove system shells. + +Successful authentication must produce the protected root-owned effect. Before +authentication, and after a rejected password, the checks require no effects and +no unprivileged retry. The runner resets state between checks and cleans up the +user, package, sudo rules, temporary workspace, and `/etc/shells`. + +Run `task test:privilege` only on a disposable Ubuntu or Debian machine. The +runner checks the distribution before it changes state, and it requires +`INSTALLER_PRIVILEGE_TEST_DISPOSABLE=1`; do not run it on a personal Linux +machine. GitHub Actions runs it directly on an `ubuntu-latest` runner without +Docker. ## Adding Features diff --git a/installer/Taskfile.yml b/installer/Taskfile.yml index 3b81968e..88d4d123 100644 --- a/installer/Taskfile.yml +++ b/installer/Taskfile.yml @@ -34,6 +34,30 @@ tasks: cmds: - go test -race ./... {{ .CLI_ARGS }} + test:privilege:build: + desc: Compile the installer privilege caller test for Linux + vars: + TARGET_ARCH: '{{default .ARCH .PRIVILEGE_TEST_ARCH}}' + OUTPUT: '{{default "bin/privilege.test" .OUTPUT}}' + env: + GOOS: linux + GOARCH: '{{.TARGET_ARCH}}' + CGO_ENABLED: '0' + cmds: + - mkdir -p bin + - go test -c -o '{{.OUTPUT}}' ./cmd + + test:privilege: + desc: Run real-authentication checks (disposable Ubuntu/Debian only) + preconditions: + - sh: test "$(uname -s)" = Linux + msg: Run task privilege:test from installer/docker/ for local testing on macOS + - sh: test "${INSTALLER_PRIVILEGE_TEST_DISPOSABLE:-}" = 1 + msg: Set INSTALLER_PRIVILEGE_TEST_DISPOSABLE=1 only on a disposable Linux machine + cmds: + - task: test:privilege:build + - sudo env INSTALLER_PRIVILEGE_TEST_DISPOSABLE=1 bash tests/privilege/run.sh bin/privilege.test + build: desc: Compile the project binary sources: diff --git a/installer/cmd/privilege_integration_test.go b/installer/cmd/privilege_integration_test.go new file mode 100644 index 00000000..502d3b99 --- /dev/null +++ b/installer/cmd/privilege_integration_test.go @@ -0,0 +1,72 @@ +package cmd + +import ( + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/MrPointer/dotfiles/installer/lib/compatibility" + "github.com/MrPointer/dotfiles/installer/lib/pkgmanager" + "github.com/stretchr/testify/require" +) + +// Test_InstallingSystemChanges_Should_RequireAuthorization_When_RunAsNormalUser +// is driven by tests/privilege/test.exp on a disposable Linux machine. +func Test_InstallingSystemChanges_Should_RequireAuthorization_When_RunAsNormalUser(t *testing.T) { + work := os.Getenv("INSTALLER_PRIVILEGE_TEST_DIR") + if testing.Short() || work == "" { + t.Skip("requires the disposable installer privilege test environment") + } + + require.Equal(t, "linux", runtime.GOOS) + marker, err := os.ReadFile(filepath.Join(work, "ready")) + require.NoError(t, err) + require.Equal(t, "installer-privilege-tests\n", string(marker)) + require.NotZero(t, os.Geteuid(), "the installer must run as a normal user") + terminal, terminalErr := os.Open("/dev/tty") + require.NoError(t, terminalErr) + require.NoError(t, terminal.Close()) + + // Use the CLI's real display policy, logger, commander, and OS manager. + // Do not pause progress or attach stdin on behalf of production callers. + plainFlag = false + nonInteractive = false + initLogger() + t.Cleanup(func() { require.NoError(t, cliLogger.Close()) }) + initCommander() + initOsManager() + + switch os.Getenv("INSTALLER_PRIVILEGE_TEST_CALLER") { + case "shell": + shellName = filepath.Base(os.Getenv("INSTALLER_PRIVILEGE_TEST_SHELL")) + shellSource = "system" + globalSysInfo = compatibility.SystemInfo{OSName: "linux", DistroName: "debian"} + err = installShell(cliLogger) + case "apt": + require.NoError(t, cliLogger.StartProgress("Installing privilege regression package")) + manager := createNativePackageManager("linux", "debian") + err = manager.InstallPackage(pkgmanager.RequestedPackageInfo{Name: filepath.Join(work, "protected.deb")}) + if err != nil { + require.NoError(t, cliLogger.FailProgress("Package installation failed", err)) + } else { + require.NoError(t, cliLogger.FinishProgress("Package installation completed")) + } + default: + t.Fatal("unknown privilege test caller") + } + + if os.Getenv("INSTALLER_PRIVILEGE_TEST_SCENARIO") == "reject" { + require.Error(t, err) + if os.Getenv("INSTALLER_PRIVILEGE_TEST_CALLER") == "apt" { + require.Contains(t, err.Error(), "failed to update package list") + } else { + require.Contains(t, err.Error(), "failed to add shell to /etc/shells") + } + t.Log("AUTHORIZATION_REJECTED") + return + } + + require.NoError(t, err) + t.Log("AUTHORIZED_OPERATION_COMPLETED") +} diff --git a/installer/docker/AGENTS.md b/installer/docker/AGENTS.md index f00a4cc0..c80382cf 100644 --- a/installer/docker/AGENTS.md +++ b/installer/docker/AGENTS.md @@ -8,7 +8,8 @@ docker/ ├── validate.sh # Environment validation script ├── ubuntu/ # Ubuntu (apt) ├── debian/ # Debian (apt) -└── fedora/ # Fedora (dnf) +├── fedora/ # Fedora (dnf) +└── privilege/ # Optional local privilege test image and launcher ``` ## Container Management @@ -26,6 +27,7 @@ Run `task` commands from `installer/docker/`: | `task :clean` | Stop container and remove image | | `task stop-all` | Stop all containers | | `task validate-all` | Validate all environments | +| `task privilege:test` | Run the privilege integration checks in a local container | Where `` is `ubuntu`, `debian`, or `fedora`. @@ -41,4 +43,35 @@ Where `` is `ubuntu`, `debian`, or `fedora`. - Containers use `testuser` (passwordless sudo) via docker-compose, or `root` with `docker run` - Homebrew on Linux installs to `/home/linuxbrew/.linuxbrew/` and is NOT in PATH by default +## Privilege Integration Tests + +Run `task privilege:test` from `installer/docker/` for local testing on macOS. +The task runs `task test:privilege:build` first, which cross-compiles +`bin/privilege.test` for Linux. Set `PRIVILEGE_TEST_ARCH` to select the target +architecture; it defaults to the host architecture. The Docker engine and image +must support that architecture, as with the existing Docker test environments. + +The task builds the optional `installer privilege test image` +(`installer-privilege-test`) from `privilege/Dockerfile`. The Ubuntu 24.04 image +contains only dependencies for repeated local runs. The test binary and shared +scripts are bind-mounted read-only. The container has no network access and runs +all checks in one disposable container, resetting state between checks. + +The Docker launcher uses the Docker-independent scripts in +`../tests/privilege/`. They exercise the real APT and shell-setup caller paths +with a cold sudo cache, once with the correct password and once with a rejected +password. Expect provides the terminal and password exchange. The shared runner +creates a password-required user, verifies that no protected operation occurs +before authentication, and verifies either the protected root-owned effect after +success or no effects and no unprivileged retry after rejection. + +`privilege/run.sh` runs Docker commands asynchronously so it can handle signals. +Its first INT or TERM stops the child and force-removes the active container. A +second signal aborts stalled cleanup, so removal can remain incomplete if the +Docker daemon is unresponsive. + +CI runs the same checks natively on a disposable Ubuntu runner; Docker is not +part of CI. For the native runner and its safety requirements, see [Privilege +Integration Tests](../AGENTS.md#privilege-integration-tests). + For E2E testing procedures, load the `testing-e2e-containers` skill. diff --git a/installer/docker/Taskfile.yml b/installer/docker/Taskfile.yml index 6f5a257a..3dae1e14 100644 --- a/installer/docker/Taskfile.yml +++ b/installer/docker/Taskfile.yml @@ -14,6 +14,16 @@ tasks: cmds: - task --list + privilege:test: + desc: Run privilege checks locally using the installer privilege test image + dir: .. + preconditions: + - sh: command -v docker + msg: Docker is required for the local installer privilege test image + cmds: + - task test:privilege:build + - bash docker/privilege/run.sh + check: desc: Check if Docker and Docker Compose are available cmds: diff --git a/installer/docker/privilege/Dockerfile b/installer/docker/privilege/Dockerfile new file mode 100644 index 00000000..4dacc497 --- /dev/null +++ b/installer/docker/privilege/Dockerfile @@ -0,0 +1,7 @@ +# Installer privilege test image: cache dependencies for repeated local runs. +# Tests and test users are supplied at runtime by the shared Linux runner. +FROM ubuntu:24.04 + +RUN apt-get update \ + && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends sudo expect passwd util-linux \ + && rm -rf /var/lib/apt/lists/* diff --git a/installer/docker/privilege/run.sh b/installer/docker/privilege/run.sh new file mode 100644 index 00000000..63fe4034 --- /dev/null +++ b/installer/docker/privilege/run.sh @@ -0,0 +1,52 @@ +#!/bin/bash +set -euo pipefail + +installer=$(cd "$(dirname "$0")/../.." && pwd) +image="installer-privilege-test" +child= +container= + +stop_child() { + if [[ -n "$child" ]]; then + kill -KILL "$child" 2>/dev/null || true + wait "$child" 2>/dev/null || true + child= + fi +} + +cleanup() { + local status=$? + trap - EXIT + # A second interrupt can abort cleanup if the Docker daemon is unresponsive. + trap 'stop_child; exit "$status"' INT TERM + stop_child + if [[ -n "$container" ]]; then + docker rm -f "$container" >/dev/null 2>&1 & + child=$! + wait "$child" || true + child= + fi + exit "$status" +} + +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +run_command() { + # Bash handles signals immediately while waiting on an asynchronous child. + # A foreground Docker command can otherwise defer the shell's signal trap. + "$@" & + child=$! + wait "$child" + child= +} + +run_command docker build -t "$image" "$installer/docker/privilege" +container="installer-privilege-$$-$RANDOM" +run_command docker run --rm --init --name "$container" --network none \ + --mount "type=bind,src=$installer/bin/privilege.test,dst=/privilege.test,readonly" \ + --mount "type=bind,src=$installer/tests/privilege,dst=/checks,readonly" \ + -e INSTALLER_PRIVILEGE_TEST_DISPOSABLE=1 \ + "$image" /bin/bash /checks/run.sh /privilege.test +container= diff --git a/installer/docs/architecture.md b/installer/docs/architecture.md index cca942b1..3776d178 100644 --- a/installer/docs/architecture.md +++ b/installer/docs/architecture.md @@ -64,7 +64,7 @@ Shared utilities that all other layers depend on: | `display_mode.go` | [Display mode][domain-display-modes] enum and behavior | | `logger/` | Logging with hierarchical progress tracking (spinners, timing, nesting) | | `osmanager/` | OS-level operations — user management, `/etc/shells`, `/etc/passwd`, environment | -| `privilege/` | Privilege escalation — detects and uses `sudo` or `doas` | +| `privilege/` | Privilege escalation — runs directly as root, otherwise selects installed `sudo` before `doas` | | `httpclient/` | HTTP client interface | | `files/` | File utility helpers | | `collections/` | Generic collection utilities | @@ -111,6 +111,7 @@ Package managers are the clearest example: `brew`, `apt`, and `dnf` all implemen | Global state in cmd, not lib | `globalPackageManager`, `globalSysInfo`, etc. in `cmd/install.go` | Keeps `lib` packages stateless and testable. The orchestration complexity lives in one place (the install command) rather than scattered across packages. | | Embedded YAML configs | `go:embed` in `internal/config/` | Single binary distribution. No config files to ship or lose. Overridable via flags for testing and customization. | | Mockery for mock generation | `.mockery.yml` config, generated `*_mock.go` files | Consistent mock generation from interface definitions. Mocks stay in sync with interfaces automatically. | +| Select escalation by installed tool | Root runs directly; non-root prefers installed `sudo`, then installed `doas` | Authentication state is not tool availability. The selected tool authenticates when the privileged command executes, so password-required `sudo` remains usable. | ## Diagram @@ -176,7 +177,7 @@ flowchart TD - **Single binary**: The installer must be distributable as a single binary with no external config files. This drives the `go:embed` pattern for YAML configs. - **Cross-platform**: Must build for Linux (amd64, arm64) and macOS (amd64, arm64). Platform-specific logic lives in `lib` packages and `utils/osmanager`, not in `cmd`. - **No daemon**: The installer runs once and exits. No persistent state between runs (except what it writes to the filesystem). This means every run is a fresh start — no state recovery or resumption. -- **Privilege boundaries**: The installer itself runs as a regular user. Privileged operations (package installation, shell registration) use explicit privilege escalation via `sudo`/`doas`. The escalator detects which tool is available. +- **Privilege boundaries**: A root process runs privileged commands directly. For a non-root process, the escalator prefers installed `sudo`, then installed `doas`; if neither is installed, it returns an error that tells the user to install and configure one. Selection checks installation only, not cached authentication or authorization. The chosen tool authenticates when the command executes; `sudo` can prompt through its controlling terminal, and the installer neither requests nor stores the password. [installation]: processes/installation.md [domain-display-modes]: domain.md#display-mode diff --git a/installer/docs/processes/installation.md b/installer/docs/processes/installation.md index 3b9c69f1..2eabcd89 100644 --- a/installer/docs/processes/installation.md +++ b/installer/docs/processes/installation.md @@ -103,7 +103,8 @@ See the individual process docs for detailed failure scenarios and handling. ## Dependencies - Internet access (for Homebrew installation, chezmoi installation, dotfiles repo clone) -- Sufficient privileges for package installation and shell changing (sudo) +- Root access or installed and configured `sudo`/`doas` for package installation and shell changing +- A controlling terminal when `sudo` requires authentication - Git (listed as a prerequisite, installed automatically if missing) [compatibility-yaml]: ../../internal/config/compatibility.yaml diff --git a/installer/docs/processes/prerequisite-installation.md b/installer/docs/processes/prerequisite-installation.md index e9504131..c77787e1 100644 --- a/installer/docs/processes/prerequisite-installation.md +++ b/installer/docs/processes/prerequisite-installation.md @@ -13,7 +13,7 @@ The [compatibility check][compat-check] returns one or more missing prerequisite - **User**: Selects which prerequisites to install (interactive mode only) - **Package resolver**: Translates abstract keys to concrete package names (see [package resolution][pkg-resolution]) - **Package manager**: Installs the resolved packages (apt, dnf, or brew) -- **Privilege escalator**: Provides sudo/doas for package installation on Linux +- **Privilege escalator**: Runs package-manager commands directly as root or selects installed `sudo` before `doas` for a non-root user ## Diagram @@ -62,6 +62,8 @@ flowchart TD 5. **Resolve and install each prerequisite** — For each selected prerequisite: - Resolve the abstract key to a concrete package name and type via the [package resolution process][pkg-resolution] - Install via the package manager (handles regular packages, groups, and patterns) + - On Linux, run privileged package-manager commands directly as root; otherwise prefer installed `sudo`, then installed `doas` + - If `sudo` needs authentication, `sudo` obtains it from the terminal when the package-manager command runs. The installer does not collect or store the password. 6. **Trigger re-check** — Return success to the caller, which re-runs compatibility checking to verify all prerequisites are now present Result: Missing prerequisites installed. The caller re-checks compatibility to confirm. @@ -91,11 +93,18 @@ Result: Missing prerequisites installed. The caller re-checks compatibility to c #### Package installation fails -- **Trigger**: Package manager returns an error (network issue, permission denied, package not found) +- **Trigger**: Package manager returns an error (network issue, rejected or unavailable authorization, package not found) - **At step**: 5 - **Handling**: Logs the failure and returns - **User impact**: Must resolve the package manager issue and retry +#### No privilege escalation tool is installed + +- **Trigger**: A non-root Linux user reaches package installation with neither `sudo` nor `doas` installed +- **At step**: 5 +- **Handling**: Returns an error instructing the user to install `sudo` or `doas` and configure access; the package manager is not retried without privileges +- **User impact**: Must install and configure one of the supported tools, or run in an appropriate root environment + #### Re-check still fails - **Trigger**: Some prerequisites couldn't be installed or the installed version doesn't satisfy the check @@ -112,8 +121,9 @@ Result: Missing prerequisites installed. The caller re-checks compatibility to c - A supported package manager (apt, dnf, or brew) - [`packagemap.yaml`][packagemap-yaml] for name resolution -- Privilege escalation (sudo/doas) for apt/dnf installations +- Root access or installed and configured `sudo`/`doas` for apt/dnf installations - Terminal/TTY for interactive prerequisite selection +- A controlling terminal when `sudo` requires authentication [compat-check]: compatibility-checking.md [installation]: installation.md diff --git a/installer/docs/processes/shell-setup.md b/installer/docs/processes/shell-setup.md index 9c1dc20a..acc3cc4b 100644 --- a/installer/docs/processes/shell-setup.md +++ b/installer/docs/processes/shell-setup.md @@ -13,7 +13,7 @@ Called during the [installation process][installation] after prerequisites are s - **Shell resolver**: Determines the expected shell binary path based on the source strategy - **Package manager**: Installs the shell if missing (brew, apt, or dnf) - **Shell changer**: Registers the shell in `/etc/shells` and changes the user's default via `usermod` or `dscl` -- **Privilege escalator**: Provides sudo/doas for system modifications +- **Privilege escalator**: Runs system modifications directly as root or selects installed `sudo` before `doas` for a non-root user ## Diagram @@ -31,8 +31,8 @@ flowchart TD F -- No --> G F1 --> G{Shell in
/etc/shells?} G -- Yes --> H - G -- No --> G1["Append to /etc/shells (sudo)"] - G1 --> H["Set default shell (sudo)"] + G -- No --> G1["Append to /etc/shells (privileged)"] + G1 --> H["Set default shell (privileged)"] H --> Z2([Shell setup complete]) style Z fill:#36a,stroke:#248,color:#fff @@ -58,10 +58,15 @@ flowchart TD - **macOS**: `dscl . -read /Users/{username} UserShell` - **Linux**: Parse field 7 of the user's `/etc/passwd` entry - If already set to the target path, skip the remaining steps -5. **Ensure shell in `/etc/shells`** — Read `/etc/shells` and check if the target path is listed. If not, append it using `sudo tee -a /etc/shells`. +5. **Ensure shell in `/etc/shells`** — Read `/etc/shells` and check if the target path is listed. If not, append it with privileged `tee -a /etc/shells`. 6. **Set as default** — Change the user's login shell: - - **macOS**: `sudo dscl . -create /Users/{username} UserShell {path}` - - **Linux**: `sudo usermod -s {path} {username}` + - **macOS**: Run `dscl . -create /Users/{username} UserShell {path}` with the selected privilege strategy + - **Linux**: Run `usermod -s {path} {username}` with the selected privilege strategy + +For both privileged steps, root runs the command directly. A non-root user uses +installed `sudo` in preference to installed `doas`. If `sudo` needs +authentication, it prompts through the terminal when the command runs; the +installer does not collect or store the password. Result: The target shell is installed and set as the user's default login shell. @@ -90,7 +95,7 @@ Result: The target shell is installed and set as the user's default login shell. #### Cannot modify `/etc/shells` -- **Trigger**: Privilege escalation fails (no sudo access, user cancels sudo prompt) +- **Trigger**: Privilege escalation is unavailable or authorization fails (neither tool is installed, access is rejected, or the terminal needed by `sudo` is unavailable) - **At step**: 5 - **Handling**: Error propagated, installer exits - **User impact**: Must manually add the shell path to `/etc/shells` @@ -111,7 +116,8 @@ Result: The target shell is installed and set as the user's default login shell. ## Dependencies - Package manager (brew, apt, or dnf) for shell installation -- `sudo`/`doas` for modifying `/etc/shells` and changing the default shell +- Root access or installed and configured `sudo`/`doas` for modifying `/etc/shells` and changing the default shell +- A controlling terminal when `sudo` requires authentication - `dscl` (macOS) or `usermod` (Linux) for setting the default shell - `/etc/passwd` (Linux) for reading the current default shell diff --git a/installer/lib/apt/apt_test.go b/installer/lib/apt/apt_test.go index 8878c363..9f41dc89 100644 --- a/installer/lib/apt/apt_test.go +++ b/installer/lib/apt/apt_test.go @@ -1,6 +1,7 @@ package apt_test import ( + "errors" "os" "testing" @@ -151,52 +152,88 @@ func Test_InstallPackage_CallsAptInstallCommand_WithSudo(t *testing.T) { require.NotNil(t, installCall, "sudo apt install call not found") } -func Test_InstallPackage_CallsAptInstallCommand_WithoutPrivilegeEscalation(t *testing.T) { +func Test_AptInstallRejectsMissingEscalationTools(t *testing.T) { mockCommander := &utils.MoqCommander{ RunCommandFunc: func(name string, args []string, opts ...utils.Option) (*utils.Result, error) { + if name == "id" { + return &utils.Result{Stdout: []byte("1000")}, nil + } return &utils.Result{}, nil }, } - mockProgramQuery := &osmanager.MoqProgramQuery{} - mockEscalator := &privilege.MoqEscalator{ - EscalateCommandFunc: func(baseCmd string, baseArgs []string) (privilege.EscalationResult, error) { - return privilege.EscalationResult{ - Method: privilege.EscalationDirect, - Command: baseCmd, - Args: baseArgs, - NeedsEscalation: false, - }, nil - }, - } - - aptManager := apt.NewAptPackageManager(logger.DefaultLogger, mockCommander, mockProgramQuery, mockEscalator, utils.DisplayModeProgress) + mockProgramQuery := &osmanager.MoqProgramQuery{ProgramExistsFunc: func(name string) (bool, error) { + return name == "id", nil + }} + escalator := privilege.NewDefaultEscalator( + logger.NoopLogger{}, + mockCommander, + &utils.MoqProgramQuery{ProgramExistsFunc: mockProgramQuery.ProgramExists}, + ) + + aptManager := apt.NewAptPackageManager( + logger.NoopLogger{}, mockCommander, mockProgramQuery, escalator, utils.DisplayModeProgress, + ) packageInfo := pkgmanager.NewRequestedPackageInfo("git", nil) err := aptManager.InstallPackage(packageInfo) - require.NoError(t, err) - + require.Error(t, err) + require.Contains(t, err.Error(), "privilege escalation for apt update") + require.Contains(t, err.Error(), "install sudo or doas") calls := mockCommander.RunCommandCalls() - require.GreaterOrEqual(t, len(calls), 2) - - // Find direct apt calls (no privilege escalation) - var updateCall, installCall *struct { - Name string - Args []string - Opts []utils.Option - } + require.Len(t, calls, 1) + require.Equal(t, "id", calls[0].Name) + require.Equal(t, []string{"-u"}, calls[0].Args) +} - for _, call := range calls { - if call.Name == "apt" && len(call.Args) >= 1 && call.Args[0] == "update" { - updateCall = &call - } - if call.Name == "apt" && len(call.Args) >= 3 && call.Args[0] == "install" && call.Args[1] == "-y" { - installCall = &call - } +func Test_AptPropagatesSudoFailureWithoutRetry(t *testing.T) { + for _, operation := range []string{"update", "install", "remove"} { + t.Run(operation, func(t *testing.T) { + commandErr := errors.New("sudo authentication or execution failed") + var executed [][]string + commander := &utils.MoqCommander{ + RunCommandFunc: func(name string, args []string, opts ...utils.Option) (*utils.Result, error) { + if name == "id" { + return &utils.Result{Stdout: []byte("1000")}, nil + } + executed = append(executed, append([]string{name}, args...)) + if name == "sudo" || name == "doas" { + if len(args) > 1 && args[0] == "apt" && args[1] != operation { + return &utils.Result{}, nil + } + return &utils.Result{ExitCode: 1}, commandErr + } + return &utils.Result{}, nil + }, + } + query := &osmanager.MoqProgramQuery{ProgramExistsFunc: func(name string) (bool, error) { + return name == "id" || name == "sudo" || name == "doas", nil + }} + escalator := privilege.NewDefaultEscalator( + logger.NoopLogger{}, + commander, + &utils.MoqProgramQuery{ProgramExistsFunc: query.ProgramExists}, + ) + manager := apt.NewAptPackageManager( + logger.NoopLogger{}, commander, query, escalator, utils.DisplayModeProgress, + ) + + var err error + var expected [][]string + if operation == "remove" { + err = manager.UninstallPackage(pkgmanager.NewPackageInfo("git", "")) + expected = [][]string{{"sudo", "apt", "remove", "-y", "git"}} + } else { + err = manager.InstallPackage(pkgmanager.NewRequestedPackageInfo("git", nil)) + expected = [][]string{{"sudo", "apt", "update"}} + if operation == "install" { + expected = append(expected, []string{"sudo", "apt", "install", "-y", "git"}) + } + } + require.ErrorIs(t, err, commandErr) + require.Equal(t, expected, executed) + }) } - - require.NotNil(t, updateCall, "apt update call not found") - require.NotNil(t, installCall, "apt install call not found") } func Test_IsPackageInstalled_ChecksInstalledPackages(t *testing.T) { diff --git a/installer/lib/dnf/dnf_test.go b/installer/lib/dnf/dnf_test.go index c2a72ff6..948632c8 100644 --- a/installer/lib/dnf/dnf_test.go +++ b/installer/lib/dnf/dnf_test.go @@ -2,6 +2,7 @@ package dnf_test import ( "errors" + "fmt" "testing" "github.com/stretchr/testify/require" @@ -24,6 +25,56 @@ func Test_DnfPackageManager_ImplementsPackageManagerInterface(t *testing.T) { require.Implements(t, (*pkgmanager.PackageManager)(nil), dnfManager) } +func Test_DnfPropagatesPrivilegeFailuresWithoutRetry(t *testing.T) { + for _, operation := range []string{"install", "remove"} { + for _, hasTools := range []bool{false, true} { + t.Run(operation+"/tools="+fmt.Sprint(hasTools), func(t *testing.T) { + commandErr := errors.New("sudo authentication or execution failed") + var executed [][]string + commander := &utils.MoqCommander{ + RunCommandFunc: func(name string, args []string, opts ...utils.Option) (*utils.Result, error) { + if name == "id" { + return &utils.Result{Stdout: []byte("1000")}, nil + } + executed = append(executed, append([]string{name}, args...)) + if name == "sudo" || name == "doas" { + return &utils.Result{ExitCode: 1}, commandErr + } + return &utils.Result{}, nil + }, + } + query := &osmanager.MoqProgramQuery{ProgramExistsFunc: func(name string) (bool, error) { + return name == "id" || hasTools && (name == "sudo" || name == "doas"), nil + }} + escalator := privilege.NewDefaultEscalator( + logger.NoopLogger{}, + commander, + &utils.MoqProgramQuery{ProgramExistsFunc: query.ProgramExists}, + ) + manager := dnf.NewDnfPackageManager( + logger.NoopLogger{}, commander, query, escalator, utils.DisplayModeProgress, + ) + + var err error + if operation == "remove" { + err = manager.UninstallPackage(pkgmanager.NewPackageInfo("git", "")) + } else { + err = manager.InstallPackage(pkgmanager.NewRequestedPackageInfo("git", nil)) + } + if hasTools { + require.ErrorIs(t, err, commandErr) + require.Equal(t, [][]string{{"sudo", "dnf", operation, "-y", "git"}}, executed) + } else { + require.Error(t, err) + require.Contains(t, err.Error(), "privilege escalation for dnf "+operation) + require.Contains(t, err.Error(), "install sudo or doas") + require.Empty(t, executed) + } + }) + } + } +} + func Test_NewDnfPackageManager_ReturnsValidInstance(t *testing.T) { mockCommander := &utils.MoqCommander{} mockProgramQuery := &osmanager.MoqProgramQuery{} diff --git a/installer/tests/privilege/invoke.sh b/installer/tests/privilege/invoke.sh new file mode 100644 index 00000000..06b19f73 --- /dev/null +++ b/installer/tests/privilege/invoke.sh @@ -0,0 +1,13 @@ +#!/bin/bash +set -euo pipefail + +work=${INSTALLER_PRIVILEGE_TEST_DIR:?} +export SUDO_PROMPT='INSTALLER_TEST_PASSWORD: ' +sudo -K +if sudo -n true; then + echo 'Expected password-required sudo with no cached authentication' >&2 + exit 2 +fi +echo AUTH_READY +exec "$work/privilege.test" -test.v \ + -test.run '^Test_InstallingSystemChanges_Should_RequireAuthorization_When_RunAsNormalUser$' diff --git a/installer/tests/privilege/observe-command.sh b/installer/tests/privilege/observe-command.sh new file mode 100644 index 00000000..b22e3503 --- /dev/null +++ b/installer/tests/privilege/observe-command.sh @@ -0,0 +1,16 @@ +#!/bin/sh +set -eu + +# Record both elevated operations and any unprivileged retry, then run the real command. +work=$(dirname "$(readlink -f "$0")") +command_name=${0##*/} +printf '%s %s %s\n' "$(id -u)" "$command_name" "$*" >> "$work/operations" +case "$command_name" in + apt) + # Keep apt update offline without changing the machine's configured sources. + exec /usr/bin/apt -o Dir::Etc::sourcelist=/dev/null -o Dir::Etc::sourceparts=- "$@" + ;; + tee) exec /usr/bin/tee "$@" ;; + usermod) exec /usr/sbin/usermod "$@" ;; + *) exit 2 ;; +esac diff --git a/installer/tests/privilege/run.sh b/installer/tests/privilege/run.sh new file mode 100644 index 00000000..4ed8e907 --- /dev/null +++ b/installer/tests/privilege/run.sh @@ -0,0 +1,124 @@ +#!/bin/bash +set -euo pipefail + +if [[ $(uname -s) != Linux || $(id -u) != 0 || + ${INSTALLER_PRIVILEGE_TEST_DISPOSABLE:-} != 1 ]]; then + echo 'Run as root only on disposable Ubuntu/Debian, with INSTALLER_PRIVILEGE_TEST_DISPOSABLE=1.' >&2 + exit 2 +fi +if ! grep -Eq '^ID="?(ubuntu|debian)"?$' /etc/os-release; then + echo 'The installer privilege checks require disposable Ubuntu or Debian.' >&2 + exit 2 +fi +binary=${1:?usage: bash tests/privilege/run.sh /path/to/privilege.test} +scripts=$(cd "$(dirname "$0")" && pwd) +for command in sudo expect runuser useradd userdel usermod chpasswd visudo dpkg-deb flock; do + command -v "$command" >/dev/null +done +# The checks modify /etc/shells and the package database; do not run concurrently. +exec 9>/var/lock/installer-privilege-tests.lock +flock -n 9 + +work=$(mktemp -d /var/tmp/installer-privilege.XXXXXX) +username="privtest$$" +shell_path="/usr/local/bin/installer-privilege-shell-$$" +sudoers="/etc/sudoers.d/installer-privilege-$$" +created_user= +package=installer-privilege-fixture +if id "$username" >/dev/null 2>&1 || [[ -e "$shell_path" || + -e /usr/share/installer-privilege-test || -e "$sudoers" ]] || + dpkg-query -W "$package" >/dev/null 2>&1; then + rmdir "$work" + echo 'Refusing to overwrite an existing test user, package, or fixture.' >&2 + exit 2 +fi + +cleanup() { + local status=$? + trap - EXIT + if dpkg-query -W "$package" >/dev/null 2>&1; then + dpkg --purge "$package" >/dev/null || status=1 + fi + if [[ -f "$work/shells.before" ]]; then + cp -p "$work/shells.before" /etc/shells || status=1 + fi + rm -f "$sudoers" "$shell_path" + if [[ -n "$created_user" ]]; then + userdel --remove "$username" || status=1 + fi + rm -rf "$work" + exit "$status" +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +chmod 755 "$work" +cp "$binary" "$work/privilege.test" +cp "$scripts/invoke.sh" "$scripts/observe-command.sh" "$scripts/test.exp" "$work/" +chmod 755 "$work/privilege.test" "$work/"*.sh +cp -p /etc/shells "$work/shells.before" +useradd --create-home --shell /bin/sh "$username" +created_user=1 +printf '%s:privilege-test-only\n' "$username" | chpasswd +ln -s /bin/bash "$shell_path" +mkdir "$work/bin" +for command in apt tee usermod; do + ln -s "$work/observe-command.sh" "$work/bin/$command" +done +cat > "$sudoers" <\nDescription: Installer privilege regression fixture\n' \ + "$package" > "$work/package/DEBIAN/control" +printf 'installed by authenticated apt\n' > "$work/package/usr/share/installer-privilege-test/protected" +dpkg-deb --build --root-owner-group "$work/package" "$work/protected.deb" +printf 'installer-privilege-tests\n' > "$work/ready" + +export INSTALLER_PRIVILEGE_TEST_DIR="$work" +export INSTALLER_PRIVILEGE_TEST_USER="$username" +export INSTALLER_PRIVILEGE_TEST_SHELL="$shell_path" +export TERM=xterm-256color LC_ALL=C +export PATH="$work/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +for caller in apt shell; do + for scenario in cold reject; do + echo "Testing installer privileges: $caller/$scenario" + cp -p "$work/shells.before" /etc/shells + /usr/sbin/usermod -s /bin/sh "$username" + if dpkg-query -W "$package" >/dev/null 2>&1; then + dpkg --purge "$package" >/dev/null + fi + cp -p /etc/passwd "$work/passwd.before" + : > "$work/operations" + chmod 666 "$work/operations" + export INSTALLER_PRIVILEGE_TEST_CALLER="$caller" + export INSTALLER_PRIVILEGE_TEST_SCENARIO="$scenario" + expect "$work/test.exp" + if [[ "$scenario" == reject ]]; then + cmp /etc/shells "$work/shells.before" + cmp /etc/passwd "$work/passwd.before" + [[ ! -e /usr/share/installer-privilege-test/protected ]] + [[ ! -s "$work/operations" ]] + elif [[ "$caller" == apt ]]; then + [[ $(cat /usr/share/installer-privilege-test/protected) == 'installed by authenticated apt' ]] + [[ $(stat -c %u /usr/share/installer-privilege-test/protected) == 0 ]] + printf '0 apt update\n0 apt install -y %s/protected.deb\n' "$work" > "$work/expected" + cmp "$work/expected" "$work/operations" + cmp /etc/shells "$work/shells.before" + cmp /etc/passwd "$work/passwd.before" + else + grep -qx "$shell_path" /etc/shells + [[ $(getent passwd "$username" | cut -d: -f7) == "$shell_path" ]] + printf '0 tee -a /etc/shells\n0 usermod -s %s %s\n' "$shell_path" "$username" > "$work/expected" + cmp "$work/expected" "$work/operations" + fi + echo "PASS: $caller/$scenario effects and execution identities" + done +done diff --git a/installer/tests/privilege/test.exp b/installer/tests/privilege/test.exp new file mode 100644 index 00000000..9f978472 --- /dev/null +++ b/installer/tests/privilege/test.exp @@ -0,0 +1,73 @@ +#!/usr/bin/expect -f +set timeout 30 +set work $env(INSTALLER_PRIVILEGE_TEST_DIR) +set scenario $env(INSTALLER_PRIVILEGE_TEST_SCENARIO) +set ready 0 +set prompts 0 +set completed 0 +set failed 0 +set rejected 0 + +proc fail {message} { + puts stderr "FAIL: $message" + exit 1 +} + +spawn /usr/sbin/runuser -u $env(INSTALLER_PRIVILEGE_TEST_USER) -- /bin/bash $work/invoke.sh +expect { + "AUTH_READY" { + set ready 1 + exp_continue + } + "INSTALLER_TEST_PASSWORD: " { + if {!$ready} { fail "unexpected password prompt during setup" } + incr prompts + if {$prompts > 1} { fail "unexpected additional password prompt" } + # Leave the default progress display running during the password prompt. + after 500 + if {[file size $work/operations] != 0 || + [file exists /usr/share/installer-privilege-test/protected] || + [catch {exec cmp /etc/shells $work/shells.before}] || + [catch {exec cmp /etc/passwd $work/passwd.before}]} { + fail "a protected operation ran before authentication" + } + if {$scenario eq "reject"} { + send -- "wrong-test-password\r" + } else { + send -- "privilege-test-only\r" + } + exp_continue + } + "AUTHORIZED_OPERATION_COMPLETED" { + set completed 1 + exp_continue + } + "AUTHORIZATION_REJECTED" { + set rejected 1 + exp_continue + } + -exact "--- FAIL:" { + set failed 1 + exp_continue + } + timeout { fail "timed out waiting for authentication or caller completion" } + eof {} +} + +set result [wait] +if {[llength $result] != 4 || [lindex $result 2] != 0} { + fail "child did not exit normally: $result" +} +set status [lindex $result 3] +if {$status != 0 || $failed} { + fail "caller assertions failed, got exit $status" +} +if {!$ready || $prompts != 1} { fail "expected one real operation password prompt" } +if {$scenario eq "reject"} { + if {!$rejected || $completed} { + fail "expected verified authorization rejection" + } +} elseif {!$completed || $rejected} { + fail "expected authenticated caller success, got exit $status" +} +puts "PASS: $scenario prompt and exit assertions" diff --git a/installer/utils/osmanager/osmanager_test.go b/installer/utils/osmanager/osmanager_test.go index 0b9052e6..6499c1b1 100644 --- a/installer/utils/osmanager/osmanager_test.go +++ b/installer/utils/osmanager/osmanager_test.go @@ -1,6 +1,7 @@ package osmanager_test import ( + "errors" "fmt" "runtime" "testing" @@ -12,6 +13,70 @@ import ( "github.com/stretchr/testify/require" ) +func Test_ShellChangesPropagatePrivilegeFailuresWithoutRetry(t *testing.T) { + tests := []struct { + name string + run func(*osmanager.UnixOsManager) error + args []string + }{ + { + name: "register shell", + run: func(manager *osmanager.UnixOsManager) error { + return manager.EnsureShellInEtcShells("/bin/zsh") + }, + args: []string{"tee", "-a", "/etc/shells"}, + }, + { + name: "set shell", + run: func(manager *osmanager.UnixOsManager) error { + return manager.SetUserShell("alice", "/bin/zsh") + }, + args: []string{"usermod", "-s", "/bin/zsh", "alice"}, + }, + } + if runtime.GOOS == "darwin" { + tests[1].args = []string{"dscl", ".", "-create", "/Users/alice", "UserShell", "/bin/zsh"} + } + for _, tt := range tests { + for _, hasTools := range []bool{false, true} { + t.Run(tt.name+"/tools="+fmt.Sprint(hasTools), func(t *testing.T) { + commandErr := errors.New("sudo authentication or execution failed") + var executed [][]string + commander := &utils.MoqCommander{ + RunCommandFunc: func(name string, args []string, opts ...utils.Option) (*utils.Result, error) { + if name == "id" { + return &utils.Result{Stdout: []byte("1000")}, nil + } + executed = append(executed, append([]string{name}, args...)) + if name == "sudo" || name == "doas" { + return &utils.Result{ExitCode: 1}, commandErr + } + return &utils.Result{}, nil + }, + } + query := &utils.MoqProgramQuery{ProgramExistsFunc: func(name string) (bool, error) { + return name == "id" || hasTools && (name == "sudo" || name == "doas"), nil + }} + fileSystem := &utils.MoqFileSystem{ReadFileContentsFunc: func(path string) ([]byte, error) { + return []byte("/bin/sh\n"), nil + }} + escalator := privilege.NewDefaultEscalator(logger.NoopLogger{}, commander, query) + manager := osmanager.NewUnixOsManager(logger.NoopLogger{}, commander, escalator, fileSystem) + + err := tt.run(manager) + if hasTools { + require.ErrorIs(t, err, commandErr) + require.Equal(t, [][]string{append([]string{"sudo"}, tt.args...)}, executed) + } else { + require.Error(t, err) + require.Contains(t, err.Error(), "install sudo or doas") + require.Empty(t, executed) + } + }) + } + } +} + func Test_UnixOsManager_SetUserShell_UsesEscalatorCommand(t *testing.T) { mockCommander := &utils.MoqCommander{ RunCommandFunc: func(name string, args []string, opts ...utils.Option) (*utils.Result, error) { diff --git a/installer/utils/privilege/privilege.go b/installer/utils/privilege/privilege.go index 0ca6fe60..110dedab 100644 --- a/installer/utils/privilege/privilege.go +++ b/installer/utils/privilege/privilege.go @@ -18,7 +18,7 @@ const ( EscalationSudo EscalationMethod = "sudo" // EscalationDoas indicates using doas for privilege escalation. EscalationDoas EscalationMethod = "doas" - // EscalationDirect indicates falling back to direct execution (may fail). + // EscalationDirect is the legacy unprivileged fallback, no longer returned by DefaultEscalator. EscalationDirect EscalationMethod = "direct" ) @@ -37,7 +37,8 @@ type EscalationResult struct { // Escalator provides smart privilege escalation for system commands. type Escalator interface { // EscalateCommand takes a base command and arguments and returns the appropriate - // escalated command based on the current system state and available tools. + // escalated command based on the current system state and installed tools. + // Authentication is handled when the returned command is executed. EscalateCommand(baseCmd string, baseArgs []string) (EscalationResult, error) // IsRunningAsRoot checks if the current process has root privileges. @@ -68,16 +69,12 @@ func NewDefaultEscalator(logger logger.Logger, commander utils.Commander, progra // EscalateCommand implements smart privilege escalation strategy. // It determines the best method for privilege escalation based on: // -// 1. Root containers/users: Run commands directly (no privilege escalation needed) -// 2. Non-root with sudo: Use sudo for privilege escalation -// 3. Non-root with doas: Use doas as alternative to sudo (OpenBSD, some Linux) -// 4. Bare containers: Fall back to direct execution with warning +// 1. Root containers/users: Run commands directly (no privilege escalation needed). +// 2. Non-root with sudo installed: Use sudo for privilege escalation. +// 3. Non-root with only doas installed: Use doas for privilege escalation. +// 4. Non-root without either tool: Return an actionable error. // -// This approach handles common scenarios like: -// - Docker containers running as root (no sudo needed) -// - Minimal Ubuntu containers without sudo package -// - Systems with alternative privilege escalation tools -// - Regular user systems with proper sudo setup +// Tool selection does not authenticate; execution handles authentication and authorization. func (e *DefaultEscalator) EscalateCommand(baseCmd string, baseArgs []string) (EscalationResult, error) { e.logger.Debug("Escalating command to run with privileges: %s %s", baseCmd, strings.Join(baseArgs, " ")) @@ -134,14 +131,7 @@ func (e *DefaultEscalator) EscalateCommand(baseCmd string, baseArgs []string) (E }, nil } - // Fall back to direct execution (might fail, but let's try) - e.logger.Warning("Running as non-root without sudo/doas - command may fail due to insufficient privileges") - return EscalationResult{ - Method: EscalationDirect, - Command: baseCmd, - Args: baseArgs, - NeedsEscalation: false, - }, nil + return EscalationResult{}, fmt.Errorf("privilege escalation required: install sudo or doas and configure access") } // IsRunningAsRoot checks if the current process is running as root. @@ -168,7 +158,8 @@ func (e *DefaultEscalator) IsRunningAsRoot() (bool, error) { return uid == "0", nil } -// GetAvailableEscalationMethods returns all escalation methods available on this system. +// GetAvailableEscalationMethods returns installed escalation tools in preference order, +// or EscalationNone when running as root. It does not check authentication or authorization. func (e *DefaultEscalator) GetAvailableEscalationMethods() ([]EscalationMethod, error) { methods := []EscalationMethod{} @@ -190,43 +181,25 @@ func (e *DefaultEscalator) GetAvailableEscalationMethods() ([]EscalationMethod, methods = append(methods, EscalationDoas) } - // Direct execution is always available as fallback - methods = append(methods, EscalationDirect) + if len(methods) == 0 { + return nil, fmt.Errorf("privilege escalation required: install sudo or doas and configure access") + } return methods, nil } -// isSudoAvailable checks if sudo is available and usable. -// First checks if the sudo command exists, then tests if it can be used -// without a password prompt using the -n (non-interactive) flag. -// This handles cases where sudo exists but requires password authentication. +// isSudoAvailable checks if sudo is installed, regardless of authentication state. func (e *DefaultEscalator) isSudoAvailable() bool { e.logger.Trace("Checking if sudo is available") - // First check if sudo command exists exists, err := e.programQuery.ProgramExists("sudo") - if err != nil || !exists { - return false - } - - // Test if sudo can be used (with -n flag for non-interactive) - _, err = e.commander.RunCommand("sudo", []string{"-n", "true"}, utils.WithCaptureOutput()) - return err == nil + return err == nil && exists } -// isDoasAvailable checks if doas is available and usable. -// doas is an alternative to sudo commonly found on OpenBSD and some Linux systems. -// Like sudo, we test both existence and usability with non-interactive flag. +// isDoasAvailable checks if doas is installed, regardless of authentication state. func (e *DefaultEscalator) isDoasAvailable() bool { e.logger.Trace("Checking if doas is available") - // First check if doas command exists exists, err := e.programQuery.ProgramExists("doas") - if err != nil || !exists { - return false - } - - // Test if doas can be used (with -n flag for non-interactive) - _, err = e.commander.RunCommand("doas", []string{"-n", "true"}, utils.WithCaptureOutput()) - return err == nil + return err == nil && exists } diff --git a/installer/utils/privilege/privilege_test.go b/installer/utils/privilege/privilege_test.go index fbc632d4..6b075a8a 100644 --- a/installer/utils/privilege/privilege_test.go +++ b/installer/utils/privilege/privilege_test.go @@ -112,7 +112,7 @@ func Test_EscalateCommand_NonRootWithDoas_ReturnsDoasCommand(t *testing.T) { require.True(t, result.NeedsEscalation) } -func Test_EscalateCommand_NonRootWithoutPrivilegeEscalation_ReturnsDirectCommand(t *testing.T) { +func Test_EscalateCommand_NonRootWithoutPrivilegeEscalation_ReturnsActionableError(t *testing.T) { mockCommander := &utils.MoqCommander{ RunCommandFunc: func(name string, args []string, opts ...utils.Option) (*utils.Result, error) { if name == "id" && len(args) == 1 && args[0] == "-u" { @@ -136,11 +136,11 @@ func Test_EscalateCommand_NonRootWithoutPrivilegeEscalation_ReturnsDirectCommand result, err := escalator.EscalateCommand("apt", []string{"install", "git"}) - require.NoError(t, err) - require.Equal(t, privilege.EscalationDirect, result.Method) - require.Equal(t, "apt", result.Command) - require.Equal(t, []string{"install", "git"}, result.Args) - require.False(t, result.NeedsEscalation) + require.Error(t, err) + require.Contains(t, err.Error(), "sudo") + require.Contains(t, err.Error(), "doas") + require.Contains(t, err.Error(), "install") + require.Equal(t, privilege.EscalationResult{}, result) } func Test_EscalateCommand_EmptyCommand_ReturnsError(t *testing.T) { @@ -256,7 +256,7 @@ func Test_GetAvailableEscalationMethods_AsRoot_ReturnsNoneOnly(t *testing.T) { require.Equal(t, []privilege.EscalationMethod{privilege.EscalationNone}, methods) } -func Test_GetAvailableEscalationMethods_AsNonRootWithSudo_ReturnsSudoAndDirect(t *testing.T) { +func Test_GetAvailableEscalationMethods_AsNonRootWithSudo_ReturnsSudoOnly(t *testing.T) { mockCommander := &utils.MoqCommander{ RunCommandFunc: func(name string, args []string, opts ...utils.Option) (*utils.Result, error) { if name == "id" && len(args) == 1 && args[0] == "-u" { @@ -277,9 +277,7 @@ func Test_GetAvailableEscalationMethods_AsNonRootWithSudo_ReturnsSudoAndDirect(t methods, err := escalator.GetAvailableEscalationMethods() require.NoError(t, err) - require.Contains(t, methods, privilege.EscalationSudo) - require.Contains(t, methods, privilege.EscalationDirect) - require.NotContains(t, methods, privilege.EscalationNone) + require.Equal(t, []privilege.EscalationMethod{privilege.EscalationSudo}, methods) } func Test_GetAvailableEscalationMethods_AsNonRootWithBothSudoAndDoas_ReturnsAll(t *testing.T) { @@ -303,13 +301,10 @@ func Test_GetAvailableEscalationMethods_AsNonRootWithBothSudoAndDoas_ReturnsAll( methods, err := escalator.GetAvailableEscalationMethods() require.NoError(t, err) - require.Contains(t, methods, privilege.EscalationSudo) - require.Contains(t, methods, privilege.EscalationDoas) - require.Contains(t, methods, privilege.EscalationDirect) - require.Len(t, methods, 3) + require.Equal(t, []privilege.EscalationMethod{privilege.EscalationSudo, privilege.EscalationDoas}, methods) } -func Test_GetAvailableEscalationMethods_AsNonRootWithoutPrivilegeEscalation_ReturnsDirectOnly(t *testing.T) { +func Test_GetAvailableEscalationMethods_AsNonRootWithoutPrivilegeEscalation_ReturnsActionableError(t *testing.T) { mockCommander := &utils.MoqCommander{ RunCommandFunc: func(name string, args []string, opts ...utils.Option) (*utils.Result, error) { if name == "id" && len(args) == 1 && args[0] == "-u" { @@ -326,8 +321,74 @@ func Test_GetAvailableEscalationMethods_AsNonRootWithoutPrivilegeEscalation_Retu methods, err := escalator.GetAvailableEscalationMethods() - require.NoError(t, err) - require.Equal(t, []privilege.EscalationMethod{privilege.EscalationDirect}, methods) + require.Error(t, err) + require.Contains(t, err.Error(), "sudo") + require.Contains(t, err.Error(), "doas") + require.Contains(t, err.Error(), "install") + require.Empty(t, methods) +} + +func Test_EscalationSelectsInstalledToolsWithoutCachedAuthentication(t *testing.T) { + tests := []struct { + name string + sudo bool + doas bool + method privilege.EscalationMethod + methods []privilege.EscalationMethod + }{ + { + name: "password required sudo", + sudo: true, + method: privilege.EscalationSudo, + methods: []privilege.EscalationMethod{privilege.EscalationSudo}, + }, + { + name: "password required doas", + doas: true, + method: privilege.EscalationDoas, + methods: []privilege.EscalationMethod{privilege.EscalationDoas}, + }, + { + name: "sudo preferred over doas", + sudo: true, + doas: true, + method: privilege.EscalationSudo, + methods: []privilege.EscalationMethod{privilege.EscalationSudo, privilege.EscalationDoas}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + commander := &utils.MoqCommander{ + RunCommandFunc: func(name string, args []string, opts ...utils.Option) (*utils.Result, error) { + if name == "id" { + require.Equal(t, []string{"-u"}, args) + return &utils.Result{Stdout: []byte("1000\n")}, nil + } + return &utils.Result{ExitCode: 1}, fmt.Errorf("%s: authentication required", name) + }, + } + query := &utils.MoqProgramQuery{ProgramExistsFunc: func(name string) (bool, error) { + return name == "id" || name == "sudo" && tt.sudo || name == "doas" && tt.doas, nil + }} + escalator := privilege.NewDefaultEscalator(logger.NoopLogger{}, commander, query) + + t.Run("command", func(t *testing.T) { + result, err := escalator.EscalateCommand("apt", []string{"install", "-y", "git"}) + require.NoError(t, err) + require.Equal(t, privilege.EscalationResult{ + Method: tt.method, + Command: string(tt.method), + Args: []string{"apt", "install", "-y", "git"}, + NeedsEscalation: true, + }, result) + }) + t.Run("available methods", func(t *testing.T) { + methods, err := escalator.GetAvailableEscalationMethods() + require.NoError(t, err) + require.Equal(t, tt.methods, methods) + }) + }) + } } func Test_EscalateCommand_HandlesRootCheckFailure_GracefullyFallsBackToNonRoot(t *testing.T) {