fix(auth): harden unified diagnostic execution
This commit is contained in:
@@ -13,9 +13,13 @@ import (
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf16"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/config"
|
||||
@@ -76,9 +80,9 @@ func RunWithRunner(ctx context.Context, installation config.Installation, args [
|
||||
|
||||
// AuthDiagnostic is the closed JSON contract emitted by the backend diagnostic command.
|
||||
type AuthDiagnostic struct {
|
||||
Level string `json:"level"`
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Level string `json:"level"`
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Field *string `json:"field,omitempty"`
|
||||
}
|
||||
|
||||
@@ -89,6 +93,19 @@ type AuthDiagnostics struct {
|
||||
Checks []AuthDiagnostic `json:"checks"`
|
||||
}
|
||||
|
||||
type authDiagnosticWire struct {
|
||||
Level string `json:"level"`
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Field json.RawMessage `json:"field"`
|
||||
}
|
||||
|
||||
type authDiagnosticsWire struct {
|
||||
Ready bool `json:"ready"`
|
||||
Mode string `json:"mode"`
|
||||
Checks []authDiagnosticWire `json:"checks"`
|
||||
}
|
||||
|
||||
func parseCheckArgs(args []string) (jsonMode, interactive bool, err error) {
|
||||
for _, arg := range args {
|
||||
switch arg {
|
||||
@@ -160,20 +177,95 @@ func validAuthDiagnostics(report AuthDiagnostics) bool {
|
||||
if len(report.Checks) == 0 || len(report.Checks) > 129 {
|
||||
return false
|
||||
}
|
||||
seen := make(map[string]struct{}, len(report.Checks))
|
||||
hasError := false
|
||||
for _, check := range report.Checks {
|
||||
if (check.Level != "error" && check.Level != "info") || check.Message == "" || len(check.Message) > 512 {
|
||||
if (check.Level != "error" && check.Level != "info") || !safeDiagnosticText(check.Message) {
|
||||
return false
|
||||
}
|
||||
if _, ok := authDiagnosticCodes[check.Code]; !ok {
|
||||
return false
|
||||
}
|
||||
if check.Field != nil && (*check.Field == "" || len(*check.Field) > 512) {
|
||||
if check.Field != nil && (!safeDiagnosticText(*check.Field) ||
|
||||
check.Code != "oidc_mapped_group_missing" && check.Code != "oidc_mapped_group_ambiguous") {
|
||||
return false
|
||||
}
|
||||
field := ""
|
||||
if check.Field != nil {
|
||||
field = *check.Field
|
||||
}
|
||||
key := check.Code + "\x00" + field
|
||||
if _, duplicate := seen[key]; duplicate {
|
||||
return false
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
hasError = hasError || check.Level == "error"
|
||||
}
|
||||
if report.Ready {
|
||||
return len(report.Checks) == 1 && report.Checks[0].Level == "info" &&
|
||||
report.Checks[0].Code == "auth_ready" && report.Checks[0].Field == nil
|
||||
}
|
||||
if !hasError {
|
||||
return false
|
||||
}
|
||||
for _, check := range report.Checks {
|
||||
if check.Code == "auth_ready" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func safeDiagnosticText(value string) bool {
|
||||
if value == "" || utf16Length(value) > 512 || strings.TrimSpace(value) != value {
|
||||
return false
|
||||
}
|
||||
for _, character := range value {
|
||||
if unicode.IsControl(character) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func utf16Length(value string) int {
|
||||
length := 0
|
||||
for _, character := range value {
|
||||
length += utf16.RuneLen(character)
|
||||
}
|
||||
return length
|
||||
}
|
||||
|
||||
func decodeAuthDiagnostics(value string) (AuthDiagnostics, error) {
|
||||
if !utf8.ValidString(value) {
|
||||
return AuthDiagnostics{}, errors.New("authentication diagnostic report is invalid")
|
||||
}
|
||||
decoder := json.NewDecoder(strings.NewReader(value))
|
||||
decoder.DisallowUnknownFields()
|
||||
var wire authDiagnosticsWire
|
||||
if err := decoder.Decode(&wire); err != nil || decoder.Decode(&struct{}{}) != io.EOF {
|
||||
return AuthDiagnostics{}, errors.New("authentication diagnostic report is invalid")
|
||||
}
|
||||
report := AuthDiagnostics{Ready: wire.Ready, Mode: wire.Mode, Checks: make([]AuthDiagnostic, 0, len(wire.Checks))}
|
||||
for _, item := range wire.Checks {
|
||||
var field *string
|
||||
if item.Field != nil {
|
||||
var decoded string
|
||||
if string(item.Field) == "null" || json.Unmarshal(item.Field, &decoded) != nil {
|
||||
return AuthDiagnostics{}, errors.New("authentication diagnostic report is invalid")
|
||||
}
|
||||
field = &decoded
|
||||
}
|
||||
report.Checks = append(report.Checks, AuthDiagnostic{
|
||||
Level: item.Level, Code: item.Code, Message: item.Message, Field: field,
|
||||
})
|
||||
}
|
||||
if !validAuthDiagnostics(report) {
|
||||
return AuthDiagnostics{}, errors.New("authentication diagnostic report is invalid")
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
func authenticationSecretValues(installation config.Installation) []string {
|
||||
files, err := installation.SecretFiles()
|
||||
if err != nil {
|
||||
@@ -260,18 +352,29 @@ func runCheck(ctx context.Context, installation config.Installation, runner comp
|
||||
if interactive {
|
||||
command = append(command, "--interactive")
|
||||
}
|
||||
result, err := runner.Run(bounded, installation.ComposeArgs(command...), nil)
|
||||
result, err := compose.RunBounded(runner, bounded, installation.ComposeArgs(command...), nil, compose.CaptureLimits{
|
||||
StdoutBytes: maxAuthDiagnosticOutputBytes,
|
||||
StderrBytes: maxAuthDiagnosticOutputBytes,
|
||||
})
|
||||
secrets := authenticationSecretValues(installation)
|
||||
if err != nil || result.ExitCode != 0 || len(result.Stdout) > maxAuthDiagnosticOutputBytes || len(result.Stderr) > maxAuthDiagnosticOutputBytes {
|
||||
var exitError *exec.ExitError
|
||||
validProcessOutcome := result.ExitCode == 0 && err == nil ||
|
||||
result.ExitCode == 1 && (err == nil || errors.As(err, &exitError))
|
||||
if !validProcessOutcome {
|
||||
return AuthDiagnostics{}, "", errors.New("authentication diagnostic command failed")
|
||||
}
|
||||
decoder := json.NewDecoder(strings.NewReader(result.Stdout))
|
||||
decoder.DisallowUnknownFields()
|
||||
var report AuthDiagnostics
|
||||
if err := decoder.Decode(&report); err != nil || decoder.Decode(&struct{}{}) != io.EOF || !validAuthDiagnostics(report) {
|
||||
report, decodeErr := decodeAuthDiagnostics(result.Stdout)
|
||||
if decodeErr != nil {
|
||||
return AuthDiagnostics{}, "", errors.New("authentication diagnostic report is invalid")
|
||||
}
|
||||
return sanitizeAuthDiagnostics(report, secrets), devicePrompt(result.Stderr, secrets), nil
|
||||
if report.Ready != (result.ExitCode == 0) {
|
||||
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 safe, devicePrompt(result.Stderr, secrets), nil
|
||||
}
|
||||
|
||||
func authFailure(stderr io.Writer, message string) int {
|
||||
|
||||
@@ -49,6 +49,113 @@ func TestAuthCheckRunsOneShotCoreDiagnosticWithPristineJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCheckEmitsValidFailedReportFromRealExitError(t *testing.T) {
|
||||
installation := authInstallation(newAuthDirectory(t))
|
||||
runner := compose.NewRunner(writeAuthExecutable(t, `#!/bin/sh
|
||||
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
|
||||
`))
|
||||
var stdout, stderr bytes.Buffer
|
||||
|
||||
code := RunWithRunner(context.Background(), installation, []string{"check", "--json"}, strings.NewReader(""), &stdout, &stderr, runner)
|
||||
|
||||
if code != 1 {
|
||||
t.Fatalf("auth check = %d, want diagnostic failure 1; stdout=%q stderr=%q", code, stdout.String(), stderr.String())
|
||||
}
|
||||
var report AuthDiagnostics
|
||||
if err := json.Unmarshal(stdout.Bytes(), &report); err != nil || report.Ready || report.Checks[0].Code != "oidc_secret_missing" {
|
||||
t.Fatalf("auth check stdout is not the pristine failed report: %q: %#v, %v", stdout.String(), report, err)
|
||||
}
|
||||
if stderr.Len() != 0 {
|
||||
t.Fatalf("auth check stderr = %q, want empty", stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCheckRejectsExitAndReportSemanticMismatches(t *testing.T) {
|
||||
ready := `{"ready":true,"mode":"oidc","checks":[{"level":"info","code":"auth_ready","message":"Authentication is ready."}]}`
|
||||
failed := `{"ready":false,"mode":"oidc","checks":[{"level":"error","code":"oidc_secret_missing","message":"A required OIDC or group catalog secret is unavailable."}]}`
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
exit int
|
||||
report string
|
||||
}{
|
||||
{name: "zero with failed report", exit: 0, report: failed},
|
||||
{name: "one with ready report", exit: 1, report: ready},
|
||||
{name: "two with failed report", exit: 2, report: failed},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
runner := runnerFunc(func(_ context.Context, _ []string, _ io.Reader) (compose.Result, error) {
|
||||
var err error
|
||||
if test.exit != 0 {
|
||||
err = errors.New("process exited")
|
||||
}
|
||||
return compose.Result{Stdout: test.report, ExitCode: test.exit}, err
|
||||
})
|
||||
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("mismatch accepted: code=%d stdout=%q stderr=%q", code, stdout.String(), stderr.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCheckRejectsCancellationEvenIfTheKilledChildReportsExitOne(t *testing.T) {
|
||||
failed := `{"ready":false,"mode":"oidc","checks":[{"level":"error","code":"oidc_secret_missing","message":"A required OIDC or group catalog secret is unavailable."}]}`
|
||||
runner := runnerFunc(func(_ context.Context, _ []string, _ io.Reader) (compose.Result, error) {
|
||||
return compose.Result{Stdout: failed, ExitCode: 1}, context.DeadlineExceeded
|
||||
})
|
||||
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("cancelled report accepted: code=%d stdout=%q stderr=%q", code, stdout.String(), stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthDiagnosticsContractRejectsContradictionsDuplicatesAndAttackerFields(t *testing.T) {
|
||||
field := "Configured Group"
|
||||
validFailure := AuthDiagnostics{Ready: false, Mode: "oidc", Checks: []AuthDiagnostic{{
|
||||
Level: "error", Code: "oidc_mapped_group_missing", Message: "A configured authorization group does not exist.", Field: &field,
|
||||
}}}
|
||||
if !validAuthDiagnostics(validFailure) {
|
||||
t.Fatal("valid failed report was rejected")
|
||||
}
|
||||
for _, report := range []AuthDiagnostics{
|
||||
{Ready: true, Mode: "oidc", Checks: []AuthDiagnostic{{Level: "error", Code: "oidc_secret_missing", Message: "failure"}}},
|
||||
{Ready: false, Mode: "oidc", Checks: []AuthDiagnostic{{Level: "info", Code: "auth_ready", Message: "ready"}}},
|
||||
{Ready: false, Mode: "oidc", Checks: []AuthDiagnostic{{Level: "info", Code: "auth_config_invalid", Message: "not an error"}}},
|
||||
{Ready: false, Mode: "oidc", Checks: []AuthDiagnostic{
|
||||
{Level: "error", Code: "oidc_secret_missing", Message: "failure"},
|
||||
{Level: "error", Code: "oidc_secret_missing", Message: "duplicate"},
|
||||
}},
|
||||
{Ready: false, Mode: "oidc", Checks: []AuthDiagnostic{{Level: "error", Code: "oidc_secret_missing", Message: "failure", Field: &field}}},
|
||||
{Ready: false, Mode: "oidc", Checks: []AuthDiagnostic{{Level: "error", Code: "oidc_mapped_group_missing", Message: "failure", Field: stringPointer(" attacker ")}}},
|
||||
{Ready: false, Mode: "oidc", Checks: []AuthDiagnostic{{Level: "error", Code: "oidc_mapped_group_missing", Message: "failure", Field: stringPointer("attacker\u0085field")}}},
|
||||
} {
|
||||
if validAuthDiagnostics(report) {
|
||||
t.Fatalf("invalid authentication report accepted: %#v", report)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCheckRejectsNullAndUnexpectedDiagnosticFields(t *testing.T) {
|
||||
for _, report := range []string{
|
||||
`{"ready":false,"mode":"oidc","checks":[{"level":"error","code":"oidc_mapped_group_missing","message":"failure","field":null}]}`,
|
||||
`{"ready":false,"mode":"oidc","checks":[{"level":"error","code":"oidc_secret_missing","message":"failure","unexpected":"attacker"}]}`,
|
||||
} {
|
||||
runner := runnerFunc(func(_ context.Context, _ []string, _ io.Reader) (compose.Result, error) {
|
||||
return compose.Result{Stdout: report, ExitCode: 1}, nil
|
||||
})
|
||||
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("hostile field accepted: code=%d stdout=%q stderr=%q", code, stdout.String(), stderr.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthCheckInteractiveForwardsOnlyTheValidatedDevicePrompt(t *testing.T) {
|
||||
installation := authInstallation(newAuthDirectory(t))
|
||||
var calls [][]string
|
||||
@@ -96,8 +203,8 @@ func TestAuthCheckRedactsFailedCoreOutputAndRejectsMalformedReports(t *testing.T
|
||||
}
|
||||
runner := runnerFunc(func(_ context.Context, _ []string, _ io.Reader) (compose.Result, error) {
|
||||
return compose.Result{
|
||||
Stdout: "not-json auth-check-secret token-sentinel /private/sentinel $argon2id$hash-sentinel",
|
||||
Stderr: "auth-check-secret cookie-sentinel /private/sentinel",
|
||||
Stdout: "not-json auth-check-secret token-sentinel /private/sentinel $argon2id$hash-sentinel",
|
||||
Stderr: "auth-check-secret cookie-sentinel /private/sentinel",
|
||||
ExitCode: 23,
|
||||
}, errors.New("core failed")
|
||||
})
|
||||
@@ -419,6 +526,17 @@ func writePasswordFile(t *testing.T, password string) string {
|
||||
return path
|
||||
}
|
||||
|
||||
func writeAuthExecutable(t *testing.T, contents string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "fake-docker")
|
||||
if err := os.WriteFile(path, []byte(contents), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func stringPointer(value string) *string { return &value }
|
||||
|
||||
func authInstallation(directory string) config.Installation {
|
||||
installation := config.Installation{}
|
||||
installation.Authentication.ConfigDirectory = directory
|
||||
|
||||
Reference in New Issue
Block a user