Compare commits

..
6 Commits
Author SHA1 Message Date
proxyctl coordinator 30f7206b14 fix: simplify dashboard and disable unauthorized actions
hermetic-ci / test (push) Canceled after 0s
2026-08-30 15:49:04 +08:00
proxyctl coordinator 416425a9bf docs: streamline README and split detailed guides
hermetic-ci / test (push) Canceled after 0s
2026-08-30 11:35:52 +08:00
proxyctl coordinator 2786b03b96 refactor: simplify path policy and TUI reducers
hermetic-ci / test (push) Canceled after 0s
2026-08-30 11:17:41 +08:00
proxyctl coordinator 8928986830 fix: harden operations and configuration recovery 2026-08-30 11:13:45 +08:00
proxyctl coordinator e34bf7d989 chore: ignore local tooling artifacts
hermetic-ci / test (push) Canceled after 0s
2026-08-30 10:12:39 +08:00
proxyctl coordinator 61e88a6281 chore: move issue tracking to Gitea 2026-08-30 10:00:23 +08:00
78 changed files with 1176 additions and 1003 deletions
-5
View File
@@ -1,5 +0,0 @@
# CodeGraph data files — local to each machine, not for committing.
# Ignore everything in .codegraph/ except this file itself, so transient
# files (the database, daemon.pid, sockets, logs) never show up in git.
*
!.gitignore
+8
View File
@@ -0,0 +1,8 @@
# Local tool state
/.codegraph/
# Local build and test artifacts
/proxyctl
/dist/
/coverage.out
/*.test
@@ -1,18 +0,0 @@
# 01 — Create and activate persistent Proxy Profiles
**What to build:** A runnable `proxyctl` TUI in which a user can manage validated Proxy Profiles and select an Active Profile, establishing the first complete path from keyboard interaction through the Application Module to durable configuration.
**Blocked by:** None — can start immediately.
**Status:** done
- [ ] Running `proxyctl` without arguments opens a keyboard-driven TUI and shows the Active Profile or a clear no-Profile state.
- [ ] The Profile page lets the user create, view, edit, delete, and activate uniquely named Proxy Profiles.
- [ ] Single proxy mode accepts one URL and expands it for compatible protocol uses without losing the user's value when advanced editing is opened.
- [ ] Advanced mode supports distinct HTTP, HTTPS, and ALL/SOCKS URLs.
- [ ] URL validation accepts only HTTP, HTTPS, SOCKS5, and SOCKS5H with valid hosts and ports and presents actionable validation errors.
- [ ] Bypass validation accepts exact hostnames, domain suffixes, IPv4, IPv6, and CIDR, then normalizes and deduplicates entries.
- [ ] No Profile is guessed or created automatically; the main page remains accessible when no Active Profile exists.
- [ ] Profile configuration follows XDG conventions, is written atomically, and is restricted to the owning user.
- [ ] Proxy passwords are obscured in rendered output and redacted from all errors produced by this slice.
- [ ] Application-level tests drive Profile behavior through the Interface consumed by the TUI rather than private helpers.
@@ -1,20 +0,0 @@
# 02 — Safely control the Shell Target
**What to build:** The first complete Target Adapter, allowing Bash and Zsh users to enable or disable the Active Profile from the TUI and have the invoking parent Shell synchronize after exit, while establishing the reusable Target seam and safety model for later integrations.
**Blocked by:** 01 — Create and activate persistent Proxy Profiles.
**Status:** done
- [ ] A shared Target Interface exposes description, inspection, and desired-state operations without leaking platform paths or commands to the TUI.
- [ ] The Shell Target is Available only for detected Bash or Zsh environments; unsupported Shells are explained outside the main Target list.
- [ ] Enabling writes the Active Profile as conventional upper- and lower-case HTTP, HTTPS, ALL, and bypass environment assignments.
- [ ] Disabling emits the required unsets and restores any prior recognized Shell proxy state rather than silently discarding it.
- [ ] Attempts to enable without an Active Profile fail immediately with a route to Profile management.
- [ ] Inspection distinguishes Enabled, Disabled, External, and Drifted according to the glossary.
- [ ] The TUI shows an applying state and changes the switch only after success; failures preserve or re-inspect the actual state and show a redacted explanation.
- [ ] Shell integration install and uninstall operations are explicit, idempotent, and preserve unrelated user startup configuration.
- [ ] After an integrated TUI invocation exits, the parent Bash or Zsh session loads the generated assignments or unsets.
- [ ] Recovery metadata follows XDG state conventions, uses atomic writes and owner-only permissions where secrets may be present.
- [ ] When invoked through `sudo`, Profile and user Target state resolve to the invoking user; a direct root login resolves to root.
- [ ] A reusable Target contract harness verifies availability, all four states, enable, disable, restoration, idempotency, validation failure, permission failure, partial failure, and secret redaction without touching the host Shell configuration.
-18
View File
@@ -1,18 +0,0 @@
# 03 — Control the APT Target
**What to build:** An APT Target that persistently applies the Active Profile on Debian-family systems, preserves pre-existing APT proxy behavior, and reports real configuration and permission outcomes through the common Target experience.
**Blocked by:** 02 — Safely control the Shell Target.
**Status:** done
- [ ] APT is Available only when the expected Debian-family tooling and configuration capability are detected.
- [ ] The Target explanation states that APT supports proxy environment variables and that this integration provides persistent, privilege-boundary-safe configuration.
- [ ] Enabling uses an isolated `proxyctl`-owned overlay wherever supported and does not rewrite unrelated APT configuration.
- [ ] Disabling removes only the managed overlay and restores any previously effective recognized configuration.
- [ ] Inspection reports Enabled when effective managed values match the Active Profile, External for recognized non-managed proxy settings, Drifted for mismatched managed settings, and Disabled otherwise.
- [ ] Supported Profile protocol values and Bypass entries are translated without silently omitting data.
- [ ] An incompatible protocol or Bypass entry prevents mutation and identifies the incompatible value.
- [ ] Missing write authority produces immediate permission feedback and leaves or re-inspects the actual state.
- [ ] Repeated enable and disable operations are idempotent.
- [ ] Adapter contract and Target-specific tests use an isolated filesystem and fake APT command behavior; they never modify host package-manager configuration.
@@ -1,18 +0,0 @@
# 04 — Control the Docker containers/builds Target
**What to build:** A Docker client Target that applies the Active Profile as defaults for new containers and builds while preserving unrelated client configuration and clearly distinguishing this behavior from Docker daemon proxying.
**Blocked by:** 02 — Safely control the Shell Target.
**Status:** done
- [ ] The Target is Available when the standard Docker client configuration model can be used for the owning user.
- [ ] Its explanation states that it affects new containers and builds, not Docker daemon registry access or existing containers.
- [ ] Enabling safely merges managed proxy defaults without removing unrelated Docker client settings.
- [ ] Disabling restores recognized prior proxy defaults and retains all unrelated configuration.
- [ ] Inspection distinguishes Enabled, Disabled, External, and Drifted, including externally edited managed values.
- [ ] HTTP, HTTPS, ALL/SOCKS, and Bypass values are applied only where Docker's documented model can represent them.
- [ ] Unsupported Profile data prevents mutation and is reported rather than silently discarded.
- [ ] Secret-bearing configuration is owner-restricted and credentials are redacted from UI errors and logs.
- [ ] Writes are atomic and repeated operations are idempotent.
- [ ] Adapter contract and Target-specific tests use isolated Docker client configuration and never contact or modify a real Docker daemon.
@@ -1,18 +0,0 @@
# 05 — Control the GNOME desktop proxy Target
**What to build:** A GNOME desktop Target that applies the Active Profile through GNOME's official settings model, restores prior desktop proxy settings safely, and appears only when the required settings schema is available.
**Blocked by:** 02 — Safely control the Shell Target.
**Status:** done
- [ ] The Target is Available only when the expected GNOME settings command and proxy schema are usable for the owning user.
- [ ] The explanation states that it affects applications consuming GNOME system network settings and does not promise coverage of every graphical application.
- [ ] Enabling records the recognized original proxy mode and values before applying the Active Profile.
- [ ] Disabling restores the recorded original settings when managed values remain under `proxyctl` ownership.
- [ ] Inspection distinguishes Enabled, Disabled, External, and Drifted using positive evidence from GNOME settings.
- [ ] HTTP, HTTPS, SOCKS, and Bypass values are translated only when their semantics can be preserved.
- [ ] Any unrepresentable protocol or Bypass rule rejects the operation before mutation with an actionable explanation.
- [ ] Running through `sudo` operates on the invoking user's GNOME settings rather than root's desktop settings.
- [ ] Command, session-bus, schema, and permission failures are reflected immediately without false success.
- [ ] Adapter contract and Target-specific tests use a fake settings command and never modify the active desktop session.
@@ -1,19 +0,0 @@
# 06 — Control the Docker daemon Target
**What to build:** A systemd-managed Docker daemon Target that configures daemon network proxying separately from container defaults and performs an explicit, confirmed restart with truthful post-operation state.
**Blocked by:** 02 — Safely control the Shell Target.
**Status:** done
- [ ] The Target is Available only when a supported systemd-managed Docker daemon is detected.
- [ ] The explanation states that it affects daemon operations such as registry access, not container network traffic or container/build defaults.
- [ ] Pressing Space presents a restart warning before any configuration mutation.
- [ ] Cancelling the warning performs no file write, manager reload, or daemon restart.
- [ ] Confirming applies the compatible Active Profile through a managed daemon configuration surface, reloads manager configuration as required, and immediately restarts Docker.
- [ ] There is no Pending Restart state; success is reported only after restart and post-operation inspection succeed.
- [ ] Failure to write, reload, or restart produces immediate redacted feedback and re-inspects actual configuration as Enabled, Disabled, External, or Drifted.
- [ ] Existing recognized daemon proxy configuration is preserved and restored when the managed Target is disabled.
- [ ] Unsupported protocol or Bypass data rejects the operation before mutation rather than being omitted.
- [ ] Missing authority is reported as a normal permission error; the Adapter never initiates privilege escalation.
- [ ] Adapter contract and Target-specific tests fake systemd and Docker behavior and prove cancellation, command ordering, restart failure, restoration, and idempotency without touching the host daemon.
@@ -1,18 +0,0 @@
# 07 — Diagnose and reset managed Target state
**What to build:** Operational maintenance behavior that lets users inspect configuration and permission problems, safely restore every managed Target before uninstalling, and troubleshoot failures from bounded redacted local logs.
**Blocked by:** 02 — Safely control the Shell Target.
**Status:** done
- [ ] `proxyctl doctor` performs read-only checks of Profile validity, identity resolution, storage permissions, Target availability, detected state, required commands, and relevant write authority.
- [ ] Diagnostic output states the evidence behind External or Drifted results and redacts all credentials.
- [ ] `proxyctl reset` requires confirmation before changing any Target.
- [ ] A confirmed reset attempts to disable every managed Target through the same Target Interface used by the TUI and restores recorded original state where safe.
- [ ] Reset reports each Target result independently, preserves truthful state after partial failure, and exits unsuccessfully when any requested cleanup fails.
- [ ] Cancellation performs no Target mutation.
- [ ] Mutating operations are protected against concurrent `proxyctl` processes so recovery metadata cannot be corrupted.
- [ ] Local logs record operation type, Target, result, and redacted failure detail without credentials or full authenticated URLs.
- [ ] Log growth is bounded through rotation or equivalent retention behavior.
- [ ] The maintenance commands have process-level tests using fake Targets and isolated XDG locations; tests never modify the host system.
@@ -1,20 +0,0 @@
# 08 — Coordinate the Active Profile and complete the Target panel
**What to build:** The complete everyday TUI experience across all first-release Targets, including dynamic discovery, contextual help, coordinated Active Profile changes, immediate per-Target progress, and safe handling of Profile deletion.
**Blocked by:** 03 — Control the APT Target; 04 — Control the Docker containers/builds Target; 05 — Control the GNOME desktop proxy Target; 06 — Control the Docker daemon Target; 07 — Diagnose and reset managed Target state.
**Status:** done
- [ ] The main panel lists only Available Targets and refreshes availability and state on demand.
- [ ] The help page lists every built-in Target, including hidden Targets and the reason each was not detected.
- [ ] The selected Target's summary explains effects, non-effects, configuration ownership, expected permissions, and relevant side effects.
- [ ] Arrow keys and `j`/`k` navigate, Space toggles, `p` opens Profile management, `r` refreshes, `?` opens help, and `q`/Escape returns or exits consistently.
- [ ] The Active Profile is always visible on the main panel, including a clear absent state.
- [ ] Attempting to enable any Target without an Active Profile fails immediately and points to Profile management; disabling remains possible.
- [ ] Changing the Active Profile updates every Enabled Target one at a time and reflects progress and completion immediately on each row.
- [ ] A cross-Target partial failure keeps successful updates, re-inspects failed Targets, marks Drifted where appropriate, and presents a redacted summary without attempting global rollback.
- [ ] Deleting the final Proxy Profile requires confirmation, leaves existing managed configuration in place as Drifted, and prevents re-enabling until a new Active Profile exists.
- [ ] External configuration can be temporarily overlaid by the Active Profile and is restored to External when the managed Target is disabled.
- [ ] TUI tests cover key-to-intent mapping, page transitions, Active Profile rendering, all Target states, confirmation dialogs, progress, errors, and explanations without duplicating Application behavior tests.
- [ ] Full Application integration tests exercise multiple fake and real hermetic Adapters through Active Profile switching and partial failure.
-18
View File
@@ -1,18 +0,0 @@
# 09 — Publish a verifiable proxyctl v1
**What to build:** A documented and reproducible first release that users on Linux amd64 and arm64 can install, verify, operate safely, diagnose, and remove without relying on distribution-specific packaging.
**Blocked by:** 08 — Coordinate the Active Profile and complete the Target panel.
**Status:** done
- [ ] `proxyctl version` reports the build version in human-readable and script-friendly output.
- [ ] Process-level smoke tests cover default TUI startup, version, doctor, reset confirmation, and Shell integration install/uninstall using an isolated environment.
- [ ] The full automated suite proves no test modifies real Shell startup files, package-manager configuration, Docker state, GNOME settings, or system services.
- [ ] Reproducible release automation builds single Linux binaries for amd64 and arm64.
- [ ] Release automation emits SHA-256 checksums for every distributed binary or archive.
- [ ] User documentation explains installation, first Profile creation, Shell integration, each Target's effects, all status meanings, permission behavior, explicit `sudo` use, Docker restart risk, diagnostics, reset, and uninstall cleanup.
- [ ] Documentation states that `proxyctl` does not manage proxy processes, test connectivity, elevate privileges internally, collect telemetry, or check for updates automatically.
- [ ] Documentation identifies the supported Linux, Shell, APT, Docker, and GNOME boundaries and the intentionally deferred integrations.
- [ ] Source installation through Go tooling works without relying on deb, rpm, AUR, Snap, Flatpak, or another distribution package.
- [ ] A clean-machine verification demonstrates installation, a Profile workflow, at least one hermetic Target workflow, diagnosis, reset, and removal.
@@ -1,19 +0,0 @@
# 01 — Build the responsive TUI foundation
**What to build:** Replace the current unbounded terminal document with a responsive, styled application shell that preserves the existing reachable workflows while establishing the layout, theme, redaction, and page seams required by the redesign.
**Blocked by:** None — can start immediately.
**Status:** done
- [x] Bubble Tea remains the runtime, with Bubbles and Lip Gloss available as direct production dependencies.
- [x] Production runs in the terminal alternate screen and restores the previous screen on normal exit.
- [x] The complete TUI Model handles terminal resize messages and renders a usable wide layout at 120×36.
- [x] The same Model renders a usable single-column layout at 80×24.
- [x] Terminals below 60×16 render a concise minimum-size message instead of a corrupted interface.
- [x] Selection and focus survive resize whenever their referenced item still exists.
- [x] Semantic styling supports light, dark, and `NO_COLOR` rendering without making color the only signal.
- [x] All text entering the presentation layer crosses one defensive credential-redaction path.
- [x] Application coordination, responsive layout, semantic theme, pages, and reusable rendering no longer accumulate in one monolithic implementation.
- [x] Existing Target and Proxy Profile workflows remain reachable; no long-lived legacy/new TUI switch is introduced.
- [x] Complete-Model tests cover the three agreed terminal-size classes.
@@ -1,20 +0,0 @@
# 02 — Deliver the Operations Console dashboard
**What to build:** Give users the accepted Operations Console experience: a stable, scannable Target list and concise selected-Target details, side by side on wide terminals and stacked on narrow terminals.
**Blocked by:** 01 — Build the responsive TUI foundation.
**Status:** done
- [x] The header shows a compact proxyctl identity, the Active Profile, and counts for the current Target states.
- [x] Available Targets appear in stable product order by default.
- [x] A contextual action reveals unavailable Targets and their detection evidence without changing product order.
- [x] Each Target row combines a standard Unicode/ASCII-safe symbol, explicit state text, and semantic styling.
- [x] The selected Target details prioritize state, evidence, affected scope, permissions, ownership/restoration implications, and restart risk.
- [x] Wide terminals show Target list and details panes side by side; narrow terminals stack the same regions.
- [x] Tab changes pane focus, the focused pane is visible without relying only on color, and arrows navigate within the focused pane.
- [x] Long Target lists and details remain reachable through list/viewport scrolling.
- [x] The footer shows only actions valid for the current focus and state.
- [x] Resizing preserves selection by Target identity rather than fragile row position.
- [x] Complete-Model tests cover every Target state, unavailable visibility, long content, focus, scrolling, and wide/narrow rendering.
- [x] Production rendering is rewritten from the spec; prototype branch `prototype/tui-operations-console` commit `364f28d` is reference material only and is not copied into production.
@@ -1,23 +0,0 @@
# 03 — Stream progressive startup and refresh
**What to build:** Show the dashboard immediately and update each Target independently as detection completes, both at startup and when the user refreshes.
**Blocked by:** 02 — Deliver the Operations Console dashboard.
**Status:** done
- [x] Interactive application construction exposes Target identity and descriptions before availability and inspection complete.
- [x] Startup renders every known Target in a structured Checking state without waiting for aggregate detection.
- [x] Availability and inspection results stream to the TUI one Target at a time.
- [x] Refresh uses the same progressive behavior rather than a separate aggregate-only path.
- [x] Checking rows display a non-color-only progress cue and update independently on success or failure.
- [x] Independent completion order does not reorder Targets or move selection to a different identity.
- [x] A Target detection failure is represented truthfully without preventing unrelated Target results from appearing.
- [x] The progressive Application Interface contains presentation-independent phases and results rather than Bubble Tea types or strings that callers must parse.
- [x] Existing non-interactive maintenance behavior remains compatible.
- [x] Application tests cover independent completion order, mixed success/failure, and final snapshots.
- [x] Complete-Model tests prove the first useful frame precedes detection completion and each subsequent result updates only the relevant row.
## Answer
Progressive startup and refresh now publish authoritative Application snapshots per Target while generation checks discard stale overlapping results. Application state and snapshots share one lock, dispatch invalidates in-flight detection before committing mutations, and the dashboard retains selected Target identity—including a newly unavailable selected Target. Adapter detection failures are classified truthfully without changing maintenance inspection semantics.
@@ -1,21 +0,0 @@
# 04 — Unify operation coordination and status feedback
**What to build:** Give every interactive operation one coherent model for progress, serialization, confirmations, current status, partial failure, and safe exit while keeping the dashboard browsable.
**Blocked by:** 03 — Stream progressive startup and refresh.
**Status:** done
- [x] Detection, Target mutation, and Active Profile transition use one presentation-independent progressive operation contract where their semantics overlap.
- [x] System mutations remain serialized and a conflicting action exposes an actionable disabled reason instead of silently ignoring input.
- [x] During a mutation, users can still select Targets, scroll details, and open existing read-only Help.
- [x] The affected Target row displays progress while the status area describes the current step.
- [x] Successful status is replaceable by later activity.
- [x] Current errors remain visible until acknowledged, superseded by explicit resolution, or replaced by a directly related result.
- [x] Current error details can be expanded without introducing an activity-history page.
- [x] Partial Active Profile transitions retain successful Target updates, preserve the no-cross-Target-rollback rule, and focus the first failed Target.
- [x] Confirmation state, progress, and final result are structured; the TUI does not parse user-facing strings to infer operation state.
- [x] `q` on the dashboard and Ctrl+C on any page request exit; during a mutation the UI visibly reports deferred exit and exits only after safe completion.
- [x] No new work can begin after deferred exit is requested.
- [x] The concrete Application remains usable by existing synchronous callers while obsolete interactive fallback paths are removed after migration.
- [x] Application and complete-Model tests cover browsing while busy, blocked mutations, persistent errors, partial failure, confirmation, and deferred exit.
@@ -1,24 +0,0 @@
# 05 — Add contextual Target actions and Drift Resolution
**What to build:** Replace the ambiguous Target toggle with actions that reflect the selected Target's real state, including explicit Drift Resolution choices.
**Blocked by:** 04 — Unify operation coordination and status feedback.
**Status:** done
- [x] A Disabled Target offers Enable.
- [x] An Enabled Target offers Disable.
- [x] An External Target offers Apply Profile and explains that proxyctl will begin managing the configuration while preserving restorable state.
- [x] A Drifted Target offers Resolve rather than silently choosing a direction.
- [x] Drift Resolution offers Reapply Active Profile and Restore Original as separate intents.
- [x] Reapply uses the Active Profile and returns truthful Enabled, Drifted, or failure state.
- [x] Restore Original reuses existing ownership safeguards and refuses safely when restoration evidence is insufficient.
- [x] No Adapter ownership, restoration, or cross-Target rollback semantics are weakened.
- [x] Docker restart confirmation remains required for relevant actions and cancellation is the default focused choice.
- [x] Routine reversible actions do not gain new confirmation dialogs.
- [x] Action availability and disabled reasons are structured in the Application snapshot rather than inferred from rendered labels.
- [x] Application and complete-Model tests cover all Target states, both Drift Resolution branches, missing Active Profile, ownership loss, confirmation, and cancellation without mutation.
## Answer
The Application snapshot now exposes contextual Target actions and Drift Resolution choices as structured availability plus disabled reasons. Dispatch revalidates every Target intent against that current structure immediately before confirmation or `SetDesired`, so stale, checking, failed, unavailable, profile-dependent, and ownership-sensitive intents fail without unsafe mutation. Reapply and Restore retain Adapter `SetDesired` semantics and existing restoration safeguards, while the complete Model preserves explicit resolution and safe-default confirmation/cancellation behavior.
@@ -1,19 +0,0 @@
# 06 — Add the searchable Active Profile picker
**What to build:** Let users search for and activate a Proxy Profile directly from the dashboard without mixing routine switching with Profile management.
**Blocked by:** 02 — Deliver the Operations Console dashboard; 04 — Unify operation coordination and status feedback.
**Status:** done
- [x] A dashboard action opens a keyboard-only modal Profile picker.
- [x] The Active Profile is pinned first and all remaining Profiles are sorted by name.
- [x] The picker supports filtering and scrolling across more Profiles than fit in the terminal.
- [x] Enter activates the selected Profile and Escape closes the picker without mutation.
- [x] Activation uses the unified progressive operation contract and displays per-Target progress on the dashboard.
- [x] Docker restart confirmation appears when required, with cancellation as the safe default.
- [x] Partial failure retains successful Target updates, closes or preserves the picker predictably, and focuses the first failed Target.
- [x] Search text and selection survive resize when the selected Profile still exists.
- [x] Empty and no-match states provide clear next actions without conflating switching with creation.
- [x] Profile names and all operation text are defensively redacted before rendering.
- [x] Complete-Model tests cover ordering, search, keyboard selection, resize, activation, confirmation, cancellation, partial failure, and empty states.
@@ -1,19 +0,0 @@
# 07 — Build the dedicated Profile management page
**What to build:** Provide a scrollable keyboard-first page for creating, editing, reviewing, and deleting Proxy Profiles while keeping activation in the dashboard picker.
**Blocked by:** 01 — Build the responsive TUI foundation; 04 — Unify operation coordination and status feedback.
**Status:** done
- [x] Profile management is a distinct page from the dashboard activation picker.
- [x] The Profile list scrolls and keeps selection visible with more entries than fit on screen.
- [x] The selected Profile's mode, obscured URLs, and Bypass values are reviewable without exposing credentials.
- [x] Create, edit, and delete entry points are available through contextual keyboard actions.
- [x] Deletion uses a reusable confirmation dialog with cancellation focused by default.
- [x] Deleting the final Proxy Profile clearly explains that existing managed configuration remains and becomes Drifted.
- [x] Escape and `q` return to the previous page; Ctrl+C follows the global exit contract.
- [x] Operations disabled by in-flight work expose a reason rather than silently ignoring input.
- [x] Selection and viewport survive resize and CRUD results whenever the referenced Profile still exists.
- [x] Empty-state copy provides a direct creation path and does not incorrectly claim no Active Profile when non-active Profiles exist.
- [x] Complete-Model tests cover long lists, details, create/edit entry, deletion confirmation, final deletion, cancellation, resize, and navigation consistency.
@@ -1,19 +0,0 @@
# 08 — Deliver the mature Profile editor
**What to build:** Replace append-only Profile editing with efficient terminal text inputs, precise validation, and a live Bypass interpretation that users can trust before saving.
**Blocked by:** 07 — Build the dedicated Profile management page.
**Status:** done
- [x] Name and URL fields support insertion, cursor movement, Home, End, Delete, Backspace, paste, and horizontal scrolling.
- [x] Focus is explicit and remains understandable without color.
- [x] Single and Advanced mode transitions preserve values according to existing Proxy Profile semantics.
- [x] Field-specific validation appears beside the relevant field and updates when input changes.
- [x] Save uses the same canonical Profile validation semantics as the live feedback, preventing contradictory results.
- [x] Bypass accepts efficient delimited input and displays a live normalized, deduplicated preview.
- [x] Invalid Bypass entries are identified individually without hiding valid entries.
- [x] Proxy credentials remain obscured during entry, scrolling, validation, review, errors, and resize.
- [x] Save returns to management with the saved Profile selected; cancel leaves persistence unchanged.
- [x] Long URLs and Bypass content remain usable at 80×24.
- [x] Complete-Model tests cover editing operations, paste, horizontal scrolling, mode transitions, validation lifecycle, Bypass preview, save, cancel, resize, and adversarial secret-bearing input.
@@ -1,19 +0,0 @@
# 09 — Attach Protocol Probe to the Profile field
**What to build:** Make Protocol Probe an explicit, user-initiated URL-field action whose progress and result remain attached to the input that produced them.
**Blocked by:** 08 — Deliver the mature Profile editor.
**Status:** done
- [x] The applicable URL field visibly offers Protocol Probe and documents its keyboard shortcut.
- [x] Probe never runs when the form opens, when focus changes, or when a Profile is saved.
- [x] Progress, endpoint-safe status, and detected capabilities render with the initiating field rather than as unrelated global status.
- [x] HTTP-only detection populates the established HTTP representation.
- [x] SOCKS5-only detection preserves the established `socks5h` semantics.
- [x] Dual HTTP/SOCKS5 detection creates the established compatible Advanced Profile values.
- [x] Editing the relevant URL, changing mode, saving, or cancelling invalidates an in-flight result.
- [x] Repeated invocation while the same probe is active does not start duplicate work.
- [x] Userinfo and credentials never appear in dial evidence, status, errors, or rendered frames.
- [x] Failure and unrecognized-protocol results leave user input editable and do not prevent saving a manually chosen value.
- [x] Complete-Model tests cover all capabilities, failure, explicit invocation, no hidden network work, duplicate suppression, resize, and every stale-result path.
@@ -1,19 +0,0 @@
# 10 — Unify Help, dialogs, and navigation
**What to build:** Give every page a consistent keyboard navigation and modal model, with scrollable contextual Help that can be consulted without losing current work.
**Blocked by:** 04 — Unify operation coordination and status feedback; 07 — Build the dedicated Profile management page.
**Status:** done
- [x] Help opens as a scrollable contextual dialog over the current page rather than an unbounded static document.
- [x] Help describes actions valid for the current page, focus, Target state, and operation state.
- [x] Escape closes the top dialog or returns one page level.
- [x] `q` returns from child pages and exits only from the dashboard.
- [x] Ctrl+C requests exit from every page and follows deferred-exit safety during mutations.
- [x] Closing a dialog restores the prior page, focus, selection, and viewport when still valid.
- [x] Dialog stacking and confirmation precedence are deterministic; an input cannot accidentally act on content behind a dialog.
- [x] Dialogs resize within the agreed terminal bounds and preserve meaningful focus.
- [x] Help can be opened and scrolled during a mutation while conflicting actions remain disabled.
- [x] Footer hints agree with actual accepted keys, including cancel and back behavior.
- [x] Complete-Model tests cover Help from every page, long Help, nested dialog precedence, resize, focus restoration, `q`, Escape, Ctrl+C, and in-flight operation behavior.
@@ -1,24 +0,0 @@
# 11 — Harden accessibility, privacy, and rendering
**What to build:** Verify and finish the redesigned TUI across supported terminal sizes, color modes, hostile text, and process lifecycle so that visual polish does not compromise meaning, privacy, or reliability.
**Blocked by:** 03 — Stream progressive startup and refresh; 04 — Unify operation coordination and status feedback; 05 — Add contextual Target actions and Drift Resolution; 06 — Add the searchable Active Profile picker; 07 — Build the dedicated Profile management page; 08 — Deliver the mature Profile editor; 09 — Attach Protocol Probe to the Profile field; 10 — Unify Help, dialogs, and navigation.
**Status:** done
- [x] Fixed-size render coverage includes 120×36, 80×24, and 59×15 across the completed workflows.
- [x] Light, dark, and `NO_COLOR` renders retain readable state, focus, progress, warnings, disabled actions, and errors.
- [x] Standard Unicode symbols have a safe rendering strategy and no Nerd Font dependency.
- [x] Long Target names, Profile names, evidence, details, URLs, Bypass values, errors, and confirmation copy remain bounded and reachable.
- [x] Secrets injected through valid and malformed Profile fields, evidence, notices, errors, progress, command output, and confirmations never appear in any rendered frame.
- [x] Resize stress preserves valid page, dialog, focus, selection, viewport, in-flight operation, and deferred-exit state.
- [x] Alternate-screen process tests verify normal exit and safe deferred exit restore the prior terminal screen.
- [x] Startup, refresh, Target action, Active Profile switching, management, editor, Probe, Help, and Drift Resolution each have complete-Model behavioral coverage.
- [x] Tests assert semantic behavior rather than private component structure or raw styling calls.
- [x] Existing Application and Adapter suites remain green without duplicating Target configuration tests in the TUI.
- [x] Documentation describes the redesigned keyboard model, responsive size behavior, Profile switching, contextual Target actions, and privacy boundaries.
- [x] Full repository and hermetic verification pass without modifying real Shell, APT, Docker, GNOME, or systemd state.
## Answer
Final hardening now exercises every completed workflow through the production Model at all supported size classes, checks semantic equivalence across light, dark, and `NO_COLOR`, uses cell-width bounds for Unicode content, rejects private-use/Nerd Font glyphs, and preserves complete interaction state through resize stress. Every untrusted ingress is credential-redacted and stripped of terminal controls before semantic styling; the final frame pass only validates controls and does not reparse clipped prose. Long fields, Bypass previews, errors, and arbitrary confirmation copy remain scrollable through resize at nonterminal offsets. Real subprocess tests under a PTY prove alternate-screen restoration after normal exit and after exit is deferred for an already-blocked Target mutation. Unprivileged hermetic verification hashes all readable host paths and compares stable metadata plus explicit markers for protected paths without sudo. README documents the final keyboard, responsive, contextual-action, accessibility, lifecycle, and privacy contracts.
+2 -2
View File
@@ -1,8 +1,8 @@
## Agent skills ## Agent skills
### Issue tracker ### Issue tracking
Issues are tracked as local Markdown files under `.scratch/`. See `docs/agents/issue-tracker.md`. Issues are managed in the repository's Gitea issue tracker. Use `tea` for issue operations; do not create local ticket trees. Long-lived product and design specifications belong under `docs/specs/`.
### Domain docs ### Domain docs
+51 -88
View File
@@ -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
View File
@@ -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.")
+2 -2
View File
@@ -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())
} }
} }
+5 -7
View File
@@ -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")
+6 -2
View File
@@ -17,8 +17,12 @@ This is a single-context repo:
``` ```
/ /
├── CONTEXT.md ├── CONTEXT.md
├── docs/adr/ ├── docs/
└── src/ │ ├── adr/
│ ├── research/
│ └── specs/
├── cmd/
└── internal/
``` ```
## Use the glossary's vocabulary ## Use the glossary's vocabulary
-30
View File
@@ -1,30 +0,0 @@
# Issue tracker: Local Markdown
Issues and specs for this repo live as Markdown files in `.scratch/`.
## Conventions
- One feature per directory: `.scratch/<feature-slug>/`
- The spec is `.scratch/<feature-slug>/spec.md`
- Implementation issues are one file per ticket at
`.scratch/<feature-slug>/issues/<NN>-<slug>.md`
- Tickets are numbered from `01`
- Comments and conversation history are appended under `## Comments`
## When a skill says "publish to the issue tracker"
Create a new file under `.scratch/<feature-slug>/`, creating the directory if needed.
## When a skill says "fetch the relevant ticket"
Read the referenced file. The user will normally provide its path or issue number.
## Wayfinding operations
- Map: `.scratch/<effort>/map.md`
- Child ticket: `.scratch/<effort>/issues/NN-<slug>.md`
- `Type:` records `research`, `prototype`, `grilling`, or `task`
- `Status:` records `claimed` or `resolved`
- `Blocked by: NN, NN` declares blocking relationships
- Claim a ticket by setting `Status: claimed`
- Resolve it by adding `## Answer`, setting `Status: resolved`, and updating the map
+36
View File
@@ -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.
+54
View File
@@ -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.
@@ -1,5 +1,3 @@
Status: ready-for-agent
# proxyctl v1 specification # proxyctl v1 specification
## Problem Statement ## Problem Statement
@@ -1,5 +1,3 @@
Status: ready-for-agent
# Efficient professional TUI redesign # Efficient professional TUI redesign
## Problem Statement ## Problem Statement
+75
View File
@@ -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.
+122 -66
View File
@@ -2,9 +2,10 @@ package app
import ( import (
"context" "context"
"crypto/sha256"
"encoding/hex"
"errors" "errors"
"fmt" "fmt"
"strings"
"sync" "sync"
"time" "time"
@@ -28,11 +29,21 @@ const (
) )
type Intent struct { type Intent struct {
Kind IntentKind Kind IntentKind
Name string Name string
Profile profile.Profile Profile profile.Profile
Confirm bool Confirm bool
TargetID string ConfirmationToken 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.
@@ -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
@@ -186,15 +198,16 @@ func NewWithTargetsAndRuntime(store profile.Store, targets []target.Target, muta
return nil, err return nil, err
} }
a := &Application{ a := &Application{
store: store, store: store,
state: state, state: state,
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),
detectionPhase: make(map[string]TargetDetectionPhase), mutationBlockReasons: make(map[string]string),
detectionErr: make(map[string]error), detectionPhase: make(map[string]TargetDetectionPhase),
mutationLock: mutationLock, detectionErr: make(map[string]error),
logger: logger, mutationLock: mutationLock,
logger: logger,
} }
for _, adapter := range a.targets { for _, adapter := range a.targets {
id := adapter.ID() id := adapter.ID()
@@ -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
@@ -289,8 +310,9 @@ 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 != "" {
confirmation := &Confirmation{Title: "Confirm " + a.targetDescriptions[selectedIndex].Name + " Target change", Summary: warning, token := confirmationToken("target", intent.TargetID, fmt.Sprint(intent.Kind), fmt.Sprint(selectedSnapshot.State), fmt.Sprint(policy.desired), warning)
ConfirmLabel: "Continue", CancelLabel: "Cancel", HighImpact: true} if !intent.Confirm || intent.ConfirmationToken != token {
return Result{Snapshot: a.Snapshot(), ConfirmationRequest: confirmation, confirmation := &Confirmation{Title: "Confirm " + a.targetDescriptions[selectedIndex].Name + " Target change", Summary: warning,
Status: OperationStatus{Summary: confirmation.Title, TargetID: intent.TargetID}} ConfirmLabel: "Continue", CancelLabel: "Cancel", HighImpact: true, Token: token}
return Result{Snapshot: a.Snapshot(), ConfirmationRequest: confirmation,
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
+18 -3
View File
@@ -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() {
+53 -1
View File
@@ -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")
} }
+54 -1
View File
@@ -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
View File
@@ -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
} }
+31 -35
View File
@@ -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
+18 -6
View File
@@ -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)
} }
+35
View File
@@ -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)
}
+31
View File
@@ -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
View File
@@ -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"`
+27
View File
@@ -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}
+36
View File
@@ -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")
+14
View File
@@ -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))
}
+29
View File
@@ -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)
}
})
}
}
+2 -4
View File
@@ -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
+3 -4
View File
@@ -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))
}
+68
View File
@@ -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)
}
}
+15 -20
View File
@@ -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,8 +307,19 @@ func (a *Adapter) disable() error {
if metadata.OriginalScript != nil { if metadata.OriginalScript != nil {
restored = []byte(*metadata.OriginalScript) restored = []byte(*metadata.OriginalScript)
} }
if err := a.writeOwned(a.configuration.EnvironmentFile, restored); err != nil { current, err := a.files.ReadFile(a.configuration.EnvironmentFile)
return fmt.Errorf("restore Shell environment: %w", err) 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 {
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)
+21
View File
@@ -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)
+8
View File
@@ -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 {
+14
View File
@@ -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
+6
View File
@@ -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
+2 -2
View File
@@ -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)
} }
} }
+3 -6
View File
@@ -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 -41
View File
@@ -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
}
+10 -15
View File
@@ -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]")
} }
+7 -45
View File
@@ -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
}
+10 -10
View File
@@ -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",
) )
+9 -6
View File
@@ -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)
}) })
+87 -76
View File
@@ -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,67 +243,79 @@ func driftResolutionAction(selected app.TargetSnapshot, kind app.TargetActionKin
return app.TargetAction{Kind: kind}, false return app.TargetAction{Kind: kind}, false
} }
func (m Model) updateProfilePicker(key tea.KeyMsg) (tea.Model, tea.Cmd) {
switch key.String() {
case "esc":
m.picker.close()
return m, nil
case "enter":
selected, ok := m.picker.selected(m.snapshot)
if !ok {
return m, nil
}
m.picker.close()
return m.beginProfileActivation(app.Intent{Kind: app.ActivateProfile, Name: selected.Name})
default:
return m, m.picker.update(key, m.snapshot)
}
}
func (m Model) updateOperationConfirmation(key tea.KeyMsg) (tea.Model, tea.Cmd) {
switch m.operation.confirmationDialog.update(key.String()) {
case confirmationAccepted:
confirmed, ok := m.operation.confirmedIntent()
if !ok {
return m, nil
}
m.status = ""
return m, m.startOperation(confirmed)
case confirmationCancelled:
m.operation.cancelConfirmation()
}
return m, nil
}
func (m Model) updateDriftResolution(key tea.KeyMsg) (tea.Model, tea.Cmd) {
switch key.String() {
case "enter", "esc", "n", "q":
m.driftResolutionTargetID = ""
return m, nil
case "r", "o":
kind := app.ReapplyActiveProfileAction
if key.String() == "o" {
kind = app.RestoreOriginalAction
}
selected, ok := newTargetCatalog(m.snapshot, true, m.driftResolutionTargetID).selected(m.driftResolutionTargetID)
if !ok {
m.driftResolutionTargetID = ""
m.operation.status = app.OperationStatus{Kind: app.StatusBlocked, Summary: "Drift Resolution is unavailable because the Target is no longer present"}
return m, nil
}
action, ok := driftResolutionAction(selected, kind)
if !ok || !action.Available {
reason := action.DisabledReason
if reason == "" {
reason = "This Drift Resolution action is unavailable"
}
m.operation.status = app.OperationStatus{Kind: app.StatusBlocked, Summary: reason}
return m, nil
}
intent, _ := kind.Intent(selected.ID)
m.driftResolutionTargetID = ""
return m, m.startOperation(intent)
}
return m, nil
}
func (m Model) updateMain(key tea.KeyMsg) (tea.Model, tea.Cmd) { func (m Model) updateMain(key tea.KeyMsg) (tea.Model, tea.Cmd) {
if m.picker.open { if m.picker.open {
switch key.String() { return m.updateProfilePicker(key)
case "esc":
m.picker.close()
return m, nil
case "enter":
selected, ok := m.picker.selected(m.snapshot)
if !ok {
return m, nil
}
m.picker.close()
return m.beginProfileActivation(app.Intent{Kind: app.ActivateProfile, Name: selected.Name})
default:
return m, m.picker.update(key, m.snapshot)
}
} }
if m.operation.confirmation != nil { if m.operation.confirmation != nil {
switch m.operation.confirmationDialog.update(key.String()) { return m.updateOperationConfirmation(key)
case confirmationAccepted:
confirmed, ok := m.operation.confirmedIntent()
if !ok {
return m, nil
}
m.status = ""
return m, m.startOperation(confirmed)
case confirmationCancelled:
m.operation.cancelConfirmation()
}
return m, nil
} }
if m.driftResolutionTargetID != "" { if m.driftResolutionTargetID != "" {
switch key.String() { return m.updateDriftResolution(key)
case "enter", "esc", "n", "q":
m.driftResolutionTargetID = ""
return m, nil
case "r", "o":
kind := app.ReapplyActiveProfileAction
if key.String() == "o" {
kind = app.RestoreOriginalAction
}
selected, ok := newTargetCatalog(m.snapshot, true, m.driftResolutionTargetID).selected(m.driftResolutionTargetID)
if !ok {
m.driftResolutionTargetID = ""
m.operation.status = app.OperationStatus{Kind: app.StatusBlocked, Summary: "Drift Resolution is unavailable because the Target is no longer present"}
return m, nil
}
action, ok := driftResolutionAction(selected, kind)
if !ok || !action.Available {
reason := action.DisabledReason
if reason == "" {
reason = "This Drift Resolution action is unavailable"
}
m.operation.status = app.OperationStatus{Kind: app.StatusBlocked, Summary: reason}
return m, nil
}
intent, _ := kind.Intent(selected.ID)
m.driftResolutionTargetID = ""
return m, m.startOperation(intent)
}
return m, nil
} }
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) {
+16 -3
View File
@@ -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 {
+20
View File
@@ -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
View File
@@ -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 {
return "↑/k ↓/j PgUp/PgDn: browse Tab: focus Targets\n?: help q/Ctrl+C: defer exit; mutations disabled"
}
if width < 70 {
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 { if operation.active {
footer = "↑/k ↓/j PgUp/PgDn: scroll Tab: focus Targets " + visibility + " ?: help\nq/Ctrl+C: defer safe exit; mutations disabled" return "↑/↓: Scroll Tab: Targets ?: Help q: Stop"
} }
return footer return "↑/↓: Scroll Tab: Targets " + visibility + "\np: Profile m: Profiles r: Refresh ?: Help q: Quit"
}
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 {
return actions + "\n?: help q/Ctrl+C: defer exit; mutations disabled"
}
if width < 70 {
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 { if operation.active {
footer = actions + "\n?: help q: defer safe exit; new mutations disabled" return action + " ↑/↓: Select Tab: Details\n?: Help q: Stop"
} }
return footer return action + " ↑/↓: Select Tab: Details " + visibility + "\np: Profile m: Profiles r: Refresh ?: Help q: Quit"
} }
func (p terminalPresentation) profilesView(model presentationState) terminalPage { func (p terminalPresentation) profilesView(model presentationState) terminalPage {
-2
View File
@@ -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 ""
+3 -3
View File
@@ -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())
} }
} }
+1 -1
View File
@@ -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 {
+9 -9
View File
@@ -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"},
+9 -9
View File
@@ -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)
+32 -17
View File
@@ -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' exit 1
do }
grep -Fq "$text" "$readme" || { done
echo "README is missing required documentation: $text" >&2 }
exit 1
}
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'
+1 -1
View File
@@ -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"
+32 -6
View File
@@ -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() {