feat: add diagnostics and safe reset maintenance

This commit is contained in:
proxyctl coordinator
2026-07-17 03:28:29 +08:00
parent 3003450dce
commit d4c76e4b3c
13 changed files with 1041 additions and 23 deletions
+145 -18
View File
@@ -1,14 +1,22 @@
package main
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"syscall"
tea "github.com/charmbracelet/bubbletea"
"golang.org/x/sys/unix"
"proxyctl/internal/app"
"proxyctl/internal/operationlock"
"proxyctl/internal/oplog"
"proxyctl/internal/profile"
"proxyctl/internal/shell"
"proxyctl/internal/target"
@@ -50,31 +58,56 @@ func runWithEnvironment(args []string, input io.Reader, output io.Writer, enviro
return err
}
shellTarget := shell.New(shellConfiguration, files, environment)
targets := []target.Target{shellTarget}
stateDirectory := filepath.Dir(shellConfiguration.RecoveryFile)
mutationLock := operationlock.NewOwned(filepath.Join(stateDirectory, "operation.lock"), 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)
if len(args) != 0 {
if len(args) != 2 || args[0] != "shell" || (args[1] != "install" && args[1] != "uninstall") {
return fmt.Errorf("usage: proxyctl [shell install|shell uninstall]")
}
availability := shellTarget.Availability(context.Background())
if !availability.Available {
return fmt.Errorf("Shell Target unavailable: %s", availability.Evidence)
}
if args[1] == "install" {
if err := shellTarget.Install(context.Background(), executable); err != nil {
return err
switch {
case len(args) == 2 && args[0] == "shell" && (args[1] == "install" || args[1] == "uninstall"):
availability := shellTarget.Availability(context.Background())
if !availability.Available {
return fmt.Errorf("Shell Target unavailable: %s", availability.Evidence)
}
unlock, err := mutationLock.Lock(context.Background())
if err != nil {
return fmt.Errorf("lock proxyctl mutation: %w", err)
}
defer unlock()
operation := "shell-" + args[1]
var operationErr error
if args[1] == "install" {
operationErr = shellTarget.Install(context.Background(), executable)
} else {
operationErr = shellTarget.Uninstall(context.Background())
}
result, detail := "success", "Shell integration changed"
if operationErr != nil {
result, detail = "failure", operationErr.Error()
}
_ = logger.Write(app.LogEntry{Operation: operation, Target: shellTarget.ID(), Result: result, Detail: detail})
if operationErr != nil {
return operationErr
}
if args[1] == "install" {
fmt.Fprintln(output, "Shell integration installed; restart or source your Shell startup file once.")
} else {
fmt.Fprintln(output, "Shell integration uninstalled.")
}
fmt.Fprintln(output, "Shell integration installed; restart or source your Shell startup file once.")
return nil
case len(args) == 1 && args[0] == "doctor":
checks := diagnosticChecks(profileConfiguration)
return runMaintenanceCommand(args, input, output, store, targets, mutationLock, logger, checks)
case len(args) == 1 && args[0] == "reset":
return runMaintenanceCommand(args, input, output, store, targets, mutationLock, logger, nil)
default:
return fmt.Errorf("usage: proxyctl [doctor|reset|shell install|shell uninstall]")
}
if err := shellTarget.Uninstall(context.Background()); err != nil {
return err
}
fmt.Fprintln(output, "Shell integration uninstalled.")
return nil
}
store := profile.NewOwnedFileStoreAt(profileConfiguration.Path, profileConfiguration.Owner, profileConfiguration.TrustedRoot)
application, err := app.NewWithTargets(store, []target.Target{shellTarget})
application, err := app.NewWithTargetsAndRuntime(store, targets, mutationLock, logger)
if err != nil {
return err
}
@@ -82,3 +115,97 @@ func runWithEnvironment(args []string, input io.Reader, output io.Writer, enviro
_, err = program.Run()
return err
}
func runMaintenanceCommand(args []string, input io.Reader, output io.Writer, store *profile.FileStore, targets []target.Target, mutationLock app.MutationLock, logger app.OperationLogger, checks []target.Check) error {
if len(args) != 1 {
return errors.New("invalid maintenance command")
}
if args[0] == "doctor" {
state, err := store.ReadOnlyLoad()
profileCheck := target.Check{Name: "Profile validity", OK: err == nil, Evidence: "Profile configuration is valid"}
if err != nil {
profileCheck.Evidence = err.Error()
}
checks = append([]target.Check{profileCheck}, checks...)
report := app.NewMaintenance(state, targets, nil, nil).Doctor(context.Background(), checks)
fmt.Fprint(output, report.String())
return nil
}
if args[0] != "reset" {
return errors.New("invalid maintenance command")
}
fmt.Fprint(output, "Reset every managed Target and restore recorded original state? [y/N] ")
answer, _ := bufio.NewReader(input).ReadString('\n')
answer = strings.ToLower(strings.TrimSpace(answer))
if answer != "y" && answer != "yes" {
fmt.Fprintln(output, "Reset cancelled; no Targets changed.")
return nil
}
state, err := store.Load()
if err != nil {
return err
}
result := app.NewMaintenance(state, targets, mutationLock, logger).Reset(context.Background(), true)
for _, item := range result.Targets {
if item.Skipped {
fmt.Fprintf(output, "%s: skipped (%s) — %s\n", item.TargetID, item.Inspection.State, profile.RedactText(item.Inspection.Evidence))
continue
}
if item.Err != nil {
fmt.Fprintf(output, "%s: failed (%s) — %s\n", item.TargetID, item.Inspection.State, profile.RedactText(item.Err.Error()))
continue
}
fmt.Fprintf(output, "%s: reset (%s) — %s\n", item.TargetID, item.Inspection.State, profile.RedactText(item.Inspection.Evidence))
}
return result.Err
}
func diagnosticChecks(configuration profile.Configuration) []target.Check {
identity := target.Check{Name: "identity resolution", OK: true, Evidence: fmt.Sprintf("configuration owner %s (uid %d, gid %d)", configuration.Owner.Username, configuration.Owner.UID, configuration.Owner.GID)}
ok, evidence := storagePermissions(configuration)
storage := target.Check{Name: "storage permissions", OK: ok, Evidence: evidence}
return []target.Check{identity, storage}
}
func storagePermissions(configuration profile.Configuration) (bool, string) {
ok, evidence := writableLocation(configuration.Path)
info, err := os.Stat(configuration.Path)
if os.IsNotExist(err) {
return ok, evidence + "; Profile configuration does not exist yet"
}
if err != nil {
return false, evidence + "; Profile configuration cannot be inspected: " + err.Error()
}
if info.Mode().Perm() != 0o600 {
return false, fmt.Sprintf("%s; Profile configuration mode is %o, want 600", evidence, info.Mode().Perm())
}
if stat, present := info.Sys().(*syscall.Stat_t); present && int(stat.Uid) != configuration.Owner.UID {
return false, fmt.Sprintf("%s; Profile configuration owner uid is %d, want %d", evidence, stat.Uid, configuration.Owner.UID)
}
return ok, evidence + "; Profile configuration is owner-only"
}
// writableLocation observes current authority without creating or changing files.
func writableLocation(path string) (bool, string) {
candidate := path
for {
info, err := os.Stat(candidate)
if err == nil {
if !info.IsDir() {
candidate = filepath.Dir(candidate)
}
if err := unix.Access(candidate, unix.W_OK); err != nil {
return false, candidate + " is not writable: " + err.Error()
}
return true, candidate + " is writable"
}
if !os.IsNotExist(err) {
return false, candidate + " cannot be inspected: " + err.Error()
}
parent := filepath.Dir(candidate)
if parent == candidate {
return false, path + " has no writable existing ancestor"
}
candidate = parent
}
}
+128
View File
@@ -0,0 +1,128 @@
package main
import (
"bytes"
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"proxyctl/internal/operationlock"
"proxyctl/internal/oplog"
"proxyctl/internal/profile"
"proxyctl/internal/target"
)
type processFakeTarget struct {
id string
state target.State
err error
calls int
}
func (f *processFakeTarget) ID() string { return f.id }
func (f *processFakeTarget) Description() target.Description { return target.Description{Name: f.id} }
func (f *processFakeTarget) Availability(context.Context) target.Availability {
return target.Availability{Available: true, Evidence: "fake executable found"}
}
func (f *processFakeTarget) Inspect(context.Context, *profile.Profile) target.Inspection {
return target.Inspection{State: f.state, Evidence: "fake evidence for http://alice:secret@proxy.test"}
}
func (f *processFakeTarget) SetDesired(context.Context, bool, *profile.Profile) target.OperationResult {
f.calls++
if f.err == nil {
f.state = target.Disabled
}
return target.OperationResult{Inspection: target.Inspection{State: f.state, Evidence: "re-inspected fake state"}, Err: f.err}
}
func (f *processFakeTarget) DiagnosticChecks(context.Context, *profile.Profile) []target.Check {
return []target.Check{{Name: "required commands", OK: true, Evidence: "fake helper found"}, {Name: "write authority", OK: true, Evidence: "fake location writable"}}
}
func TestDoctorCommandUsesFakeTargetsAndIsolatedXDGWithoutMutation(t *testing.T) {
xdg := filepath.Join(t.TempDir(), "xdg-config")
store := profile.NewFileStore(filepath.Join(xdg, "proxyctl", "profiles.json"))
fake := &processFakeTarget{id: "fake", state: target.External}
var output bytes.Buffer
if err := runMaintenanceCommand([]string{"doctor"}, strings.NewReader(""), &output, store, []target.Target{fake}, nil, nil, []target.Check{{Name: "identity resolution", OK: true, Evidence: "fake user"}, {Name: "storage permissions", OK: true, Evidence: xdg}}); err != nil {
t.Fatal(err)
}
text := output.String()
for _, want := range []string{"Profile validity", "identity resolution", "storage permissions", "Target availability", "External", "required commands", "write authority"} {
if !strings.Contains(text, want) {
t.Errorf("doctor output missing %q: %s", want, text)
}
}
if strings.Contains(text, "secret") {
t.Fatalf("doctor leaked credentials: %s", text)
}
if fake.calls != 0 {
t.Fatalf("doctor mutated fake Target %d times", fake.calls)
}
if _, err := os.Stat(xdg); !os.IsNotExist(err) {
t.Fatalf("doctor created isolated XDG path: %v", err)
}
}
func TestDoctorStoragePermissionCheckIsReadOnly(t *testing.T) {
path := filepath.Join(t.TempDir(), "proxyctl", "profiles.json")
writeConfig(t, path, `{"profiles":[]}`)
if err := os.Chmod(path, 0o644); err != nil {
t.Fatal(err)
}
configuration := profile.Configuration{Path: path, Owner: profile.UserIdentity{UID: os.Getuid(), GID: os.Getgid()}}
checks := diagnosticChecks(configuration)
if checks[1].OK || !strings.Contains(checks[1].Evidence, "want 600") {
t.Fatalf("storage check = %#v", checks[1])
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != 0o644 {
t.Fatalf("doctor permission check changed mode to %o", info.Mode().Perm())
}
}
func TestResetCommandCancellationAndTruthfulPartialFailureWithFakeTargets(t *testing.T) {
root := t.TempDir()
config := filepath.Join(root, "xdg-config", "proxyctl", "profiles.json")
writeConfig(t, config, `{"profiles":[]}`)
store := profile.NewFileStore(config)
good := &processFakeTarget{id: "good", state: target.Enabled}
bad := &processFakeTarget{id: "bad", state: target.Drifted, err: errors.New("remove http://bob:hunter2@proxy.test failed")}
external := &processFakeTarget{id: "external", state: target.External}
stateDir := filepath.Join(root, "xdg-state", "proxyctl")
lock := operationlock.New(filepath.Join(stateDir, "operation.lock"))
logger := oplog.New(filepath.Join(stateDir, "operations.log"), 1024, 1)
var output bytes.Buffer
if err := runMaintenanceCommand([]string{"reset"}, strings.NewReader("no\n"), &output, store, []target.Target{good, bad, external}, lock, logger, nil); err != nil {
t.Fatal(err)
}
if good.calls+bad.calls+external.calls != 0 || !strings.Contains(output.String(), "cancelled") {
t.Fatalf("cancel result output=%q calls=%d/%d/%d", output.String(), good.calls, bad.calls, external.calls)
}
output.Reset()
err := runMaintenanceCommand([]string{"reset"}, strings.NewReader("yes\n"), &output, store, []target.Target{good, bad, external}, lock, logger, nil)
if err == nil {
t.Fatal("partial reset returned success")
}
text := output.String()
if good.calls != 1 || bad.calls != 1 || external.calls != 0 || !strings.Contains(text, "good: reset (Disabled)") || !strings.Contains(text, "bad: failed (Drifted)") || !strings.Contains(text, "external: skipped (External)") {
t.Fatalf("partial reset output=%q calls=%d/%d/%d", text, good.calls, bad.calls, external.calls)
}
if strings.Contains(text, "hunter2") || strings.Contains(err.Error(), "hunter2") {
t.Fatalf("reset leaked credentials: output=%q err=%v", text, err)
}
logData, readErr := os.ReadFile(filepath.Join(stateDir, "operations.log"))
if readErr != nil {
t.Fatal(readErr)
}
if strings.Contains(string(logData), "hunter2") || strings.Contains(string(logData), "bob:") {
t.Fatalf("log leaked full authenticated URL: %s", logData)
}
}