fix(auth): harden interactive diagnostic lifecycle
This commit is contained in:
@@ -16,6 +16,7 @@ import (
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf16"
|
||||
@@ -37,6 +38,10 @@ const interactiveAuthCheckTimeout = 12 * time.Minute
|
||||
|
||||
const maxAuthDiagnosticOutputBytes = 64 * 1024
|
||||
|
||||
const maxDevicePromptLineBytes = 4 * 1024
|
||||
|
||||
const maxDeviceVerificationURIBytes = 2 * 1024
|
||||
|
||||
var errCommandRefused = errors.New("authentication command refused")
|
||||
|
||||
var writeNewAuthFile = safeio.WriteCanonicalNewFile
|
||||
@@ -131,14 +136,11 @@ func checkCommand(ctx context.Context, installation config.Installation, args []
|
||||
if err != nil {
|
||||
return authFailure(stderr, authMessage(err))
|
||||
}
|
||||
report, prompt, err := runCheck(ctx, installation, runner, interactive, false)
|
||||
report, err := runCheck(ctx, installation, runner, interactive, false, stderr)
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, "tht: authentication diagnostics could not be completed")
|
||||
return 1
|
||||
}
|
||||
if interactive && prompt != "" {
|
||||
fmt.Fprintln(stderr, prompt)
|
||||
}
|
||||
if jsonMode {
|
||||
if err := json.NewEncoder(stdout).Encode(report); err != nil {
|
||||
fmt.Fprintln(stderr, "tht: authentication diagnostic report could not be written")
|
||||
@@ -292,28 +294,102 @@ func sanitizeAuthDiagnostics(report AuthDiagnostics, secrets []string) AuthDiagn
|
||||
return report
|
||||
}
|
||||
|
||||
func devicePrompt(stderr string, secrets []string) string {
|
||||
if len(stderr) > maxAuthDiagnosticOutputBytes {
|
||||
type devicePromptStream struct {
|
||||
mu sync.Mutex
|
||||
pending []byte
|
||||
discarding bool
|
||||
emitted bool
|
||||
secrets []string
|
||||
output io.Writer
|
||||
writeErr error
|
||||
}
|
||||
|
||||
func newDevicePromptStream(secrets []string, outputWriter io.Writer) *devicePromptStream {
|
||||
return &devicePromptStream{
|
||||
pending: make([]byte, 0, 256), secrets: append([]string(nil), secrets...), output: outputWriter,
|
||||
}
|
||||
}
|
||||
|
||||
func (stream *devicePromptStream) Observe(chunk []byte) {
|
||||
stream.mu.Lock()
|
||||
defer stream.mu.Unlock()
|
||||
for _, value := range chunk {
|
||||
if value == '\n' {
|
||||
if !stream.discarding {
|
||||
stream.emitLineLocked(string(stream.pending))
|
||||
}
|
||||
stream.pending = stream.pending[:0]
|
||||
stream.discarding = false
|
||||
continue
|
||||
}
|
||||
if stream.discarding {
|
||||
continue
|
||||
}
|
||||
if len(stream.pending) >= maxDevicePromptLineBytes {
|
||||
stream.pending = stream.pending[:0]
|
||||
stream.discarding = true
|
||||
continue
|
||||
}
|
||||
stream.pending = append(stream.pending, value)
|
||||
}
|
||||
}
|
||||
|
||||
func (stream *devicePromptStream) Finish() error {
|
||||
stream.mu.Lock()
|
||||
defer stream.mu.Unlock()
|
||||
if !stream.discarding && len(stream.pending) > 0 {
|
||||
stream.emitLineLocked(string(stream.pending))
|
||||
}
|
||||
stream.pending = nil
|
||||
stream.discarding = false
|
||||
return stream.writeErr
|
||||
}
|
||||
|
||||
func (stream *devicePromptStream) emitLineLocked(line string) {
|
||||
if stream.emitted || stream.output == nil {
|
||||
return
|
||||
}
|
||||
prompt := parseDevicePromptLine(output.Sanitize(line, stream.secrets))
|
||||
if prompt == "" {
|
||||
return
|
||||
}
|
||||
stream.emitted = true
|
||||
if _, err := fmt.Fprintln(stream.output, prompt); err != nil {
|
||||
stream.writeErr = errors.New("authentication device prompt could not be written")
|
||||
}
|
||||
}
|
||||
|
||||
func parseDevicePromptLine(line string) string {
|
||||
const prefix = "Open "
|
||||
const separator = " and enter code "
|
||||
if len(line) == 0 || len(line) > maxDevicePromptLineBytes || !utf8.ValidString(line) ||
|
||||
strings.TrimSpace(line) != line || !strings.HasPrefix(line, prefix) {
|
||||
return ""
|
||||
}
|
||||
for _, line := range strings.Split(output.Sanitize(stderr, secrets), "\n") {
|
||||
const prefix = "Open "
|
||||
const separator = " and enter code "
|
||||
if !strings.HasPrefix(line, prefix) {
|
||||
continue
|
||||
for _, character := range line {
|
||||
if unicode.IsControl(character) {
|
||||
return ""
|
||||
}
|
||||
parts := strings.Split(strings.TrimPrefix(line, prefix), separator)
|
||||
if len(parts) != 2 || !validDeviceVerificationURI(parts[0]) || !validDeviceUserCode(parts[1]) {
|
||||
continue
|
||||
}
|
||||
return prefix + parts[0] + separator + parts[1]
|
||||
}
|
||||
return ""
|
||||
payload := strings.TrimPrefix(line, prefix)
|
||||
if strings.Count(payload, separator) != 1 {
|
||||
return ""
|
||||
}
|
||||
verificationURI, userCode, found := strings.Cut(payload, separator)
|
||||
if !found || !validDeviceVerificationURI(verificationURI) || !validDeviceUserCode(userCode) {
|
||||
return ""
|
||||
}
|
||||
return prefix + verificationURI + separator + userCode
|
||||
}
|
||||
|
||||
func validDeviceVerificationURI(value string) bool {
|
||||
if len(value) == 0 || len(value) > maxDeviceVerificationURIBytes || !utf8.ValidString(value) {
|
||||
return false
|
||||
}
|
||||
parsed, err := url.Parse(value)
|
||||
return err == nil && parsed.Scheme == "https" && parsed.Host != "" && parsed.User == nil && parsed.Fragment == ""
|
||||
return err == nil && parsed.IsAbs() && parsed.Scheme == "https" && parsed.Host != "" &&
|
||||
parsed.Hostname() != "" && parsed.User == nil && parsed.Opaque == "" && parsed.Fragment == "" &&
|
||||
!strings.ContainsAny(value, " \t\r\n")
|
||||
}
|
||||
|
||||
func validDeviceUserCode(value string) bool {
|
||||
@@ -334,17 +410,16 @@ func validDeviceUserCode(value string) bool {
|
||||
// Check invokes the exact backend diagnostic command. Normal host checks always use one-shot
|
||||
// Compose execution; aggregate doctor passes useRunningCore=true only after confirming core runs.
|
||||
func Check(ctx context.Context, installation config.Installation, runner compose.Runner, interactive, useRunningCore bool) (AuthDiagnostics, error) {
|
||||
report, _, err := runCheck(ctx, installation, runner, interactive, useRunningCore)
|
||||
return report, err
|
||||
return runCheck(ctx, installation, runner, interactive, useRunningCore, nil)
|
||||
}
|
||||
|
||||
func runCheck(ctx context.Context, installation config.Installation, runner compose.Runner, interactive, useRunningCore bool) (AuthDiagnostics, string, error) {
|
||||
func runCheck(ctx context.Context, installation config.Installation, runner compose.Runner, interactive, useRunningCore bool, promptOutput io.Writer) (AuthDiagnostics, error) {
|
||||
if runner == nil {
|
||||
return AuthDiagnostics{}, "", errors.New("authentication diagnostic runner is unavailable")
|
||||
return AuthDiagnostics{}, errors.New("authentication diagnostic runner is unavailable")
|
||||
}
|
||||
secrets, err := authenticationSecretValues(installation)
|
||||
if err != nil {
|
||||
return AuthDiagnostics{}, "", err
|
||||
return AuthDiagnostics{}, err
|
||||
}
|
||||
timeout := authCheckTimeout
|
||||
if interactive {
|
||||
@@ -356,35 +431,48 @@ func runCheck(ctx context.Context, installation config.Installation, runner comp
|
||||
if !useRunningCore {
|
||||
containerName, err := compose.NewOneShotContainerName("thothii-auth-check")
|
||||
if err != nil {
|
||||
return AuthDiagnostics{}, "", errors.New("authentication diagnostic command failed")
|
||||
return AuthDiagnostics{}, errors.New("authentication diagnostic command failed")
|
||||
}
|
||||
command = []string{"run", "--rm", "--no-deps", "--no-TTY", "--name", containerName, "core", "node", "dist/auth/diagnostic-command.js", "--json"}
|
||||
}
|
||||
if interactive {
|
||||
command = append(command, "--interactive")
|
||||
}
|
||||
result, err := compose.RunBounded(runner, bounded, installation.ComposeArgs(command...), nil, compose.CaptureLimits{
|
||||
var promptStream *devicePromptStream
|
||||
var stderrObserver func([]byte)
|
||||
if interactive && promptOutput != nil {
|
||||
promptStream = newDevicePromptStream(secrets, promptOutput)
|
||||
stderrObserver = promptStream.Observe
|
||||
}
|
||||
result, err := compose.RunBoundedStreaming(runner, bounded, installation.ComposeArgs(command...), nil, compose.CaptureLimits{
|
||||
StdoutBytes: maxAuthDiagnosticOutputBytes,
|
||||
StderrBytes: maxAuthDiagnosticOutputBytes,
|
||||
})
|
||||
}, stderrObserver)
|
||||
if promptStream != nil {
|
||||
if promptErr := promptStream.Finish(); promptErr != nil {
|
||||
return AuthDiagnostics{}, promptErr
|
||||
}
|
||||
}
|
||||
var exitError *exec.ExitError
|
||||
validProcessOutcome := result.ExitCode == 0 && err == nil ||
|
||||
result.ExitCode == 1 && (err == nil || errors.As(err, &exitError))
|
||||
unsafeLifecycle := errors.Is(err, compose.ErrOutputLimit) || errors.Is(err, compose.ErrProcessReap) ||
|
||||
errors.Is(err, compose.ErrContainerCleanup) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)
|
||||
validProcessOutcome := !unsafeLifecycle && (result.ExitCode == 0 && err == nil ||
|
||||
result.ExitCode == 1 && (err == nil || errors.As(err, &exitError)))
|
||||
if !validProcessOutcome {
|
||||
return AuthDiagnostics{}, "", errors.New("authentication diagnostic command failed")
|
||||
return AuthDiagnostics{}, errors.New("authentication diagnostic command failed")
|
||||
}
|
||||
report, decodeErr := decodeAuthDiagnostics(result.Stdout)
|
||||
if decodeErr != nil {
|
||||
return AuthDiagnostics{}, "", errors.New("authentication diagnostic report is invalid")
|
||||
return AuthDiagnostics{}, errors.New("authentication diagnostic report is invalid")
|
||||
}
|
||||
if report.Ready != (result.ExitCode == 0) {
|
||||
return AuthDiagnostics{}, "", errors.New("authentication diagnostic command failed")
|
||||
return AuthDiagnostics{}, errors.New("authentication diagnostic command failed")
|
||||
}
|
||||
safe := sanitizeAuthDiagnostics(report, secrets)
|
||||
if !validAuthDiagnostics(safe) {
|
||||
return AuthDiagnostics{}, "", errors.New("authentication diagnostic report is invalid")
|
||||
return AuthDiagnostics{}, errors.New("authentication diagnostic report is invalid")
|
||||
}
|
||||
return safe, devicePrompt(result.Stderr, secrets), nil
|
||||
return safe, nil
|
||||
}
|
||||
|
||||
func authFailure(stderr io.Writer, message string) int {
|
||||
|
||||
@@ -9,7 +9,9 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/config"
|
||||
@@ -49,6 +51,7 @@ func TestAuthCheckRunsOneShotCoreDiagnosticWithPristineJSON(t *testing.T) {
|
||||
func TestAuthCheckEmitsValidFailedReportFromRealExitError(t *testing.T) {
|
||||
installation := authInstallation(newAuthDirectory(t))
|
||||
runner := compose.NewRunner(writeAuthExecutable(t, `#!/bin/sh
|
||||
if [ "$1" = "container" ]; then exit 0; fi
|
||||
printf '%s\n' '{"ready":false,"mode":"oidc","checks":[{"level":"error","code":"oidc_secret_missing","message":"A required OIDC or group catalog secret is unavailable."}]}'
|
||||
exit 1
|
||||
`))
|
||||
@@ -187,6 +190,90 @@ func TestAuthCheckInteractiveForwardsOnlyTheValidatedDevicePrompt(t *testing.T)
|
||||
assertAuthOneShotCommand(t, installation, calls[0], true)
|
||||
}
|
||||
|
||||
func TestAuthCheckInteractiveStreamsOnlyASanitizedPromptBeforePollingCompletes(t *testing.T) {
|
||||
installation := authInstallation(newAuthDirectory(t))
|
||||
root := filepath.Dir(installation.EnvFile)
|
||||
secretFile := filepath.Join(root, "prompt-secret")
|
||||
if err := os.WriteFile(secretFile, []byte("prompt-secret-sentinel"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(installation.EnvFile, []byte("PROMPT_TOKEN_FILE="+secretFile+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
started := filepath.Join(root, "started")
|
||||
release := filepath.Join(root, "release")
|
||||
t.Setenv("THT_AUTH_STREAM_STARTED", started)
|
||||
t.Setenv("THT_AUTH_STREAM_RELEASE", release)
|
||||
runner := compose.NewRunner(writeAuthExecutable(t, `#!/bin/sh
|
||||
if [ "$1" = "container" ]; then exit 0; fi
|
||||
printf '%s\n' 'untrusted prompt-secret-sentinel child output' >&2
|
||||
printf '%s' 'Open https://issuer.example.test/device?token=' >&2
|
||||
printf '%s\n' 'prompt-secret-sentinel and enter code ABCD-EFGH' >&2
|
||||
: > "$THT_AUTH_STREAM_STARTED"
|
||||
while [ ! -f "$THT_AUTH_STREAM_RELEASE" ]; do sleep 0.01; done
|
||||
printf '%s\n' '{"ready":true,"mode":"oidc","checks":[{"level":"info","code":"auth_ready","message":"Authentication is ready."}]}'
|
||||
`))
|
||||
var stdout bytes.Buffer
|
||||
stderr := &synchronizedBuffer{}
|
||||
done := make(chan int, 1)
|
||||
go func() {
|
||||
done <- RunWithRunner(context.Background(), installation, []string{"check", "--json", "--interactive"}, strings.NewReader(""), &stdout, stderr, runner)
|
||||
}()
|
||||
|
||||
if !waitForFile(started, 5*time.Second) {
|
||||
t.Fatal("interactive diagnostic did not start")
|
||||
}
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
streamed := false
|
||||
for time.Now().Before(deadline) {
|
||||
if stderr.String() == "Open https://issuer.example.test/device?token=[REDACTED] and enter code ABCD-EFGH\n" {
|
||||
streamed = true
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if err := os.WriteFile(release, []byte("release"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case code := <-done:
|
||||
if code != 0 {
|
||||
t.Fatalf("interactive auth check = %d, stdout=%q stderr=%q", code, stdout.String(), stderr.String())
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("interactive diagnostic did not finish")
|
||||
}
|
||||
if !streamed {
|
||||
t.Fatalf("device prompt was not streamed before polling completed: stderr=%q", stderr.String())
|
||||
}
|
||||
if strings.Contains(stderr.String(), "prompt-secret-sentinel") || strings.Contains(stderr.String(), "untrusted") {
|
||||
t.Fatalf("interactive auth leaked raw child stderr: %q", stderr.String())
|
||||
}
|
||||
if !json.Valid(stdout.Bytes()) {
|
||||
t.Fatalf("interactive JSON stdout is not pristine: %q", stdout.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDevicePromptGrammarRejectsUnboundedAmbiguousOrUnsafeLines(t *testing.T) {
|
||||
valid := "Open https://issuer.example.test/device?tenant=one and enter code ABCD-EFGH"
|
||||
if got := parseDevicePromptLine(valid); got != valid {
|
||||
t.Fatalf("valid prompt = %q, want %q", got, valid)
|
||||
}
|
||||
for _, line := range []string{
|
||||
"Open http://issuer.example.test/device and enter code ABCD-EFGH",
|
||||
"Open https://user@issuer.example.test/device and enter code ABCD-EFGH",
|
||||
"Open https://issuer.example.test/device#fragment and enter code ABCD-EFGH",
|
||||
"Open https://issuer.example.test/device and enter code ABCD-EFGH and enter code IJKL-MNOP",
|
||||
"Open https://issuer.example.test/device and enter code ABCD EFGH",
|
||||
"Open https://issuer.example.test/device\r and enter code ABCD-EFGH",
|
||||
"Open https://issuer.example.test/" + strings.Repeat("a", maxDevicePromptLineBytes) + " and enter code ABCD-EFGH",
|
||||
} {
|
||||
if prompt := parseDevicePromptLine(line); prompt != "" {
|
||||
t.Fatalf("unsafe prompt accepted: %q", prompt)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCheckFailsBeforeExecutionWhenDeclaredSecretCorpusIsIncomplete(t *testing.T) {
|
||||
installation := authInstallation(newAuthDirectory(t))
|
||||
installation.EnvFile = filepath.Join(t.TempDir(), "operator.env")
|
||||
@@ -201,13 +288,29 @@ func TestAuthCheckFailsBeforeExecutionWhenDeclaredSecretCorpusIsIncomplete(t *te
|
||||
})
|
||||
var stdout, stderr bytes.Buffer
|
||||
|
||||
code := RunWithRunner(context.Background(), installation, []string{"check", "--json"}, strings.NewReader(""), &stdout, &stderr, runner)
|
||||
code := RunWithRunner(context.Background(), installation, []string{"check", "--json", "--interactive"}, strings.NewReader(""), &stdout, &stderr, runner)
|
||||
|
||||
if code != 1 || calls != 0 || stdout.Len() != 0 || stderr.String() != "tht: authentication diagnostics could not be completed\n" {
|
||||
t.Fatalf("incomplete corpus was not refused before execution: code=%d calls=%d stdout=%q stderr=%q", code, calls, stdout.String(), stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCheckRejectsAValidReportWhenOneShotCleanupFails(t *testing.T) {
|
||||
runner := runnerFunc(func(_ context.Context, _ []string, _ io.Reader) (compose.Result, error) {
|
||||
return compose.Result{
|
||||
Stdout: `{"ready":true,"mode":"oidc","checks":[{"level":"info","code":"auth_ready","message":"Authentication is ready."}]}`,
|
||||
ExitCode: 0,
|
||||
}, compose.ErrContainerCleanup
|
||||
})
|
||||
var stdout, stderr bytes.Buffer
|
||||
|
||||
code := RunWithRunner(context.Background(), authInstallation(newAuthDirectory(t)), []string{"check", "--json"}, strings.NewReader(""), &stdout, &stderr, runner)
|
||||
|
||||
if code != 1 || stdout.Len() != 0 || stderr.String() != "tht: authentication diagnostics could not be completed\n" {
|
||||
t.Fatalf("cleanup failure accepted: code=%d stdout=%q stderr=%q", code, stdout.String(), stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCheckRedactsFailedCoreOutputAndRejectsMalformedReports(t *testing.T) {
|
||||
installation := authInstallation(newAuthDirectory(t))
|
||||
secretPath := filepath.Join(t.TempDir(), "auth-check-secret")
|
||||
@@ -249,6 +352,34 @@ func (run runnerFunc) Run(ctx context.Context, args []string, input io.Reader) (
|
||||
return run(ctx, args, input)
|
||||
}
|
||||
|
||||
type synchronizedBuffer struct {
|
||||
mu sync.Mutex
|
||||
buffer bytes.Buffer
|
||||
}
|
||||
|
||||
func (b *synchronizedBuffer) Write(value []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buffer.Write(value)
|
||||
}
|
||||
|
||||
func (b *synchronizedBuffer) String() string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buffer.String()
|
||||
}
|
||||
|
||||
func waitForFile(path string, timeout time.Duration) bool {
|
||||
deadline := time.Now().Add(timeout)
|
||||
for time.Now().Before(deadline) {
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
return true
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func assertAuthOneShotCommand(t *testing.T, installation config.Installation, got []string, interactive bool) {
|
||||
t.Helper()
|
||||
prefix := installation.ComposeArgs("run", "--rm", "--no-deps", "--no-TTY", "--name")
|
||||
|
||||
Reference in New Issue
Block a user