fix(auth): harden interactive diagnostic lifecycle
This commit is contained in:
@@ -3,12 +3,16 @@
|
||||
package compose
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const finalTerminationBound = 2 * time.Second
|
||||
const processTreeTerminationBound = 2 * time.Second
|
||||
const createNewProcessGroup = 0x00000200
|
||||
|
||||
func configureProcess(command *exec.Cmd) {
|
||||
@@ -19,11 +23,34 @@ func terminateProcess(command *exec.Cmd, done <-chan error) error {
|
||||
if command.Process == nil {
|
||||
return nil
|
||||
}
|
||||
treeErr := terminateWindowsProcessTree(command.Process.Pid)
|
||||
_ = command.Process.Kill()
|
||||
select {
|
||||
case <-done:
|
||||
if treeErr != nil {
|
||||
return ErrProcessReap
|
||||
}
|
||||
return nil
|
||||
case <-time.After(finalTerminationBound):
|
||||
return ErrProcessReap
|
||||
}
|
||||
}
|
||||
|
||||
func terminateWindowsProcessTree(pid int) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), processTreeTerminationBound)
|
||||
defer cancel()
|
||||
command := windowsTreeKillCommand(ctx, pid)
|
||||
command.Stdout = io.Discard
|
||||
command.Stderr = io.Discard
|
||||
if err := command.Run(); err != nil {
|
||||
return ErrProcessReap
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ErrProcessReap
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func windowsTreeKillCommand(ctx context.Context, pid int) *exec.Cmd {
|
||||
return exec.CommandContext(ctx, "taskkill.exe", "/PID", strconv.Itoa(pid), "/T", "/F")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package compose
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWindowsTerminationUsesBoundedExactPIDTreeKillWithoutAShell(t *testing.T) {
|
||||
source, err := os.ReadFile("process_windows.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := string(source)
|
||||
for _, required := range []string{
|
||||
"context.WithTimeout", "exec.CommandContext", `"taskkill.exe"`, `"/PID"`,
|
||||
"strconv.Itoa", `"/T"`, `"/F"`, "io.Discard", "ErrProcessReap",
|
||||
} {
|
||||
if !strings.Contains(text, required) {
|
||||
t.Errorf("process_windows.go is missing %q", required)
|
||||
}
|
||||
}
|
||||
for _, forbidden := range []string{"cmd.exe", "powershell", `exec.Command("taskkill.exe"`} {
|
||||
if strings.Contains(strings.ToLower(text), strings.ToLower(forbidden)) {
|
||||
t.Errorf("process_windows.go contains unsafe command form %q", forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//go:build windows
|
||||
|
||||
package compose
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWindowsTreeKillCommandUsesExactPIDArgumentArray(t *testing.T) {
|
||||
command := windowsTreeKillCommand(context.Background(), 4242)
|
||||
want := []string{"taskkill.exe", "/PID", "4242", "/T", "/F"}
|
||||
if !reflect.DeepEqual(command.Args, want) {
|
||||
t.Fatalf("taskkill args = %#v, want %#v", command.Args, want)
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,10 @@ type boundedRunner interface {
|
||||
RunBounded(context.Context, []string, io.Reader, CaptureLimits) (Result, error)
|
||||
}
|
||||
|
||||
type boundedStreamingRunner interface {
|
||||
RunBoundedStreaming(context.Context, []string, io.Reader, CaptureLimits, func([]byte)) (Result, error)
|
||||
}
|
||||
|
||||
// execRunner executes the Docker CLI. It never invokes a shell.
|
||||
type execRunner struct {
|
||||
binary string
|
||||
@@ -78,10 +82,16 @@ func (r execRunner) Run(ctx context.Context, args []string, stdin io.Reader) (Re
|
||||
|
||||
// RunBounded invokes Docker while enforcing both stream limits during capture.
|
||||
func (r execRunner) RunBounded(ctx context.Context, args []string, stdin io.Reader, limits CaptureLimits) (Result, error) {
|
||||
return r.runBounded(ctx, args, stdin, limits, true)
|
||||
return r.runBounded(ctx, args, stdin, limits, true, nil)
|
||||
}
|
||||
|
||||
func (r execRunner) runBounded(ctx context.Context, args []string, stdin io.Reader, limits CaptureLimits, manageOneShot bool) (Result, error) {
|
||||
// RunBoundedStreaming retains bounded stderr capture while synchronously observing only the
|
||||
// retained prefix. It is used for the one validated interactive device-flow prompt.
|
||||
func (r execRunner) RunBoundedStreaming(ctx context.Context, args []string, stdin io.Reader, limits CaptureLimits, stderrObserver func([]byte)) (Result, error) {
|
||||
return r.runBounded(ctx, args, stdin, limits, true, stderrObserver)
|
||||
}
|
||||
|
||||
func (r execRunner) runBounded(ctx context.Context, args []string, stdin io.Reader, limits CaptureLimits, manageOneShot bool, stderrObserver func([]byte)) (Result, error) {
|
||||
if err := validCaptureLimits(limits); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
@@ -101,8 +111,8 @@ func (r execRunner) runBounded(ctx context.Context, args []string, stdin io.Read
|
||||
configureProcess(command)
|
||||
command.Stdin = stdin
|
||||
overflow := make(chan struct{}, 1)
|
||||
stdout := newCappedBuffer(limits.StdoutBytes, overflow)
|
||||
stderr := newCappedBuffer(limits.StderrBytes, overflow)
|
||||
stdout := newCappedBuffer(limits.StdoutBytes, overflow, nil)
|
||||
stderr := newCappedBuffer(limits.StderrBytes, overflow, stderrObserver)
|
||||
command.Stdout = stdout
|
||||
command.Stderr = stderr
|
||||
if err := command.Start(); err != nil {
|
||||
@@ -128,7 +138,7 @@ func (r execRunner) runBounded(ctx context.Context, args []string, stdin io.Read
|
||||
lifecycleErr = errors.Join(lifecycleErr, ErrProcessReap)
|
||||
}
|
||||
}
|
||||
if interrupted && containerName != "" {
|
||||
if containerName != "" {
|
||||
if err := r.cleanupOneShotContainer(containerName); err != nil {
|
||||
lifecycleErr = errors.Join(lifecycleErr, ErrContainerCleanup)
|
||||
}
|
||||
@@ -138,20 +148,27 @@ func (r execRunner) runBounded(ctx context.Context, args []string, stdin io.Read
|
||||
result.ExitCode = command.ProcessState.ExitCode()
|
||||
}
|
||||
if stdout.Overflowed() || stderr.Overflowed() {
|
||||
return result, errors.Join(ErrOutputLimit, lifecycleErr)
|
||||
return result, joinLifecycleError(ErrOutputLimit, lifecycleErr)
|
||||
}
|
||||
if interrupted {
|
||||
return result, errors.Join(processErr, lifecycleErr)
|
||||
return result, joinLifecycleError(processErr, lifecycleErr)
|
||||
}
|
||||
if processErr == nil {
|
||||
return result, nil
|
||||
return result, lifecycleErr
|
||||
}
|
||||
var exitError *exec.ExitError
|
||||
if errors.As(processErr, &exitError) {
|
||||
result.ExitCode = exitError.ExitCode()
|
||||
return result, processErr
|
||||
return result, joinLifecycleError(processErr, lifecycleErr)
|
||||
}
|
||||
return result, processErr
|
||||
return result, joinLifecycleError(processErr, lifecycleErr)
|
||||
}
|
||||
|
||||
func joinLifecycleError(processErr, lifecycleErr error) error {
|
||||
if lifecycleErr == nil {
|
||||
return processErr
|
||||
}
|
||||
return errors.Join(processErr, lifecycleErr)
|
||||
}
|
||||
|
||||
// NewOneShotContainerName returns a Docker-safe, cross-process unique name with a bounded prefix.
|
||||
@@ -253,7 +270,7 @@ func (r execRunner) cleanupOneShotContainer(name string) error {
|
||||
return nil
|
||||
}
|
||||
limits := CaptureLimits{StdoutBytes: cleanupCaptureBytes, StderrBytes: cleanupCaptureBytes}
|
||||
if _, err := r.runBounded(ctx, []string{"container", "rm", "-f", name}, nil, limits, false); err != nil {
|
||||
if _, err := r.runBounded(ctx, []string{"container", "rm", "-f", name}, nil, limits, false, nil); err != nil {
|
||||
return ErrContainerCleanup
|
||||
}
|
||||
exists, err = r.oneShotContainerExists(ctx, name)
|
||||
@@ -267,7 +284,7 @@ func (r execRunner) oneShotContainerExists(ctx context.Context, name string) (bo
|
||||
limits := CaptureLimits{StdoutBytes: cleanupCaptureBytes, StderrBytes: cleanupCaptureBytes}
|
||||
result, err := r.runBounded(ctx, []string{
|
||||
"container", "ls", "--all", "--quiet", "--filter", "name=^/" + name + "$",
|
||||
}, nil, limits, false)
|
||||
}, nil, limits, false, nil)
|
||||
if err != nil {
|
||||
return false, ErrContainerCleanup
|
||||
}
|
||||
@@ -294,6 +311,22 @@ func RunBounded(runner Runner, ctx context.Context, args []string, stdin io.Read
|
||||
return result, err
|
||||
}
|
||||
|
||||
// RunBoundedStreaming uses the production runner's during-capture observer. Compatibility
|
||||
// runners are observed only after their already-bounded result returns.
|
||||
func RunBoundedStreaming(runner Runner, ctx context.Context, args []string, stdin io.Reader, limits CaptureLimits, stderrObserver func([]byte)) (Result, error) {
|
||||
if err := validCaptureLimits(limits); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
if streaming, ok := runner.(boundedStreamingRunner); ok {
|
||||
return streaming.RunBoundedStreaming(ctx, args, stdin, limits, stderrObserver)
|
||||
}
|
||||
result, err := RunBounded(runner, ctx, args, stdin, limits)
|
||||
if stderrObserver != nil && result.Stderr != "" {
|
||||
stderrObserver([]byte(result.Stderr))
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
|
||||
func validCaptureLimits(limits CaptureLimits) error {
|
||||
if limits.StdoutBytes < 1 || limits.StderrBytes < 1 ||
|
||||
limits.StdoutBytes > maximumCaptureBytes || limits.StderrBytes > maximumCaptureBytes {
|
||||
@@ -323,23 +356,24 @@ type cappedBuffer struct {
|
||||
contents []byte
|
||||
maximum int
|
||||
overflow chan<- struct{}
|
||||
observer func([]byte)
|
||||
exceeded bool
|
||||
}
|
||||
|
||||
func newCappedBuffer(maximum int, overflow chan<- struct{}) *cappedBuffer {
|
||||
func newCappedBuffer(maximum int, overflow chan<- struct{}, observer func([]byte)) *cappedBuffer {
|
||||
capacity := maximum
|
||||
if capacity > 4096 {
|
||||
capacity = 4096
|
||||
}
|
||||
return &cappedBuffer{contents: make([]byte, 0, capacity), maximum: maximum, overflow: overflow}
|
||||
return &cappedBuffer{contents: make([]byte, 0, capacity), maximum: maximum, overflow: overflow, observer: observer}
|
||||
}
|
||||
|
||||
func (b *cappedBuffer) Write(value []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
remaining := b.maximum - len(b.contents)
|
||||
kept := 0
|
||||
if remaining > 0 {
|
||||
kept := len(value)
|
||||
kept = len(value)
|
||||
if kept > remaining {
|
||||
kept = remaining
|
||||
}
|
||||
@@ -352,6 +386,14 @@ func (b *cappedBuffer) Write(value []byte) (int, error) {
|
||||
default:
|
||||
}
|
||||
}
|
||||
var observed []byte
|
||||
if kept > 0 && b.observer != nil {
|
||||
observed = append([]byte(nil), value[:kept]...)
|
||||
}
|
||||
b.mu.Unlock()
|
||||
if len(observed) > 0 {
|
||||
b.observer(observed)
|
||||
}
|
||||
return len(value), nil
|
||||
}
|
||||
|
||||
@@ -397,3 +439,11 @@ func (r InstallationRunner) RunBounded(ctx context.Context, args []string, stdin
|
||||
}
|
||||
return RunBounded(r.Runner, ctx, args, stdin, limits)
|
||||
}
|
||||
|
||||
// RunBoundedStreaming preserves the stderr observer across installation argument injection.
|
||||
func (r InstallationRunner) RunBoundedStreaming(ctx context.Context, args []string, stdin io.Reader, limits CaptureLimits, stderrObserver func([]byte)) (Result, error) {
|
||||
if len(args) > 0 && args[0] == "compose" {
|
||||
return RunBoundedStreaming(r.Runner, ctx, r.Installation.ComposeArgs(args[1:]...), stdin, limits, stderrObserver)
|
||||
}
|
||||
return RunBoundedStreaming(r.Runner, ctx, args, stdin, limits, stderrObserver)
|
||||
}
|
||||
|
||||
@@ -116,6 +116,107 @@ func TestRunnerCleansUpNamedComposeContainerAfterCancellation(t *testing.T) {
|
||||
assertContainerCleanup(t, logFile, marker, name)
|
||||
}
|
||||
|
||||
func TestRunnerVerifiesAndRemovesNamedComposeContainerAfterNormalExit(t *testing.T) {
|
||||
logFile := filepath.Join(t.TempDir(), "calls.log")
|
||||
marker := filepath.Join(t.TempDir(), "container-present")
|
||||
if err := os.WriteFile(marker, []byte("present"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("THT_RUNNER_TEST_LOG", logFile)
|
||||
t.Setenv("THT_RUNNER_TEST_MARKER", marker)
|
||||
t.Setenv("THT_RUNNER_TEST_MODE", "normal")
|
||||
runner := NewRunner(writeExecutable(t, cleanupAwareDockerScript))
|
||||
name := "thothii-cleanup-normal-sentinel"
|
||||
|
||||
result, err := RunBounded(runner, context.Background(), []string{
|
||||
"compose", "run", "--rm", "--name", name, "core",
|
||||
}, nil, CaptureLimits{StdoutBytes: 1024, StderrBytes: 1024})
|
||||
|
||||
if err != nil || result.ExitCode != 0 {
|
||||
t.Fatalf("RunBounded() result=%#v error=%v, want clean exit", result, err)
|
||||
}
|
||||
assertContainerCleanup(t, logFile, marker, name)
|
||||
}
|
||||
|
||||
func TestRunnerVerifiesAndRemovesNamedComposeContainerAfterExpectedExitOne(t *testing.T) {
|
||||
logFile := filepath.Join(t.TempDir(), "calls.log")
|
||||
marker := filepath.Join(t.TempDir(), "container-present")
|
||||
if err := os.WriteFile(marker, []byte("present"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("THT_RUNNER_TEST_LOG", logFile)
|
||||
t.Setenv("THT_RUNNER_TEST_MARKER", marker)
|
||||
t.Setenv("THT_RUNNER_TEST_MODE", "exit-one")
|
||||
runner := NewRunner(writeExecutable(t, cleanupAwareDockerScript))
|
||||
name := "thothii-cleanup-exit-one-sentinel"
|
||||
|
||||
result, err := RunBounded(runner, context.Background(), []string{
|
||||
"compose", "run", "--rm", "--name", name, "core",
|
||||
}, nil, CaptureLimits{StdoutBytes: 1024, StderrBytes: 1024})
|
||||
|
||||
var exitError *exec.ExitError
|
||||
if !errors.As(err, &exitError) || errors.Is(err, ErrContainerCleanup) || result.ExitCode != 1 {
|
||||
t.Fatalf("RunBounded() result=%#v error=%v, want original exit 1", result, err)
|
||||
}
|
||||
assertContainerCleanup(t, logFile, marker, name)
|
||||
}
|
||||
|
||||
func TestRunnerAcceptsANamedOneShotAlreadyRemovedByRm(t *testing.T) {
|
||||
logFile := filepath.Join(t.TempDir(), "calls.log")
|
||||
marker := filepath.Join(t.TempDir(), "container-absent")
|
||||
t.Setenv("THT_RUNNER_TEST_LOG", logFile)
|
||||
t.Setenv("THT_RUNNER_TEST_MARKER", marker)
|
||||
t.Setenv("THT_RUNNER_TEST_MODE", "normal")
|
||||
runner := NewRunner(writeExecutable(t, cleanupAwareDockerScript))
|
||||
name := "thothii-cleanup-already-removed-sentinel"
|
||||
|
||||
result, err := RunBounded(runner, context.Background(), []string{
|
||||
"compose", "run", "--rm", "--name", name, "core",
|
||||
}, nil, CaptureLimits{StdoutBytes: 1024, StderrBytes: 1024})
|
||||
|
||||
if err != nil || result.ExitCode != 0 {
|
||||
t.Fatalf("RunBounded() result=%#v error=%v, want clean exit", result, err)
|
||||
}
|
||||
calls, readErr := os.ReadFile(logFile)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if !strings.Contains(string(calls), "container ls --all --quiet --filter name=^/"+name+"$") ||
|
||||
strings.Contains(string(calls), "container rm -f "+name) {
|
||||
t.Fatalf("Docker calls = %q, want absence verification without forced removal", calls)
|
||||
}
|
||||
if _, statErr := os.Stat(marker); !os.IsNotExist(statErr) {
|
||||
t.Fatalf("named one-shot unexpectedly left residue: %v", statErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerJoinsCleanupFailureAfterNormalExit(t *testing.T) {
|
||||
logFile := filepath.Join(t.TempDir(), "calls.log")
|
||||
marker := filepath.Join(t.TempDir(), "container-present")
|
||||
if err := os.WriteFile(marker, []byte("present"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("THT_RUNNER_TEST_LOG", logFile)
|
||||
t.Setenv("THT_RUNNER_TEST_MARKER", marker)
|
||||
t.Setenv("THT_RUNNER_TEST_MODE", "normal-cleanup-fails")
|
||||
runner := NewRunner(writeExecutable(t, cleanupAwareDockerScript))
|
||||
name := "thothii-cleanup-failure-sentinel"
|
||||
|
||||
result, err := RunBounded(runner, context.Background(), []string{
|
||||
"compose", "run", "--rm", "--name", name, "core",
|
||||
}, nil, CaptureLimits{StdoutBytes: 1024, StderrBytes: 1024})
|
||||
|
||||
if result.ExitCode != 0 || !errors.Is(err, ErrContainerCleanup) {
|
||||
t.Fatalf("RunBounded() result=%#v error=%v, want cleanup failure joined to exit 0", result, err)
|
||||
}
|
||||
if strings.Contains(err.Error(), name) {
|
||||
t.Fatalf("RunBounded() exposed the container name: %v", err)
|
||||
}
|
||||
if _, statErr := os.Stat(marker); statErr != nil {
|
||||
t.Fatalf("cleanup failure test unexpectedly removed marker: %v", statErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerSurfacesCleanupFailureWithoutContainerName(t *testing.T) {
|
||||
logFile := filepath.Join(t.TempDir(), "calls.log")
|
||||
marker := filepath.Join(t.TempDir(), "container-present")
|
||||
@@ -270,13 +371,19 @@ if [ "$1" = "container" ] && [ "$2" = "ls" ]; then
|
||||
exit 0
|
||||
fi
|
||||
if [ "$1" = "container" ] && [ "$2" = "rm" ]; then
|
||||
if [ "$THT_RUNNER_TEST_MODE" = "cleanup-fails" ]; then exit 9; fi
|
||||
case "$THT_RUNNER_TEST_MODE" in *cleanup-fails) exit 9 ;; esac
|
||||
rm -f "$THT_RUNNER_TEST_MARKER"
|
||||
exit 0
|
||||
fi
|
||||
if [ "$THT_RUNNER_TEST_MODE" = "flood" ]; then
|
||||
while :; do printf '0123456789abcdef'; printf 'fedcba9876543210' >&2; done
|
||||
fi
|
||||
if [ "$THT_RUNNER_TEST_MODE" = "normal" ] || [ "$THT_RUNNER_TEST_MODE" = "normal-cleanup-fails" ]; then
|
||||
exit 0
|
||||
fi
|
||||
if [ "$THT_RUNNER_TEST_MODE" = "exit-one" ]; then
|
||||
exit 1
|
||||
fi
|
||||
trap '' TERM INT
|
||||
while :; do sleep 1; done
|
||||
`
|
||||
|
||||
Reference in New Issue
Block a user