fix: harden maintenance operations

This commit is contained in:
proxyctl coordinator
2026-07-17 03:50:18 +08:00
parent d4c76e4b3c
commit b28ebca2d7
9 changed files with 273 additions and 83 deletions
+22 -1
View File
@@ -51,10 +51,16 @@ func (processEnvironment) LookupEnv(name string) (string, bool) { return os.Look
func runWithEnvironment(args []string, input io.Reader, output io.Writer, environment profile.IdentityEnvironment, files shell.FileSystem, executable string) error {
profileConfiguration, err := profile.ResolveConfiguration(environment)
if err != nil {
if len(args) == 1 && args[0] == "doctor" {
fmt.Fprintf(output, "[FAIL] identity resolution — %s\n", profile.RedactText(err.Error()))
}
return err
}
shellConfiguration, err := shell.ResolveConfiguration(environment)
if err != nil {
if len(args) == 1 && args[0] == "doctor" {
fmt.Fprintf(output, "[FAIL] Shell Target configuration — %s\n", profile.RedactText(err.Error()))
}
return err
}
shellTarget := shell.New(shellConfiguration, files, environment)
@@ -129,6 +135,9 @@ func runMaintenanceCommand(args []string, input io.Reader, output io.Writer, sto
checks = append([]target.Check{profileCheck}, checks...)
report := app.NewMaintenance(state, targets, nil, nil).Doctor(context.Background(), checks)
fmt.Fprint(output, report.String())
if !report.Healthy() {
return errors.New("doctor found configuration problems")
}
return nil
}
if args[0] != "reset" {
@@ -141,11 +150,19 @@ func runMaintenanceCommand(args []string, input io.Reader, output io.Writer, sto
fmt.Fprintln(output, "Reset cancelled; no Targets changed.")
return nil
}
if mutationLock == nil {
return errors.New("mutation lock is not configured")
}
unlock, err := mutationLock.Lock(context.Background())
if err != nil {
return fmt.Errorf("lock proxyctl mutation: %w", err)
}
defer unlock()
state, err := store.Load()
if err != nil {
return err
}
result := app.NewMaintenance(state, targets, mutationLock, logger).Reset(context.Background(), true)
result := app.NewMaintenance(state, targets, heldMutationLock{}, 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))
@@ -160,6 +177,10 @@ func runMaintenanceCommand(args []string, input io.Reader, output io.Writer, sto
return result.Err
}
type heldMutationLock struct{}
func (heldMutationLock) Lock(context.Context) (func(), error) { return func() {}, nil }
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)
+82
View File
@@ -5,6 +5,7 @@ import (
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
@@ -15,6 +16,16 @@ import (
"proxyctl/internal/target"
)
type failingIdentityEnvironment struct{}
func (failingIdentityEnvironment) CurrentUser() (profile.UserIdentity, error) {
return profile.UserIdentity{}, errors.New("identity lookup failed")
}
func (failingIdentityEnvironment) LookupUser(string) (profile.UserIdentity, error) {
return profile.UserIdentity{}, os.ErrNotExist
}
func (failingIdentityEnvironment) LookupEnv(string) (string, bool) { return "", false }
type processFakeTarget struct {
id string
state target.State
@@ -66,6 +77,24 @@ func TestDoctorCommandUsesFakeTargetsAndIsolatedXDGWithoutMutation(t *testing.T)
}
}
func TestDoctorReportsIdentityResolutionFailureStructurally(t *testing.T) {
var output bytes.Buffer
err := runWithEnvironment([]string{"doctor"}, strings.NewReader(""), &output, failingIdentityEnvironment{}, nil, "/test/proxyctl")
if err == nil || !strings.Contains(output.String(), "[FAIL] identity resolution") || !strings.Contains(output.String(), "identity lookup failed") {
t.Fatalf("doctor identity failure err=%v output=%q", err, output.String())
}
}
func TestDoctorReturnsFailureWhenAnyCheckFails(t *testing.T) {
store := profile.NewFileStore(filepath.Join(t.TempDir(), "profiles.json"))
fake := &processFakeTarget{id: "fake", state: target.Drifted}
var output bytes.Buffer
err := runMaintenanceCommand([]string{"doctor"}, strings.NewReader(""), &output, store, []target.Target{fake}, nil, nil, []target.Check{{Name: "identity", OK: true, Evidence: "ok"}})
if err == nil || !strings.Contains(output.String(), "[FAIL]") {
t.Fatalf("unhealthy doctor err=%v output=%q", err, output.String())
}
}
func TestDoctorStoragePermissionCheckIsReadOnly(t *testing.T) {
path := filepath.Join(t.TempDir(), "proxyctl", "profiles.json")
writeConfig(t, path, `{"profiles":[]}`)
@@ -86,6 +115,59 @@ func TestDoctorStoragePermissionCheckIsReadOnly(t *testing.T) {
}
}
func TestMaintenanceCommandsRunThroughBuiltBinaryWithIsolatedXDG(t *testing.T) {
root := t.TempDir()
binary := filepath.Join(root, "proxyctl")
build := exec.Command("go", "build", "-o", binary, ".")
if output, err := build.CombinedOutput(); err != nil {
t.Fatalf("build proxyctl: %v\n%s", err, output)
}
environment := isolatedProcessEnvironment(root)
doctor := exec.Command(binary, "doctor")
doctor.Env = environment
doctorOutput, doctorErr := doctor.CombinedOutput()
if doctorErr == nil || !strings.Contains(string(doctorOutput), "[FAIL]") || !strings.Contains(string(doctorOutput), "Target availability") {
t.Fatalf("doctor process err=%v output=%q", doctorErr, doctorOutput)
}
cancel := exec.Command(binary, "reset")
cancel.Env = environment
cancel.Stdin = strings.NewReader("no\n")
cancelOutput, err := cancel.CombinedOutput()
if err != nil || !strings.Contains(string(cancelOutput), "Reset cancelled") {
t.Fatalf("cancel process err=%v output=%q", err, cancelOutput)
}
confirmed := exec.Command(binary, "reset")
confirmed.Env = environment
confirmed.Stdin = strings.NewReader("yes\n")
confirmedOutput, err := confirmed.CombinedOutput()
if err != nil || !strings.Contains(string(confirmedOutput), "shell: skipped (Disabled)") {
t.Fatalf("confirmed process err=%v output=%q", err, confirmedOutput)
}
if _, err := os.Stat(filepath.Join(root, "home", ".bashrc")); !os.IsNotExist(err) {
t.Fatalf("process smoke test touched a Shell startup file: %v", err)
}
}
func isolatedProcessEnvironment(root string) []string {
blocked := map[string]bool{"HOME": true, "XDG_CONFIG_HOME": true, "XDG_STATE_HOME": true, "SHELL": true, "SUDO_USER": true, "HTTP_PROXY": true, "http_proxy": true, "HTTPS_PROXY": true, "https_proxy": true, "ALL_PROXY": true, "all_proxy": true, "NO_PROXY": true, "no_proxy": true}
environment := make([]string, 0, len(os.Environ())+4)
for _, item := range os.Environ() {
name, _, _ := strings.Cut(item, "=")
if !blocked[name] {
environment = append(environment, item)
}
}
return append(environment,
"HOME="+filepath.Join(root, "home"),
"XDG_CONFIG_HOME="+filepath.Join(root, "config"),
"XDG_STATE_HOME="+filepath.Join(root, "state"),
"SHELL=/bin/fish",
)
}
func TestResetCommandCancellationAndTruthfulPartialFailureWithFakeTargets(t *testing.T) {
root := t.TempDir()
config := filepath.Join(root, "xdg-config", "proxyctl", "profiles.json")