732 lines
34 KiB
Go
732 lines
34 KiB
Go
package authconfig
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
|
"github.com/aritmolab/thothii/tools/tht/internal/config"
|
|
"github.com/aritmolab/thothii/tools/tht/internal/safeio"
|
|
)
|
|
|
|
func TestAuthCheckRunsOneShotCoreDiagnosticWithPristineJSON(t *testing.T) {
|
|
installation := authInstallation(newAuthDirectory(t))
|
|
var calls [][]string
|
|
runner := runnerFunc(func(_ context.Context, args []string, _ io.Reader) (compose.Result, error) {
|
|
calls = append(calls, append([]string(nil), args...))
|
|
return compose.Result{Stdout: `{"ready":true,"mode":"oidc","checks":[{"level":"info","code":"auth_ready","message":"Authentication is ready."}]}` + "\n"}, nil
|
|
})
|
|
var stdout, stderr bytes.Buffer
|
|
|
|
code := RunWithRunner(context.Background(), installation, []string{"check", "--json"}, strings.NewReader(""), &stdout, &stderr, runner)
|
|
|
|
if code != 0 {
|
|
t.Fatalf("auth check = %d, stdout=%q stderr=%q", code, stdout.String(), stderr.String())
|
|
}
|
|
var report AuthDiagnostics
|
|
if err := json.Unmarshal(stdout.Bytes(), &report); err != nil {
|
|
t.Fatalf("auth check stdout is not pristine JSON: %q: %v", stdout.String(), err)
|
|
}
|
|
if !report.Ready || report.Mode != "oidc" || len(report.Checks) != 1 || report.Checks[0].Code != "auth_ready" {
|
|
t.Fatalf("auth check report = %#v", report)
|
|
}
|
|
if stderr.Len() != 0 {
|
|
t.Fatalf("auth check stderr = %q", stderr.String())
|
|
}
|
|
if len(calls) != 1 {
|
|
t.Fatalf("Docker calls = %#v, want one", calls)
|
|
}
|
|
assertAuthOneShotCommand(t, installation, calls[0], false)
|
|
}
|
|
|
|
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
|
|
`))
|
|
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{
|
|
`{"mode":"oidc","checks":[{"level":"error","code":"oidc_secret_missing","message":"failure"}]}`,
|
|
`{"ready":null,"mode":"oidc","checks":[{"level":"error","code":"oidc_secret_missing","message":"failure"}]}`,
|
|
`{"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
|
|
runner := runnerFunc(func(_ context.Context, args []string, _ io.Reader) (compose.Result, error) {
|
|
calls = append(calls, append([]string(nil), args...))
|
|
return compose.Result{
|
|
Stdout: `{"ready":true,"mode":"oidc","checks":[{"level":"info","code":"auth_ready","message":"Authentication is ready."}]}` + "\n",
|
|
Stderr: "Open https://issuer.example.test/device and enter code ABCD-EFGH\nnot-a-device-prompt secret-sentinel\n",
|
|
}, nil
|
|
})
|
|
var stdout, stderr bytes.Buffer
|
|
|
|
code := RunWithRunner(context.Background(), installation, []string{"check", "--interactive"}, strings.NewReader(""), &stdout, &stderr, runner)
|
|
|
|
if code != 0 {
|
|
t.Fatalf("interactive auth check = %d, stdout=%q stderr=%q", code, stdout.String(), stderr.String())
|
|
}
|
|
if stdout.String() != "authentication: passed\n" {
|
|
t.Fatalf("interactive auth stdout = %q", stdout.String())
|
|
}
|
|
if stderr.String() != "Open https://issuer.example.test/device and enter code ABCD-EFGH\n" {
|
|
t.Fatalf("interactive auth stderr = %q", stderr.String())
|
|
}
|
|
if strings.Contains(stdout.String()+stderr.String(), "secret-sentinel") {
|
|
t.Fatalf("interactive auth output leaked untrusted stderr: stdout=%q stderr=%q", stdout.String(), stderr.String())
|
|
}
|
|
if len(calls) != 1 {
|
|
t.Fatalf("Docker calls = %#v, want one", calls)
|
|
}
|
|
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")
|
|
missing := filepath.Join(t.TempDir(), "missing-pi-auth.json")
|
|
if err := os.WriteFile(installation.EnvFile, []byte("PI_AUTH_FILE="+missing+"\n"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
calls := 0
|
|
runner := runnerFunc(func(_ context.Context, _ []string, _ io.Reader) (compose.Result, error) {
|
|
calls++
|
|
return compose.Result{Stdout: `{"ready":true,"mode":"oidc","checks":[{"level":"info","code":"auth_ready","message":"Authentication is ready."}]}`}, nil
|
|
})
|
|
var stdout, stderr bytes.Buffer
|
|
|
|
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")
|
|
if err := os.WriteFile(secretPath, []byte("auth-check-secret"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
installation.EnvFile = filepath.Join(t.TempDir(), "operator.env")
|
|
if err := os.WriteFile(installation.EnvFile, []byte("AUTH_CHECK_TOKEN_FILE="+secretPath+"\n"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
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",
|
|
ExitCode: 23,
|
|
}, errors.New("core failed")
|
|
})
|
|
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 1; stderr=%q", code, stderr.String())
|
|
}
|
|
combined := stdout.String() + stderr.String()
|
|
leaked := strings.Contains(combined, "auth-check-secret") ||
|
|
strings.Contains(combined, "token-sentinel") ||
|
|
strings.Contains(combined, "cookie-sentinel") ||
|
|
strings.Contains(combined, "/private/sentinel") ||
|
|
strings.Contains(combined, "$argon2id$hash-sentinel")
|
|
if stdout.Len() != 0 || leaked {
|
|
t.Fatalf("auth check leaked a core failure: stdout=%q stderr=%q", stdout.String(), stderr.String())
|
|
}
|
|
}
|
|
|
|
type runnerFunc func(context.Context, []string, io.Reader) (compose.Result, error)
|
|
|
|
func (run runnerFunc) Run(ctx context.Context, args []string, input io.Reader) (compose.Result, error) {
|
|
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")
|
|
suffix := []string{"core", "node", "dist/auth/diagnostic-command.js", "--json"}
|
|
if interactive {
|
|
suffix = append(suffix, "--interactive")
|
|
}
|
|
if len(got) != len(prefix)+1+len(suffix) ||
|
|
strings.Join(got[:len(prefix)], "\x00") != strings.Join(prefix, "\x00") ||
|
|
strings.Join(got[len(prefix)+1:], "\x00") != strings.Join(suffix, "\x00") {
|
|
t.Fatalf("auth check Docker call = %#v, want named one-shot command", got)
|
|
}
|
|
name := got[len(prefix)]
|
|
if !strings.HasPrefix(name, "thothii-auth-check-") || len(name) != len("thothii-auth-check-")+24 {
|
|
t.Fatalf("auth check container name = %q, want unique bounded name", name)
|
|
}
|
|
for _, character := range name {
|
|
if !(character >= 'a' && character <= 'z' || character >= '0' && character <= '9' || character == '-') {
|
|
t.Fatalf("auth check container name = %q, want safe characters", name)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRunConfiguresLocalRegistryAndRedactsStatusJSON(t *testing.T) {
|
|
directory := newAuthDirectory(t)
|
|
passwordFile := writePasswordFile(t, "this is a local test password\n")
|
|
installation := authInstallation(directory)
|
|
|
|
var stdout, stderr bytes.Buffer
|
|
if code := Run(context.Background(), installation, []string{
|
|
"configure", "--mode", "local", "--public-url", "http://127.0.0.1:8080",
|
|
"--admin-user", "admin", "--admin-display-name", "Local administrator", "--password-file", passwordFile,
|
|
}, strings.NewReader(""), &stdout, &stderr); code != 0 {
|
|
t.Fatalf("local configure = %d, stdout=%q stderr=%q", code, stdout.String(), stderr.String())
|
|
}
|
|
if stdout.Len() != 0 || stderr.Len() != 0 {
|
|
t.Fatalf("local configure wrote machine output: stdout=%q stderr=%q", stdout.String(), stderr.String())
|
|
}
|
|
|
|
stdout.Reset()
|
|
if code := Run(context.Background(), installation, []string{"status", "--json"}, strings.NewReader(""), &stdout, &stderr); code != 0 {
|
|
t.Fatalf("status = %d, stderr=%q", code, stderr.String())
|
|
}
|
|
var status struct {
|
|
Mode string `json:"mode"`
|
|
PublicURL string `json:"publicUrl"`
|
|
UserCounts map[string]int `json:"userCounts"`
|
|
Revision string `json:"configRevision"`
|
|
}
|
|
if err := json.Unmarshal(stdout.Bytes(), &status); err != nil {
|
|
t.Fatalf("status stdout is not pristine JSON: %q: %v", stdout.String(), err)
|
|
}
|
|
if status.Mode != "local" || status.PublicURL != "http://127.0.0.1:8080" || status.UserCounts["admin"] != 1 || status.Revision == "" {
|
|
t.Fatalf("status = %#v", status)
|
|
}
|
|
if strings.Contains(stdout.String()+stderr.String(), "this is a local test password") || strings.Contains(stdout.String()+stderr.String(), "$argon2id$") {
|
|
t.Fatalf("status exposed password material: stdout=%q stderr=%q", stdout.String(), stderr.String())
|
|
}
|
|
}
|
|
|
|
func TestRunConfiguresOIDCFixedGroupsAndRefusesIdenticalGroups(t *testing.T) {
|
|
for name, test := range map[string]struct {
|
|
args []string
|
|
wantMode string
|
|
}{
|
|
"configured": {
|
|
args: []string{"configure", "--mode", "oidc", "--public-url", "https://thothii.example.org", "--issuer", "https://authentik.example.org/application/o/thothii/", "--client-id", "thothii", "--authentik-base-url", "https://authentik.example.org", "--user-group", "TOT Users", "--admin-group", "TOT Admin"},
|
|
wantMode: "oidc",
|
|
},
|
|
"ambiguous groups": {
|
|
args: []string{"configure", "--mode", "oidc", "--public-url", "https://thothii.example.org", "--issuer", "https://authentik.example.org/application/o/thothii/", "--client-id", "thothii", "--authentik-base-url", "https://authentik.example.org", "--user-group", "same", "--admin-group", "same"},
|
|
},
|
|
} {
|
|
t.Run(name, func(t *testing.T) {
|
|
directory := newAuthDirectory(t)
|
|
var stdout, stderr bytes.Buffer
|
|
code := Run(context.Background(), authInstallation(directory), test.args, strings.NewReader(""), &stdout, &stderr)
|
|
if test.wantMode == "" {
|
|
if code == 0 || strings.Contains(stdout.String()+stderr.String(), "same") && strings.Contains(stdout.String()+stderr.String(), "secret") {
|
|
t.Fatalf("ambiguous groups accepted or exposed unsafe detail: code=%d stdout=%q stderr=%q", code, stdout.String(), stderr.String())
|
|
}
|
|
return
|
|
}
|
|
if code != 0 {
|
|
t.Fatalf("OIDC configure = %d, stdout=%q stderr=%q", code, stdout.String(), stderr.String())
|
|
}
|
|
config, _, err := Load(directory)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if config.Mode != test.wantMode || config.Authorization.GroupRoles["TOT Users"][0] != RoleUser || config.Authorization.GroupRoles["TOT Admin"][0] != RoleAdmin {
|
|
t.Fatalf("OIDC config = %#v", config)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestRunMutatesLocalUsersAndPreservesLastAdministrator(t *testing.T) {
|
|
directory := newAuthDirectory(t)
|
|
installation := authInstallation(directory)
|
|
adminPassword := writePasswordFile(t, "initial administrator password\n")
|
|
userPassword := writePasswordFile(t, "ordinary user password one\n")
|
|
if code := Run(context.Background(), installation, []string{"configure", "--mode", "local", "--public-url", "http://127.0.0.1:8080", "--admin-user", "admin", "--password-file", adminPassword}, strings.NewReader(""), ioDiscard{}, ioDiscard{}); code != 0 {
|
|
t.Fatalf("configure = %d", code)
|
|
}
|
|
for _, args := range [][]string{
|
|
{"user", "add", "operator", "--role", "user", "--display-name", "Operator", "--password-file", userPassword},
|
|
{"user", "set-password", "operator", "--password-file", adminPassword},
|
|
{"user", "grant", "operator", "--role", "admin"},
|
|
{"user", "revoke", "operator", "--role", "admin"},
|
|
{"user", "disable", "operator"},
|
|
{"user", "enable", "operator"},
|
|
} {
|
|
var stdout, stderr bytes.Buffer
|
|
if code := Run(context.Background(), installation, args, strings.NewReader(""), &stdout, &stderr); code != 0 {
|
|
t.Fatalf("%v = %d stdout=%q stderr=%q", args, code, stdout.String(), stderr.String())
|
|
}
|
|
if strings.Contains(stdout.String()+stderr.String(), "initial administrator password") || strings.Contains(stdout.String()+stderr.String(), "$argon2id$") {
|
|
t.Fatalf("%v exposed password material", args)
|
|
}
|
|
}
|
|
var stdout, stderr bytes.Buffer
|
|
if code := Run(context.Background(), installation, []string{"user", "disable", "admin"}, strings.NewReader(""), &stdout, &stderr); code == 0 {
|
|
t.Fatal("last administrator disable succeeded")
|
|
}
|
|
if code := Run(context.Background(), installation, []string{"user", "revoke", "admin", "--role", "admin"}, strings.NewReader(""), &stdout, &stderr); code == 0 {
|
|
t.Fatal("last administrator revoke succeeded")
|
|
}
|
|
}
|
|
|
|
func TestRunLogoutAllIncrementsRevisionAndUserCommandsRefuseOIDC(t *testing.T) {
|
|
directory := newAuthDirectory(t)
|
|
installation := authInstallation(directory)
|
|
passwordFile := writePasswordFile(t, "initial administrator password\n")
|
|
if code := Run(context.Background(), installation, []string{"configure", "--mode", "local", "--public-url", "http://127.0.0.1:8080", "--admin-user", "admin", "--password-file", passwordFile}, strings.NewReader(""), ioDiscard{}, ioDiscard{}); code != 0 {
|
|
t.Fatalf("configure = %d", code)
|
|
}
|
|
if code := Run(context.Background(), installation, []string{"user", "logout-all", "admin", "--yes"}, strings.NewReader(""), ioDiscard{}, ioDiscard{}); code != 0 {
|
|
t.Fatalf("logout all = %d", code)
|
|
}
|
|
_, registry, err := Load(directory)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if registry.Users[0].AuthRevision != 2 {
|
|
t.Fatalf("logout-all revision = %d, want 2", registry.Users[0].AuthRevision)
|
|
}
|
|
|
|
oidcDirectory := newAuthDirectory(t)
|
|
if code := Run(context.Background(), authInstallation(oidcDirectory), []string{"configure", "--mode", "oidc", "--public-url", "https://thothii.example.org", "--issuer", "https://authentik.example.org/application/o/thothii/", "--client-id", "thothii", "--authentik-base-url", "https://authentik.example.org", "--user-group", "TOT Users", "--admin-group", "TOT Admin"}, strings.NewReader(""), ioDiscard{}, ioDiscard{}); code != 0 {
|
|
t.Fatalf("OIDC configure = %d", code)
|
|
}
|
|
if code := Run(context.Background(), authInstallation(oidcDirectory), []string{"user", "list", "--json"}, strings.NewReader(""), ioDiscard{}, ioDiscard{}); code == 0 {
|
|
t.Fatal("OIDC user command succeeded")
|
|
}
|
|
}
|
|
|
|
func TestRunRefusesNonTTYPasswordsWithoutPasswordFile(t *testing.T) {
|
|
directory := newAuthDirectory(t)
|
|
var stdout, stderr bytes.Buffer
|
|
code := Run(context.Background(), authInstallation(directory), []string{"configure", "--mode", "local", "--public-url", "http://127.0.0.1:8080", "--admin-user", "admin"}, strings.NewReader("not a password source"), &stdout, &stderr)
|
|
if code == 0 || !strings.Contains(stderr.String(), "--password-file") {
|
|
t.Fatalf("non-TTY password source was accepted: code=%d stdout=%q stderr=%q", code, stdout.String(), stderr.String())
|
|
}
|
|
}
|
|
|
|
func TestRunBumpsRevisionExactlyOnceForEverySecurityMutation(t *testing.T) {
|
|
directory := newAuthDirectory(t)
|
|
installation := authInstallation(directory)
|
|
adminPassword := writePasswordFile(t, "initial administrator password\n")
|
|
userPassword := writePasswordFile(t, "ordinary user password one\n")
|
|
if code := Run(context.Background(), installation, []string{"configure", "--mode", "local", "--public-url", "http://127.0.0.1:8080", "--admin-user", "admin", "--password-file", adminPassword}, strings.NewReader(""), ioDiscard{}, ioDiscard{}); code != 0 {
|
|
t.Fatalf("configure = %d", code)
|
|
}
|
|
if code := Run(context.Background(), installation, []string{"user", "add", "operator", "--role", "user", "--password-file", userPassword}, strings.NewReader(""), ioDiscard{}, ioDiscard{}); code != 0 {
|
|
t.Fatalf("add = %d", code)
|
|
}
|
|
for _, test := range []struct {
|
|
args []string
|
|
wantRevision uint64
|
|
wantCode int
|
|
}{
|
|
{[]string{"user", "set-password", "operator", "--password-file", adminPassword}, 2, 0},
|
|
{[]string{"user", "disable", "operator"}, 3, 0},
|
|
{[]string{"user", "disable", "operator"}, 3, 0}, // intentional idempotent no-op
|
|
{[]string{"user", "enable", "operator"}, 4, 0},
|
|
{[]string{"user", "enable", "operator"}, 4, 0}, // intentional idempotent no-op
|
|
{[]string{"user", "grant", "operator", "--role", "admin"}, 5, 0},
|
|
{[]string{"user", "grant", "operator", "--role", "admin"}, 5, 2}, // rejected duplicate
|
|
{[]string{"user", "revoke", "operator", "--role", "admin"}, 6, 0},
|
|
{[]string{"user", "revoke", "operator", "--role", "admin"}, 6, 2}, // rejected duplicate
|
|
{[]string{"user", "logout-all", "operator", "--yes"}, 7, 0},
|
|
} {
|
|
code := Run(context.Background(), installation, test.args, strings.NewReader(""), ioDiscard{}, ioDiscard{})
|
|
if code != test.wantCode {
|
|
t.Fatalf("%v = %d, want %d", test.args, code, test.wantCode)
|
|
}
|
|
if got := authRevisionFor(t, directory, "operator"); got != test.wantRevision {
|
|
t.Fatalf("%v revision = %d, want %d", test.args, got, test.wantRevision)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRunUserListJSONRedactsPasswordHash(t *testing.T) {
|
|
directory := newAuthDirectory(t)
|
|
installation := authInstallation(directory)
|
|
passwordFile := writePasswordFile(t, "this is a local test password\n")
|
|
if code := Run(context.Background(), installation, []string{"configure", "--mode", "local", "--public-url", "http://127.0.0.1:8080", "--admin-user", "admin", "--password-file", passwordFile}, strings.NewReader(""), ioDiscard{}, ioDiscard{}); code != 0 {
|
|
t.Fatalf("configure = %d", code)
|
|
}
|
|
var stdout, stderr bytes.Buffer
|
|
if code := Run(context.Background(), installation, []string{"user", "list", "--json"}, strings.NewReader(""), &stdout, &stderr); code != 0 {
|
|
t.Fatalf("list = %d, stderr=%q", code, stderr.String())
|
|
}
|
|
var listed struct {
|
|
Users []User `json:"users"`
|
|
}
|
|
if err := json.Unmarshal(stdout.Bytes(), &listed); err != nil || len(listed.Users) != 1 {
|
|
t.Fatalf("list JSON = %q, err=%v", stdout.String(), err)
|
|
}
|
|
if strings.Contains(stdout.String()+stderr.String(), "this is a local test password") || strings.Contains(stdout.String()+stderr.String(), "$argon2id$") || strings.Contains(stdout.String(), "passwordHash") {
|
|
t.Fatalf("list JSON exposed password material: stdout=%q stderr=%q", stdout.String(), stderr.String())
|
|
}
|
|
}
|
|
|
|
func TestStrictOptionParsersRejectEmptyDuplicateMissingAndWrongModeFlags(t *testing.T) {
|
|
for _, args := range [][]string{
|
|
{"--mode", "local", "--public-url", "http://127.0.0.1:8080", "--admin-display-name", "", "--admin-display-name", "Admin"},
|
|
{"--mode", "local", "--public-url", "http://127.0.0.1:8080", "--issuer", "https://auth.example.org/"},
|
|
{"--mode", "oidc", "--public-url", "https://thothii.example.org", "--issuer", "https://auth.example.org/", "--client-id", "client", "--authentik-base-url", "https://auth.example.org", "--user-group", "users", "--admin-group", "admins", "--password-file", "password-file"},
|
|
{"--mode", "local", "--public-url"},
|
|
} {
|
|
if _, err := parseConfigure(args); err == nil {
|
|
t.Fatalf("parseConfigure(%q) accepted unsafe options", args)
|
|
}
|
|
}
|
|
for _, args := range [][]string{
|
|
{"operator", "--role", "user", "--display-name", "", "--display-name", "Operator"},
|
|
{"operator", "--role", "user", "--password-file", ""},
|
|
{"operator", "--role"},
|
|
} {
|
|
if _, _, err := parseUserRolePassword(args); err == nil {
|
|
t.Fatalf("parseUserRolePassword(%q) accepted unsafe options", args)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestConfigureRecoversSafeOrphanUsersFileAfterInterruptedBootstrap(t *testing.T) {
|
|
directory := writeAuthFiles(t, defaultAuthYAML, registryYAML(adminUserYAML("abandoned", "Abandoned", true, "admin")))
|
|
if err := safeio.RemoveCanonicalPrivateRegular(filepath.Join(directory, authFileName)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
passwordFile := writePasswordFile(t, "this is a local test password\n")
|
|
if code := Run(context.Background(), authInstallation(directory), []string{"configure", "--mode", "local", "--public-url", "http://127.0.0.1:8080", "--admin-user", "admin", "--password-file", passwordFile}, strings.NewReader(""), ioDiscard{}, ioDiscard{}); code != 0 {
|
|
t.Fatalf("recovered configure = %d", code)
|
|
}
|
|
if got := authRevisionFor(t, directory, "admin"); got != 1 {
|
|
t.Fatalf("recovered initial administrator revision = %d, want 1", got)
|
|
}
|
|
}
|
|
|
|
func TestConfigureRollsBackPublishFailureAndRetrySucceeds(t *testing.T) {
|
|
for _, failAt := range []int{1, 2} {
|
|
t.Run("publish failure", func(t *testing.T) {
|
|
directory := newAuthDirectory(t)
|
|
passwordFile := writePasswordFile(t, "this is a local test password\n")
|
|
previous := writeNewAuthFile
|
|
calls := 0
|
|
writeNewAuthFile = func(path string, contents []byte, mode os.FileMode) error {
|
|
calls++
|
|
if calls == failAt {
|
|
return errors.New("injected publish failure")
|
|
}
|
|
return previous(path, contents, mode)
|
|
}
|
|
t.Cleanup(func() { writeNewAuthFile = previous })
|
|
if code := Run(context.Background(), authInstallation(directory), []string{"configure", "--mode", "local", "--public-url", "http://127.0.0.1:8080", "--admin-user", "admin", "--password-file", passwordFile}, strings.NewReader(""), ioDiscard{}, ioDiscard{}); code == 0 {
|
|
t.Fatal("configure succeeded despite injected publish failure")
|
|
}
|
|
for _, name := range []string{authFileName, usersFileName} {
|
|
if _, err := os.Lstat(filepath.Join(directory, name)); !errors.Is(err, os.ErrNotExist) {
|
|
t.Fatalf("%s remains after failed bootstrap: %v", name, err)
|
|
}
|
|
}
|
|
writeNewAuthFile = previous
|
|
if code := Run(context.Background(), authInstallation(directory), []string{"configure", "--mode", "local", "--public-url", "http://127.0.0.1:8080", "--admin-user", "admin", "--password-file", passwordFile}, strings.NewReader(""), ioDiscard{}, ioDiscard{}); code != 0 {
|
|
t.Fatalf("retry = %d", code)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func authRevisionFor(t *testing.T, directory, username string) uint64 {
|
|
t.Helper()
|
|
_, registry, err := Load(directory)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
user := registry.FindByUsername(username)
|
|
if user == nil {
|
|
t.Fatalf("missing user %q", username)
|
|
}
|
|
return user.AuthRevision
|
|
}
|
|
|
|
func writePasswordFile(t *testing.T, password string) string {
|
|
t.Helper()
|
|
path := filepath.Join(newAuthDirectory(t), "password")
|
|
if err := os.Mkdir(filepath.Dir(path), 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(path, []byte(password), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
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{EnvFile: filepath.Join(filepath.Dir(directory), "operator.env")}
|
|
installation.Authentication.ConfigDirectory = directory
|
|
return installation
|
|
}
|
|
|
|
func newAuthDirectory(t *testing.T) string {
|
|
t.Helper()
|
|
root, err := filepath.EvalSymlinks(t.TempDir())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(root, "operator.env"), []byte("SAFE_VALUE=1\n"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return filepath.Join(root, "auth")
|
|
}
|
|
|
|
type ioDiscard struct{}
|
|
|
|
func (ioDiscard) Write(contents []byte) (int, error) { return len(contents), nil }
|