feat(auth): include authentication in workspace and tht diagnostics
This commit is contained in:
@@ -15,8 +15,11 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/compose"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/config"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/output"
|
||||
"github.com/aritmolab/thothii/tools/tht/internal/safeio"
|
||||
"golang.org/x/term"
|
||||
"gopkg.in/yaml.v3"
|
||||
@@ -24,6 +27,12 @@ import (
|
||||
|
||||
const maxPasswordFileBytes int64 = 1025
|
||||
|
||||
const authCheckTimeout = 45 * time.Second
|
||||
|
||||
const interactiveAuthCheckTimeout = 12 * time.Minute
|
||||
|
||||
const maxAuthDiagnosticOutputBytes = 64 * 1024
|
||||
|
||||
var errCommandRefused = errors.New("authentication command refused")
|
||||
|
||||
var writeNewAuthFile = safeio.WriteCanonicalNewFile
|
||||
@@ -32,7 +41,12 @@ var removeAuthFile = safeio.RemoveCanonicalPrivateRegular
|
||||
// Run implements the host-only authentication operator surface. It accepts password bytes only
|
||||
// from an echo-free terminal or a bounded private file, and never writes them to either stream.
|
||||
func Run(ctx context.Context, installation config.Installation, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||
_ = ctx
|
||||
return RunWithRunner(ctx, installation, args, stdin, stdout, stderr, compose.NewRunner(""))
|
||||
}
|
||||
|
||||
// RunWithRunner retains the operator grammar while providing the shared shell-free runner seam
|
||||
// used by the aggregate doctor and command tests.
|
||||
func RunWithRunner(ctx context.Context, installation config.Installation, args []string, stdin io.Reader, stdout, stderr io.Writer, runner compose.Runner) int {
|
||||
if len(args) == 0 {
|
||||
return authFailure(stderr, "auth requires a subcommand")
|
||||
}
|
||||
@@ -54,12 +68,212 @@ func Run(ctx context.Context, installation config.Installation, args []string, s
|
||||
}
|
||||
return 0
|
||||
case "check":
|
||||
return authFailure(stderr, "auth check is not available in this release")
|
||||
return checkCommand(ctx, installation, args[1:], stdout, stderr, runner)
|
||||
default:
|
||||
return authFailure(stderr, "unknown auth subcommand")
|
||||
}
|
||||
}
|
||||
|
||||
// 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"`
|
||||
Field *string `json:"field,omitempty"`
|
||||
}
|
||||
|
||||
// AuthDiagnostics is intentionally isomorphic to backend AuthDiagnostics.
|
||||
type AuthDiagnostics struct {
|
||||
Ready bool `json:"ready"`
|
||||
Mode string `json:"mode"`
|
||||
Checks []AuthDiagnostic `json:"checks"`
|
||||
}
|
||||
|
||||
func parseCheckArgs(args []string) (jsonMode, interactive bool, err error) {
|
||||
for _, arg := range args {
|
||||
switch arg {
|
||||
case "--json":
|
||||
if jsonMode {
|
||||
return false, false, errCommandRefused
|
||||
}
|
||||
jsonMode = true
|
||||
case "--interactive":
|
||||
if interactive {
|
||||
return false, false, errCommandRefused
|
||||
}
|
||||
interactive = true
|
||||
default:
|
||||
return false, false, errCommandRefused
|
||||
}
|
||||
}
|
||||
return jsonMode, interactive, nil
|
||||
}
|
||||
|
||||
func checkCommand(ctx context.Context, installation config.Installation, args []string, stdout, stderr io.Writer, runner compose.Runner) int {
|
||||
jsonMode, interactive, err := parseCheckArgs(args)
|
||||
if err != nil {
|
||||
return authFailure(stderr, authMessage(err))
|
||||
}
|
||||
report, prompt, err := runCheck(ctx, installation, runner, interactive, false)
|
||||
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")
|
||||
return 1
|
||||
}
|
||||
} else {
|
||||
status := "failed"
|
||||
if report.Ready {
|
||||
status = "passed"
|
||||
}
|
||||
fmt.Fprintf(stdout, "authentication: %s\n", status)
|
||||
for _, check := range report.Checks {
|
||||
if check.Level == "error" {
|
||||
fmt.Fprintf(stdout, "%s: %s\n", check.Code, check.Message)
|
||||
}
|
||||
}
|
||||
}
|
||||
if report.Ready {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
var authDiagnosticCodes = map[string]struct{}{
|
||||
"auth_ready": {}, "auth_config_incomplete": {}, "auth_config_invalid": {}, "auth_session_store_invalid": {},
|
||||
"local_user_registry_invalid": {}, "local_admin_missing": {}, "oidc_secret_missing": {},
|
||||
"oidc_discovery_unreachable": {}, "oidc_issuer_mismatch": {}, "oidc_jwks_unreachable": {},
|
||||
"oidc_group_catalog_unreachable": {}, "oidc_group_catalog_unauthorized": {}, "oidc_mapped_group_missing": {},
|
||||
"oidc_mapped_group_ambiguous": {}, "oidc_groups_claim_invalid": {}, "oidc_device_flow_unavailable": {},
|
||||
}
|
||||
|
||||
func validAuthDiagnostics(report AuthDiagnostics) bool {
|
||||
if report.Mode != "local" && report.Mode != "oidc" && report.Mode != "upstream" && report.Mode != "none" && report.Mode != "mock" {
|
||||
return false
|
||||
}
|
||||
if len(report.Checks) == 0 || len(report.Checks) > 129 {
|
||||
return false
|
||||
}
|
||||
for _, check := range report.Checks {
|
||||
if (check.Level != "error" && check.Level != "info") || check.Message == "" || len(check.Message) > 512 {
|
||||
return false
|
||||
}
|
||||
if _, ok := authDiagnosticCodes[check.Code]; !ok {
|
||||
return false
|
||||
}
|
||||
if check.Field != nil && (*check.Field == "" || len(*check.Field) > 512) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func authenticationSecretValues(installation config.Installation) []string {
|
||||
files, err := installation.SecretFiles()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
values, err := output.SecretValuesFromFiles(files)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func sanitizeAuthDiagnostics(report AuthDiagnostics, secrets []string) AuthDiagnostics {
|
||||
for index := range report.Checks {
|
||||
report.Checks[index].Message = output.Sanitize(report.Checks[index].Message, secrets)
|
||||
if report.Checks[index].Field != nil {
|
||||
field := output.Sanitize(*report.Checks[index].Field, secrets)
|
||||
report.Checks[index].Field = &field
|
||||
}
|
||||
}
|
||||
return report
|
||||
}
|
||||
|
||||
func devicePrompt(stderr string, secrets []string) string {
|
||||
if len(stderr) > maxAuthDiagnosticOutputBytes {
|
||||
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
|
||||
}
|
||||
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 ""
|
||||
}
|
||||
|
||||
func validDeviceVerificationURI(value string) bool {
|
||||
parsed, err := url.Parse(value)
|
||||
return err == nil && parsed.Scheme == "https" && parsed.Host != "" && parsed.User == nil && parsed.Fragment == ""
|
||||
}
|
||||
|
||||
func validDeviceUserCode(value string) bool {
|
||||
if len(value) < 4 || len(value) > 256 {
|
||||
return false
|
||||
}
|
||||
for _, character := range value {
|
||||
letter := (character >= 'A' && character <= 'Z') || (character >= 'a' && character <= 'z')
|
||||
digit := character >= '0' && character <= '9'
|
||||
punctuation := character == '-' || character == '.' || character == '_' || character == '~'
|
||||
if !letter && !digit && !punctuation {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
func runCheck(ctx context.Context, installation config.Installation, runner compose.Runner, interactive, useRunningCore bool) (AuthDiagnostics, string, error) {
|
||||
if runner == nil {
|
||||
return AuthDiagnostics{}, "", errors.New("authentication diagnostic runner is unavailable")
|
||||
}
|
||||
timeout := authCheckTimeout
|
||||
if interactive {
|
||||
timeout = interactiveAuthCheckTimeout
|
||||
}
|
||||
bounded, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
command := []string{"run", "--rm", "--no-deps", "--no-TTY", "core", "node", "dist/auth/diagnostic-command.js", "--json"}
|
||||
if useRunningCore {
|
||||
command = []string{"exec", "-T", "core", "node", "dist/auth/diagnostic-command.js", "--json"}
|
||||
}
|
||||
if interactive {
|
||||
command = append(command, "--interactive")
|
||||
}
|
||||
result, err := runner.Run(bounded, installation.ComposeArgs(command...), nil)
|
||||
secrets := authenticationSecretValues(installation)
|
||||
if err != nil || result.ExitCode != 0 || len(result.Stdout) > maxAuthDiagnosticOutputBytes || len(result.Stderr) > maxAuthDiagnosticOutputBytes {
|
||||
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) {
|
||||
return AuthDiagnostics{}, "", errors.New("authentication diagnostic report is invalid")
|
||||
}
|
||||
return sanitizeAuthDiagnostics(report, secrets), devicePrompt(result.Stderr, secrets), nil
|
||||
}
|
||||
|
||||
func authFailure(stderr io.Writer, message string) int {
|
||||
fmt.Fprintf(stderr, "tht: %s\n", message)
|
||||
return 2
|
||||
|
||||
Reference in New Issue
Block a user