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 {
|
||||
|
||||
Reference in New Issue
Block a user