Compare commits
4
Commits
e34bf7d989
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
30f7206b14 | ||
|
|
416425a9bf | ||
|
|
2786b03b96 | ||
|
|
8928986830 |
@@ -1,145 +1,108 @@
|
|||||||
# proxyctl
|
# proxyctl
|
||||||
|
|
||||||
`proxyctl` is a keyboard-driven Linux TUI for coordinating one **Active Profile** across independently switchable proxy **Targets**. It manages proxy configuration surfaces; it does not run a proxy server.
|
`proxyctl` is a keyboard-driven Linux TUI that applies one **Active Profile** to independently switchable proxy **Targets**. It configures existing system components; it does not run a proxy server.
|
||||||
|
|
||||||
## Supported systems
|
## Supported systems
|
||||||
|
|
||||||
The v1 binaries target Linux on amd64 and arm64. General TUI behavior and the Shell Target are distribution-independent. The supported Target boundaries are:
|
Linux amd64 and arm64 are supported.
|
||||||
|
|
||||||
- **Shell:** Bash and Zsh only.
|
| Target | Scope |
|
||||||
- **APT:** Debian-family systems with `apt-config` and `apt.conf.d`.
|
|---|---|
|
||||||
- **Docker daemon:** Docker installations managed by systemd.
|
| Shell | Bash and Zsh sessions |
|
||||||
- **Docker containers/builds:** the standard per-user Docker client `config.json` model.
|
| APT | Debian-family `apt` configuration |
|
||||||
- **GNOME:** sessions exposing the expected `org.gnome.system.proxy` settings schemas.
|
| Docker daemon | systemd-managed Docker service |
|
||||||
|
| Docker containers/builds | Per-user Docker client defaults |
|
||||||
|
| GNOME | `org.gnome.system.proxy` settings |
|
||||||
|
|
||||||
Unavailable Targets are hidden from the main panel; `?` opens contextual, scrollable Help over the current page and includes every built-in Target and its detection evidence.
|
Unavailable Targets are hidden by default. Press `u` to show them and `?` for contextual help.
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
### Verified release binary
|
### Release binary
|
||||||
|
|
||||||
Download the binary for your architecture together with `SHA256SUMS`, then verify it before installing:
|
Download the binary for your architecture together with `SHA256SUMS`, then verify and install it:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
grep 'proxyctl-linux-amd64$' SHA256SUMS | sha256sum -c - # substitute arm64 when needed
|
grep 'proxyctl-linux-amd64$' SHA256SUMS | sha256sum -c - # use arm64 when needed
|
||||||
chmod +x proxyctl-linux-amd64 # use proxyctl-linux-arm64 on arm64
|
chmod +x proxyctl-linux-amd64
|
||||||
install -m 0755 proxyctl-linux-amd64 "$HOME/.local/bin/proxyctl"
|
install -m 0755 proxyctl-linux-amd64 "$HOME/.local/bin/proxyctl"
|
||||||
proxyctl version
|
proxyctl version
|
||||||
proxyctl version --short # exact value only, for scripts
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Release output is two single binaries, not packages or archives. The project does not publish deb, rpm, AUR, Snap, Flatpak, or similar packages.
|
### From source
|
||||||
|
|
||||||
### Install from source with Go
|
Go 1.24 or newer is required:
|
||||||
|
|
||||||
Go 1.24 or newer is required. From a source checkout:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
go install ./cmd/proxyctl
|
go install ./cmd/proxyctl
|
||||||
```
|
```
|
||||||
|
|
||||||
The executable is placed in `GOBIN`, or in `$(go env GOPATH)/bin` when `GOBIN` is unset. Ensure that directory is on `PATH`. Source builds report `dev` unless a release version is injected by release automation.
|
## Quick start
|
||||||
|
|
||||||
## First use and Profiles
|
|
||||||
|
|
||||||
Start the Target panel with no arguments:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
proxyctl
|
proxyctl
|
||||||
```
|
```
|
||||||
|
|
||||||
Press `m` for Proxy Profile management, then `n` to create a Profile, enter a name and proxy URL, and press Ctrl+S to save. The editor supports cursor movement, Home, End, Delete, Backspace, insertion, paste, and horizontal scrolling; Tab or the arrow keys move between fields, and Escape cancels without saving. Validation stays beside each field. The management page supports reviewing obscured connection details, editing, and safe deletion; Active Profile switching remains a separate dashboard picker workflow rather than a management action. Single mode applies one URL to HTTP, HTTPS, and ALL/SOCKS. Ctrl+T selects advanced mode for separate values without discarding values entered in either mode. A bare `host:port` is accepted and normalized to `http://`. The Single proxy URL field visibly offers Protocol Probe with Ctrl+D; it runs only on that explicit keypress, and its credential-safe progress and HTTP/SOCKS5 result stay with the initiating URL context rather than global status. When one endpoint supports both protocols, the probe switches the form to advanced mode, retains a read-only Single URL probe source row, and fills HTTP/HTTPS with `http://` and ALL/SOCKS with `socks5://`. Bypass accepts comma- or newline-delimited hostnames, domain suffixes, IPv4, IPv6, and CIDR entries; the editor previews normalized, deduplicated values and identifies invalid items before save.
|
1. Press `m`, then `n`, to create a Proxy Profile.
|
||||||
|
2. Enter a name and proxy URL; press Ctrl+S to save.
|
||||||
|
3. Press `p` on the dashboard to select the Active Profile.
|
||||||
|
4. Select a Target with `↑`/`↓` or `j`/`k`.
|
||||||
|
5. Press Space to enable, disable, apply, or resolve that Target.
|
||||||
|
|
||||||
The dashboard shows the Active Profile. Press `p` to open the searchable Active Profile picker, type to filter, use arrows to select, and press Enter to activate; Escape cancels without changing the Active Profile. Use arrows or `j`/`k` to select an Available Target and Space to run its contextual action: Enable, Disable, Apply Profile, or Resolve. Drift Resolution explicitly offers Reapply Active Profile and Restore Original; restoration refuses safely if proxyctl no longer has sufficient ownership evidence. Press `r` to refresh detection, `u` to show unavailable Targets, and `?` on any page or dialog for contextual Help. Help scrolls with arrows, `j`/`k`, Page Up/Page Down, Home, and End; `q` or Escape closes it without changing the page, focus, selection, or viewport beneath it. Applying or reapplying requires an Active Profile, while Restore Original remains available without one.
|
Common keys:
|
||||||
|
|
||||||
Escape closes the top dialog or returns one page level. `q` returns from child pages and exits only from the unobscured dashboard (in the searchable Profile picker it remains search input). Ctrl+C requests exit everywhere. If a system mutation is running, either dashboard `q` or Ctrl+C visibly defers exit until the mutation completes safely; Target browsing and Help remain available while conflicting changes are disabled.
|
| Key | Action |
|
||||||
|
|---|---|
|
||||||
|
| `p` | Switch Active Profile |
|
||||||
|
| `m` | Manage Profiles |
|
||||||
|
| Space | Run the selected Target action |
|
||||||
|
| `r` | Refresh Target detection |
|
||||||
|
| `u` | Show unavailable Targets |
|
||||||
|
| `?` | Contextual help |
|
||||||
|
| `q` / Esc | Back or exit |
|
||||||
|
|
||||||
## TUI keyboard, responsive, and accessibility behavior
|
For Profile modes, Protocol Probe, Target states, complete keyboard behavior, and accessibility details, see [docs/user-guide.md](docs/user-guide.md).
|
||||||
|
|
||||||
The dashboard is keyboard-only. Up/Down or `j`/`k` moves within the focused region, Tab moves between the Target list and details, Page Up/Page Down scrolls long details, and the fixed footer lists the actions currently accepted. Focus always has a text marker such as `[focused]`, not color alone. Confirmation dialogs start on Cancel; Left/Right or Tab changes the choice and Enter activates it. Errors remain visible until acknowledged or directly resolved and can be expanded with `e`; progress appears both on the affected Target row and in the status area.
|
|
||||||
|
|
||||||
At 100×28 and larger, Targets and details are side by side. From 60–99 columns, the same workflow uses a single-column layout. Below 60×16, proxyctl shows only a minimum-size warning; resizing back restores the current page, selection, focus, scroll position, dialog, and in-flight operation. The TUI uses the terminal alternate screen and restores the prior shell screen after normal or safely deferred exit.
|
|
||||||
|
|
||||||
State is always communicated by a standard Unicode/ASCII-safe symbol and an explicit word (`● Enabled`, `○ Disabled`, `◇ External`, `! Drifted`, `… Checking`); no Nerd Font is required. Styling adapts to light and dark terminal backgrounds. Set `NO_COLOR` to disable color without losing state, focus, progress, warning, disabled-action, or error meaning.
|
|
||||||
|
|
||||||
Profiles are human-readable under the user's XDG configuration directory (normally `~/.config/proxyctl/profiles.json`) and are stored owner-only because proxy URLs may contain credentials.
|
|
||||||
|
|
||||||
## Shell integration
|
## Shell integration
|
||||||
|
|
||||||
A child TUI cannot change its parent Shell. Install the one-time Bash/Zsh startup hook:
|
A child TUI cannot modify its parent Shell. Install the Bash/Zsh startup hook once:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
proxyctl shell install
|
proxyctl shell install
|
||||||
```
|
```
|
||||||
|
|
||||||
Restart or source the startup file once. Thereafter the wrapper reloads proxy exports and unsets after `proxyctl` exits. The Shell Target emits conventional upper- and lower-case `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, and `NO_PROXY` forms. Remove the hook with:
|
Restart or source the startup file. Remove the hook with:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
proxyctl shell uninstall
|
proxyctl shell uninstall
|
||||||
```
|
```
|
||||||
|
|
||||||
Fish and other Shells are intentionally unsupported in v1.
|
## System Targets and permissions
|
||||||
|
|
||||||
## What each Target affects
|
APT and Docker daemon changes normally require root authority. `proxyctl` never invokes `sudo`, `pkexec`, or another elevation mechanism itself. Start it explicitly with `sudo proxyctl` when system Targets are required.
|
||||||
|
|
||||||
1. **Shell** — commands started by integrated Bash/Zsh sessions. It does not change existing processes, system services, Docker, or desktop settings.
|
Docker daemon changes reload systemd and restart Docker. Review the confirmation before proceeding.
|
||||||
2. **APT** — persistent APT package operations across Shell and privilege boundaries through a tool-owned `apt.conf.d` overlay. It does not configure other package managers and requires no service restart.
|
|
||||||
3. **Docker daemon** — daemon operations such as registry access. It does not set container networking or container/build defaults. Every change reloads systemd and immediately restarts Docker; confirm only when disruption to running work is acceptable.
|
|
||||||
4. **Docker containers/builds** — proxy variables and build arguments for future containers and builds via the owning user's Docker client configuration. It does not affect existing containers, the Docker CLI connection, or the daemon.
|
|
||||||
5. **GNOME** — GNOME system proxy settings used by compatible desktop applications. It does not rewrite browser-specific profiles or configure non-GNOME desktops. GNOME settings cannot express `socks5h` remote-DNS semantics, and the Protocol Probe fills `socks5h` for SOCKS-only endpoints; switch to advanced mode and enter `socks5` when a SOCKS endpoint must work through the GNOME Target.
|
|
||||||
|
|
||||||
proxyctl prefers isolated, tool-owned overlays. Where that is impossible it records original values and a last-applied fingerprint so disable/reset can restore prior state safely.
|
See [docs/security.md](docs/security.md) for privilege boundaries, credential handling, restoration guarantees, and project scope.
|
||||||
|
|
||||||
## Target states
|
|
||||||
|
|
||||||
- **Enabled:** actual managed configuration matches the Active Profile.
|
|
||||||
- **Disabled:** no managed or positively recognized external proxy configuration was detected.
|
|
||||||
- **External:** a recognized proxy configuration exists but is not owned by proxyctl.
|
|
||||||
- **Drifted:** managed configuration exists but no longer matches the Active Profile, including partial failures or configuration left when the final Profile is deleted.
|
|
||||||
|
|
||||||
External detection is best-effort; Disabled does not claim that every possible configuration source was exhaustively searched.
|
|
||||||
|
|
||||||
## Permissions, sudo, and restarts
|
|
||||||
|
|
||||||
User Targets normally need only user-file permissions. APT and Docker daemon files generally require authority to write system locations, and Docker daemon operations require authority to reload/restart its systemd service.
|
|
||||||
|
|
||||||
proxyctl **never** runs `sudo`, `pkexec`, or another elevation mechanism. Permission failures are reported normally. If system Targets are wanted, the user must explicitly start `sudo proxyctl`; under sudo, the invoking user remains the owner of Profiles, Shell, Docker client, and GNOME configuration while current root authority is available to system Targets. In a direct root login, root is the owner. Review the Docker restart warning before confirming any daemon change.
|
|
||||||
|
|
||||||
## Diagnose, reset, and remove
|
## Diagnose, reset, and remove
|
||||||
|
|
||||||
Run read-only diagnostics for Profile validity, storage permissions, required commands, Target availability/state, and Target-specific authority:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
proxyctl doctor
|
proxyctl doctor # read-only diagnostics
|
||||||
|
proxyctl reset # restore managed Targets
|
||||||
|
proxyctl shell uninstall # remove Shell startup integration
|
||||||
```
|
```
|
||||||
|
|
||||||
Before removal, restore every managed Target. The command asks for confirmation and does nothing when declined:
|
Complete a successful reset before deleting recovery state or uninstalling the executable.
|
||||||
|
|
||||||
```sh
|
## Privacy
|
||||||
proxyctl reset
|
|
||||||
proxyctl shell uninstall
|
|
||||||
```
|
|
||||||
|
|
||||||
Inspect failures and rerun until reset reports no failed managed Target. Then remove the installed executable and, after retaining any desired logs, remove empty proxyctl configuration/state directories. Do not delete recovery state before a successful reset because it may be needed to restore original settings.
|
proxyctl has no telemetry, automatic update checks, or automatic proxy-connectivity tests. Network traffic is generated only by the user-initiated Protocol Probe. Diagnostic output and logs redact credentials; stored Profile and Target configuration can still contain credentials and is protected with restrictive file permissions.
|
||||||
|
|
||||||
## Privacy and safety boundaries
|
## Documentation
|
||||||
|
|
||||||
proxyctl has no telemetry, automatic update checks, or automatic proxy-connectivity tests. It does not contact the network on its own; the only network traffic it generates is the user-initiated Protocol Probe (Ctrl+D in the Profile form), a handshake check that never forwards traffic through the proxy and never contacts anything beyond the endpoint itself. Local diagnostic logs are credential-redacted and bounded in size. Every TUI frame defensively redacts credentials from Profile values, Target evidence, progress, notices, errors and command output, and confirmation copy immediately before rendering, including malformed credential-bearing URLs. Profile form frames mask the entire URL userinfo while retaining the underlying value for saving. Proxy credentials remain present where a selected Target requires them, so normal local file security still matters.
|
- [User guide](docs/user-guide.md)
|
||||||
|
- [Security and operational boundaries](docs/security.md)
|
||||||
proxyctl does **not** manage or supervise proxy processes such as Clash, sing-box, or Xray. It does not manage subscriptions, nodes, latency, routing rules, transparent proxying, TUN/iptables/nftables, arbitrary services or commands, plugins, or a complete headless Profile/Target CLI.
|
- [Development and release verification](docs/development.md)
|
||||||
|
- [Product specifications](docs/specs/)
|
||||||
Deferred integrations include DNF, Git-specific settings, npm/pip, arbitrary systemd services, Firefox policies, Chromium launch flags, KDE and other desktops, Snap/Ubuntu Core, Fish, Windows, macOS, distribution packages, mouse interaction, and cross-Target rollback. Conventional Shell variables may already cover some deferred command-line tools.
|
- [Linux Target research](docs/research/linux-proxy-targets.md)
|
||||||
|
|
||||||
Support is limited to the Linux architectures and Target boundaries above. When reporting an issue, include `proxyctl version`, redacted `proxyctl doctor` output, distribution/desktop/Shell details, and the affected Target/state. Never include unredacted proxy credentials.
|
|
||||||
|
|
||||||
## Build and verification
|
|
||||||
|
|
||||||
Create reproducible Linux binaries and checksums without packages or archives:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
VERSION=v1.0.0 ./scripts/build-release.sh
|
|
||||||
sha256sum -c dist/SHA256SUMS
|
|
||||||
file dist/proxyctl-linux-amd64 dist/proxyctl-linux-arm64
|
|
||||||
```
|
|
||||||
|
|
||||||
`./scripts/test-release.sh` builds twice, compares binaries and checksum manifests, verifies both checksums, and checks ELF architectures. `./scripts/verify-clean-machine.sh` uses an isolated identity and XDG roots to exercise `go install`, Profile and hermetic Target workflows, doctor, reset cancellation, Shell install/uninstall, removal, and unchanged host-state snapshots.
|
|
||||||
|
|||||||
+15
-3
@@ -103,7 +103,16 @@ func runWithEnvironmentAndTargets(args []string, input io.Reader, output io.Writ
|
|||||||
}
|
}
|
||||||
targets := append([]target.Target{shellTarget}, systemTargets...)
|
targets := append([]target.Target{shellTarget}, systemTargets...)
|
||||||
stateDirectory := filepath.Dir(shellConfiguration.RecoveryFile)
|
stateDirectory := filepath.Dir(shellConfiguration.RecoveryFile)
|
||||||
mutationLock := operationlock.NewOwned(filepath.Join(stateDirectory, "operation.lock"), profileConfiguration.Owner.UID, profileConfiguration.Owner.GID)
|
userMutationLock := operationlock.NewOwned(filepath.Join(stateDirectory, "operation.lock"), profileConfiguration.Owner.UID, profileConfiguration.Owner.GID)
|
||||||
|
var mutationLock app.MutationLock = userMutationLock
|
||||||
|
if os.Geteuid() == 0 {
|
||||||
|
// Every elevated process also takes a root-owned lock that the invoking
|
||||||
|
// user cannot replace while a system Target mutation is in flight.
|
||||||
|
mutationLock = operationlock.NewGroup(
|
||||||
|
operationlock.New("/run/lock/proxyctl/operation.lock"),
|
||||||
|
userMutationLock,
|
||||||
|
)
|
||||||
|
}
|
||||||
logger := oplog.NewOwned(filepath.Join(stateDirectory, "operations.log"), 64*1024, 3, profileConfiguration.Owner.UID, profileConfiguration.Owner.GID)
|
logger := oplog.NewOwned(filepath.Join(stateDirectory, "operations.log"), 64*1024, 3, profileConfiguration.Owner.UID, profileConfiguration.Owner.GID)
|
||||||
store := profile.NewOwnedFileStoreAt(profileConfiguration.Path, profileConfiguration.Owner, profileConfiguration.TrustedRoot)
|
store := profile.NewOwnedFileStoreAt(profileConfiguration.Path, profileConfiguration.Owner, profileConfiguration.TrustedRoot)
|
||||||
|
|
||||||
@@ -130,9 +139,12 @@ func runWithEnvironmentAndTargets(args []string, input io.Reader, output io.Writ
|
|||||||
if operationErr != nil {
|
if operationErr != nil {
|
||||||
result, detail = "failure", operationErr.Error()
|
result, detail = "failure", operationErr.Error()
|
||||||
}
|
}
|
||||||
_ = logger.Write(app.LogEntry{Operation: operation, Target: shellTarget.ID(), Result: result, Detail: detail})
|
logErr := logger.Write(app.LogEntry{Operation: operation, Target: shellTarget.ID(), Result: result, Detail: detail})
|
||||||
if operationErr != nil {
|
if operationErr != nil {
|
||||||
return operationErr
|
return errors.Join(operationErr, logErr)
|
||||||
|
}
|
||||||
|
if logErr != nil {
|
||||||
|
return fmt.Errorf("Shell integration changed but the operation log could not be written: %w", logErr)
|
||||||
}
|
}
|
||||||
if args[1] == "install" {
|
if args[1] == "install" {
|
||||||
fmt.Fprintln(output, "Shell integration installed; restart or source your Shell startup file once.")
|
fmt.Fprintln(output, "Shell integration installed; restart or source your Shell startup file once.")
|
||||||
|
|||||||
@@ -97,8 +97,8 @@ func TestDefaultInvocationLoadsPersistedActiveProfile(t *testing.T) {
|
|||||||
if err := runWithSystemTargets(nil, strings.NewReader("q"), &output, []target.Target{}); err != nil {
|
if err := runWithSystemTargets(nil, strings.NewReader("q"), &output, []target.Target{}); err != nil {
|
||||||
t.Fatalf("run proxyctl: %v", err)
|
t.Fatalf("run proxyctl: %v", err)
|
||||||
}
|
}
|
||||||
if !strings.Contains(output.String(), "Active Profile: office") {
|
if !strings.Contains(output.String(), "Profile: office") {
|
||||||
t.Fatalf("default TUI output missing Active Profile: %q", output.String())
|
t.Fatalf("default TUI output missing Profile: %q", output.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -247,19 +247,17 @@ func TestCommandsRunAsRealProcessesInsideIsolatedUserState(t *testing.T) {
|
|||||||
}
|
}
|
||||||
defaultView := string(defaultOutput)
|
defaultView := string(defaultOutput)
|
||||||
for _, expected := range []string{
|
for _, expected := range []string{
|
||||||
"proxyctl Operations Console",
|
"proxyctl Profile: No Active Profile",
|
||||||
"Active Profile: No Active Profile",
|
|
||||||
"Targets: ● Enabled 0 ○ Disabled 1 ◇ External 0 ! Drifted 1",
|
|
||||||
"▶ Targets [focused]",
|
"▶ Targets [focused]",
|
||||||
"> ○ Disabled Shell",
|
"> ○ Disabled Shell",
|
||||||
"! Drifted Docker daemon",
|
"! Drifted Docker daemon",
|
||||||
"Target details",
|
"Target details",
|
||||||
"State: ○ Disabled",
|
"○ Disabled",
|
||||||
"Evidence: no recognized Shell proxy configuration detected",
|
"no recognized Shell proxy configuration detected",
|
||||||
"Tab: focus details",
|
"Tab: Details",
|
||||||
} {
|
} {
|
||||||
if !strings.Contains(defaultView, expected) {
|
if !strings.Contains(defaultView, expected) {
|
||||||
t.Errorf("default Operations Console missing %q; output=%q", expected, defaultOutput)
|
t.Errorf("default dashboard missing %q; output=%q", expected, defaultOutput)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
versionOutput, err := invoke("", "version", "--short")
|
versionOutput, err := invoke("", "version", "--short")
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Development and release verification
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- Go 1.24 or newer
|
||||||
|
- Linux
|
||||||
|
- GNU `sha256sum`, `stat`, and `find`
|
||||||
|
- `file`
|
||||||
|
|
||||||
|
## Local verification
|
||||||
|
|
||||||
|
```sh
|
||||||
|
gofmt -w .
|
||||||
|
go test ./...
|
||||||
|
go vet ./...
|
||||||
|
./scripts/check-docs.sh
|
||||||
|
./scripts/test-hermetic.sh
|
||||||
|
./scripts/test-release.sh
|
||||||
|
./scripts/verify-clean-machine.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
`test-hermetic.sh` runs the complete uncached Go suite as an unprivileged user and verifies that readable host configuration content and metadata remain unchanged.
|
||||||
|
|
||||||
|
`verify-clean-machine.sh` uses isolated identity and XDG roots to exercise installation, Profile workflows, hermetic Target workflows, diagnostics, reset confirmation, Shell integration, and removal.
|
||||||
|
|
||||||
|
## Release build
|
||||||
|
|
||||||
|
```sh
|
||||||
|
VERSION=v1.0.0 ./scripts/build-release.sh
|
||||||
|
sha256sum -c dist/SHA256SUMS
|
||||||
|
file dist/proxyctl-linux-amd64 dist/proxyctl-linux-arm64
|
||||||
|
```
|
||||||
|
|
||||||
|
The release consists of Linux amd64 and arm64 single binaries plus `SHA256SUMS`; it does not produce distribution packages or archives.
|
||||||
|
|
||||||
|
`test-release.sh` builds twice, compares binaries and checksum manifests, validates both architectures and checksums, and verifies that process-test seams cannot enter a release artifact.
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# Security and operational boundaries
|
||||||
|
|
||||||
|
## Privileges
|
||||||
|
|
||||||
|
User Targets normally require only access to user-owned files. APT and Docker daemon configuration generally require root authority.
|
||||||
|
|
||||||
|
proxyctl never starts `sudo`, `pkexec`, or another elevation mechanism. Run `sudo proxyctl` explicitly when system Targets are needed. Under sudo, the invoking user remains the owner of Profiles, Shell integration, Docker client configuration, and GNOME settings; root authority is used for system Targets. A direct root login uses root as the owner.
|
||||||
|
|
||||||
|
Docker daemon changes reload systemd and restart Docker immediately after confirmation.
|
||||||
|
|
||||||
|
## Configuration recovery
|
||||||
|
|
||||||
|
proxyctl prefers isolated, tool-owned overlays. Where shared configuration must be edited, it records the original value and a fingerprint of the last applied state.
|
||||||
|
|
||||||
|
Restore and reset operations refuse to overwrite configuration that changed after proxyctl applied it. Recovery metadata must not be deleted before a successful reset.
|
||||||
|
|
||||||
|
Use:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
proxyctl doctor
|
||||||
|
proxyctl reset
|
||||||
|
proxyctl shell uninstall
|
||||||
|
```
|
||||||
|
|
||||||
|
Inspect and resolve all failures before removing the executable or state directory.
|
||||||
|
|
||||||
|
## Credentials and privacy
|
||||||
|
|
||||||
|
Proxy URLs may contain credentials. Profile, recovery, and managed credential-bearing files use restrictive permissions. Docker daemon configuration is owner-only while proxyctl manages credential-bearing proxy values.
|
||||||
|
|
||||||
|
The TUI, diagnostics, errors, command output, and bounded local operation logs defensively redact credentials. Profile editor frames obscure URL user information. Credentials remain present in underlying configuration where a selected Target requires them, so host file security still matters.
|
||||||
|
|
||||||
|
proxyctl has:
|
||||||
|
|
||||||
|
- no telemetry
|
||||||
|
- no automatic update checks
|
||||||
|
- no automatic proxy-connectivity tests
|
||||||
|
|
||||||
|
The user-initiated Protocol Probe contacts only the entered endpoint, performs protocol handshakes, and never forwards traffic through the proxy.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
proxyctl configures proxy settings; it does **not** manage or supervise proxy processes such as Clash, sing-box, or Xray. It does not manage subscriptions, nodes, latency, routing rules, transparent proxying, TUN/iptables/nftables, arbitrary services, or plugins.
|
||||||
|
|
||||||
|
It currently excludes DNF, Git-specific settings, npm/pip settings, arbitrary systemd services, browser policies, KDE, Fish, Windows, macOS, distribution packages, mouse interaction, and cross-Target rollback.
|
||||||
|
|
||||||
|
Support is limited to the Linux architectures and Targets documented in the README. When reporting an issue, include:
|
||||||
|
|
||||||
|
- `proxyctl version`
|
||||||
|
- redacted `proxyctl doctor` output
|
||||||
|
- distribution and desktop/Shell details
|
||||||
|
- affected Target and state
|
||||||
|
|
||||||
|
Never include unredacted proxy credentials.
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# User guide
|
||||||
|
|
||||||
|
## Profiles
|
||||||
|
|
||||||
|
A Proxy Profile contains proxy URLs and bypass rules. The Active Profile is the source applied to every Enabled Target.
|
||||||
|
|
||||||
|
Open Profile management with `m`:
|
||||||
|
|
||||||
|
- `n`: create a Profile
|
||||||
|
- `e` or Enter: edit the selected Profile
|
||||||
|
- `d`: safely delete the selected Profile
|
||||||
|
- Ctrl+S: save the editor
|
||||||
|
- Ctrl+T: switch between Single and Advanced modes
|
||||||
|
|
||||||
|
Single mode applies one URL to HTTP, HTTPS, and ALL/SOCKS. Advanced mode accepts separate values. A bare `host:port` is normalized to `http://`.
|
||||||
|
|
||||||
|
Bypass entries may be comma- or newline-delimited hostnames, domain suffixes, IPv4/IPv6 addresses, or CIDR ranges. The editor normalizes and deduplicates valid entries.
|
||||||
|
|
||||||
|
### Protocol Probe
|
||||||
|
|
||||||
|
Press Ctrl+D while editing the Single proxy URL to run an explicit handshake probe. It reports HTTP and SOCKS5 support without forwarding traffic or contacting another endpoint.
|
||||||
|
|
||||||
|
If both protocols are detected, the editor changes to Advanced mode and fills HTTP/HTTPS with `http://` and ALL/SOCKS with `socks5://`. GNOME cannot represent `socks5h` remote-DNS semantics; use Advanced mode with `socks5` when GNOME must use that endpoint.
|
||||||
|
|
||||||
|
## Dashboard
|
||||||
|
|
||||||
|
Press `p` to search and select the Active Profile. Select Targets with arrows or `j`/`k`; Space runs the contextual action:
|
||||||
|
|
||||||
|
- **Enable** a Disabled Target
|
||||||
|
- **Disable** an Enabled Target
|
||||||
|
- **Apply Profile** to an External Target
|
||||||
|
- **Resolve** a Drifted Target by reapplying the Active Profile or restoring the original configuration
|
||||||
|
|
||||||
|
Restoration refuses to overwrite configuration that changed after proxyctl applied it.
|
||||||
|
|
||||||
|
Other controls:
|
||||||
|
|
||||||
|
- `r`: refresh detection
|
||||||
|
- `u`: show unavailable Targets
|
||||||
|
- Tab: switch between Target list and details
|
||||||
|
- Page Up/Page Down: scroll details
|
||||||
|
- `e`: expand or collapse the current error
|
||||||
|
- `x`: acknowledge the current error
|
||||||
|
- `?`: contextual Help
|
||||||
|
- `q` or Esc: close the current page/dialog; `q` exits from the unobscured dashboard
|
||||||
|
- Ctrl+C: request exit
|
||||||
|
|
||||||
|
Conflicting actions are disabled while a mutation runs. Exit requests cancel cancellable work and wait for the operation to settle safely.
|
||||||
|
|
||||||
|
## Target states
|
||||||
|
|
||||||
|
- **Enabled:** managed configuration matches the Active Profile.
|
||||||
|
- **Disabled:** no managed or positively recognized external proxy configuration was detected.
|
||||||
|
- **External:** recognized proxy configuration exists outside proxyctl ownership.
|
||||||
|
- **Drifted:** managed configuration no longer matches the Active Profile, including partial failures.
|
||||||
|
|
||||||
|
External detection is best-effort. Disabled does not claim that every possible configuration source was exhaustively searched.
|
||||||
|
|
||||||
|
## What each Target affects
|
||||||
|
|
||||||
|
1. **Shell** — future commands in integrated Bash/Zsh sessions. It does not change existing processes or services.
|
||||||
|
2. **APT** — persistent Debian-family package operations through a tool-owned `apt.conf.d` overlay.
|
||||||
|
3. **Docker daemon** — registry and daemon traffic. Every change reloads systemd and restarts Docker.
|
||||||
|
4. **Docker containers/builds** — proxy defaults for future containers and builds in the owning user's Docker client configuration. It does not configure the daemon.
|
||||||
|
5. **GNOME** — compatible desktop applications using GNOME system proxy settings. It does not rewrite browser-specific profiles.
|
||||||
|
|
||||||
|
## Responsive and accessible TUI
|
||||||
|
|
||||||
|
At 100×28 and larger, Targets and details are side by side. At 60–99 columns they use one column. Below 60×16, proxyctl displays a minimum-size warning and restores interaction state after resize.
|
||||||
|
|
||||||
|
Focus and state never rely on color alone. States include symbols and words such as `● Enabled`, `○ Disabled`, `◇ External`, `! Drifted`, and `… Checking`. No Nerd Font is required. Set `NO_COLOR` to disable color.
|
||||||
|
|
||||||
|
Confirmation dialogs start on Cancel. The TUI uses the terminal alternate screen and restores the previous screen after exit.
|
||||||
|
|
||||||
|
Profiles are normally stored at `~/.config/proxyctl/profiles.json` with owner-only permissions.
|
||||||
+103
-47
@@ -2,9 +2,10 @@ package app
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -32,9 +33,19 @@ type Intent struct {
|
|||||||
Name string
|
Name string
|
||||||
Profile profile.Profile
|
Profile profile.Profile
|
||||||
Confirm bool
|
Confirm bool
|
||||||
|
ConfirmationToken string
|
||||||
TargetID string
|
TargetID string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func confirmationToken(parts ...string) string {
|
||||||
|
hash := sha256.New()
|
||||||
|
for _, part := range parts {
|
||||||
|
_, _ = hash.Write([]byte(part))
|
||||||
|
_, _ = hash.Write([]byte{0})
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(hash.Sum(nil))
|
||||||
|
}
|
||||||
|
|
||||||
// TargetActionKind identifies a Target action independently of display labels.
|
// TargetActionKind identifies a Target action independently of display labels.
|
||||||
type TargetActionKind uint8
|
type TargetActionKind uint8
|
||||||
|
|
||||||
@@ -153,6 +164,7 @@ type Application struct {
|
|||||||
targetDescriptions []target.Description
|
targetDescriptions []target.Description
|
||||||
availabilities map[string]target.Availability
|
availabilities map[string]target.Availability
|
||||||
inspections map[string]target.Inspection
|
inspections map[string]target.Inspection
|
||||||
|
mutationBlockReasons map[string]string
|
||||||
detectionPhase map[string]TargetDetectionPhase
|
detectionPhase map[string]TargetDetectionPhase
|
||||||
detectionErr map[string]error
|
detectionErr map[string]error
|
||||||
detectionGeneration uint64
|
detectionGeneration uint64
|
||||||
@@ -191,6 +203,7 @@ func NewWithTargetsAndRuntime(store profile.Store, targets []target.Target, muta
|
|||||||
targets: append([]target.Target(nil), targets...),
|
targets: append([]target.Target(nil), targets...),
|
||||||
availabilities: make(map[string]target.Availability),
|
availabilities: make(map[string]target.Availability),
|
||||||
inspections: make(map[string]target.Inspection),
|
inspections: make(map[string]target.Inspection),
|
||||||
|
mutationBlockReasons: make(map[string]string),
|
||||||
detectionPhase: make(map[string]TargetDetectionPhase),
|
detectionPhase: make(map[string]TargetDetectionPhase),
|
||||||
detectionErr: make(map[string]error),
|
detectionErr: make(map[string]error),
|
||||||
mutationLock: mutationLock,
|
mutationLock: mutationLock,
|
||||||
@@ -218,7 +231,7 @@ func (a *Application) snapshotLocked() Snapshot {
|
|||||||
availability := a.availabilities[id]
|
availability := a.availabilities[id]
|
||||||
inspection := a.inspections[id]
|
inspection := a.inspections[id]
|
||||||
phase := a.detectionPhase[id]
|
phase := a.detectionPhase[id]
|
||||||
primary, resolution := contextualTargetActions(phase, availability.Available, inspection.State, state.ActiveProfile != "")
|
primary, resolution := contextualTargetActions(phase, availability.Available, inspection.State, state.ActiveProfile != "", a.mutationBlockReasons[id])
|
||||||
snapshot.Targets = append(snapshot.Targets, TargetSnapshot{
|
snapshot.Targets = append(snapshot.Targets, TargetSnapshot{
|
||||||
ID: id, Description: a.targetDescriptions[i], DetectionPhase: phase, DetectionErr: a.detectionErr[id],
|
ID: id, Description: a.targetDescriptions[i], DetectionPhase: phase, DetectionErr: a.detectionErr[id],
|
||||||
Available: availability.Available, AvailabilityEvidence: availability.Evidence, State: inspection.State, Evidence: inspection.Evidence,
|
Available: availability.Available, AvailabilityEvidence: availability.Evidence, State: inspection.State, Evidence: inspection.Evidence,
|
||||||
@@ -228,7 +241,7 @@ func (a *Application) snapshotLocked() Snapshot {
|
|||||||
return snapshot
|
return snapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
func contextualTargetActions(phase TargetDetectionPhase, available bool, state target.State, hasActiveProfile bool) (TargetAction, []TargetAction) {
|
func contextualTargetActions(phase TargetDetectionPhase, available bool, state target.State, hasActiveProfile bool, mutationBlockReason string) (TargetAction, []TargetAction) {
|
||||||
primaryKind := primaryTargetActionKind(state)
|
primaryKind := primaryTargetActionKind(state)
|
||||||
primary := TargetAction{Kind: primaryKind, Available: primaryKind != 0}
|
primary := TargetAction{Kind: primaryKind, Available: primaryKind != 0}
|
||||||
if primaryKind == 0 {
|
if primaryKind == 0 {
|
||||||
@@ -242,6 +255,10 @@ func contextualTargetActions(phase TargetDetectionPhase, available bool, state t
|
|||||||
primary.Available = false
|
primary.Available = false
|
||||||
primary.DisabledReason = "This action is unavailable because there is no Active Profile; open Profile management first"
|
primary.DisabledReason = "This action is unavailable because there is no Active Profile; open Profile management first"
|
||||||
}
|
}
|
||||||
|
if primary.Available && mutationBlockReason != "" {
|
||||||
|
primary.Available = false
|
||||||
|
primary.DisabledReason = mutationBlockReason
|
||||||
|
}
|
||||||
if state != target.Drifted {
|
if state != target.Drifted {
|
||||||
return primary, nil
|
return primary, nil
|
||||||
}
|
}
|
||||||
@@ -260,6 +277,10 @@ func contextualTargetActions(phase TargetDetectionPhase, available bool, state t
|
|||||||
action.Available = false
|
action.Available = false
|
||||||
action.DisabledReason = reason
|
action.DisabledReason = reason
|
||||||
}
|
}
|
||||||
|
if action.Available && mutationBlockReason != "" {
|
||||||
|
action.Available = false
|
||||||
|
action.DisabledReason = mutationBlockReason
|
||||||
|
}
|
||||||
resolution = append(resolution, action)
|
resolution = append(resolution, action)
|
||||||
}
|
}
|
||||||
return primary, resolution
|
return primary, resolution
|
||||||
@@ -291,6 +312,7 @@ func targetActionDisabledReason(phase TargetDetectionPhase, available bool) stri
|
|||||||
type targetDetectionOutcome struct {
|
type targetDetectionOutcome struct {
|
||||||
targetID string
|
targetID string
|
||||||
detection target.Detection
|
detection target.Detection
|
||||||
|
mutationBlockReason string
|
||||||
}
|
}
|
||||||
|
|
||||||
type targetDetectionUpdate struct {
|
type targetDetectionUpdate struct {
|
||||||
@@ -299,7 +321,7 @@ type targetDetectionUpdate struct {
|
|||||||
complete bool
|
complete bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *Application) beginTargetDetection() (Snapshot, <-chan targetDetectionUpdate) {
|
func (a *Application) beginTargetDetection(ctx context.Context) (Snapshot, <-chan targetDetectionUpdate) {
|
||||||
a.stateMu.Lock()
|
a.stateMu.Lock()
|
||||||
a.detectionGeneration++
|
a.detectionGeneration++
|
||||||
generation := a.detectionGeneration
|
generation := a.detectionGeneration
|
||||||
@@ -316,7 +338,10 @@ func (a *Application) beginTargetDetection() (Snapshot, <-chan targetDetectionUp
|
|||||||
for i, adapter := range a.targets {
|
for i, adapter := range a.targets {
|
||||||
adapter, id := adapter, a.targetIDs[i]
|
adapter, id := adapter, a.targetIDs[i]
|
||||||
go func() {
|
go func() {
|
||||||
outcomes <- targetDetectionOutcome{targetID: id, detection: detectTarget(adapter, active)}
|
outcomes <- targetDetectionOutcome{
|
||||||
|
targetID: id, detection: detectTarget(ctx, adapter, active),
|
||||||
|
mutationBlockReason: mutationBlockReason(ctx, adapter),
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
go func() {
|
go func() {
|
||||||
@@ -334,6 +359,7 @@ func (a *Application) beginTargetDetection() (Snapshot, <-chan targetDetectionUp
|
|||||||
}
|
}
|
||||||
a.availabilities[outcome.targetID] = outcome.detection.Availability
|
a.availabilities[outcome.targetID] = outcome.detection.Availability
|
||||||
a.inspections[outcome.targetID] = outcome.detection.Inspection
|
a.inspections[outcome.targetID] = outcome.detection.Inspection
|
||||||
|
a.mutationBlockReasons[outcome.targetID] = outcome.mutationBlockReason
|
||||||
a.detectionPhase[outcome.targetID] = phase
|
a.detectionPhase[outcome.targetID] = phase
|
||||||
a.detectionErr[outcome.targetID] = outcome.detection.Err
|
a.detectionErr[outcome.targetID] = outcome.detection.Err
|
||||||
update := targetDetectionUpdate{snapshot: a.snapshotLocked(), targetID: outcome.targetID}
|
update := targetDetectionUpdate{snapshot: a.snapshotLocked(), targetID: outcome.targetID}
|
||||||
@@ -351,28 +377,45 @@ func (a *Application) beginTargetDetection() (Snapshot, <-chan targetDetectionUp
|
|||||||
return checking, updates
|
return checking, updates
|
||||||
}
|
}
|
||||||
|
|
||||||
func detectTarget(adapter target.Target, active *profile.Profile) target.Detection {
|
func detectTarget(ctx context.Context, adapter target.Target, active *profile.Profile) target.Detection {
|
||||||
if detector, ok := adapter.(target.Detector); ok {
|
if detector, ok := adapter.(target.Detector); ok {
|
||||||
return detector.Detect(context.Background(), active)
|
return detector.Detect(ctx, active)
|
||||||
}
|
}
|
||||||
return target.Detection{
|
return target.Detection{
|
||||||
Availability: adapter.Availability(context.Background()),
|
Availability: adapter.Availability(ctx),
|
||||||
Inspection: adapter.Inspect(context.Background(), active),
|
Inspection: adapter.Inspect(ctx, active),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func mutationBlockReason(ctx context.Context, adapter target.Target) string {
|
||||||
|
authorizer, ok := adapter.(target.MutationAuthorizer)
|
||||||
|
if !ok {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
check := authorizer.MutationAuthority(ctx)
|
||||||
|
if check.OK {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if check.Evidence == "" {
|
||||||
|
return "The current process does not have authority to change this Target"
|
||||||
|
}
|
||||||
|
return check.Evidence
|
||||||
|
}
|
||||||
|
|
||||||
func (a *Application) Dispatch(intent Intent) Result {
|
func (a *Application) Dispatch(intent Intent) Result {
|
||||||
return a.dispatch(intent, nil)
|
ctx, cancel := context.WithTimeout(context.Background(), operationTimeout)
|
||||||
|
defer cancel()
|
||||||
|
return a.dispatch(ctx, intent, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *Application) dispatch(intent Intent, publish func(Result)) Result {
|
func (a *Application) dispatch(ctx context.Context, intent Intent, publish func(Result)) Result {
|
||||||
// Serialize local mutation workflows even when tests intentionally omit the
|
// Serialize local mutation workflows even when tests intentionally omit the
|
||||||
// cross-process MutationLock.
|
// cross-process MutationLock.
|
||||||
a.dispatchMu.Lock()
|
a.dispatchMu.Lock()
|
||||||
defer a.dispatchMu.Unlock()
|
defer a.dispatchMu.Unlock()
|
||||||
|
|
||||||
if a.mutationLock != nil {
|
if a.mutationLock != nil {
|
||||||
unlock, err := a.mutationLock.Lock(context.Background())
|
unlock, err := a.mutationLock.Lock(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Result{Snapshot: a.Snapshot(), Err: fmt.Errorf("lock proxyctl mutation: %w", err)}
|
return Result{Snapshot: a.Snapshot(), Err: fmt.Errorf("lock proxyctl mutation: %w", err)}
|
||||||
}
|
}
|
||||||
@@ -388,16 +431,16 @@ func (a *Application) dispatch(intent Intent, publish func(Result)) Result {
|
|||||||
}
|
}
|
||||||
a.replaceState(fresh)
|
a.replaceState(fresh)
|
||||||
if intent.Kind == ActivateProfile {
|
if intent.Kind == ActivateProfile {
|
||||||
a.refreshInspections()
|
a.refreshInspections(ctx)
|
||||||
}
|
}
|
||||||
if isTargetMutationIntent(intent.Kind) {
|
if isTargetMutationIntent(intent.Kind) {
|
||||||
return a.setTargetDesired(intent, publish)
|
return a.setTargetDesired(ctx, intent, publish)
|
||||||
}
|
}
|
||||||
if intent.Kind == RefreshTargets {
|
if intent.Kind == RefreshTargets {
|
||||||
return a.refreshTargets(publish)
|
return a.refreshTargets(ctx, publish)
|
||||||
}
|
}
|
||||||
if intent.Kind == ActivateProfile {
|
if intent.Kind == ActivateProfile {
|
||||||
return a.activateProfile(intent, publish)
|
return a.activateProfile(ctx, intent, publish)
|
||||||
}
|
}
|
||||||
var notice string
|
var notice string
|
||||||
next, err := a.store.Mutate(func(current profile.State) (profile.State, error) {
|
next, err := a.store.Mutate(func(current profile.State) (profile.State, error) {
|
||||||
@@ -416,7 +459,7 @@ func (a *Application) dispatch(intent Intent, publish func(Result)) Result {
|
|||||||
})
|
})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
a.replaceState(next)
|
a.replaceState(next)
|
||||||
a.refreshInspections()
|
a.refreshInspections(ctx)
|
||||||
} else {
|
} else {
|
||||||
var committed *profile.CommitError
|
var committed *profile.CommitError
|
||||||
if errors.As(err, &committed) {
|
if errors.As(err, &committed) {
|
||||||
@@ -434,7 +477,7 @@ func (a *Application) dispatch(intent Intent, publish func(Result)) Result {
|
|||||||
return Result{Snapshot: a.Snapshot(), Notice: notice, Err: err}
|
return Result{Snapshot: a.Snapshot(), Notice: notice, Err: err}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *Application) activateProfile(intent Intent, publish func(Result)) Result {
|
func (a *Application) activateProfile(ctx context.Context, intent Intent, publish func(Result)) Result {
|
||||||
state := a.stateCopy()
|
state := a.stateCopy()
|
||||||
if index(state, intent.Name) < 0 {
|
if index(state, intent.Name) < 0 {
|
||||||
return Result{Snapshot: a.Snapshot(), Err: fmt.Errorf("Profile %q does not exist", intent.Name)}
|
return Result{Snapshot: a.Snapshot(), Err: fmt.Errorf("Profile %q does not exist", intent.Name)}
|
||||||
@@ -446,23 +489,28 @@ func (a *Application) activateProfile(intent Intent, publish func(Result)) Resul
|
|||||||
inspections := a.inspectionsCopy()
|
inspections := a.inspectionsCopy()
|
||||||
var enabled []int
|
var enabled []int
|
||||||
var warnings []string
|
var warnings []string
|
||||||
|
confirmationScope := []string{"activate-profile", intent.Name}
|
||||||
for i, adapter := range a.targets {
|
for i, adapter := range a.targets {
|
||||||
id := a.targetIDs[i]
|
id := a.targetIDs[i]
|
||||||
if inspections[id].State != target.Enabled {
|
if inspections[id].State != target.Enabled {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
enabled = append(enabled, i)
|
enabled = append(enabled, i)
|
||||||
|
confirmationScope = append(confirmationScope, id)
|
||||||
if warning := adapter.Confirmation(true); warning != "" {
|
if warning := adapter.Confirmation(true); warning != "" {
|
||||||
warnings = append(warnings, a.targetDescriptions[i].Name+": "+warning)
|
detail := a.targetDescriptions[i].Name + ": " + warning
|
||||||
|
warnings = append(warnings, detail)
|
||||||
|
confirmationScope = append(confirmationScope, detail)
|
||||||
|
} else {
|
||||||
|
confirmationScope = append(confirmationScope, "")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(warnings) > 0 && !intent.Confirm {
|
token := confirmationToken(confirmationScope...)
|
||||||
message := "Changing the Active Profile requires confirmation:\n" + strings.Join(warnings, "\n")
|
if len(warnings) > 0 && (!intent.Confirm || intent.ConfirmationToken != token) {
|
||||||
confirmation := &Confirmation{
|
confirmation := &Confirmation{
|
||||||
Title: "Confirm Active Profile change", Summary: "Changing the Active Profile has high-impact Target effects.",
|
Title: "Confirm Active Profile change", Summary: "Changing the Active Profile has high-impact Target effects.",
|
||||||
Details: warnings, ConfirmLabel: "Change Profile", CancelLabel: "Cancel", HighImpact: true,
|
Details: warnings, ConfirmLabel: "Change Profile", CancelLabel: "Cancel", HighImpact: true, Token: token,
|
||||||
}
|
}
|
||||||
_ = message
|
|
||||||
return Result{Snapshot: a.Snapshot(), ConfirmationRequest: confirmation,
|
return Result{Snapshot: a.Snapshot(), ConfirmationRequest: confirmation,
|
||||||
Status: OperationStatus{Summary: confirmation.Title}}
|
Status: OperationStatus{Summary: confirmation.Title}}
|
||||||
}
|
}
|
||||||
@@ -489,7 +537,7 @@ func (a *Application) activateProfile(intent Intent, publish func(Result)) Resul
|
|||||||
// without the state lock, then publish all observations atomically.
|
// without the state lock, then publish all observations atomically.
|
||||||
observed := make(map[string]target.Inspection, len(a.targets))
|
observed := make(map[string]target.Inspection, len(a.targets))
|
||||||
for i, adapter := range a.targets {
|
for i, adapter := range a.targets {
|
||||||
observed[a.targetIDs[i]] = adapter.Inspect(context.Background(), active)
|
observed[a.targetIDs[i]] = adapter.Inspect(ctx, active)
|
||||||
}
|
}
|
||||||
a.replaceInspections(observed)
|
a.replaceInspections(observed)
|
||||||
|
|
||||||
@@ -505,16 +553,25 @@ func (a *Application) activateProfile(intent Intent, publish func(Result)) Resul
|
|||||||
publish(Result{Snapshot: a.Snapshot(), Progress: []TargetProgress{{TargetID: id, Phase: TargetProgressRunning, State: a.inspection(id).State}}, Notice: "Updating " + name + " Target",
|
publish(Result{Snapshot: a.Snapshot(), Progress: []TargetProgress{{TargetID: id, Phase: TargetProgressRunning, State: a.inspection(id).State}}, Notice: "Updating " + name + " Target",
|
||||||
Status: OperationStatus{Summary: "Updating " + name + " Target", TargetID: id}})
|
Status: OperationStatus{Summary: "Updating " + name + " Target", TargetID: id}})
|
||||||
}
|
}
|
||||||
operation := adapter.SetDesired(context.Background(), true, active)
|
operation := adapter.SetDesired(ctx, true, active)
|
||||||
inspection := operation.Inspection
|
inspection := operation.Inspection
|
||||||
var safeErr error
|
var safeErr error
|
||||||
if operation.Err != nil {
|
if operation.Err != nil {
|
||||||
// A failure-returned inspection may predate a partial write. Always
|
// A failure-returned inspection may predate a partial write. Always
|
||||||
// inspect explicitly against the new Active Profile before publishing.
|
// inspect explicitly against the new Active Profile before publishing.
|
||||||
inspection = adapter.Inspect(context.Background(), active)
|
inspection = adapter.Inspect(ctx, active)
|
||||||
safeErr = fmt.Errorf("%s (fresh inspection: %s — %s)", profile.RedactText(operation.Err.Error()), inspection.State, profile.RedactText(inspection.Evidence))
|
safeErr = fmt.Errorf("%s (fresh inspection: %s — %s)", profile.RedactText(operation.Err.Error()), inspection.State, profile.RedactText(inspection.Evidence))
|
||||||
}
|
}
|
||||||
a.replaceInspection(id, inspection)
|
a.replaceInspection(id, inspection)
|
||||||
|
if a.logger != nil {
|
||||||
|
outcome, detail := "success", inspection.Evidence
|
||||||
|
if safeErr != nil {
|
||||||
|
outcome, detail = "failure", safeErr.Error()
|
||||||
|
}
|
||||||
|
if logErr := a.logger.Write(LogEntry{Time: time.Now(), Operation: "switch-Active-Profile", Target: id, Result: outcome, Detail: RedactLogDetail(detail)}); logErr != nil {
|
||||||
|
safeErr = errors.Join(safeErr, fmt.Errorf("write %s Target operation log: %w", name, logErr))
|
||||||
|
}
|
||||||
|
}
|
||||||
progressPhase := TargetProgressSucceeded
|
progressPhase := TargetProgressSucceeded
|
||||||
if safeErr != nil {
|
if safeErr != nil {
|
||||||
progressPhase = TargetProgressFailed
|
progressPhase = TargetProgressFailed
|
||||||
@@ -528,13 +585,6 @@ func (a *Application) activateProfile(intent Intent, publish func(Result)) Resul
|
|||||||
}
|
}
|
||||||
publish(Result{Snapshot: a.Snapshot(), Progress: []TargetProgress{item}, Notice: name + " Target update completed", Status: status, Err: safeErr})
|
publish(Result{Snapshot: a.Snapshot(), Progress: []TargetProgress{item}, Notice: name + " Target update completed", Status: status, Err: safeErr})
|
||||||
}
|
}
|
||||||
if a.logger != nil {
|
|
||||||
outcome, detail := "success", inspection.Evidence
|
|
||||||
if safeErr != nil {
|
|
||||||
outcome, detail = "failure", safeErr.Error()
|
|
||||||
}
|
|
||||||
_ = a.logger.Write(LogEntry{Time: time.Now(), Operation: "switch-Active-Profile", Target: id, Result: outcome, Detail: RedactLogDetail(detail)})
|
|
||||||
}
|
|
||||||
if safeErr != nil {
|
if safeErr != nil {
|
||||||
failures = append(failures, fmt.Errorf("%s Target: %w", name, safeErr))
|
failures = append(failures, fmt.Errorf("%s Target: %w", name, safeErr))
|
||||||
}
|
}
|
||||||
@@ -545,7 +595,7 @@ func (a *Application) activateProfile(intent Intent, publish func(Result)) Resul
|
|||||||
for i, adapter := range a.targets {
|
for i, adapter := range a.targets {
|
||||||
id := a.targetIDs[i]
|
id := a.targetIDs[i]
|
||||||
if !updated[id] {
|
if !updated[id] {
|
||||||
remaining[id] = adapter.Inspect(context.Background(), active)
|
remaining[id] = adapter.Inspect(ctx, active)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
a.mergeInspections(remaining)
|
a.mergeInspections(remaining)
|
||||||
@@ -622,12 +672,13 @@ func (a *Application) replaceInspection(id string, inspection target.Inspection)
|
|||||||
// publishTargetDetection atomically replaces all availability, inspection, and
|
// publishTargetDetection atomically replaces all availability, inspection, and
|
||||||
// failure fields from one targeted check. Detect runs before this method, so no
|
// failure fields from one targeted check. Detect runs before this method, so no
|
||||||
// Application state mutex is held while adapter code executes.
|
// Application state mutex is held while adapter code executes.
|
||||||
func (a *Application) publishTargetDetection(id string, detection target.Detection) Snapshot {
|
func (a *Application) publishTargetDetection(id string, detection target.Detection, mutationBlockReason string) Snapshot {
|
||||||
a.stateMu.Lock()
|
a.stateMu.Lock()
|
||||||
defer a.stateMu.Unlock()
|
defer a.stateMu.Unlock()
|
||||||
a.detectionGeneration++
|
a.detectionGeneration++
|
||||||
a.availabilities[id] = detection.Availability
|
a.availabilities[id] = detection.Availability
|
||||||
a.inspections[id] = detection.Inspection
|
a.inspections[id] = detection.Inspection
|
||||||
|
a.mutationBlockReasons[id] = mutationBlockReason
|
||||||
a.detectionErr[id] = detection.Err
|
a.detectionErr[id] = detection.Err
|
||||||
a.detectionPhase[id] = TargetReady
|
a.detectionPhase[id] = TargetReady
|
||||||
if detection.Err != nil {
|
if detection.Err != nil {
|
||||||
@@ -670,8 +721,8 @@ func targetByID(snapshot Snapshot, id string) (TargetSnapshot, string) {
|
|||||||
return TargetSnapshot{ID: id}, id
|
return TargetSnapshot{ID: id}, id
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *Application) refreshTargets(publish func(Result)) Result {
|
func (a *Application) refreshTargets(ctx context.Context, publish func(Result)) Result {
|
||||||
checking, updates := a.beginTargetDetection()
|
checking, updates := a.beginTargetDetection(ctx)
|
||||||
if publish != nil {
|
if publish != nil {
|
||||||
progress := make([]TargetProgress, 0, len(checking.Targets))
|
progress := make([]TargetProgress, 0, len(checking.Targets))
|
||||||
for _, item := range checking.Targets {
|
for _, item := range checking.Targets {
|
||||||
@@ -714,11 +765,11 @@ func (a *Application) refreshTargets(publish func(Result)) Result {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *Application) refreshInspections() {
|
func (a *Application) refreshInspections(ctx context.Context) {
|
||||||
active := a.activeProfile()
|
active := a.activeProfile()
|
||||||
inspections := make(map[string]target.Inspection, len(a.targets))
|
inspections := make(map[string]target.Inspection, len(a.targets))
|
||||||
for i, adapter := range a.targets {
|
for i, adapter := range a.targets {
|
||||||
inspections[a.targetIDs[i]] = adapter.Inspect(context.Background(), active)
|
inspections[a.targetIDs[i]] = adapter.Inspect(ctx, active)
|
||||||
}
|
}
|
||||||
a.replaceInspections(inspections)
|
a.replaceInspections(inspections)
|
||||||
}
|
}
|
||||||
@@ -769,7 +820,7 @@ func validateTargetAction(intent Intent, selected TargetSnapshot) (targetActionP
|
|||||||
return policy, nil
|
return policy, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *Application) setTargetDesired(intent Intent, publish func(Result)) Result {
|
func (a *Application) setTargetDesired(ctx context.Context, intent Intent, publish func(Result)) Result {
|
||||||
selectedIndex := -1
|
selectedIndex := -1
|
||||||
for i, id := range a.targetIDs {
|
for i, id := range a.targetIDs {
|
||||||
if id == intent.TargetID {
|
if id == intent.TargetID {
|
||||||
@@ -785,27 +836,30 @@ func (a *Application) setTargetDesired(intent Intent, publish func(Result)) Resu
|
|||||||
// This targeted check runs inside dispatch serialization and immediately
|
// This targeted check runs inside dispatch serialization and immediately
|
||||||
// before action validation. Adapter calls happen without stateMu; the full
|
// before action validation. Adapter calls happen without stateMu; the full
|
||||||
// outcome is then published under one lock before policy is derived.
|
// outcome is then published under one lock before policy is derived.
|
||||||
detection := detectTarget(selected, active)
|
detection := detectTarget(ctx, selected, active)
|
||||||
snapshot := a.publishTargetDetection(intent.TargetID, detection)
|
snapshot := a.publishTargetDetection(intent.TargetID, detection, mutationBlockReason(ctx, selected))
|
||||||
selectedSnapshot := snapshot.Targets[selectedIndex]
|
selectedSnapshot := snapshot.Targets[selectedIndex]
|
||||||
policy, err := validateTargetAction(intent, selectedSnapshot)
|
policy, err := validateTargetAction(intent, selectedSnapshot)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Result{Snapshot: snapshot, Err: err}
|
return Result{Snapshot: snapshot, Err: err}
|
||||||
}
|
}
|
||||||
if warning := selected.Confirmation(policy.desired); warning != "" && !intent.Confirm {
|
if warning := selected.Confirmation(policy.desired); warning != "" {
|
||||||
|
token := confirmationToken("target", intent.TargetID, fmt.Sprint(intent.Kind), fmt.Sprint(selectedSnapshot.State), fmt.Sprint(policy.desired), warning)
|
||||||
|
if !intent.Confirm || intent.ConfirmationToken != token {
|
||||||
confirmation := &Confirmation{Title: "Confirm " + a.targetDescriptions[selectedIndex].Name + " Target change", Summary: warning,
|
confirmation := &Confirmation{Title: "Confirm " + a.targetDescriptions[selectedIndex].Name + " Target change", Summary: warning,
|
||||||
ConfirmLabel: "Continue", CancelLabel: "Cancel", HighImpact: true}
|
ConfirmLabel: "Continue", CancelLabel: "Cancel", HighImpact: true, Token: token}
|
||||||
return Result{Snapshot: a.Snapshot(), ConfirmationRequest: confirmation,
|
return Result{Snapshot: a.Snapshot(), ConfirmationRequest: confirmation,
|
||||||
Status: OperationStatus{Summary: confirmation.Title, TargetID: intent.TargetID}}
|
Status: OperationStatus{Summary: confirmation.Title, TargetID: intent.TargetID}}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if publish != nil {
|
if publish != nil {
|
||||||
publish(Result{Snapshot: snapshot, Progress: []TargetProgress{{TargetID: intent.TargetID, Phase: TargetProgressRunning, State: selectedSnapshot.State}},
|
publish(Result{Snapshot: snapshot, Progress: []TargetProgress{{TargetID: intent.TargetID, Phase: TargetProgressRunning, State: selectedSnapshot.State}},
|
||||||
Status: OperationStatus{Summary: "Updating " + a.targetDescriptions[selectedIndex].Name + " Target", TargetID: intent.TargetID}})
|
Status: OperationStatus{Summary: "Updating " + a.targetDescriptions[selectedIndex].Name + " Target", TargetID: intent.TargetID}})
|
||||||
}
|
}
|
||||||
result := selected.SetDesired(context.Background(), policy.desired, active)
|
result := selected.SetDesired(ctx, policy.desired, active)
|
||||||
inspection := result.Inspection
|
inspection := result.Inspection
|
||||||
if result.Err != nil {
|
if result.Err != nil {
|
||||||
inspection = selected.Inspect(context.Background(), active)
|
inspection = selected.Inspect(ctx, active)
|
||||||
}
|
}
|
||||||
a.replaceInspection(intent.TargetID, inspection)
|
a.replaceInspection(intent.TargetID, inspection)
|
||||||
outcome, detail := "success", inspection.Evidence
|
outcome, detail := "success", inspection.Evidence
|
||||||
@@ -813,7 +867,9 @@ func (a *Application) setTargetDesired(intent Intent, publish func(Result)) Resu
|
|||||||
outcome, detail = "failure", result.Err.Error()
|
outcome, detail = "failure", result.Err.Error()
|
||||||
}
|
}
|
||||||
if a.logger != nil {
|
if a.logger != nil {
|
||||||
_ = a.logger.Write(LogEntry{Time: time.Now(), Operation: policy.operation, Target: intent.TargetID, Result: outcome, Detail: RedactLogDetail(detail)})
|
if logErr := a.logger.Write(LogEntry{Time: time.Now(), Operation: policy.operation, Target: intent.TargetID, Result: outcome, Detail: RedactLogDetail(detail)}); logErr != nil {
|
||||||
|
result.Err = errors.Join(result.Err, fmt.Errorf("write Target operation log: %w", logErr))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
notice := ""
|
notice := ""
|
||||||
progressPhase := TargetProgressSucceeded
|
progressPhase := TargetProgressSucceeded
|
||||||
|
|||||||
@@ -1,5 +1,12 @@
|
|||||||
package app
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const operationTimeout = 5 * time.Minute
|
||||||
|
|
||||||
// StatusKind gives presentation layers semantics without requiring them to
|
// StatusKind gives presentation layers semantics without requiring them to
|
||||||
// inspect user-facing status text.
|
// inspect user-facing status text.
|
||||||
type StatusKind uint8
|
type StatusKind uint8
|
||||||
@@ -27,6 +34,9 @@ type Confirmation struct {
|
|||||||
ConfirmLabel string
|
ConfirmLabel string
|
||||||
CancelLabel string
|
CancelLabel string
|
||||||
HighImpact bool
|
HighImpact bool
|
||||||
|
// Token binds acceptance to the exact state and operation scope that was
|
||||||
|
// presented. Presentation layers must return it with the confirmed Intent.
|
||||||
|
Token string
|
||||||
}
|
}
|
||||||
|
|
||||||
// TargetProgressPhase describes one Target's part in an operation stream.
|
// TargetProgressPhase describes one Target's part in an operation stream.
|
||||||
@@ -189,6 +199,7 @@ func (u OperationUpdate) IsTerminal() bool { return u.Decode().IsTerm
|
|||||||
type OperationStream struct {
|
type OperationStream struct {
|
||||||
Snapshot Snapshot
|
Snapshot Snapshot
|
||||||
Updates <-chan OperationUpdate
|
Updates <-chan OperationUpdate
|
||||||
|
Cancel context.CancelFunc
|
||||||
}
|
}
|
||||||
|
|
||||||
// InteractiveModule is the presentation-independent Application seam used by
|
// InteractiveModule is the presentation-independent Application seam used by
|
||||||
@@ -216,16 +227,20 @@ func (a *Application) StartOperation(intent Intent) OperationStream {
|
|||||||
a.interactiveOperation = true
|
a.interactiveOperation = true
|
||||||
a.interactiveMu.Unlock()
|
a.interactiveMu.Unlock()
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), operationTimeout)
|
||||||
updates := make(chan OperationUpdate, 2*len(a.targets)+2)
|
updates := make(chan OperationUpdate, 2*len(a.targets)+2)
|
||||||
go func() {
|
go func() {
|
||||||
defer close(updates)
|
defer close(updates)
|
||||||
defer a.finishInteractiveOperation()
|
defer cancel()
|
||||||
final := a.dispatch(intent, func(result Result) {
|
final := a.dispatch(ctx, intent, func(result Result) {
|
||||||
updates <- runningOperationUpdate(result)
|
updates <- runningOperationUpdate(result)
|
||||||
})
|
})
|
||||||
|
// Release the Application gate before publishing the terminal update so
|
||||||
|
// an immediate confirmation retry cannot observe a stale busy state.
|
||||||
|
a.finishInteractiveOperation()
|
||||||
updates <- terminalOperationUpdate(final)
|
updates <- terminalOperationUpdate(final)
|
||||||
}()
|
}()
|
||||||
return OperationStream{Snapshot: initial, Updates: updates}
|
return OperationStream{Snapshot: initial, Updates: updates, Cancel: cancel}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *Application) finishInteractiveOperation() {
|
func (a *Application) finishInteractiveOperation() {
|
||||||
|
|||||||
@@ -83,6 +83,45 @@ func (t *coordinatedOperationTarget) SetDesired(_ context.Context, enabled bool,
|
|||||||
return target.OperationResult{Inspection: target.Inspection{State: t.state, Evidence: "completed"}}
|
return target.OperationResult{Inspection: target.Inspection{State: t.state, Evidence: "completed"}}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type cancellableOperationTarget struct{ started chan struct{} }
|
||||||
|
|
||||||
|
func (t *cancellableOperationTarget) ID() string { return "cancellable" }
|
||||||
|
func (t *cancellableOperationTarget) Description() target.Description {
|
||||||
|
return target.Description{Name: "Cancellable"}
|
||||||
|
}
|
||||||
|
func (t *cancellableOperationTarget) Availability(context.Context) target.Availability {
|
||||||
|
return target.Availability{Available: true}
|
||||||
|
}
|
||||||
|
func (t *cancellableOperationTarget) Inspect(context.Context, *profile.Profile) target.Inspection {
|
||||||
|
return target.Inspection{State: target.Disabled, Evidence: "not changed"}
|
||||||
|
}
|
||||||
|
func (t *cancellableOperationTarget) Confirmation(bool) string { return "" }
|
||||||
|
func (t *cancellableOperationTarget) SetDesired(ctx context.Context, _ bool, _ *profile.Profile) target.OperationResult {
|
||||||
|
close(t.started)
|
||||||
|
<-ctx.Done()
|
||||||
|
return target.OperationResult{Inspection: target.Inspection{State: target.Disabled}, Err: ctx.Err()}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInteractiveOperationCancellationReachesTarget(t *testing.T) {
|
||||||
|
adapter := &cancellableOperationTarget{started: make(chan struct{})}
|
||||||
|
application, err := app.NewWithTargets(profile.NewFileStore(filepath.Join(t.TempDir(), "profiles.json")), []target.Target{adapter})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
createAndActivate(t, application)
|
||||||
|
refreshApplicationTargets(t, application)
|
||||||
|
operation := application.StartOperation(app.Intent{Kind: app.EnableTarget, TargetID: adapter.ID()})
|
||||||
|
<-adapter.started
|
||||||
|
operation.Cancel()
|
||||||
|
var final app.OperationUpdate
|
||||||
|
for update := range operation.Updates {
|
||||||
|
final = update
|
||||||
|
}
|
||||||
|
if !final.IsFailed() || !errors.Is(final.Err(), context.Canceled) {
|
||||||
|
t.Fatalf("cancelled operation final update = %#v", final)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestInteractiveOperationStreamSerializesMutationAndPublishesStructuredProgress(t *testing.T) {
|
func TestInteractiveOperationStreamSerializesMutationAndPublishesStructuredProgress(t *testing.T) {
|
||||||
adapter := &coordinatedOperationTarget{id: "shell", state: target.Disabled, started: make(chan struct{}), release: make(chan struct{})}
|
adapter := &coordinatedOperationTarget{id: "shell", state: target.Disabled, started: make(chan struct{}), release: make(chan struct{})}
|
||||||
application, err := app.NewWithTargets(profile.NewFileStore(filepath.Join(t.TempDir(), "profiles.json")), []target.Target{adapter})
|
application, err := app.NewWithTargets(profile.NewFileStore(filepath.Join(t.TempDir(), "profiles.json")), []target.Target{adapter})
|
||||||
@@ -224,9 +263,22 @@ func TestInteractiveOperationStreamUsesStructuredConfirmation(t *testing.T) {
|
|||||||
operation := application.StartOperation(app.Intent{Kind: app.EnableTarget, TargetID: adapter.ID()})
|
operation := application.StartOperation(app.Intent{Kind: app.EnableTarget, TargetID: adapter.ID()})
|
||||||
update := <-operation.Updates
|
update := <-operation.Updates
|
||||||
confirmation := update.Confirmation()
|
confirmation := update.Confirmation()
|
||||||
if !update.IsConfirmation() || confirmation == nil || confirmation.Title == "" || confirmation.CancelLabel == "" {
|
if !update.IsConfirmation() || confirmation == nil || confirmation.Title == "" || confirmation.CancelLabel == "" || confirmation.Token == "" {
|
||||||
t.Fatalf("confirmation update = %#v", update)
|
t.Fatalf("confirmation update = %#v", update)
|
||||||
}
|
}
|
||||||
|
// Retry immediately after the terminal confirmation, before observing the
|
||||||
|
// first stream close. The Application gate must already be released.
|
||||||
|
retry := application.StartOperation(app.Intent{Kind: app.EnableTarget, TargetID: adapter.ID(), Confirm: true, ConfirmationToken: confirmation.Token})
|
||||||
|
var final app.OperationUpdate
|
||||||
|
for next := range retry.Updates {
|
||||||
|
if next.Decode().Kind == app.OperationClosed {
|
||||||
|
t.Fatalf("immediate confirmed retry observed stale operation gate: %#v", next)
|
||||||
|
}
|
||||||
|
final = next
|
||||||
|
}
|
||||||
|
if !final.IsSucceeded() {
|
||||||
|
t.Fatalf("confirmed retry final update = %#v", final)
|
||||||
|
}
|
||||||
if _, open := <-operation.Updates; open {
|
if _, open := <-operation.Updates; open {
|
||||||
t.Fatal("confirmation operation stream did not close")
|
t.Fatal("confirmation operation stream did not close")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -92,12 +92,46 @@ func TestApplicationRequiresTargetConfirmationBeforeMutation(t *testing.T) {
|
|||||||
if warning.ConfirmationRequest == nil || warning.Err != nil || len(adapter.calls) != 0 || warning.Snapshot.Targets[0].State != target.Disabled {
|
if warning.ConfirmationRequest == nil || warning.Err != nil || len(adapter.calls) != 0 || warning.Snapshot.Targets[0].State != target.Disabled {
|
||||||
t.Fatalf("unconfirmed result = %#v, calls=%v", warning, adapter.calls)
|
t.Fatalf("unconfirmed result = %#v, calls=%v", warning, adapter.calls)
|
||||||
}
|
}
|
||||||
confirmed := application.Dispatch(app.Intent{Kind: app.EnableTarget, TargetID: "docker-daemon", Confirm: true})
|
adapter.confirmation = "Updated restart warning after state changed."
|
||||||
|
stale := application.Dispatch(app.Intent{Kind: app.EnableTarget, TargetID: "docker-daemon", Confirm: true, ConfirmationToken: warning.ConfirmationRequest.Token})
|
||||||
|
if stale.ConfirmationRequest == nil || stale.ConfirmationRequest.Token == warning.ConfirmationRequest.Token || len(adapter.calls) != 0 {
|
||||||
|
t.Fatalf("stale confirmation was accepted = %#v, calls=%v", stale, adapter.calls)
|
||||||
|
}
|
||||||
|
confirmed := application.Dispatch(app.Intent{Kind: app.EnableTarget, TargetID: "docker-daemon", Confirm: true, ConfirmationToken: stale.ConfirmationRequest.Token})
|
||||||
if confirmed.Err != nil || len(adapter.calls) != 1 || confirmed.Snapshot.Targets[0].State != target.Enabled {
|
if confirmed.Err != nil || len(adapter.calls) != 1 || confirmed.Snapshot.Targets[0].State != target.Enabled {
|
||||||
t.Fatalf("confirmed result = %#v, calls=%v", confirmed, adapter.calls)
|
t.Fatalf("confirmed result = %#v, calls=%v", confirmed, adapter.calls)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type authorityTarget struct {
|
||||||
|
*fakeTarget
|
||||||
|
allowed bool
|
||||||
|
reason string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *authorityTarget) MutationAuthority(context.Context) target.Check {
|
||||||
|
return target.Check{Name: "mutation authority", OK: t.allowed, Evidence: t.reason}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestApplicationDisablesMutationWhenCurrentProcessLacksAuthority(t *testing.T) {
|
||||||
|
adapter := &authorityTarget{fakeTarget: &fakeTarget{available: true, state: target.Disabled}, reason: "requires elevated authority"}
|
||||||
|
application, err := app.NewWithTargets(profile.NewFileStore(filepath.Join(t.TempDir(), "profiles.json")), []target.Target{adapter})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
createAndActivate(t, application)
|
||||||
|
refreshApplicationTargets(t, application)
|
||||||
|
|
||||||
|
snapshot := application.Snapshot()
|
||||||
|
if snapshot.Targets[0].PrimaryAction.Available || snapshot.Targets[0].PrimaryAction.DisabledReason != adapter.reason {
|
||||||
|
t.Fatalf("authority policy = %#v", snapshot.Targets[0].PrimaryAction)
|
||||||
|
}
|
||||||
|
result := application.Dispatch(app.Intent{Kind: app.EnableTarget, TargetID: adapter.ID()})
|
||||||
|
if result.Err == nil || !strings.Contains(result.Err.Error(), adapter.reason) || len(adapter.calls) != 0 {
|
||||||
|
t.Fatalf("blocked mutation result = %#v calls=%v", result, adapter.calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type targetWithID struct {
|
type targetWithID struct {
|
||||||
*fakeTarget
|
*fakeTarget
|
||||||
id string
|
id string
|
||||||
@@ -105,6 +139,25 @@ type targetWithID struct {
|
|||||||
|
|
||||||
func (t targetWithID) ID() string { return t.id }
|
func (t targetWithID) ID() string { return t.id }
|
||||||
|
|
||||||
|
func TestTargetMutationReportsLoggingFailureAfterKeepingAppliedState(t *testing.T) {
|
||||||
|
adapter := &fakeTarget{available: true, state: target.Disabled}
|
||||||
|
logger := &recordingLog{err: errors.New("log device full")}
|
||||||
|
application, err := app.NewWithTargetsAndRuntime(profile.NewFileStore(filepath.Join(t.TempDir(), "profiles.json")), []target.Target{adapter}, nil, logger)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
createAndActivate(t, application)
|
||||||
|
refreshApplicationTargets(t, application)
|
||||||
|
|
||||||
|
result := application.Dispatch(app.Intent{Kind: app.EnableTarget, TargetID: adapter.ID()})
|
||||||
|
if result.Err == nil || !strings.Contains(result.Err.Error(), "operation log") || result.Snapshot.Targets[0].State != target.Enabled {
|
||||||
|
t.Fatalf("logging failure result = %#v", result)
|
||||||
|
}
|
||||||
|
if len(logger.entries) != 1 {
|
||||||
|
t.Fatalf("log attempts = %#v", logger.entries)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestApplicationHidesUnavailableTargetButKeepsExplanation(t *testing.T) {
|
func TestApplicationHidesUnavailableTargetButKeepsExplanation(t *testing.T) {
|
||||||
adapter := &fakeTarget{available: false, state: target.Disabled}
|
adapter := &fakeTarget{available: false, state: target.Disabled}
|
||||||
application, err := app.NewWithTargets(profile.NewFileStore(filepath.Join(t.TempDir(), "profiles.json")), []target.Target{adapter})
|
application, err := app.NewWithTargets(profile.NewFileStore(filepath.Join(t.TempDir(), "profiles.json")), []target.Target{adapter})
|
||||||
|
|||||||
+12
-5
@@ -2,7 +2,6 @@
|
|||||||
package apt
|
package apt
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -15,6 +14,7 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"proxyctl/internal/execsafe"
|
||||||
"proxyctl/internal/profile"
|
"proxyctl/internal/profile"
|
||||||
"proxyctl/internal/securefs"
|
"proxyctl/internal/securefs"
|
||||||
"proxyctl/internal/target"
|
"proxyctl/internal/target"
|
||||||
@@ -77,7 +77,7 @@ type Runner interface {
|
|||||||
|
|
||||||
type systemRunner struct{}
|
type systemRunner struct{}
|
||||||
|
|
||||||
func (systemRunner) LookPath(name string) (string, error) { return exec.LookPath(name) }
|
func (systemRunner) LookPath(name string) (string, error) { return execsafe.LookPath(name) }
|
||||||
func (systemRunner) Output(ctx context.Context, name string, args ...string) ([]byte, error) {
|
func (systemRunner) Output(ctx context.Context, name string, args ...string) ([]byte, error) {
|
||||||
return exec.CommandContext(ctx, name, args...).Output()
|
return exec.CommandContext(ctx, name, args...).Output()
|
||||||
}
|
}
|
||||||
@@ -130,6 +130,14 @@ func (a *Adapter) Confirmation(bool) string { return "" }
|
|||||||
|
|
||||||
// DiagnosticChecks observes the APT command, configuration schema, and current
|
// DiagnosticChecks observes the APT command, configuration schema, and current
|
||||||
// filesystem authority without changing the overlay or effective settings.
|
// filesystem authority without changing the overlay or effective settings.
|
||||||
|
func (a *Adapter) MutationAuthority(context.Context) target.Check {
|
||||||
|
check := target.ReadOnlyWriteAuthority(a.configuration.OverlayFile)
|
||||||
|
if !check.OK {
|
||||||
|
check.Evidence += "; run proxyctl with sufficient authority (normally sudo proxyctl)"
|
||||||
|
}
|
||||||
|
return check
|
||||||
|
}
|
||||||
|
|
||||||
func (a *Adapter) DiagnosticChecks(ctx context.Context, _ *profile.Profile) []target.Check {
|
func (a *Adapter) DiagnosticChecks(ctx context.Context, _ *profile.Profile) []target.Check {
|
||||||
commandCheck := target.Check{Name: "required command", OK: true, Evidence: "apt-config is available"}
|
commandCheck := target.Check{Name: "required command", OK: true, Evidence: "apt-config is available"}
|
||||||
command, err := a.runner.LookPath("apt-config")
|
command, err := a.runner.LookPath("apt-config")
|
||||||
@@ -435,9 +443,8 @@ func aptQuote(value string) string {
|
|||||||
|
|
||||||
func parseConfiguration(data []byte) map[string]string {
|
func parseConfiguration(data []byte) map[string]string {
|
||||||
settings := make(map[string]string)
|
settings := make(map[string]string)
|
||||||
scanner := bufio.NewScanner(strings.NewReader(string(data)))
|
for _, raw := range strings.Split(string(data), "\n") {
|
||||||
for scanner.Scan() {
|
line := strings.TrimSpace(raw)
|
||||||
line := strings.TrimSpace(scanner.Text())
|
|
||||||
if line == "" || strings.HasPrefix(line, "//") || strings.HasPrefix(line, "#") {
|
if line == "" || strings.HasPrefix(line, "//") || strings.HasPrefix(line, "#") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"proxyctl/internal/pathutil"
|
||||||
"proxyctl/internal/profile"
|
"proxyctl/internal/profile"
|
||||||
"proxyctl/internal/securefs"
|
"proxyctl/internal/securefs"
|
||||||
"proxyctl/internal/target"
|
"proxyctl/internal/target"
|
||||||
@@ -79,24 +80,7 @@ func ResolveConfiguration(environment profile.IdentityEnvironment) (Configuratio
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ResolveConfigurationForCurrentProcess() (Configuration, error) {
|
func pathWithin(path, parent string) bool { return pathutil.Within(path, parent) }
|
||||||
return ResolveConfiguration(systemEnvironment{})
|
|
||||||
}
|
|
||||||
|
|
||||||
type systemEnvironment struct{}
|
|
||||||
|
|
||||||
func (systemEnvironment) CurrentUser() (profile.UserIdentity, error) {
|
|
||||||
return profile.SystemCurrentUser()
|
|
||||||
}
|
|
||||||
func (systemEnvironment) LookupUser(name string) (profile.UserIdentity, error) {
|
|
||||||
return profile.SystemLookupUser(name)
|
|
||||||
}
|
|
||||||
func (systemEnvironment) LookupEnv(name string) (string, bool) { return os.LookupEnv(name) }
|
|
||||||
|
|
||||||
func pathWithin(path, parent string) bool {
|
|
||||||
relative, err := filepath.Rel(parent, path)
|
|
||||||
return err == nil && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))
|
|
||||||
}
|
|
||||||
|
|
||||||
type Ownership struct{ UID, GID int }
|
type Ownership struct{ UID, GID int }
|
||||||
|
|
||||||
@@ -329,6 +313,7 @@ func (a *Adapter) enable(active *profile.Profile) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("read Docker client configuration for safe JSON merge: %w", err)
|
return fmt.Errorf("read Docker client configuration for safe JSON merge: %w", err)
|
||||||
}
|
}
|
||||||
|
observedConfig := fingerprintDocument(config, configPresent)
|
||||||
metadata, managed, recoveryErr := a.readRecovery()
|
metadata, managed, recoveryErr := a.readRecovery()
|
||||||
if recoveryErr != nil && !errors.Is(recoveryErr, fs.ErrNotExist) {
|
if recoveryErr != nil && !errors.Is(recoveryErr, fs.ErrNotExist) {
|
||||||
return fmt.Errorf("read Docker client recovery metadata: %w", recoveryErr)
|
return fmt.Errorf("read Docker client recovery metadata: %w", recoveryErr)
|
||||||
@@ -362,6 +347,9 @@ func (a *Adapter) enable(active *profile.Profile) error {
|
|||||||
applyDesired(defaults, desired)
|
applyDesired(defaults, desired)
|
||||||
setChildObject(proxies, "default", defaults)
|
setChildObject(proxies, "default", defaults)
|
||||||
setChildObject(config, "proxies", proxies)
|
setChildObject(config, "proxies", proxies)
|
||||||
|
if err := a.requireConfigUnchanged(observedConfig); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if err := a.writeConfig(config); err != nil {
|
if err := a.writeConfig(config); err != nil {
|
||||||
return fmt.Errorf("write Docker client proxy defaults after recovery metadata persisted: %w", err)
|
return fmt.Errorf("write Docker client proxy defaults after recovery metadata persisted: %w", err)
|
||||||
}
|
}
|
||||||
@@ -380,6 +368,7 @@ func (a *Adapter) disable() error {
|
|||||||
if err != nil && !errors.Is(err, fs.ErrNotExist) {
|
if err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||||
return fmt.Errorf("read Docker client configuration for restoration: %w", err)
|
return fmt.Errorf("read Docker client configuration for restoration: %w", err)
|
||||||
}
|
}
|
||||||
|
observedConfig := fingerprintDocument(config, configPresent)
|
||||||
if !configPresent {
|
if !configPresent {
|
||||||
config = make(map[string]json.RawMessage)
|
config = make(map[string]json.RawMessage)
|
||||||
}
|
}
|
||||||
@@ -422,6 +411,9 @@ func (a *Adapter) disable() error {
|
|||||||
} else {
|
} else {
|
||||||
setChildObject(config, "proxies", proxies)
|
setChildObject(config, "proxies", proxies)
|
||||||
}
|
}
|
||||||
|
if err := a.requireConfigUnchanged(observedConfig); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if len(config) == 0 && !metadata.ConfigPresent {
|
if len(config) == 0 && !metadata.ConfigPresent {
|
||||||
if err := a.files.Remove(a.configuration.ConfigFile); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
if err := a.files.Remove(a.configuration.ConfigFile); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||||
return fmt.Errorf("remove newly created empty Docker client configuration: %w", err)
|
return fmt.Errorf("remove newly created empty Docker client configuration: %w", err)
|
||||||
@@ -543,23 +535,6 @@ func applyDesired(defaults map[string]json.RawMessage, desired map[string]string
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
func recognizesProxyDefaults(config map[string]json.RawMessage) bool {
|
|
||||||
proxies, _, err := childObject(config, "proxies")
|
|
||||||
if err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
defaults, _, err := childObject(proxies, "default")
|
|
||||||
if err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
for _, key := range append(append([]string(nil), managedKeys...), "ftpProxy") {
|
|
||||||
var value string
|
|
||||||
if raw, ok := defaults[key]; ok && json.Unmarshal(raw, &value) == nil && value != "" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
type managedValue struct {
|
type managedValue struct {
|
||||||
Present bool `json:"present"`
|
Present bool `json:"present"`
|
||||||
@@ -612,6 +587,27 @@ func fingerprintSnapshot(snapshot map[string]managedValue) string {
|
|||||||
sum := sha256.Sum256(data)
|
sum := sha256.Sum256(data)
|
||||||
return hex.EncodeToString(sum[:])
|
return hex.EncodeToString(sum[:])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func fingerprintDocument(config map[string]json.RawMessage, present bool) string {
|
||||||
|
data, _ := json.Marshal(struct {
|
||||||
|
Present bool `json:"present"`
|
||||||
|
Config map[string]json.RawMessage `json:"config"`
|
||||||
|
}{Present: present, Config: config})
|
||||||
|
sum := sha256.Sum256(data)
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Adapter) requireConfigUnchanged(expected string) error {
|
||||||
|
current, present, err := a.readConfig()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("re-read Docker client configuration before atomic replacement: %w", err)
|
||||||
|
}
|
||||||
|
if fingerprintDocument(current, present) != expected {
|
||||||
|
return errors.New("Docker client configuration changed concurrently; refusing to overwrite external updates")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func cloneRaw(value json.RawMessage) json.RawMessage { return append(json.RawMessage(nil), value...) }
|
func cloneRaw(value json.RawMessage) json.RawMessage { return append(json.RawMessage(nil), value...) }
|
||||||
func (a *Adapter) ownership() *Ownership {
|
func (a *Adapter) ownership() *Ownership {
|
||||||
if !a.configuration.OwnFiles {
|
if !a.configuration.OwnFiles {
|
||||||
|
|||||||
@@ -656,6 +656,39 @@ func (f *failingFS) AtomicWrite(path string, data []byte, mode os.FileMode, owne
|
|||||||
return f.FileSystem.AtomicWrite(path, data, mode, owner)
|
return f.FileSystem.AtomicWrite(path, data, mode, owner)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type concurrentChangeFS struct {
|
||||||
|
dockerclient.FileSystem
|
||||||
|
configPath string
|
||||||
|
reads int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *concurrentChangeFS) ReadFile(path string) ([]byte, error) {
|
||||||
|
if path == f.configPath {
|
||||||
|
f.reads++
|
||||||
|
if f.reads == 3 {
|
||||||
|
if err := os.WriteFile(path, []byte(`{"auths":{"registry.example":{"auth":"external-update"}}}`), 0o600); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return f.FileSystem.ReadFile(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConcurrentDockerConfigChangeIsNotOverwritten(t *testing.T) {
|
||||||
|
files := &concurrentChangeFS{FileSystem: dockerclient.OSFileSystem{}}
|
||||||
|
a := newAdapter(t, files)
|
||||||
|
files.configPath = a.ConfigPath()
|
||||||
|
writeConfig(t, a.ConfigPath(), `{"auths":{"registry.example":{"auth":"original"}}}`)
|
||||||
|
|
||||||
|
result := a.SetDesired(context.Background(), true, activeProfile())
|
||||||
|
if result.Err == nil || !strings.Contains(result.Err.Error(), "changed concurrently") {
|
||||||
|
t.Fatalf("concurrent update result = %#v", result)
|
||||||
|
}
|
||||||
|
if got := readFile(t, a.ConfigPath()); !strings.Contains(got, "external-update") || strings.Contains(got, "httpProxy") {
|
||||||
|
t.Fatalf("external Docker config update was overwritten: %s", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type countingFS struct {
|
type countingFS struct {
|
||||||
dockerclient.FileSystem
|
dockerclient.FileSystem
|
||||||
writes int
|
writes int
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"proxyctl/internal/execsafe"
|
||||||
"proxyctl/internal/profile"
|
"proxyctl/internal/profile"
|
||||||
"proxyctl/internal/securefs"
|
"proxyctl/internal/securefs"
|
||||||
"proxyctl/internal/target"
|
"proxyctl/internal/target"
|
||||||
@@ -64,7 +65,11 @@ type CommandRunner interface {
|
|||||||
type ExecRunner struct{}
|
type ExecRunner struct{}
|
||||||
|
|
||||||
func (ExecRunner) Run(ctx context.Context, name string, args ...string) ([]byte, error) {
|
func (ExecRunner) Run(ctx context.Context, name string, args ...string) ([]byte, error) {
|
||||||
output, err := exec.CommandContext(ctx, name, args...).CombinedOutput()
|
command, err := execsafe.LookPath(name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
output, err := exec.CommandContext(ctx, command, args...).CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return output, fmt.Errorf("%s: %s: %w", name, strings.TrimSpace(string(output)), err)
|
return output, fmt.Errorf("%s: %s: %w", name, strings.TrimSpace(string(output)), err)
|
||||||
}
|
}
|
||||||
@@ -127,6 +132,15 @@ func (a *Adapter) Confirmation(bool) string {
|
|||||||
|
|
||||||
// DiagnosticChecks performs only systemctl show and filesystem reads/metadata
|
// DiagnosticChecks performs only systemctl show and filesystem reads/metadata
|
||||||
// probes; service reload/restart and all configuration mutations are excluded.
|
// probes; service reload/restart and all configuration mutations are excluded.
|
||||||
|
func (a *Adapter) MutationAuthority(context.Context) target.Check {
|
||||||
|
if a.authority.EffectiveUID() != 0 {
|
||||||
|
return target.Check{Name: "mutation authority", Evidence: "Docker daemon changes require root authority; restart with sudo proxyctl"}
|
||||||
|
}
|
||||||
|
check := target.ReadOnlyWriteAuthority(a.configuration.DaemonConfigPath, a.configuration.RecoveryPath)
|
||||||
|
check.Name = "mutation authority"
|
||||||
|
return check
|
||||||
|
}
|
||||||
|
|
||||||
func (a *Adapter) DiagnosticChecks(ctx context.Context, _ *profile.Profile) []target.Check {
|
func (a *Adapter) DiagnosticChecks(ctx context.Context, _ *profile.Profile) []target.Check {
|
||||||
commandCheck := target.Check{Name: "required command and service", OK: true, Evidence: "systemctl can inspect the loaded docker.service"}
|
commandCheck := target.Check{Name: "required command and service", OK: true, Evidence: "systemctl can inspect the loaded docker.service"}
|
||||||
if availability, err := a.detect(ctx); err != nil || !availability.Available {
|
if availability, err := a.detect(ctx); err != nil || !availability.Available {
|
||||||
@@ -336,11 +350,9 @@ func (a *Adapter) enable(ctx context.Context, p profile.Profile) error {
|
|||||||
return fmt.Errorf("persist Docker daemon recovery metadata before changing configuration: %w", err)
|
return fmt.Errorf("persist Docker daemon recovery metadata before changing configuration: %w", err)
|
||||||
}
|
}
|
||||||
if fingerprint(current) != desiredFingerprint {
|
if fingerprint(current) != desiredFingerprint {
|
||||||
mode := os.FileMode(0o600)
|
// Managed proxy URLs may contain credentials. Keep the live configuration
|
||||||
if metadata.OriginalExists {
|
// owner-only; disable restores the original mode with the original data.
|
||||||
mode = os.FileMode(metadata.OriginalMode)
|
if err := a.files.AtomicWrite(a.configuration.DaemonConfigPath, desired, 0o600); err != nil {
|
||||||
}
|
|
||||||
if err := a.files.AtomicWrite(a.configuration.DaemonConfigPath, desired, mode); err != nil {
|
|
||||||
return fmt.Errorf("write Docker daemon configuration after recovery metadata persisted: %w", err)
|
return fmt.Errorf("write Docker daemon configuration after recovery metadata persisted: %w", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -546,6 +546,9 @@ func TestDockerDaemonPreservesAndRestoresExistingConfiguration(t *testing.T) {
|
|||||||
if got := a.SetDesired(context.Background(), true, activeProfile()); got.Err != nil {
|
if got := a.SetDesired(context.Background(), true, activeProfile()); got.Err != nil {
|
||||||
t.Fatal(got.Err)
|
t.Fatal(got.Err)
|
||||||
}
|
}
|
||||||
|
if info, err := os.Stat(daemonPath); err != nil || info.Mode().Perm() != 0o600 {
|
||||||
|
t.Fatalf("managed mode = %v, %v; want owner-only", info, err)
|
||||||
|
}
|
||||||
if got := a.SetDesired(context.Background(), false, nil); got.Err != nil || got.Inspection.State != target.External {
|
if got := a.SetDesired(context.Background(), false, nil); got.Err != nil || got.Inspection.State != target.External {
|
||||||
t.Fatalf("disable = %#v", got)
|
t.Fatalf("disable = %#v", got)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
// Package execsafe resolves privileged system commands without consulting the
|
||||||
|
// caller-controlled PATH.
|
||||||
|
package execsafe
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
var systemDirectories = []string{"/usr/sbin", "/usr/bin", "/sbin", "/bin"}
|
||||||
|
|
||||||
|
// LookPath resolves a bare command name only from standard system directories.
|
||||||
|
func LookPath(name string) (string, error) {
|
||||||
|
if name == "" || filepath.Base(name) != name || strings.ContainsRune(name, filepath.Separator) {
|
||||||
|
return "", fmt.Errorf("unsafe system command name %q", name)
|
||||||
|
}
|
||||||
|
for _, directory := range systemDirectories {
|
||||||
|
candidate := filepath.Join(directory, name)
|
||||||
|
info, err := os.Stat(candidate)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("inspect trusted system command %s: %w", candidate, err)
|
||||||
|
}
|
||||||
|
if info.Mode().IsRegular() && info.Mode().Perm()&0o111 != 0 {
|
||||||
|
return candidate, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("%w: trusted system command %s", exec.ErrNotFound, name)
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package execsafe_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"proxyctl/internal/execsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLookPathUsesOnlyTrustedSystemDirectories(t *testing.T) {
|
||||||
|
path, err := execsafe.LookPath("sh")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !filepath.IsAbs(path) || filepath.Base(path) != "sh" {
|
||||||
|
t.Fatalf("resolved path = %q", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLookPathRejectsPathsAndMissingCommands(t *testing.T) {
|
||||||
|
for _, name := range []string{"../systemctl", "/tmp/systemctl", "dir/systemctl", ""} {
|
||||||
|
if _, err := execsafe.LookPath(name); err == nil {
|
||||||
|
t.Fatalf("unsafe name %q was accepted", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := execsafe.LookPath("proxyctl-command-that-does-not-exist"); !errors.Is(err, exec.ErrNotFound) {
|
||||||
|
t.Fatalf("missing command error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-18
@@ -20,6 +20,7 @@ import (
|
|||||||
"syscall"
|
"syscall"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"proxyctl/internal/pathutil"
|
||||||
"proxyctl/internal/profile"
|
"proxyctl/internal/profile"
|
||||||
"proxyctl/internal/securefs"
|
"proxyctl/internal/securefs"
|
||||||
"proxyctl/internal/target"
|
"proxyctl/internal/target"
|
||||||
@@ -194,24 +195,7 @@ func ResolveConfiguration(environment profile.IdentityEnvironment) (Configuratio
|
|||||||
return Configuration{CommandName: "gsettings", UID: owner.UID, GID: owner.GID, Username: owner.Username, HomeDir: owner.HomeDir, ConfigDir: configDir, DataDir: dataDir, CacheDir: cacheDir, RuntimeDir: runtimeDir, SessionBus: sessionBus, StateFile: filepath.Join(stateDir, "proxyctl", "gnome.json"), TrustedRoot: trustedRoot}, nil
|
return Configuration{CommandName: "gsettings", UID: owner.UID, GID: owner.GID, Username: owner.Username, HomeDir: owner.HomeDir, ConfigDir: configDir, DataDir: dataDir, CacheDir: cacheDir, RuntimeDir: runtimeDir, SessionBus: sessionBus, StateFile: filepath.Join(stateDir, "proxyctl", "gnome.json"), TrustedRoot: trustedRoot}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ResolveConfigurationForCurrentProcess() (Configuration, error) {
|
func pathWithin(path, parent string) bool { return pathutil.Within(path, parent) }
|
||||||
return ResolveConfiguration(systemEnvironment{})
|
|
||||||
}
|
|
||||||
|
|
||||||
type systemEnvironment struct{}
|
|
||||||
|
|
||||||
func (systemEnvironment) CurrentUser() (profile.UserIdentity, error) {
|
|
||||||
return profile.SystemCurrentUser()
|
|
||||||
}
|
|
||||||
func (systemEnvironment) LookupUser(name string) (profile.UserIdentity, error) {
|
|
||||||
return profile.SystemLookupUser(name)
|
|
||||||
}
|
|
||||||
func (systemEnvironment) LookupEnv(name string) (string, bool) { return os.LookupEnv(name) }
|
|
||||||
|
|
||||||
func pathWithin(path, parent string) bool {
|
|
||||||
relative, err := filepath.Rel(parent, path)
|
|
||||||
return err == nil && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))
|
|
||||||
}
|
|
||||||
|
|
||||||
type settings struct {
|
type settings struct {
|
||||||
Mode string `json:"mode"`
|
Mode string `json:"mode"`
|
||||||
|
|||||||
@@ -13,6 +13,10 @@ import (
|
|||||||
"proxyctl/internal/securefs"
|
"proxyctl/internal/securefs"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type Locker interface {
|
||||||
|
Lock(context.Context) (func(), error)
|
||||||
|
}
|
||||||
|
|
||||||
type Lock struct {
|
type Lock struct {
|
||||||
path string
|
path string
|
||||||
uid int
|
uid int
|
||||||
@@ -20,6 +24,29 @@ type Lock struct {
|
|||||||
owned bool
|
owned bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Group struct{ locks []Locker }
|
||||||
|
|
||||||
|
func NewGroup(locks ...Locker) *Group { return &Group{locks: append([]Locker(nil), locks...)} }
|
||||||
|
|
||||||
|
func (g *Group) Lock(ctx context.Context) (func(), error) {
|
||||||
|
var unlocks []func()
|
||||||
|
for _, lock := range g.locks {
|
||||||
|
unlock, err := lock.Lock(ctx)
|
||||||
|
if err != nil {
|
||||||
|
for i := len(unlocks) - 1; i >= 0; i-- {
|
||||||
|
unlocks[i]()
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
unlocks = append(unlocks, unlock)
|
||||||
|
}
|
||||||
|
return func() {
|
||||||
|
for i := len(unlocks) - 1; i >= 0; i-- {
|
||||||
|
unlocks[i]()
|
||||||
|
}
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
func New(path string) *Lock { return &Lock{path: path} }
|
func New(path string) *Lock { return &Lock{path: path} }
|
||||||
func NewOwned(path string, uid, gid int) *Lock {
|
func NewOwned(path string, uid, gid int) *Lock {
|
||||||
return &Lock{path: path, uid: uid, gid: gid, owned: true}
|
return &Lock{path: path, uid: uid, gid: gid, owned: true}
|
||||||
|
|||||||
@@ -10,6 +10,42 @@ import (
|
|||||||
"proxyctl/internal/operationlock"
|
"proxyctl/internal/operationlock"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type recordingLocker struct {
|
||||||
|
name string
|
||||||
|
events *[]string
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l recordingLocker) Lock(context.Context) (func(), error) {
|
||||||
|
*l.events = append(*l.events, "lock "+l.name)
|
||||||
|
if l.err != nil {
|
||||||
|
return nil, l.err
|
||||||
|
}
|
||||||
|
return func() { *l.events = append(*l.events, "unlock "+l.name) }, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGroupAcquiresInOrderAndReleasesInReverse(t *testing.T) {
|
||||||
|
var events []string
|
||||||
|
group := operationlock.NewGroup(
|
||||||
|
recordingLocker{name: "system", events: &events},
|
||||||
|
recordingLocker{name: "user", events: &events},
|
||||||
|
)
|
||||||
|
unlock, err := group.Lock(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
unlock()
|
||||||
|
want := []string{"lock system", "lock user", "unlock user", "unlock system"}
|
||||||
|
if len(events) != len(want) {
|
||||||
|
t.Fatalf("events = %v, want %v", events, want)
|
||||||
|
}
|
||||||
|
for i := range want {
|
||||||
|
if events[i] != want[i] {
|
||||||
|
t.Fatalf("events = %v, want %v", events, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestLockRejectsSymlinkedStateAncestor(t *testing.T) {
|
func TestLockRejectsSymlinkedStateAncestor(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
victim := filepath.Join(root, "victim")
|
victim := filepath.Join(root, "victim")
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
// Package pathutil contains lexical path-policy helpers. It does not replace
|
||||||
|
// descriptor-anchored filesystem access for security-sensitive operations.
|
||||||
|
package pathutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Within reports whether path is parent itself or a lexical descendant.
|
||||||
|
func Within(path, parent string) bool {
|
||||||
|
relative, err := filepath.Rel(parent, path)
|
||||||
|
return err == nil && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package pathutil_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"proxyctl/internal/pathutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWithinUsesComponentBoundaries(t *testing.T) {
|
||||||
|
parent := filepath.Join(string(filepath.Separator), "home", "alice")
|
||||||
|
for _, test := range []struct {
|
||||||
|
name string
|
||||||
|
path string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{name: "same", path: parent, want: true},
|
||||||
|
{name: "child", path: filepath.Join(parent, ".config", "proxyctl"), want: true},
|
||||||
|
{name: "cleaned child", path: filepath.Join(parent, "tmp", "..", ".config"), want: true},
|
||||||
|
{name: "parent", path: filepath.Dir(parent), want: false},
|
||||||
|
{name: "sibling prefix", path: parent + "-backup", want: false},
|
||||||
|
} {
|
||||||
|
t.Run(test.name, func(t *testing.T) {
|
||||||
|
if got := pathutil.Within(test.path, parent); got != test.want {
|
||||||
|
t.Fatalf("Within(%q, %q) = %v, want %v", test.path, parent, got, test.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
|
|
||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
|
|
||||||
|
"proxyctl/internal/pathutil"
|
||||||
"proxyctl/internal/securefs"
|
"proxyctl/internal/securefs"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -184,10 +185,7 @@ func ConfigPathWith(environment IdentityEnvironment) (string, error) {
|
|||||||
return configuration.Path, err
|
return configuration.Path, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func pathWithin(path, parent string) bool {
|
func pathWithin(path, parent string) bool { return pathutil.Within(path, parent) }
|
||||||
relative, err := filepath.Rel(parent, path)
|
|
||||||
return err == nil && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))
|
|
||||||
}
|
|
||||||
|
|
||||||
type CommitError struct {
|
type CommitError struct {
|
||||||
Err error
|
Err error
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
|
|
||||||
|
"proxyctl/internal/pathutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Owner struct{ UID, GID int }
|
type Owner struct{ UID, GID int }
|
||||||
@@ -341,7 +343,4 @@ func regular(file *os.File) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func within(path, root string) bool {
|
func within(path, root string) bool { return pathutil.Within(path, root) }
|
||||||
relative, err := filepath.Rel(root, path)
|
|
||||||
return err == nil && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package securefs_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"proxyctl/internal/securefs"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAtomicWriteCreatesAndReplacesRegularFile(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
path := filepath.Join(root, "state", "config.json")
|
||||||
|
store := securefs.Store{TrustedRoot: root}
|
||||||
|
if err := store.AtomicWrite(path, []byte("first\n"), 0o640); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := store.AtomicWrite(path, []byte("second\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if string(data) != "second\n" || info.Mode().Perm() != 0o600 {
|
||||||
|
t.Fatalf("content=%q mode=%o", data, info.Mode().Perm())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAtomicWriteRejectsSymlinkWithoutChangingVictim(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
victim := filepath.Join(root, "victim")
|
||||||
|
if err := os.WriteFile(victim, []byte("unchanged"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
path := filepath.Join(root, "managed")
|
||||||
|
if err := os.Symlink(victim, path); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
store := securefs.Store{TrustedRoot: root}
|
||||||
|
if err := store.AtomicWrite(path, []byte("replaced"), 0o600); err == nil {
|
||||||
|
t.Fatal("AtomicWrite followed a final symlink")
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(victim)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if string(data) != "unchanged" {
|
||||||
|
t.Fatalf("victim changed: %q", data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStoreRejectsPathsOutsideTrustedRoot(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
outside := filepath.Join(t.TempDir(), "outside")
|
||||||
|
store := securefs.Store{TrustedRoot: root}
|
||||||
|
if err := store.AtomicWrite(outside, []byte("data"), 0o600); err == nil {
|
||||||
|
t.Fatal("AtomicWrite escaped TrustedRoot")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(outside); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Fatalf("outside path changed: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
+13
-18
@@ -14,6 +14,7 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"proxyctl/internal/pathutil"
|
||||||
"proxyctl/internal/profile"
|
"proxyctl/internal/profile"
|
||||||
"proxyctl/internal/securefs"
|
"proxyctl/internal/securefs"
|
||||||
"proxyctl/internal/target"
|
"proxyctl/internal/target"
|
||||||
@@ -84,24 +85,7 @@ func ResolveConfiguration(environment profile.IdentityEnvironment) (Configuratio
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ResolveConfigurationForCurrentProcess() (Configuration, error) {
|
func pathWithin(path, parent string) bool { return pathutil.Within(path, parent) }
|
||||||
return ResolveConfiguration(systemEnvironment{})
|
|
||||||
}
|
|
||||||
|
|
||||||
type systemEnvironment struct{}
|
|
||||||
|
|
||||||
func (systemEnvironment) CurrentUser() (profile.UserIdentity, error) {
|
|
||||||
return profile.SystemCurrentUser()
|
|
||||||
}
|
|
||||||
func (systemEnvironment) LookupUser(name string) (profile.UserIdentity, error) {
|
|
||||||
return profile.SystemLookupUser(name)
|
|
||||||
}
|
|
||||||
func (systemEnvironment) LookupEnv(name string) (string, bool) { return os.LookupEnv(name) }
|
|
||||||
|
|
||||||
func pathWithin(path, parent string) bool {
|
|
||||||
relative, err := filepath.Rel(parent, path)
|
|
||||||
return err == nil && relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))
|
|
||||||
}
|
|
||||||
|
|
||||||
type Environment interface{ LookupEnv(string) (string, bool) }
|
type Environment interface{ LookupEnv(string) (string, bool) }
|
||||||
type MapEnvironment map[string]string
|
type MapEnvironment map[string]string
|
||||||
@@ -323,9 +307,20 @@ func (a *Adapter) disable() error {
|
|||||||
if metadata.OriginalScript != nil {
|
if metadata.OriginalScript != nil {
|
||||||
restored = []byte(*metadata.OriginalScript)
|
restored = []byte(*metadata.OriginalScript)
|
||||||
}
|
}
|
||||||
|
current, err := a.files.ReadFile(a.configuration.EnvironmentFile)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("read managed Shell environment before restore: %w", err)
|
||||||
|
}
|
||||||
|
switch currentFingerprint := fingerprint(current); currentFingerprint {
|
||||||
|
case fingerprint(restored):
|
||||||
|
// A previous recovery completed the file write but not metadata cleanup.
|
||||||
|
case metadata.Fingerprint:
|
||||||
if err := a.writeOwned(a.configuration.EnvironmentFile, restored); err != nil {
|
if err := a.writeOwned(a.configuration.EnvironmentFile, restored); err != nil {
|
||||||
return fmt.Errorf("restore Shell environment: %w", err)
|
return fmt.Errorf("restore Shell environment: %w", err)
|
||||||
}
|
}
|
||||||
|
default:
|
||||||
|
return errors.New("Shell environment changed after proxyctl applied it; refusing to overwrite current configuration or discard recovery metadata")
|
||||||
|
}
|
||||||
if err := a.files.Remove(a.configuration.RecoveryFile); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
if err := a.files.Remove(a.configuration.RecoveryFile); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||||
return fmt.Errorf("remove Shell recovery metadata after environment changed: %w", err)
|
return fmt.Errorf("remove Shell recovery metadata after environment changed: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -296,6 +296,27 @@ func TestShellTargetContract(t *testing.T) {
|
|||||||
assertState(t, a, activeProfile(), target.Drifted)
|
assertState(t, a, activeProfile(), target.Drifted)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.Run("drifted-environment-refuses-destructive-restore", func(t *testing.T) {
|
||||||
|
a := newAdapter(t, shellName, nil)
|
||||||
|
if result := a.SetDesired(context.Background(), true, activeProfile()); result.Err != nil {
|
||||||
|
t.Fatal(result.Err)
|
||||||
|
}
|
||||||
|
changed := "export HTTP_PROXY='http://user-change.example:8080'\n"
|
||||||
|
if err := os.WriteFile(a.EnvironmentPath(), []byte(changed), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result := a.SetDesired(context.Background(), false, nil)
|
||||||
|
if result.Err == nil || result.Inspection.State != target.Drifted {
|
||||||
|
t.Fatalf("unsafe restore = %#v", result)
|
||||||
|
}
|
||||||
|
if got := readFile(t, a.EnvironmentPath()); got != changed {
|
||||||
|
t.Fatalf("drifted environment overwritten:\n%s", got)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(a.RecoveryPath()); err != nil {
|
||||||
|
t.Fatalf("recovery metadata removed after refused restore: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
t.Run("validation-and-redaction", func(t *testing.T) {
|
t.Run("validation-and-redaction", func(t *testing.T) {
|
||||||
fs := &failingFS{FileSystem: shell.OSFileSystem{}, failWrite: true}
|
fs := &failingFS{FileSystem: shell.OSFileSystem{}, failWrite: true}
|
||||||
a := newAdapterWithFS(t, shellName, nil, fs)
|
a := newAdapterWithFS(t, shellName, nil, fs)
|
||||||
|
|||||||
@@ -69,6 +69,14 @@ func readOnlyWritablePath(path string) (bool, string) {
|
|||||||
}
|
}
|
||||||
if index == len(components)-1 {
|
if index == len(components)-1 {
|
||||||
_ = unix.Close(child)
|
_ = unix.Close(child)
|
||||||
|
if kind != unix.S_IFREG {
|
||||||
|
return false, componentPath + " is not a regular file"
|
||||||
|
}
|
||||||
|
readable, readErr := unix.Openat(current, component, unix.O_RDONLY|unix.O_NONBLOCK|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
|
||||||
|
if readErr != nil {
|
||||||
|
return false, componentPath + " cannot be read for safe atomic replacement: " + readErr.Error()
|
||||||
|
}
|
||||||
|
_ = unix.Close(readable)
|
||||||
return writableDirectory(current, currentPath, absolute)
|
return writableDirectory(current, currentPath, absolute)
|
||||||
}
|
}
|
||||||
if kind != unix.S_IFDIR {
|
if kind != unix.S_IFDIR {
|
||||||
|
|||||||
@@ -10,6 +10,20 @@ import (
|
|||||||
"proxyctl/internal/target"
|
"proxyctl/internal/target"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestReadOnlyWriteAuthorityRejectsUnreadableExistingFile(t *testing.T) {
|
||||||
|
if os.Geteuid() == 0 {
|
||||||
|
t.Skip("root can read files regardless of mode bits")
|
||||||
|
}
|
||||||
|
path := filepath.Join(t.TempDir(), "managed.json")
|
||||||
|
if err := os.WriteFile(path, []byte("{}\n"), 0o200); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
check := target.ReadOnlyWriteAuthority(path)
|
||||||
|
if check.OK || !strings.Contains(check.Evidence, "cannot be read") {
|
||||||
|
t.Fatalf("unreadable destination reported writable: %#v", check)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestReadOnlyWriteAuthorityRejectsSymlinkedFinalAndAncestorWithoutTouchingVictim(t *testing.T) {
|
func TestReadOnlyWriteAuthorityRejectsSymlinkedFinalAndAncestorWithoutTouchingVictim(t *testing.T) {
|
||||||
for _, test := range []struct {
|
for _, test := range []struct {
|
||||||
name string
|
name string
|
||||||
|
|||||||
@@ -78,6 +78,12 @@ type Diagnosable interface {
|
|||||||
DiagnosticChecks(context.Context, *profile.Profile) []Check
|
DiagnosticChecks(context.Context, *profile.Profile) []Check
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MutationAuthorizer optionally explains why a detected Target cannot be
|
||||||
|
// changed by the current process. It is read-only and presentation-independent.
|
||||||
|
type MutationAuthorizer interface {
|
||||||
|
MutationAuthority(context.Context) Check
|
||||||
|
}
|
||||||
|
|
||||||
// Target hides platform paths and commands from the application and TUI.
|
// Target hides platform paths and commands from the application and TUI.
|
||||||
type Target interface {
|
type Target interface {
|
||||||
ID() string
|
ID() string
|
||||||
|
|||||||
@@ -180,7 +180,7 @@ func TestCompleteModelPickerConfirmedActivationContinuesThroughUnifiedOperation(
|
|||||||
completion <- app.SucceededOperationUpdate(completed, app.OperationStatus{Summary: `Activated Profile "new"`}, nil)
|
completion <- app.SucceededOperationUpdate(completed, app.OperationStatus{Summary: `Activated Profile "new"`}, nil)
|
||||||
close(completion)
|
close(completion)
|
||||||
model, _ = applyOperationCommand(t, model, command)
|
model, _ = applyOperationCommand(t, model, command)
|
||||||
if view := model.View(); !strings.Contains(view, "Active Profile: new") || !strings.Contains(view, `Activated Profile "new"`) {
|
if view := model.View(); !strings.Contains(view, "Profile: new") || !strings.Contains(view, `Activated Profile "new"`) {
|
||||||
t.Fatalf("confirmed activation did not finish on the dashboard:\n%s", view)
|
t.Fatalf("confirmed activation did not finish on the dashboard:\n%s", view)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -213,7 +213,7 @@ func TestCompleteModelPickerPartialFailureKeepsProgressClosesPickerAndFocusesFai
|
|||||||
close(updates)
|
close(updates)
|
||||||
model, _ = applyOperationCommand(t, model, command)
|
model, _ = applyOperationCommand(t, model, command)
|
||||||
view := model.View()
|
view := model.View()
|
||||||
if model.selectedTargetID != "docker" || !strings.Contains(view, "> ! Drifted ! Failed Docker daemon") || !strings.Contains(view, "Current error: Activated Profile new with 1 Target update failure") || !strings.Contains(view, "Active Profile: new") {
|
if model.selectedTargetID != "docker" || !strings.Contains(view, "> ! Drifted ! Failed Docker daemon") || !strings.Contains(view, "Current error: Activated Profile new with 1 Target update failure") || !strings.Contains(view, "Profile: new") {
|
||||||
t.Fatalf("partial failure was not retained and focused: selected=%q\n%s", model.selectedTargetID, view)
|
t.Fatalf("partial failure was not retained and focused: selected=%q\n%s", model.selectedTargetID, view)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,12 +35,9 @@ func TestCompleteModelRendersAndDispatchesContextualPrimaryActions(t *testing.T)
|
|||||||
module := &targetModule{snapshot: initial, result: app.Result{Snapshot: initial, Notice: "done"}}
|
module := &targetModule{snapshot: initial, result: app.Result{Snapshot: initial, Notice: "done"}}
|
||||||
model := resizedModel(t, module, themeModeNoColor, 120, 36)
|
model := resizedModel(t, module, themeModeNoColor, 120, 36)
|
||||||
view := model.View()
|
view := model.View()
|
||||||
if !strings.Contains(view, "Action: "+test.label) || !strings.Contains(view, "Space: "+test.label) {
|
if !strings.Contains(view, "Space: "+test.label) {
|
||||||
t.Fatalf("contextual action not rendered:\n%s", view)
|
t.Fatalf("contextual action not rendered:\n%s", view)
|
||||||
}
|
}
|
||||||
if test.state == target.External && (!strings.Contains(view, "proxyctl will begin managing this configuration") || !strings.Contains(view, "while preserving restorable state")) {
|
|
||||||
t.Fatalf("Apply Profile ownership explanation missing:\n%s", view)
|
|
||||||
}
|
|
||||||
|
|
||||||
updated, command := model.Update(tea.KeyMsg{Type: tea.KeySpace})
|
updated, command := model.Update(tea.KeyMsg{Type: tea.KeySpace})
|
||||||
model = updated.(Model)
|
model = updated.(Model)
|
||||||
@@ -91,7 +88,7 @@ func TestCompleteModelRendersUnknownTargetStateAsStructurallyUnavailable(t *test
|
|||||||
model := resizedModel(t, module, themeModeNoColor, 120, 36)
|
model := resizedModel(t, module, themeModeNoColor, 120, 36)
|
||||||
|
|
||||||
view := model.View()
|
view := model.View()
|
||||||
if !strings.Contains(view, "Action: Unavailable") || !strings.Contains(view, "Action unavailable:") || !strings.Contains(view, "state is unknown") || !strings.Contains(view, "Space: Unavailable disabled") {
|
if !strings.Contains(view, "Unavailable:") || !strings.Contains(view, "Target actions are unavailable") || !strings.Contains(view, "unknown") || !strings.Contains(view, "Space: Unavailable unavailable") {
|
||||||
t.Fatalf("unknown Target action was not structurally unavailable:\n%s", view)
|
t.Fatalf("unknown Target action was not structurally unavailable:\n%s", view)
|
||||||
}
|
}
|
||||||
updated, command := model.Update(tea.KeyMsg{Type: tea.KeySpace})
|
updated, command := model.Update(tea.KeyMsg{Type: tea.KeySpace})
|
||||||
@@ -108,7 +105,7 @@ func TestCompleteModelUsesStructuredDisabledReasonWithoutInferringFromState(t *t
|
|||||||
module := &targetModule{snapshot: initial}
|
module := &targetModule{snapshot: initial}
|
||||||
model := resizedModel(t, module, themeModeNoColor, 120, 36)
|
model := resizedModel(t, module, themeModeNoColor, 120, 36)
|
||||||
view := model.View()
|
view := model.View()
|
||||||
if !strings.Contains(view, "No Active Profile is selected") || !strings.Contains(view, "Space: Enable disabled") {
|
if !strings.Contains(view, "No Active Profile is selected") || !strings.Contains(view, "Space: Enable unavailable") {
|
||||||
t.Fatalf("structured disabled reason missing:\n%s", view)
|
t.Fatalf("structured disabled reason missing:\n%s", view)
|
||||||
}
|
}
|
||||||
updated, command := model.Update(tea.KeyMsg{Type: tea.KeySpace})
|
updated, command := model.Update(tea.KeyMsg{Type: tea.KeySpace})
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
package tui
|
package tui
|
||||||
|
|
||||||
import (
|
import "proxyctl/internal/app"
|
||||||
"proxyctl/internal/app"
|
|
||||||
"proxyctl/internal/target"
|
|
||||||
)
|
|
||||||
|
|
||||||
func targetActionLabel(kind app.TargetActionKind) string {
|
func targetActionLabel(kind app.TargetActionKind) string {
|
||||||
switch kind {
|
switch kind {
|
||||||
@@ -101,40 +98,3 @@ func (c targetCatalog) retain(id string, formerIndex int) string {
|
|||||||
}
|
}
|
||||||
return c.items[max(0, min(len(c.items)-1, formerIndex))].ID
|
return c.items[max(0, min(len(c.items)-1, formerIndex))].ID
|
||||||
}
|
}
|
||||||
|
|
||||||
type targetStateCounts struct {
|
|
||||||
enabled int
|
|
||||||
disabled int
|
|
||||||
external int
|
|
||||||
drifted int
|
|
||||||
checking int
|
|
||||||
failed int
|
|
||||||
}
|
|
||||||
|
|
||||||
func countAvailableTargetStates(snapshot app.Snapshot) targetStateCounts {
|
|
||||||
var counts targetStateCounts
|
|
||||||
for _, item := range snapshot.Targets {
|
|
||||||
switch item.DetectionPhase {
|
|
||||||
case app.TargetChecking:
|
|
||||||
counts.checking++
|
|
||||||
continue
|
|
||||||
case app.TargetDetectionFailed:
|
|
||||||
counts.failed++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if !item.Available {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
switch item.State {
|
|
||||||
case target.Enabled:
|
|
||||||
counts.enabled++
|
|
||||||
case target.Disabled:
|
|
||||||
counts.disabled++
|
|
||||||
case target.External:
|
|
||||||
counts.external++
|
|
||||||
case target.Drifted:
|
|
||||||
counts.drifted++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return counts
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -23,9 +23,8 @@ func TestCompleteModelWideOperationsConsoleShowsStableAvailableTargetDashboard(t
|
|||||||
|
|
||||||
view := resizedModel(t, module, themeModeNoColor, 120, 36).View()
|
view := resizedModel(t, module, themeModeNoColor, 120, 36).View()
|
||||||
assertUsableFrame(t, view, 120, 36,
|
assertUsableFrame(t, view, 120, 36,
|
||||||
"proxyctl", "Active Profile: office",
|
"proxyctl", "Profile: office",
|
||||||
"● Enabled 1", "○ Disabled 1", "◇ External 1", "! Drifted 1",
|
"> ● Enabled", "Shell", "matches Active Profile",
|
||||||
"> ● Enabled", "Shell", "State: ● Enabled", "Evidence: matches Active Profile",
|
|
||||||
)
|
)
|
||||||
if strings.Contains(view, "APT") || strings.Contains(view, "apt-config was not detected") {
|
if strings.Contains(view, "APT") || strings.Contains(view, "apt-config was not detected") {
|
||||||
t.Fatalf("default dashboard included an unavailable Target:\n%s", view)
|
t.Fatalf("default dashboard included an unavailable Target:\n%s", view)
|
||||||
@@ -71,12 +70,8 @@ func TestCompleteModelDashboardRevealsUnavailableEvidenceAndStructuredDetails(t
|
|||||||
|
|
||||||
view := model.View()
|
view := model.View()
|
||||||
assertUsableFrame(t, view, 120, 36,
|
assertUsableFrame(t, view, 120, 36,
|
||||||
"> ○ Unavailable APT", "State: ○ Unavailable", "Evidence: apt-config was not detected",
|
"> ○ Unavailable APT", "○ Unavailable", "apt-config was not detected",
|
||||||
"Affects: package operations across privilege boundaries",
|
"Persistent package proxy.", "u: Hide unavailable",
|
||||||
"Permissions: pre-existing root write authority",
|
|
||||||
"Ownership & restoration: isolated overlay; disabling reveals the", "previous configuration",
|
|
||||||
"Restart risk: none", "Persistent package proxy.", "Longer APT explanation.",
|
|
||||||
"u: hide unavailable",
|
|
||||||
)
|
)
|
||||||
if !(strings.Index(view, "Shell") < strings.Index(view, "APT") && strings.Index(view, "APT") < strings.Index(view, "Docker daemon")) {
|
if !(strings.Index(view, "Shell") < strings.Index(view, "APT") && strings.Index(view, "APT") < strings.Index(view, "Docker daemon")) {
|
||||||
t.Fatalf("revealing unavailable Targets changed product order:\n%s", view)
|
t.Fatalf("revealing unavailable Targets changed product order:\n%s", view)
|
||||||
@@ -95,7 +90,7 @@ func TestCompleteModelNarrowDashboardFocusAndIndependentScrollingRetainTargetIde
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
targets[22].Description.Summary = "Selected identity summary"
|
targets[22].Description.Summary = "Selected identity summary"
|
||||||
targets[22].Description.Details = strings.Repeat("Scrollable detail line. ", 45) + "END OF TARGET DETAILS"
|
targets[22].Evidence = strings.Repeat("Scrollable evidence line. ", 45) + "END OF TARGET EVIDENCE"
|
||||||
module := &recordingModule{snapshot: app.Snapshot{ActiveProfile: "office", Targets: targets}}
|
module := &recordingModule{snapshot: app.Snapshot{ActiveProfile: "office", Targets: targets}}
|
||||||
model := resizedModel(t, module, themeModeNoColor, 80, 24)
|
model := resizedModel(t, module, themeModeNoColor, 80, 24)
|
||||||
for range 22 {
|
for range 22 {
|
||||||
@@ -103,7 +98,7 @@ func TestCompleteModelNarrowDashboardFocusAndIndependentScrollingRetainTargetIde
|
|||||||
}
|
}
|
||||||
|
|
||||||
view := model.View()
|
view := model.View()
|
||||||
assertUsableFrame(t, view, 80, 24, "> ○ Disabled Product Target 22", "Selected identity summary", "▶ Targets [focused]")
|
assertUsableFrame(t, view, 80, 24, "> ○ Disabled Product Target 22", "▶ Targets [focused]")
|
||||||
|
|
||||||
model = updateKey(model, "tab")
|
model = updateKey(model, "tab")
|
||||||
for range 70 {
|
for range 70 {
|
||||||
@@ -111,16 +106,16 @@ func TestCompleteModelNarrowDashboardFocusAndIndependentScrollingRetainTargetIde
|
|||||||
}
|
}
|
||||||
view = model.View()
|
view = model.View()
|
||||||
assertUsableFrame(t, view, 80, 24,
|
assertUsableFrame(t, view, 80, 24,
|
||||||
"> ○ Disabled Product Target 22", "▶ Target details [focused]", "END OF", "TARGET DETAILS",
|
"> ○ Disabled Product Target 22", "▶ Target details [focused]", "END OF", "TARGET EVIDENCE",
|
||||||
"↑/k ↓/j PgUp/PgDn: scroll", "Tab: focus Targets",
|
"↑/↓: Scroll", "Tab: Targets",
|
||||||
)
|
)
|
||||||
|
|
||||||
model = resize(model, 120, 36)
|
model = resize(model, 120, 36)
|
||||||
view = model.View()
|
view = model.View()
|
||||||
assertUsableFrame(t, view, 120, 36, "> ○ Disabled Product Target 22", "END OF TARGET DETAILS", "▶ Target details [focused]")
|
assertUsableFrame(t, view, 120, 36, "> ○ Disabled Product Target 22", "END OF TARGET", "EVIDENCE", "▶ Target details [focused]")
|
||||||
if !sameLine(view, "Targets", "Target details") {
|
if !sameLine(view, "Targets", "Target details") {
|
||||||
t.Fatalf("resized dashboard did not become side by side:\n%s", view)
|
t.Fatalf("resized dashboard did not become side by side:\n%s", view)
|
||||||
}
|
}
|
||||||
model = resize(model, 80, 24)
|
model = resize(model, 80, 24)
|
||||||
assertUsableFrame(t, model.View(), 80, 24, "> ○ Disabled Product Target 22", "END OF", "TARGET DETAILS", "▶ Target details [focused]")
|
assertUsableFrame(t, model.View(), 80, 24, "> ○ Disabled Product Target 22", "END OF", "TARGET EVIDENCE", "▶ Target details [focused]")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import (
|
|||||||
"github.com/charmbracelet/lipgloss"
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
|
||||||
"proxyctl/internal/app"
|
"proxyctl/internal/app"
|
||||||
"proxyctl/internal/target"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type dashboardRenderState struct {
|
type dashboardRenderState struct {
|
||||||
@@ -149,55 +148,18 @@ func (p terminalPresentation) targetDetails(item app.TargetSnapshot, progress ap
|
|||||||
|
|
||||||
var details strings.Builder
|
var details strings.Builder
|
||||||
details.WriteString(p.theme.section.Render(item.Description.Name))
|
details.WriteString(p.theme.section.Render(item.Description.Name))
|
||||||
fmt.Fprintf(&details, "\nState: %s\nEvidence: %s", state, evidence)
|
fmt.Fprintf(&details, "\n%s\n%s", state, evidence)
|
||||||
fmt.Fprintf(&details, "\nAction: %s", targetActionLabel(item.PrimaryAction.Kind))
|
action := targetActionLabel(item.PrimaryAction.Kind)
|
||||||
if !item.PrimaryAction.Available && item.PrimaryAction.DisabledReason != "" {
|
if item.PrimaryAction.Available {
|
||||||
fmt.Fprintf(&details, "\nAction unavailable: %s", item.PrimaryAction.DisabledReason)
|
fmt.Fprintf(&details, "\n\nSpace: %s", action)
|
||||||
}
|
} else if item.PrimaryAction.DisabledReason != "" {
|
||||||
switch item.PrimaryAction.Kind {
|
fmt.Fprintf(&details, "\n\nUnavailable: %s", item.PrimaryAction.DisabledReason)
|
||||||
case app.ApplyProfileTargetAction:
|
|
||||||
details.WriteString("\nApply Profile means proxyctl will begin managing this configuration while preserving restorable state.")
|
|
||||||
case app.ResolveDriftTargetAction:
|
|
||||||
details.WriteString("\nResolve opens Drift Resolution without choosing a recovery direction for you.")
|
|
||||||
}
|
}
|
||||||
if item.DetectionPhase == app.TargetDetectionFailed && item.DetectionErr != nil {
|
if item.DetectionPhase == app.TargetDetectionFailed && item.DetectionErr != nil {
|
||||||
fmt.Fprintf(&details, "\nCheck error: %s", item.DetectionErr)
|
fmt.Fprintf(&details, "\nCheck failed: %s", item.DetectionErr)
|
||||||
}
|
|
||||||
facts := []struct {
|
|
||||||
label string
|
|
||||||
value string
|
|
||||||
}{
|
|
||||||
{"Affects", item.Description.Scope},
|
|
||||||
{"Permissions", item.Description.Permissions},
|
|
||||||
{"Ownership & restoration", item.Description.Ownership},
|
|
||||||
{"Restart risk", item.Description.RestartRisk},
|
|
||||||
}
|
|
||||||
for _, fact := range facts {
|
|
||||||
if fact.value != "" {
|
|
||||||
fmt.Fprintf(&details, "\n%s: %s", fact.label, fact.value)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if item.Description.Summary != "" {
|
if item.Description.Summary != "" {
|
||||||
fmt.Fprintf(&details, "\n\n%s", item.Description.Summary)
|
fmt.Fprintf(&details, "\n\n%s", item.Description.Summary)
|
||||||
}
|
}
|
||||||
if item.Description.Details != "" {
|
|
||||||
fmt.Fprintf(&details, "\n\n%s", item.Description.Details)
|
|
||||||
}
|
|
||||||
return protectRenderedText(details.String())
|
return protectRenderedText(details.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p terminalPresentation) stateCountSummary(snapshot app.Snapshot) string {
|
|
||||||
counts := countAvailableTargetStates(snapshot)
|
|
||||||
summary := fmt.Sprintf("%s %d %s %d %s %d %s %d",
|
|
||||||
p.theme.renderTargetState(target.Enabled, false), counts.enabled,
|
|
||||||
p.theme.renderTargetState(target.Disabled, false), counts.disabled,
|
|
||||||
p.theme.renderTargetState(target.External, false), counts.external,
|
|
||||||
p.theme.renderTargetState(target.Drifted, false), counts.drifted)
|
|
||||||
if counts.checking > 0 {
|
|
||||||
summary += fmt.Sprintf(" %s %d", p.theme.checking.Render("… Checking"), counts.checking)
|
|
||||||
}
|
|
||||||
if counts.failed > 0 {
|
|
||||||
summary += fmt.Sprintf(" %s %d", p.theme.checkFailed.Render("! Check failed"), counts.failed)
|
|
||||||
}
|
|
||||||
return summary
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ func TestCompleteModelRendersResponsiveTerminalSizeClasses(t *testing.T) {
|
|||||||
if !sameLine(view, "Targets", "Target details") {
|
if !sameLine(view, "Targets", "Target details") {
|
||||||
t.Fatalf("wide layout did not place list and details side by side:\n%s", view)
|
t.Fatalf("wide layout did not place list and details side by side:\n%s", view)
|
||||||
}
|
}
|
||||||
assertUsableFrame(t, view, 120, 36, "Shell", "Shell summary", "Active Profile: office")
|
assertUsableFrame(t, view, 120, 36, "Shell", "Shell summary", "Profile: office")
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("narrow 80x24", func(t *testing.T) {
|
t.Run("narrow 80x24", func(t *testing.T) {
|
||||||
@@ -33,7 +33,7 @@ func TestCompleteModelRendersResponsiveTerminalSizeClasses(t *testing.T) {
|
|||||||
if sameLine(view, "Targets", "Target details") || strings.Index(view, "Target details") < strings.Index(view, "Shell") {
|
if sameLine(view, "Targets", "Target details") || strings.Index(view, "Target details") < strings.Index(view, "Shell") {
|
||||||
t.Fatalf("narrow layout did not stack list above details:\n%s", view)
|
t.Fatalf("narrow layout did not stack list above details:\n%s", view)
|
||||||
}
|
}
|
||||||
assertUsableFrame(t, view, 80, 24, "Shell", "Shell summary", "Active Profile: office")
|
assertUsableFrame(t, view, 80, 24, "Shell", "Shell summary", "Profile: office")
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("below minimum 59x15", func(t *testing.T) {
|
t.Run("below minimum 59x15", func(t *testing.T) {
|
||||||
@@ -82,11 +82,11 @@ func TestCompleteModelResizePreservesValidSelectionAndFormFocus(t *testing.T) {
|
|||||||
model := resizedModel(t, module, themeModeNoColor, 120, 36)
|
model := resizedModel(t, module, themeModeNoColor, 120, 36)
|
||||||
model = updateKey(model, "down")
|
model = updateKey(model, "down")
|
||||||
model = resize(model, 80, 24)
|
model = resize(model, 80, 24)
|
||||||
if view := model.View(); !strings.Contains(view, "> ◇ External APT") || !strings.Contains(view, "Action: Apply Profile") {
|
if view := model.View(); !strings.Contains(view, "> ◇ External APT") || !strings.Contains(view, "Space: Apply Profile") {
|
||||||
t.Fatalf("Target selection did not survive wide-to-narrow resize:\n%s", view)
|
t.Fatalf("Target selection did not survive wide-to-narrow resize:\n%s", view)
|
||||||
}
|
}
|
||||||
model = resize(model, 120, 36)
|
model = resize(model, 120, 36)
|
||||||
if view := model.View(); !strings.Contains(view, "> ◇ External APT") || !strings.Contains(view, "Action: Apply Profile") {
|
if view := model.View(); !strings.Contains(view, "> ◇ External APT") || !strings.Contains(view, "Space: Apply Profile") {
|
||||||
t.Fatalf("Target selection did not survive narrow-to-wide resize:\n%s", view)
|
t.Fatalf("Target selection did not survive narrow-to-wide resize:\n%s", view)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,7 +110,7 @@ func TestCompleteModelSemanticThemeSupportsDarkLightAndNoColor(t *testing.T) {
|
|||||||
plain := resizedModel(t, module, themeModeNoColor, 80, 24).View()
|
plain := resizedModel(t, module, themeModeNoColor, 80, 24).View()
|
||||||
|
|
||||||
for name, view := range map[string]string{"dark": dark, "light": light, "NO_COLOR": plain} {
|
for name, view := range map[string]string{"dark": dark, "light": light, "NO_COLOR": plain} {
|
||||||
for _, semantic := range []string{"Active Profile: office", "Disabled", "External", ">"} {
|
for _, semantic := range []string{"Profile: office", "Disabled", "External", ">"} {
|
||||||
if !strings.Contains(view, semantic) {
|
if !strings.Contains(view, semantic) {
|
||||||
t.Fatalf("%s theme lost non-color semantic %q:\n%s", name, semantic, view)
|
t.Fatalf("%s theme lost non-color semantic %q:\n%s", name, semantic, view)
|
||||||
}
|
}
|
||||||
@@ -134,7 +134,7 @@ func TestNewModelUsesInjectedBubbleTeaOutputForTerminalCapabilities(t *testing.T
|
|||||||
if ansiPattern.MatchString(view) {
|
if ansiPattern.MatchString(view) {
|
||||||
t.Fatalf("non-terminal Bubble Tea output received ANSI styling: %q", view)
|
t.Fatalf("non-terminal Bubble Tea output received ANSI styling: %q", view)
|
||||||
}
|
}
|
||||||
for _, semantic := range []string{"Active Profile: office", "Disabled", "External", ">"} {
|
for _, semantic := range []string{"Profile: office", "Disabled", "External", ">"} {
|
||||||
if !strings.Contains(view, semantic) {
|
if !strings.Contains(view, semantic) {
|
||||||
t.Fatalf("injected-output rendering lost semantic %q:\n%s", semantic, view)
|
t.Fatalf("injected-output rendering lost semantic %q:\n%s", semantic, view)
|
||||||
}
|
}
|
||||||
@@ -231,19 +231,19 @@ func TestCompleteModelNarrowShellKeepsLastProductionTargetStatusAndActionsVisibl
|
|||||||
|
|
||||||
assertUsableFrame(t, model.View(), 80, 24,
|
assertUsableFrame(t, model.View(), 80, 24,
|
||||||
"> ! Drifted Docker daemon",
|
"> ! Drifted Docker daemon",
|
||||||
"State: ! Drifted",
|
"! Drifted",
|
||||||
"Docker daemon selected evidence.",
|
"Docker daemon selected evidence.",
|
||||||
"Status: Refresh completed; selected Target remains actionable.",
|
"Status: Refresh completed; selected Target remains actionable.",
|
||||||
"Space: Resolve",
|
"Space: Resolve",
|
||||||
"p: switch Active Profile",
|
"p: Profile",
|
||||||
"m: manage Proxy Profiles",
|
"m: Profiles",
|
||||||
)
|
)
|
||||||
|
|
||||||
model = resize(model, 120, 36)
|
model = resize(model, 120, 36)
|
||||||
model = resize(model, 80, 24)
|
model = resize(model, 80, 24)
|
||||||
assertUsableFrame(t, model.View(), 80, 24,
|
assertUsableFrame(t, model.View(), 80, 24,
|
||||||
"> ! Drifted Docker daemon",
|
"> ! Drifted Docker daemon",
|
||||||
"State: ! Drifted",
|
"! Drifted",
|
||||||
"Docker daemon selected evidence.",
|
"Docker daemon selected evidence.",
|
||||||
"Space: Resolve",
|
"Space: Resolve",
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ func TestCompleteModelContextualHelpOpensOverEveryPageAndRestoresPageState(t *te
|
|||||||
model = updateKey(model, "down")
|
model = updateKey(model, "down")
|
||||||
model = updateKey(model, "?")
|
model = updateKey(model, "?")
|
||||||
view := model.View()
|
view := model.View()
|
||||||
assertUsableFrame(t, view, 120, 36, "Operations Console", "Contextual Help", "Dashboard", "Target details focus", "APT", "Disable")
|
assertUsableFrame(t, view, 120, 36, "Profile: office", "Contextual Help", "Dashboard", "Target details focus", "APT", "Disable")
|
||||||
|
|
||||||
model = updateKey(model, " ")
|
model = updateKey(model, " ")
|
||||||
if len(module.intents) != 0 {
|
if len(module.intents) != 0 {
|
||||||
@@ -139,7 +139,7 @@ func TestCompleteModelDialogResizeAndHelpPreserveMeaningfulFocus(t *testing.T) {
|
|||||||
|
|
||||||
updated, command := model.Update(tea.KeyMsg{Type: tea.KeyEnter})
|
updated, command := model.Update(tea.KeyMsg{Type: tea.KeyEnter})
|
||||||
model = updated.(Model)
|
model = updated.(Model)
|
||||||
if command != nil || len(module.intents) != 1 || module.intents[0].Kind != app.DeleteProfile {
|
if command == nil || len(module.intents) != 1 || module.intents[0].Kind != app.DeleteProfile {
|
||||||
t.Fatalf("resize and Help changed confirmation focus: intents=%#v", module.intents)
|
t.Fatalf("resize and Help changed confirmation focus: intents=%#v", module.intents)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -259,9 +259,9 @@ func TestCompleteModelFooterHintsMatchContextAndAcceptedKeys(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("dashboard and busy details", func(t *testing.T) {
|
t.Run("dashboard and busy details", func(t *testing.T) {
|
||||||
model := resizedModel(t, module, themeModeNoColor, 120, 36)
|
model := resizedModel(t, module, themeModeNoColor, 120, 36)
|
||||||
assertUsableFrame(t, model.View(), 120, 36, "Space: Enable", "u: show unavailable", "r: refresh", "q/Ctrl+C: quit")
|
assertUsableFrame(t, model.View(), 120, 36, "Space: Enable", "u: Show hidden", "r: Refresh", "q: Quit")
|
||||||
model = updateKey(model, "tab")
|
model = updateKey(model, "tab")
|
||||||
assertUsableFrame(t, model.View(), 120, 36, "PgUp/PgDn: scroll", "u: show unavailable", "q/Ctrl+C: quit")
|
assertUsableFrame(t, model.View(), 120, 36, "↑/↓: Scroll", "u: Show hidden", "q: Quit")
|
||||||
|
|
||||||
updates := make(chan app.OperationUpdate)
|
updates := make(chan app.OperationUpdate)
|
||||||
busyModule := &interactiveScriptModule{snapshot: operationSnapshot(), streams: []chan app.OperationUpdate{updates}}
|
busyModule := &interactiveScriptModule{snapshot: operationSnapshot(), streams: []chan app.OperationUpdate{updates}}
|
||||||
@@ -269,9 +269,12 @@ func TestCompleteModelFooterHintsMatchContextAndAcceptedKeys(t *testing.T) {
|
|||||||
model = updateKey(model, "tab")
|
model = updateKey(model, "tab")
|
||||||
updated, _ := model.Update(tea.KeyMsg{Type: tea.KeySpace})
|
updated, _ := model.Update(tea.KeyMsg{Type: tea.KeySpace})
|
||||||
model = updated.(Model)
|
model = updated.(Model)
|
||||||
assertUsableFrame(t, model.View(), 120, 36, "u: show unavailable", "q/Ctrl+C: defer safe exit", "mutations disabled")
|
assertUsableFrame(t, model.View(), 120, 36, "q: Stop")
|
||||||
model = updateKey(model, "u")
|
model = updateKey(model, "u")
|
||||||
assertUsableFrame(t, model.View(), 120, 36, "u: hide unavailable")
|
if !model.showUnavailable {
|
||||||
|
t.Fatal("u did not toggle unavailable Targets while busy")
|
||||||
|
}
|
||||||
|
assertUsableFrame(t, model.View(), 120, 36, "q: Stop")
|
||||||
close(updates)
|
close(updates)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
+38
-27
@@ -145,13 +145,24 @@ func (m Model) Update(message tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
m.operation.unexpectedClose()
|
m.operation.unexpectedClose()
|
||||||
return m, m.operation.deferredQuit()
|
return m, m.operation.deferredQuit()
|
||||||
}
|
}
|
||||||
|
completedIntent := m.operation.intent
|
||||||
m.snapshot = progress.update.Snapshot
|
m.snapshot = progress.update.Snapshot
|
||||||
m.retainTargetSelection()
|
m.retainTargetSelection()
|
||||||
m.retainProfileSelection(m.selectedProfileName, m.selected)
|
m.retainProfileSelection(m.selectedProfileName, m.selected)
|
||||||
|
decoded := progress.update.Decode()
|
||||||
if firstFailed := m.operation.apply(progress.update); firstFailed != "" {
|
if firstFailed := m.operation.apply(progress.update); firstFailed != "" {
|
||||||
m.selectedTargetID = firstFailed
|
m.selectedTargetID = firstFailed
|
||||||
m.detailsOffset = 0
|
m.detailsOffset = 0
|
||||||
}
|
}
|
||||||
|
if decoded.IsTerminal() && isProfileMutation(completedIntent.Kind) {
|
||||||
|
if decoded.Kind == app.OperationSucceeded {
|
||||||
|
m.page = profilesPage
|
||||||
|
m.form = formState{}
|
||||||
|
m.status = decoded.Status.Summary
|
||||||
|
} else if decoded.Err != nil {
|
||||||
|
m.status = "Error: " + decoded.Err.Error()
|
||||||
|
}
|
||||||
|
}
|
||||||
if m.operation.confirmation != nil {
|
if m.operation.confirmation != nil {
|
||||||
m.page = mainPage
|
m.page = mainPage
|
||||||
if m.help.open {
|
if m.help.open {
|
||||||
@@ -232,8 +243,7 @@ func driftResolutionAction(selected app.TargetSnapshot, kind app.TargetActionKin
|
|||||||
return app.TargetAction{Kind: kind}, false
|
return app.TargetAction{Kind: kind}, false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) updateMain(key tea.KeyMsg) (tea.Model, tea.Cmd) {
|
func (m Model) updateProfilePicker(key tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||||
if m.picker.open {
|
|
||||||
switch key.String() {
|
switch key.String() {
|
||||||
case "esc":
|
case "esc":
|
||||||
m.picker.close()
|
m.picker.close()
|
||||||
@@ -248,8 +258,9 @@ func (m Model) updateMain(key tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||||||
default:
|
default:
|
||||||
return m, m.picker.update(key, m.snapshot)
|
return m, m.picker.update(key, m.snapshot)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if m.operation.confirmation != nil {
|
|
||||||
|
func (m Model) updateOperationConfirmation(key tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||||
switch m.operation.confirmationDialog.update(key.String()) {
|
switch m.operation.confirmationDialog.update(key.String()) {
|
||||||
case confirmationAccepted:
|
case confirmationAccepted:
|
||||||
confirmed, ok := m.operation.confirmedIntent()
|
confirmed, ok := m.operation.confirmedIntent()
|
||||||
@@ -262,8 +273,9 @@ func (m Model) updateMain(key tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||||||
m.operation.cancelConfirmation()
|
m.operation.cancelConfirmation()
|
||||||
}
|
}
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
if m.driftResolutionTargetID != "" {
|
|
||||||
|
func (m Model) updateDriftResolution(key tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||||
switch key.String() {
|
switch key.String() {
|
||||||
case "enter", "esc", "n", "q":
|
case "enter", "esc", "n", "q":
|
||||||
m.driftResolutionTargetID = ""
|
m.driftResolutionTargetID = ""
|
||||||
@@ -293,6 +305,17 @@ func (m Model) updateMain(key tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||||||
return m, m.startOperation(intent)
|
return m, m.startOperation(intent)
|
||||||
}
|
}
|
||||||
return m, nil
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m Model) updateMain(key tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||||
|
if m.picker.open {
|
||||||
|
return m.updateProfilePicker(key)
|
||||||
|
}
|
||||||
|
if m.operation.confirmation != nil {
|
||||||
|
return m.updateOperationConfirmation(key)
|
||||||
|
}
|
||||||
|
if m.driftResolutionTargetID != "" {
|
||||||
|
return m.updateDriftResolution(key)
|
||||||
}
|
}
|
||||||
if key.String() == "e" && m.operation.currentError != nil {
|
if key.String() == "e" && m.operation.currentError != nil {
|
||||||
m.operation.errorExpanded = !m.operation.errorExpanded
|
m.operation.errorExpanded = !m.operation.errorExpanded
|
||||||
@@ -399,7 +422,7 @@ func (m Model) updateProfiles(key tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||||||
case confirmationAccepted:
|
case confirmationAccepted:
|
||||||
name := m.profileDelete.name
|
name := m.profileDelete.name
|
||||||
m.profileDelete = nil
|
m.profileDelete = nil
|
||||||
m.applyProfileMutation(app.Intent{Kind: app.DeleteProfile, Name: name, Confirm: true}, "")
|
return m, m.startOperation(app.Intent{Kind: app.DeleteProfile, Name: name, Confirm: true})
|
||||||
case confirmationCancelled:
|
case confirmationCancelled:
|
||||||
m.profileDelete = nil
|
m.profileDelete = nil
|
||||||
}
|
}
|
||||||
@@ -519,13 +542,8 @@ func (m Model) updateForm(key tea.KeyMsg) (tea.Model, tea.Cmd) {
|
|||||||
}
|
}
|
||||||
normalized := m.form.validation.Normalized
|
normalized := m.form.validation.Normalized
|
||||||
intent := app.Intent{Kind: kind, Name: m.form.originalName, Profile: normalized}
|
intent := app.Intent{Kind: kind, Name: m.form.originalName, Profile: normalized}
|
||||||
result := m.applyProfileMutation(intent, normalized.Name)
|
m.selectedProfileName = normalized.Name
|
||||||
if result.Err != nil {
|
return m, m.startOperation(intent)
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
m.page = profilesPage
|
|
||||||
m.form = formState{}
|
|
||||||
return m, nil
|
|
||||||
case tea.KeyCtrlD:
|
case tea.KeyCtrlD:
|
||||||
address, token, started := m.form.startProbe()
|
address, token, started := m.form.startProbe()
|
||||||
if !started {
|
if !started {
|
||||||
@@ -556,20 +574,13 @@ func (m Model) beginProfileActivation(intent app.Intent) (tea.Model, tea.Cmd) {
|
|||||||
return m, m.startOperation(intent)
|
return m, m.startOperation(intent)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) applyProfileMutation(intent app.Intent, preferredName string) app.Result {
|
func isProfileMutation(kind app.IntentKind) bool {
|
||||||
formerName, formerIndex := m.selectedProfileName, m.selected
|
switch kind {
|
||||||
result := m.application.Dispatch(intent)
|
case app.CreateProfile, app.UpdateProfile, app.DeleteProfile:
|
||||||
m.snapshot = result.Snapshot
|
return true
|
||||||
if preferredName == "" {
|
default:
|
||||||
preferredName = formerName
|
return false
|
||||||
}
|
}
|
||||||
m.retainProfileSelection(preferredName, formerIndex)
|
|
||||||
if result.Err != nil {
|
|
||||||
m.status = "Error: " + result.Err.Error()
|
|
||||||
} else {
|
|
||||||
m.status = result.Notice
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) selectedProfile() (profile.Profile, bool) {
|
func (m Model) selectedProfile() (profile.Profile, bool) {
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ func TestMainAndProfilePagesMapKeysAndObscurePasswords(t *testing.T) {
|
|||||||
}},
|
}},
|
||||||
}}
|
}}
|
||||||
model := NewModel(module)
|
model := NewModel(module)
|
||||||
if view := model.View(); !strings.Contains(view, "Active Profile: office") {
|
if view := model.View(); !strings.Contains(view, "Profile: office") {
|
||||||
t.Fatalf("main view missing Active Profile:\n%s", view)
|
t.Fatalf("main view missing Active Profile:\n%s", view)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,7 +130,7 @@ func TestRenderedMalformedProxyURLStillObscuresPassword(t *testing.T) {
|
|||||||
func TestNoProfileStateStaysOnAccessibleMainPage(t *testing.T) {
|
func TestNoProfileStateStaysOnAccessibleMainPage(t *testing.T) {
|
||||||
model := NewModel(&recordingModule{})
|
model := NewModel(&recordingModule{})
|
||||||
view := model.View()
|
view := model.View()
|
||||||
if !strings.Contains(view, "No Active Profile") || !strings.Contains(view, "m: manage Proxy Profiles") {
|
if !strings.Contains(view, "No Active Profile") || !strings.Contains(view, "m: Profiles") {
|
||||||
t.Fatalf("no-Profile main view is not actionable:\n%s", view)
|
t.Fatalf("no-Profile main view is not actionable:\n%s", view)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -149,7 +149,20 @@ func updateKey(model Model, key string) Model {
|
|||||||
msg = tea.KeyMsg{Type: keyType}
|
msg = tea.KeyMsg{Type: keyType}
|
||||||
}
|
}
|
||||||
updated, _ := model.Update(msg)
|
updated, _ := model.Update(msg)
|
||||||
return updated.(Model)
|
model = updated.(Model)
|
||||||
|
// In-memory test modules publish terminal operation updates synchronously.
|
||||||
|
// Drain only updates already available; real in-flight operation tests remain
|
||||||
|
// under their explicit channel control.
|
||||||
|
for model.operation.active && isProfileMutation(model.operation.intent.Kind) {
|
||||||
|
select {
|
||||||
|
case update, open := <-model.operation.updates:
|
||||||
|
updated, _ = model.Update(operationProgress{updates: model.operation.updates, update: update, closed: !open})
|
||||||
|
model = updated.(Model)
|
||||||
|
default:
|
||||||
|
return model
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return model
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateRunes(model Model, value string) Model {
|
func updateRunes(model Model, value string) Model {
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ type operationCoordinator struct {
|
|||||||
active bool
|
active bool
|
||||||
intent app.Intent
|
intent app.Intent
|
||||||
updates <-chan app.OperationUpdate
|
updates <-chan app.OperationUpdate
|
||||||
|
cancel func()
|
||||||
progress map[string]app.TargetProgressPhase
|
progress map[string]app.TargetProgressPhase
|
||||||
status app.OperationStatus
|
status app.OperationStatus
|
||||||
currentError *operationError
|
currentError *operationError
|
||||||
@@ -85,6 +86,7 @@ func (o *operationCoordinator) start(application app.InteractiveModule, intent a
|
|||||||
o.active = true
|
o.active = true
|
||||||
o.intent = intent
|
o.intent = intent
|
||||||
o.updates = stream.Updates
|
o.updates = stream.Updates
|
||||||
|
o.cancel = stream.Cancel
|
||||||
o.progress = make(map[string]app.TargetProgressPhase)
|
o.progress = make(map[string]app.TargetProgressPhase)
|
||||||
o.spinner = spinner.New(spinner.WithSpinner(applyingSpinner))
|
o.spinner = spinner.New(spinner.WithSpinner(applyingSpinner))
|
||||||
if intent.TargetID != "" {
|
if intent.TargetID != "" {
|
||||||
@@ -100,6 +102,8 @@ func operationStartingSummary(kind app.IntentKind) string {
|
|||||||
return "Checking Target availability and state…"
|
return "Checking Target availability and state…"
|
||||||
case app.ActivateProfile:
|
case app.ActivateProfile:
|
||||||
return "Changing Active Profile…"
|
return "Changing Active Profile…"
|
||||||
|
case app.CreateProfile, app.UpdateProfile, app.DeleteProfile:
|
||||||
|
return "Saving Proxy Profile changes…"
|
||||||
default:
|
default:
|
||||||
return "Starting Target mutation…"
|
return "Starting Target mutation…"
|
||||||
}
|
}
|
||||||
@@ -171,6 +175,8 @@ func relatedResolution(failed, success app.Intent) bool {
|
|||||||
return success.Kind == app.RefreshTargets
|
return success.Kind == app.RefreshTargets
|
||||||
case failed.Kind == app.ActivateProfile:
|
case failed.Kind == app.ActivateProfile:
|
||||||
return success.Kind == app.ActivateProfile && failed.Name == success.Name
|
return success.Kind == app.ActivateProfile && failed.Name == success.Name
|
||||||
|
case isProfileMutation(failed.Kind):
|
||||||
|
return isProfileMutation(success.Kind) && failed.Name == success.Name
|
||||||
case isTargetMutation(failed.Kind):
|
case isTargetMutation(failed.Kind):
|
||||||
return isTargetMutation(success.Kind) && failed.TargetID != "" && failed.TargetID == success.TargetID
|
return isTargetMutation(success.Kind) && failed.TargetID != "" && failed.TargetID == success.TargetID
|
||||||
default:
|
default:
|
||||||
@@ -188,9 +194,19 @@ func isTargetMutation(kind app.IntentKind) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (o *operationCoordinator) finish() {
|
func (o *operationCoordinator) finish() {
|
||||||
|
// start seeds speculative Running progress before the stream publishes its
|
||||||
|
// first update. A terminal update may contain no replacement progress (most
|
||||||
|
// notably a confirmation request), so never let that transient phase outlive
|
||||||
|
// the operation that created it.
|
||||||
|
for targetID, phase := range o.progress {
|
||||||
|
if phase == app.TargetProgressRunning {
|
||||||
|
delete(o.progress, targetID)
|
||||||
|
}
|
||||||
|
}
|
||||||
o.active = false
|
o.active = false
|
||||||
o.intent = app.Intent{}
|
o.intent = app.Intent{}
|
||||||
o.updates = nil
|
o.updates = nil
|
||||||
|
o.cancel = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (o *operationCoordinator) unexpectedClose() {
|
func (o *operationCoordinator) unexpectedClose() {
|
||||||
@@ -225,6 +241,7 @@ func (o *operationCoordinator) confirmedIntent() (app.Intent, bool) {
|
|||||||
}
|
}
|
||||||
intent := *o.confirmationIntent
|
intent := *o.confirmationIntent
|
||||||
intent.Confirm = true
|
intent.Confirm = true
|
||||||
|
intent.ConfirmationToken = o.confirmation.Token
|
||||||
o.confirmation = nil
|
o.confirmation = nil
|
||||||
o.confirmationDialog = confirmationDialog{}
|
o.confirmationDialog = confirmationDialog{}
|
||||||
o.confirmationIntent = nil
|
o.confirmationIntent = nil
|
||||||
@@ -245,6 +262,9 @@ func (o operationCoordinator) deferredQuit() tea.Cmd {
|
|||||||
func (o *operationCoordinator) requestQuit() tea.Cmd {
|
func (o *operationCoordinator) requestQuit() tea.Cmd {
|
||||||
o.quitRequested = true
|
o.quitRequested = true
|
||||||
if o.active {
|
if o.active {
|
||||||
|
if o.cancel != nil {
|
||||||
|
o.cancel()
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return tea.Quit
|
return tea.Quit
|
||||||
|
|||||||
+15
-52
@@ -14,12 +14,7 @@ func (p terminalPresentation) mainView(model presentationState, width, height in
|
|||||||
if activeProfile == "" {
|
if activeProfile == "" {
|
||||||
activeProfile = "No Active Profile"
|
activeProfile = "No Active Profile"
|
||||||
}
|
}
|
||||||
header := fmt.Sprintf("%s Operations Console\nActive Profile: %s Targets: %s",
|
header := fmt.Sprintf("%s Profile: %s", p.theme.title.Render("proxyctl"), activeProfile)
|
||||||
p.theme.title.Render("proxyctl"), activeProfile, p.stateCountSummary(model.snapshot))
|
|
||||||
if width < wideWidth {
|
|
||||||
header = fmt.Sprintf("%s Operations Console\nActive Profile: %s\nTargets: %s",
|
|
||||||
p.theme.title.Render("proxyctl"), activeProfile, p.stateCountSummary(model.snapshot))
|
|
||||||
}
|
|
||||||
|
|
||||||
catalog := newTargetCatalog(model.snapshot, dashboard.showUnavailable, dashboard.selectedTargetID)
|
catalog := newTargetCatalog(model.snapshot, dashboard.showUnavailable, dashboard.selectedTargetID)
|
||||||
footer := p.dashboardFooter(model, catalog)
|
footer := p.dashboardFooter(model, catalog)
|
||||||
@@ -97,62 +92,30 @@ func (p terminalPresentation) driftResolutionView(selected app.TargetSnapshot) (
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p terminalPresentation) dashboardFooter(model presentationState, catalog targetCatalog) string {
|
func (p terminalPresentation) dashboardFooter(model presentationState, catalog targetCatalog) string {
|
||||||
dashboard, operation, width := model.dashboard, model.operation, model.terminal.width
|
dashboard, operation := model.dashboard, model.operation
|
||||||
visibility := "u: show unavailable"
|
visibility := "u: Show hidden"
|
||||||
if dashboard.showUnavailable {
|
if dashboard.showUnavailable {
|
||||||
visibility = "u: hide unavailable"
|
visibility = "u: Hide unavailable"
|
||||||
|
}
|
||||||
|
if operation.exitDeferred {
|
||||||
|
return "Operation stopping; changes disabled ?: Help"
|
||||||
}
|
}
|
||||||
if dashboard.focus == targetDetailsPane {
|
if dashboard.focus == targetDetailsPane {
|
||||||
if operation.exitDeferred {
|
|
||||||
return "↑/k ↓/j PgUp/PgDn: browse Tab: focus Targets " + visibility + " ?: help\nExit pending; new work disabled until safe completion"
|
|
||||||
}
|
|
||||||
if width < wideWidth {
|
|
||||||
if operation.active {
|
if operation.active {
|
||||||
return "↑/k ↓/j PgUp/PgDn: browse Tab: focus Targets\n?: help q/Ctrl+C: defer exit; mutations disabled"
|
return "↑/↓: Scroll Tab: Targets ?: Help q: Stop"
|
||||||
}
|
}
|
||||||
if width < 70 {
|
return "↑/↓: Scroll Tab: Targets " + visibility + "\np: Profile m: Profiles r: Refresh ?: Help q: Quit"
|
||||||
return "↑/k ↓/j PgUp/PgDn: scroll Tab: focus Targets\np: switch Profile m: manage ?: help q: quit"
|
|
||||||
}
|
|
||||||
return "↑/k ↓/j PgUp/PgDn: scroll Tab: focus Targets\np: switch Active Profile m: manage Proxy Profiles ?: help q: quit"
|
|
||||||
}
|
|
||||||
footer := "↑/k ↓/j PgUp/PgDn: scroll Tab: focus Targets " + visibility + "\np: switch Active Profile m: manage Proxy Profiles ?: help q/Ctrl+C: quit"
|
|
||||||
if operation.active {
|
|
||||||
footer = "↑/k ↓/j PgUp/PgDn: scroll Tab: focus Targets " + visibility + " ?: help\nq/Ctrl+C: defer safe exit; mutations disabled"
|
|
||||||
}
|
|
||||||
return footer
|
|
||||||
}
|
|
||||||
actions := "↑/k ↓/j: select Tab: focus details " + visibility
|
|
||||||
if operation.exitDeferred {
|
|
||||||
return actions + " ?: help\nExit pending; new work disabled until safe completion"
|
|
||||||
}
|
}
|
||||||
selected, ok := catalog.selected(dashboard.selectedTargetID)
|
selected, ok := catalog.selected(dashboard.selectedTargetID)
|
||||||
availability := targetMutationAvailability(selected, ok, operation.active || operation.exitDeferred)
|
availability := targetMutationAvailability(selected, ok, operation.active)
|
||||||
label := targetActionLabel(selected.PrimaryAction.Kind)
|
action := "Space: " + targetActionLabel(selected.PrimaryAction.Kind)
|
||||||
if availability.available {
|
if !availability.available {
|
||||||
actions = "Space: " + label + " " + actions
|
action += " unavailable"
|
||||||
} else {
|
|
||||||
actions = "Space: " + label + " disabled (" + availability.compactReason + ") " + actions
|
|
||||||
}
|
}
|
||||||
if width < wideWidth {
|
|
||||||
if availability.available {
|
|
||||||
actions = "Space: " + label + " ↑/k ↓/j: select Tab: focus details"
|
|
||||||
} else {
|
|
||||||
actions = "Space: " + label + " disabled ↑/k ↓/j: select Tab: focus details"
|
|
||||||
}
|
|
||||||
|
|
||||||
if operation.active {
|
if operation.active {
|
||||||
return actions + "\n?: help q/Ctrl+C: defer exit; mutations disabled"
|
return action + " ↑/↓: Select Tab: Details\n?: Help q: Stop"
|
||||||
}
|
}
|
||||||
if width < 70 {
|
return action + " ↑/↓: Select Tab: Details " + visibility + "\np: Profile m: Profiles r: Refresh ?: Help q: Quit"
|
||||||
return actions + "\np: switch Profile m: manage ?: help q: quit"
|
|
||||||
}
|
|
||||||
return actions + "\np: switch Active Profile m: manage Proxy Profiles ?: help q: quit"
|
|
||||||
}
|
|
||||||
footer := actions + "\np: switch Active Profile m: manage Proxy Profiles r: refresh ?: help q/Ctrl+C: quit"
|
|
||||||
if operation.active {
|
|
||||||
footer = actions + "\n?: help q: defer safe exit; new mutations disabled"
|
|
||||||
}
|
|
||||||
return footer
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p terminalPresentation) profilesView(model presentationState) terminalPage {
|
func (p terminalPresentation) profilesView(model presentationState) terminalPage {
|
||||||
|
|||||||
@@ -199,8 +199,6 @@ func (f *formState) toggleMode() tea.Cmd {
|
|||||||
return f.rebuildInputs(0)
|
return f.rebuildInputs(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f formState) fieldCount() int { return len(f.inputs) }
|
|
||||||
|
|
||||||
func (f formState) currentField() profile.Field {
|
func (f formState) currentField() profile.Field {
|
||||||
if f.field < 0 || f.field >= len(f.inputs) {
|
if f.field < 0 || f.field >= len(f.inputs) {
|
||||||
return ""
|
return ""
|
||||||
|
|||||||
@@ -146,8 +146,8 @@ func TestCompleteModelProfileDeletionDialogIsSafeByDefaultAndSupportsExplicitSel
|
|||||||
model = updateKey(model, "right")
|
model = updateKey(model, "right")
|
||||||
updated, command = model.Update(tea.KeyMsg{Type: tea.KeyEnter})
|
updated, command = model.Update(tea.KeyMsg{Type: tea.KeyEnter})
|
||||||
model = updated.(Model)
|
model = updated.(Model)
|
||||||
if command != nil || len(module.intents) != 1 || module.intents[0].Kind != app.DeleteProfile || module.intents[0].Name != "office" || !module.intents[0].Confirm {
|
if command == nil || len(module.intents) != 1 || module.intents[0].Kind != app.DeleteProfile || module.intents[0].Name != "office" || !module.intents[0].Confirm {
|
||||||
t.Fatalf("focused Delete did not dispatch the confirmed mutation: intents=%#v", module.intents)
|
t.Fatalf("focused Delete did not start the confirmed mutation: intents=%#v", module.intents)
|
||||||
}
|
}
|
||||||
assertUsableFrame(t, model.View(), 80, 24, "> remote", "Proxy: http://remote.example:8080")
|
assertUsableFrame(t, model.View(), 80, 24, "> remote", "Proxy: http://remote.example:8080")
|
||||||
}
|
}
|
||||||
@@ -219,7 +219,7 @@ func TestCompleteModelProfileManagementNavigationAndBusyReasonsAreConsistent(t *
|
|||||||
model = updateKey(model, "m")
|
model = updateKey(model, "m")
|
||||||
updated, command := model.Update(back)
|
updated, command := model.Update(back)
|
||||||
model = updated.(Model)
|
model = updated.(Model)
|
||||||
if command != nil || !strings.Contains(model.View(), "Operations Console") {
|
if command != nil || !strings.Contains(model.View(), "Profile:") {
|
||||||
t.Fatalf("%q did not return to the dashboard:\n%s", back.String(), model.View())
|
t.Fatalf("%q did not return to the dashboard:\n%s", back.String(), model.View())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ func TestCompleteModelReconcilesAuthoritativeSnapshotWhenDetectionGenerationClos
|
|||||||
if next != nil || model.operation.active {
|
if next != nil || model.operation.active {
|
||||||
t.Fatalf("stale closure left detection active: next=%v active=%v", next != nil, model.operation.active)
|
t.Fatalf("stale closure left detection active: next=%v active=%v", next != nil, model.operation.active)
|
||||||
}
|
}
|
||||||
assertUsableFrame(t, model.View(), 80, 24, "> ● Enabled Shell", "Evidence: shell enabled")
|
assertUsableFrame(t, model.View(), 80, 24, "> ● Enabled Shell", "shell enabled")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *progressiveDetectionModule) detectionUpdate(id string, phase app.TargetDetectionPhase, available bool, state target.State, evidence string, err error) app.OperationUpdate {
|
func (m *progressiveDetectionModule) detectionUpdate(id string, phase app.TargetDetectionPhase, available bool, state target.State, evidence string, err error) app.OperationUpdate {
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ func TestCompleteModelFixedSizeCoverageAcrossCompletedWorkflows(t *testing.T) {
|
|||||||
}
|
}
|
||||||
return resizedModel(t, &recordingModule{snapshot: snapshot}, themeModeNoColor, width, height)
|
return resizedModel(t, &recordingModule{snapshot: snapshot}, themeModeNoColor, width, height)
|
||||||
},
|
},
|
||||||
want: []string{"Operations Console", "Checking", "Target availability"},
|
want: []string{"Profile:", "Checking", "Target availability"},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "refresh",
|
name: "refresh",
|
||||||
@@ -46,7 +46,7 @@ func TestCompleteModelFixedSizeCoverageAcrossCompletedWorkflows(t *testing.T) {
|
|||||||
}
|
}
|
||||||
return model
|
return model
|
||||||
},
|
},
|
||||||
want: []string{"Operations Console", "Checking Target availability and state"},
|
want: []string{"Profile:", "Checking Target availability and state"},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Target action",
|
name: "Target action",
|
||||||
@@ -155,7 +155,7 @@ func TestCompleteModelLightDarkAndNoColorRetainEquivalentSemantics(t *testing.T)
|
|||||||
model, _ = applyOperationCommand(t, model, command)
|
model, _ = applyOperationCommand(t, model, command)
|
||||||
model = updateKey(model, "e")
|
model = updateKey(model, "e")
|
||||||
views[mode] = progressFrame + "--- operation completed ---\n" + model.View()
|
views[mode] = progressFrame + "--- operation completed ---\n" + model.View()
|
||||||
for _, semantic := range []string{"[focused]", "Disabled", "Drifted", "Applying", "mutations disabled", "Current error:", "REDACTED", "Action: Enable"} {
|
for _, semantic := range []string{"[focused]", "Disabled", "Drifted", "Applying", "q: Stop", "Current error:", "REDACTED", "Space: Enable"} {
|
||||||
if !strings.Contains(views[mode], semantic) {
|
if !strings.Contains(views[mode], semantic) {
|
||||||
t.Fatalf("theme %d lost %q:\n%s", mode, semantic, views[mode])
|
t.Fatalf("theme %d lost %q:\n%s", mode, semantic, views[mode])
|
||||||
}
|
}
|
||||||
@@ -163,7 +163,7 @@ func TestCompleteModelLightDarkAndNoColorRetainEquivalentSemantics(t *testing.T)
|
|||||||
}
|
}
|
||||||
|
|
||||||
plain := views[themeModeNoColor]
|
plain := views[themeModeNoColor]
|
||||||
for _, symbol := range []string{"● Enabled", "○ Disabled", "! Drifted", "▶ Target details [focused]"} {
|
for _, symbol := range []string{"○ Disabled", "! Drifted", "▶ Target details [focused]"} {
|
||||||
if !strings.Contains(plain, symbol) {
|
if !strings.Contains(plain, symbol) {
|
||||||
t.Fatalf("standard Unicode/ASCII status strategy lost %q:\n%s", symbol, plain)
|
t.Fatalf("standard Unicode/ASCII status strategy lost %q:\n%s", symbol, plain)
|
||||||
}
|
}
|
||||||
@@ -188,7 +188,7 @@ func TestCompleteModelBoundsUnicodeAndKeepsLongContentReachable(t *testing.T) {
|
|||||||
snapshot.Profiles[0].Name = longProfile
|
snapshot.Profiles[0].Name = longProfile
|
||||||
snapshot.Targets[0].Description.Name = longName
|
snapshot.Targets[0].Description.Name = longName
|
||||||
snapshot.Targets[0].Evidence = strings.Repeat("証拠 and wrapped evidence ", 80) + " EVIDENCE-END"
|
snapshot.Targets[0].Evidence = strings.Repeat("証拠 and wrapped evidence ", 80) + " EVIDENCE-END"
|
||||||
snapshot.Targets[0].Description.Details = strings.Repeat("詳細 line ", 100) + " DETAILS-END"
|
snapshot.Targets[0].Evidence = strings.Repeat("証拠 and wrapped evidence ", 120) + " EVIDENCE-END"
|
||||||
model := resizedModel(t, &recordingModule{snapshot: snapshot}, themeModeNoColor, 80, 24)
|
model := resizedModel(t, &recordingModule{snapshot: snapshot}, themeModeNoColor, 80, 24)
|
||||||
|
|
||||||
assertCellBoundedFrame(t, model.View(), 80, 24, "Disabled")
|
assertCellBoundedFrame(t, model.View(), 80, 24, "Disabled")
|
||||||
@@ -196,7 +196,7 @@ func TestCompleteModelBoundsUnicodeAndKeepsLongContentReachable(t *testing.T) {
|
|||||||
for range 120 {
|
for range 120 {
|
||||||
model = updateKey(model, "pgdown")
|
model = updateKey(model, "pgdown")
|
||||||
}
|
}
|
||||||
assertCellBoundedFrame(t, model.View(), 80, 24, "DETAILS-END")
|
assertCellBoundedFrame(t, model.View(), 80, 24, "EVIDENCE-END")
|
||||||
|
|
||||||
model = updateKey(model, "m")
|
model = updateKey(model, "m")
|
||||||
for range 60 {
|
for range 60 {
|
||||||
@@ -318,7 +318,7 @@ func TestCompleteModelLongFieldsAndDialogsRemainReachableAcrossResizeAtNontermin
|
|||||||
|
|
||||||
func TestCompleteModelResizeStressPreservesDialogFocusSelectionViewportInFlightAndDeferredExit(t *testing.T) {
|
func TestCompleteModelResizeStressPreservesDialogFocusSelectionViewportInFlightAndDeferredExit(t *testing.T) {
|
||||||
snapshot := hardeningSnapshot()
|
snapshot := hardeningSnapshot()
|
||||||
snapshot.Targets[1].Description.Details = strings.Repeat("APT scrollable detail. ", 90) + " APT-VIEWPORT-END"
|
snapshot.Targets[1].Evidence = strings.Repeat("APT scrollable evidence. ", 90) + " APT-VIEWPORT-END"
|
||||||
updates := make(chan app.OperationUpdate, 2)
|
updates := make(chan app.OperationUpdate, 2)
|
||||||
module := &interactiveScriptModule{snapshot: snapshot, streams: []chan app.OperationUpdate{updates}}
|
module := &interactiveScriptModule{snapshot: snapshot, streams: []chan app.OperationUpdate{updates}}
|
||||||
model := resizedModel(t, module, themeModeNoColor, 120, 36)
|
model := resizedModel(t, module, themeModeNoColor, 120, 36)
|
||||||
@@ -354,8 +354,8 @@ func TestCompleteModelResizeStressPreservesDialogFocusSelectionViewportInFlightA
|
|||||||
|
|
||||||
model = updateKey(model, "q")
|
model = updateKey(model, "q")
|
||||||
assertCellBoundedFrame(t, model.View(), 80, 24,
|
assertCellBoundedFrame(t, model.View(), 80, 24,
|
||||||
"> ! Drifted APT", "▶ Target details [focused]", "APT-VIEWPORT-", "END",
|
"> ! Drifted APT", "▶ Target details [focused]", "VIEWPORT-END",
|
||||||
"Applying", "Exit requested", "new work disabled")
|
"Applying", "Exit requested", "changes disabled")
|
||||||
|
|
||||||
updates <- app.SucceededOperationUpdate(snapshot,
|
updates <- app.SucceededOperationUpdate(snapshot,
|
||||||
app.OperationStatus{Summary: "Shell Target is now Enabled", TargetID: "shell"},
|
app.OperationStatus{Summary: "Shell Target is now Enabled", TargetID: "shell"},
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ func TestTargetPanelShowsOnlyAvailableTargetsAndAppliesAsynchronously(t *testing
|
|||||||
module.result = app.Result{Snapshot: app.Snapshot{ActiveProfile: "office", Targets: []app.TargetSnapshot{{ID: "shell", Description: target.Description{Name: "Shell", Summary: "Exports for Bash/Zsh"}, Available: true, State: target.Enabled, Evidence: "matches", PrimaryAction: app.TargetAction{Kind: app.DisableTargetAction, Available: true}}}}, Notice: "Shell Target is now Enabled"}
|
module.result = app.Result{Snapshot: app.Snapshot{ActiveProfile: "office", Targets: []app.TargetSnapshot{{ID: "shell", Description: target.Description{Name: "Shell", Summary: "Exports for Bash/Zsh"}, Available: true, State: target.Enabled, Evidence: "matches", PrimaryAction: app.TargetAction{Kind: app.DisableTargetAction, Available: true}}}}, Notice: "Shell Target is now Enabled"}
|
||||||
model := NewModel(module)
|
model := NewModel(module)
|
||||||
view := model.View()
|
view := model.View()
|
||||||
if !strings.Contains(view, "Shell") || strings.Contains(view, "APT") || !strings.Contains(view, "Action: Apply Profile") {
|
if !strings.Contains(view, "Shell") || strings.Contains(view, "APT") || !strings.Contains(view, "Space: Apply Profile") {
|
||||||
t.Fatalf("Target panel:\n%s", view)
|
t.Fatalf("Target panel:\n%s", view)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,8 +76,8 @@ func TestTargetRestartConfirmationCancelsWithoutConfirmedMutation(t *testing.T)
|
|||||||
}
|
}
|
||||||
updated, command = model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'n'}})
|
updated, command = model.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'n'}})
|
||||||
model = updated.(Model)
|
model = updated.(Model)
|
||||||
if command != nil || len(module.intents) != 1 || strings.Contains(model.View(), "restart immediately") {
|
if command != nil || len(module.intents) != 1 || strings.Contains(model.View(), "restart immediately") || strings.Contains(model.View(), "Applying") {
|
||||||
t.Fatalf("cancel mutated = intents %#v\n%s", module.intents, model.View())
|
t.Fatalf("cancel mutated or left stale progress = intents %#v\n%s", module.intents, model.View())
|
||||||
}
|
}
|
||||||
|
|
||||||
updated, command = model.Update(tea.KeyMsg{Type: tea.KeySpace})
|
updated, command = model.Update(tea.KeyMsg{Type: tea.KeySpace})
|
||||||
@@ -104,7 +104,7 @@ func TestHelpListsEveryTargetAndMainListsOnlyAvailableTargets(t *testing.T) {
|
|||||||
}}}
|
}}}
|
||||||
model := NewModel(module)
|
model := NewModel(module)
|
||||||
view := model.View()
|
view := model.View()
|
||||||
if strings.Contains(view, "APT") || !strings.Contains(view, "Action: Enable") || !strings.Contains(view, "integration installed") {
|
if strings.Contains(view, "APT") || !strings.Contains(view, "Unavailable:") || !strings.Contains(view, "integration installed") {
|
||||||
t.Fatalf("main Target panel:\n%s", view)
|
t.Fatalf("main Target panel:\n%s", view)
|
||||||
}
|
}
|
||||||
model = updateKey(model, "?")
|
model = updateKey(model, "?")
|
||||||
@@ -123,7 +123,7 @@ func TestHelpListsEveryTargetAndMainListsOnlyAvailableTargets(t *testing.T) {
|
|||||||
t.Fatalf("scrollable Target reference:\n%s", view)
|
t.Fatalf("scrollable Target reference:\n%s", view)
|
||||||
}
|
}
|
||||||
model = updateKey(model, "esc")
|
model = updateKey(model, "esc")
|
||||||
if !strings.Contains(model.View(), "Operations Console") {
|
if !strings.Contains(model.View(), "Profile:") {
|
||||||
t.Fatalf("Escape did not return from help:\n%s", model.View())
|
t.Fatalf("Escape did not return from help:\n%s", model.View())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -279,12 +279,12 @@ func TestQAndEscapeReturnFromNestedPages(t *testing.T) {
|
|||||||
for _, key := range []tea.KeyMsg{{Type: tea.KeyRunes, Runes: []rune{'q'}}, {Type: tea.KeyEsc}} {
|
for _, key := range []tea.KeyMsg{{Type: tea.KeyRunes, Runes: []rune{'q'}}, {Type: tea.KeyEsc}} {
|
||||||
model := updateKey(NewModel(module), "?")
|
model := updateKey(NewModel(module), "?")
|
||||||
updated, command := model.Update(key)
|
updated, command := model.Update(key)
|
||||||
if command != nil || !strings.Contains(updated.(Model).View(), "Operations Console") {
|
if command != nil || !strings.Contains(updated.(Model).View(), "Profile:") {
|
||||||
t.Fatalf("help key %q did not return to Operations Console", key.String())
|
t.Fatalf("help key %q did not return to dashboard", key.String())
|
||||||
}
|
}
|
||||||
model = updateKey(NewModel(module), "m")
|
model = updateKey(NewModel(module), "m")
|
||||||
updated, command = model.Update(key)
|
updated, command = model.Update(key)
|
||||||
if command != nil || !strings.Contains(updated.(Model).View(), "Operations Console") {
|
if command != nil || !strings.Contains(updated.(Model).View(), "Profile:") {
|
||||||
t.Fatalf("Profile key %q did not return to Target panel", key.String())
|
t.Fatalf("Profile key %q did not return to Target panel", key.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -315,7 +315,7 @@ func TestActiveProfileTransitionRendersPerTargetProgress(t *testing.T) {
|
|||||||
t.Fatal("Profile transition did not start progressive operation")
|
t.Fatal("Profile transition did not start progressive operation")
|
||||||
}
|
}
|
||||||
model, command = applyOperationCommand(t, model, command)
|
model, command = applyOperationCommand(t, model, command)
|
||||||
if command == nil || !strings.Contains(model.View(), "Applying") || !strings.Contains(model.View(), "Active Profile: new") {
|
if command == nil || !strings.Contains(model.View(), "Applying") || !strings.Contains(model.View(), "Profile: new") {
|
||||||
t.Fatalf("applying progress:\n%s", model.View())
|
t.Fatalf("applying progress:\n%s", model.View())
|
||||||
}
|
}
|
||||||
model, command = applyOperationCommand(t, model, command)
|
model, command = applyOperationCommand(t, model, command)
|
||||||
|
|||||||
+30
-15
@@ -2,22 +2,37 @@
|
|||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
repo=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
|
repo=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
|
||||||
readme="$repo/README.md"
|
|
||||||
|
|
||||||
test -s "$readme"
|
require_text() {
|
||||||
for text in \
|
file=$1
|
||||||
'## Install' 'go install ./cmd/proxyctl' '## First use and Profiles' \
|
shift
|
||||||
'## Shell integration' 'Shell' 'APT' 'Docker daemon' \
|
test -s "$file"
|
||||||
'Docker containers/builds' 'GNOME' '## Target states' 'Enabled' \
|
for text
|
||||||
'Disabled' 'External' 'Drifted' '## Permissions, sudo, and restarts' \
|
do
|
||||||
'proxyctl doctor' 'proxyctl reset' 'proxyctl shell uninstall' \
|
grep -Fq "$text" "$file" || {
|
||||||
'no telemetry' 'automatic update checks' 'proxy-connectivity tests' \
|
echo "$file is missing required documentation: $text" >&2
|
||||||
'does **not** manage or supervise proxy processes' 'Support is limited'
|
|
||||||
do
|
|
||||||
grep -Fq "$text" "$readme" || {
|
|
||||||
echo "README is missing required documentation: $text" >&2
|
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
done
|
done
|
||||||
|
}
|
||||||
|
|
||||||
printf 'README documentation contract passed\n'
|
require_text "$repo/README.md" \
|
||||||
|
'## Install' 'go install ./cmd/proxyctl' '## Quick start' \
|
||||||
|
'## Shell integration' 'proxyctl doctor' 'proxyctl reset' \
|
||||||
|
'no telemetry' 'docs/user-guide.md' 'docs/security.md' 'docs/development.md'
|
||||||
|
|
||||||
|
require_text "$repo/docs/user-guide.md" \
|
||||||
|
'## Profiles' 'Protocol Probe' '## Target states' 'Enabled' 'Disabled' \
|
||||||
|
'External' 'Drifted' 'Shell' 'APT' 'Docker daemon' \
|
||||||
|
'Docker containers/builds' 'GNOME' 'NO_COLOR'
|
||||||
|
|
||||||
|
require_text "$repo/docs/security.md" \
|
||||||
|
'proxyctl never starts `sudo`' 'Configuration recovery' \
|
||||||
|
'no automatic update checks' 'does **not** manage or supervise proxy processes' \
|
||||||
|
'Support is limited'
|
||||||
|
|
||||||
|
require_text "$repo/docs/development.md" \
|
||||||
|
'go test ./...' 'go vet ./...' 'test-hermetic.sh' \
|
||||||
|
'test-release.sh' 'verify-clean-machine.sh' 'SHA256SUMS'
|
||||||
|
|
||||||
|
printf 'documentation contract passed\n'
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ snapshot() {
|
|||||||
snapshot >"$work/before"
|
snapshot >"$work/before"
|
||||||
(
|
(
|
||||||
cd "$repo"
|
cd "$repo"
|
||||||
go test ./...
|
go test -count=1 ./...
|
||||||
)
|
)
|
||||||
snapshot >"$work/after"
|
snapshot >"$work/after"
|
||||||
cmp "$work/before" "$work/after"
|
cmp "$work/before" "$work/after"
|
||||||
|
|||||||
@@ -17,15 +17,41 @@ snapshot_host_path() {
|
|||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Avoid pipelines: traversal, stat, hash, and sort failures must stop the
|
stat --printf='top-metadata\t%F\t%a\t%u\t%g\t%N\n' -- "$path"
|
||||||
# verification rather than being mistaken for an unchanged host snapshot.
|
if { [ -d "$path" ] && { [ ! -r "$path" ] || [ ! -x "$path" ]; }; } || \
|
||||||
find -H "$path" -xdev \
|
{ [ ! -d "$path" ] && [ ! -r "$path" ]; };
|
||||||
|
then
|
||||||
|
printf 'unreadable\t%s\n' "$path"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
|
||||||
|
traversal_complete=true
|
||||||
|
if ! find -H "$path" -xdev \
|
||||||
-exec stat --printf='metadata\t%F\t%a\t%u\t%g\t%N\n' -- {} + \
|
-exec stat --printf='metadata\t%F\t%a\t%u\t%g\t%N\n' -- {} + \
|
||||||
>"$work/host-snapshot-metadata"
|
>"$work/host-snapshot-metadata" 2>/dev/null
|
||||||
|
then
|
||||||
|
traversal_complete=false
|
||||||
|
fi
|
||||||
LC_ALL=C sort "$work/host-snapshot-metadata"
|
LC_ALL=C sort "$work/host-snapshot-metadata"
|
||||||
find -H "$path" -xdev -type f -exec sha256sum -- {} + \
|
|
||||||
>"$work/host-snapshot-content"
|
if ! find -H "$path" -xdev \
|
||||||
|
\( \( -type d \( ! -readable -o ! -executable \) \) -o \( -type f ! -readable \) \) \
|
||||||
|
-printf='unreadable\t%p\n' >"$work/host-snapshot-unreadable" 2>/dev/null
|
||||||
|
then
|
||||||
|
traversal_complete=false
|
||||||
|
fi
|
||||||
|
LC_ALL=C sort "$work/host-snapshot-unreadable"
|
||||||
|
|
||||||
|
if ! find -H "$path" -xdev -type f -readable -exec sha256sum -- {} + \
|
||||||
|
>"$work/host-snapshot-content" 2>/dev/null
|
||||||
|
then
|
||||||
|
traversal_complete=false
|
||||||
|
fi
|
||||||
LC_ALL=C sort "$work/host-snapshot-content"
|
LC_ALL=C sort "$work/host-snapshot-content"
|
||||||
|
|
||||||
|
if [ "$traversal_complete" = false ]; then
|
||||||
|
printf 'unreadable-descendant\t%s\n' "$path"
|
||||||
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
snapshot_host() {
|
snapshot_host() {
|
||||||
|
|||||||
Reference in New Issue
Block a user