From 0713ee06edd65f0bda70ccd2c1c158436640799a Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Sun, 8 Nov 2026 08:22:19 -0800 Subject: [PATCH 1/3] feat(auth): add break-glass login links for OIDC mode `fanout login-link --break-glass ` issues a one-time link for an active administrator when the identity provider is unavailable. In OIDC mode `/api/auth/link/verify` accepts only those links, re-checks the account is still an active administrator, and writes distinct audit events for issuing and redeeming. A break-glass link is a distinct `verifications.purpose`, so ordinary links can never match it and no migration is needed. OIDC startup still does not require FANOUT_AUTH_CODE_SECRET; issuing fails with an error naming the variable and the route stays disabled until it is set, and the code store refuses to hash credentials with an empty secret. Closes #444 --- .env.example | 2 +- README.md | 2 +- cmd/fanout/main.go | 78 +++++++-- cmd/fanout/main_test.go | 156 ++++++++++++++++- docs/authentication.md | 36 +++- internal/api/auth.go | 24 ++- internal/api/auth_test.go | 162 ++++++++++++++++++ internal/auth/audit.go | 3 +- internal/auth/code.go | 45 ++++- internal/auth/code_test.go | 75 ++++++++ internal/config/config.go | 17 +- internal/config/config_test.go | 26 +++ internal/db/generated/codes.sql.go | 11 +- internal/db/queries/codes.sql | 2 +- .../docs/docs/concepts/authentication.mdx | 28 ++- .../docs/docs/guides/troubleshooting.mdx | 4 +- site/src/content/docs/docs/reference/cli.mdx | 15 ++ .../docs/reference/configuration/auth.mdx | 2 +- 18 files changed, 637 insertions(+), 51 deletions(-) diff --git a/.env.example b/.env.example index 0c173671e..9eb0a5478 100644 --- a/.env.example +++ b/.env.example @@ -50,7 +50,7 @@ # FANOUT_ALERTS_HISTORY_DAYS= # FANOUT_AUTH_CODE_SECRET; string; secret -# Signs local sign-in codes; required in local mode with at least 32 characters. +# Signs sign-in codes and login links; needs at least 32 characters in local mode and to issue or redeem OIDC break-glass links. # Default: (empty) # FANOUT_AUTH_CODE_SECRET= # Alternatively set FANOUT_AUTH_CODE_SECRET_FILE to a secret file path; do not set both. diff --git a/README.md b/README.md index 17d33d14e..c62e8f0f7 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ change requires a restart. | `FANOUT_ADDR` | `127.0.0.1:7520` | UI, API, MCP, and both OTLP transports | | `FANOUT_DATA_DIR` | `./data` | Parquet, query state, and control SQLite | | `FANOUT_AUTH_MODE` | `local` | Login link or SMTP, or `oidc` | -| `FANOUT_AUTH_CODE_SECRET` | — | Required in local mode, 32+ characters | +| `FANOUT_AUTH_CODE_SECRET` | — | Required in local mode and for OIDC break-glass links, 32+ characters | | `FANOUT_AI_PROVIDER` | — | Empty disables chat; `anthropic` or `openai` enables it | | `ANTHROPIC_API_KEY` | — | Required for Anthropic chat | | `OPENAI_API_KEY` | — | Required for OpenAI chat | diff --git a/cmd/fanout/main.go b/cmd/fanout/main.go index 6e8c83453..e6eebc03b 100644 --- a/cmd/fanout/main.go +++ b/cmd/fanout/main.go @@ -61,8 +61,13 @@ type repairCommand struct { batch string } +type loginLinkCommand struct { + email string + breakGlass bool +} + func main() { - showVersion, loginEmail, healthURL, derivedProbe, repair, err := parseCommandLine(os.Args[1:], os.Stderr) + showVersion, loginLink, healthURL, derivedProbe, repair, err := parseCommandLine(os.Args[1:], os.Stderr) if errors.Is(err, flag.ErrHelp) { return } @@ -103,8 +108,8 @@ func main() { } return } - if loginEmail != "" { - if err := createLoginLink(cfg, loginEmail, os.Stderr); err != nil { + if loginLink != nil { + if err := createLoginLink(cfg, loginLink.email, loginLink.breakGlass, os.Stderr); err != nil { slog.Error("create login link failed", "err", err) os.Exit(1) } @@ -477,15 +482,15 @@ func main() { } } -func parseCommandLine(args []string, output io.Writer) (showVersion bool, loginEmail, healthURL string, derivedProbe bool, repair *repairCommand, err error) { +func parseCommandLine(args []string, output io.Writer) (showVersion bool, loginLink *loginLinkCommand, healthURL string, derivedProbe bool, repair *repairCommand, err error) { if len(args) == 1 && args[0] == "version" { - return true, "", "", false, nil, nil + return true, nil, "", false, nil, nil } if len(args) >= 1 && len(args) <= 2 && args[0] == "healthcheck" { if len(args) == 2 { - return false, "", args[1], false, nil, nil + return false, nil, args[1], false, nil, nil } - return false, "", "", true, nil, nil + return false, nil, "", true, nil, nil } flags := flag.NewFlagSet("fanout", flag.ContinueOnError) @@ -493,7 +498,7 @@ func parseCommandLine(args []string, output io.Writer) (showVersion bool, loginE flags.Usage = func() { fmt.Fprintln(output, "Usage of fanout:") fmt.Fprintln(output, " fanout [flags]") - fmt.Fprintln(output, " fanout login-link ") + fmt.Fprintln(output, " fanout login-link [--break-glass]") fmt.Fprintln(output, " fanout repair verify") fmt.Fprintln(output, " fanout repair quarantine --batch ") fmt.Fprintln(output, " fanout healthcheck [url]") @@ -504,22 +509,41 @@ func parseCommandLine(args []string, output io.Writer) (showVersion bool, loginE flags.BoolVar(&showVersion, "version", false, "print the Fanout version") flags.BoolVar(&showVersion, "v", false, "print the Fanout version") if err := flags.Parse(args); err != nil { - return false, "", "", false, nil, err + return false, nil, "", false, nil, err } - if flags.NArg() == 2 && flags.Arg(0) == "login-link" { - return false, flags.Arg(1), "", false, nil, nil + if flags.NArg() > 0 && flags.Arg(0) == "login-link" { + if command, ok := parseLoginLinkCommand(flags.Args()[1:]); ok { + return false, &command, "", false, nil, nil + } } if flags.NArg() > 0 && flags.Arg(0) == "repair" { repair, err := parseRepairCommand(flags.Args()[1:], output) - return false, "", "", false, repair, err + return false, nil, "", false, repair, err } if flags.NArg() != 0 { err := fmt.Errorf("unexpected arguments: %s", strings.Join(flags.Args(), " ")) fmt.Fprintln(output, err) flags.Usage() - return false, "", "", false, nil, err + return false, nil, "", false, nil, err } - return showVersion, "", "", false, nil, nil + return showVersion, nil, "", false, nil, nil +} + +// parseLoginLinkCommand accepts --break-glass on either side of the email, +// which the standard flag package cannot do once parsing reaches an operand. +func parseLoginLinkCommand(args []string) (loginLinkCommand, bool) { + var command loginLinkCommand + for _, arg := range args { + switch { + case arg == "--break-glass": + command.breakGlass = true + case strings.HasPrefix(arg, "-") || command.email != "": + return loginLinkCommand{}, false + default: + command.email = arg + } + } + return command, command.email != "" } func parseRepairCommand(args []string, output io.Writer) (*repairCommand, error) { @@ -667,8 +691,16 @@ func checkHealth(healthURL string, derivedProbe bool, certFile, clientCertFile, return nil } -func createLoginLink(cfg config.Config, rawEmail string, output io.Writer) error { - if strings.ToLower(strings.TrimSpace(cfg.AuthMode)) != "local" { +func createLoginLink(cfg config.Config, rawEmail string, breakGlass bool, output io.Writer) error { + mode := strings.ToLower(strings.TrimSpace(cfg.AuthMode)) + if breakGlass { + if mode != "oidc" { + return fmt.Errorf("--break-glass is available only in oidc auth mode; use fanout login-link in local mode") + } + if err := cfg.ValidateLoginLinkSecret(); err != nil { + return fmt.Errorf("break-glass login links need a configured secret: %w", err) + } + } else if mode != "local" { return fmt.Errorf("login links are available only in local auth mode") } email, err := auth.NormalizeEmail(rawEmail) @@ -693,12 +725,20 @@ func createLoginLink(cfg config.Config, rawEmail string, output io.Writer) error if user.Status != auth.UserStatusActive { return fmt.Errorf("user %s is suspended", email) } - token, err := auth.NewCodeStore(sqlite.DB, cfg.AuthCodeSecret).CreateLoginLink(email) + if breakGlass && user.Role != auth.RoleAdmin { + return fmt.Errorf("user %s is not an administrator; break-glass links are limited to active administrators", email) + } + codes := auth.NewCodeStore(sqlite.DB, cfg.AuthCodeSecret) + createLink, issuedEvent, label := codes.CreateLoginLink, auth.AuditEventType("login_link.issued"), "login link" + if breakGlass { + createLink, issuedEvent, label = codes.CreateBreakGlassLoginLink, auth.AuditEventType("login_link.break_glass_issued"), "break-glass login link" + } + token, err := createLink(email) if err != nil { return err } if err := auth.NewAuditStore(sqlite.DB).Record(context.Background(), auth.AuditEvent{ - EventType: "login_link.issued", + EventType: issuedEvent, Outcome: "success", TargetType: "user", TargetID: user.ID, @@ -709,7 +749,7 @@ func createLoginLink(cfg config.Config, rawEmail string, output io.Writer) error query := loginURL.Query() query.Set("login_token", token) loginURL.RawQuery = query.Encode() - fmt.Fprintf(output, "fanout: login link for %s (valid 15 minutes, single use)\n %s\n", email, loginURL.String()) + fmt.Fprintf(output, "fanout: %s for %s (valid 15 minutes, single use)\n %s\n", label, email, loginURL.String()) return nil } diff --git a/cmd/fanout/main_test.go b/cmd/fanout/main_test.go index a91915d73..9fb39fddb 100644 --- a/cmd/fanout/main_test.go +++ b/cmd/fanout/main_test.go @@ -41,7 +41,7 @@ func TestParseCommandLine(t *testing.T) { name string args []string wantVersion bool - wantEmail string + wantLink *loginLinkCommand wantHealth string wantDerived bool wantRepair *repairCommand @@ -51,7 +51,12 @@ func TestParseCommandLine(t *testing.T) { {name: "version command", args: []string{"version"}, wantVersion: true}, {name: "version flag", args: []string{"--version"}, wantVersion: true}, {name: "short version flag", args: []string{"-v"}, wantVersion: true}, - {name: "login link", args: []string{"login-link", "admin@example.com"}, wantEmail: "admin@example.com"}, + {name: "login link", args: []string{"login-link", "admin@example.com"}, wantLink: &loginLinkCommand{email: "admin@example.com"}}, + {name: "break-glass login link", args: []string{"login-link", "--break-glass", "admin@example.com"}, wantLink: &loginLinkCommand{email: "admin@example.com", breakGlass: true}}, + {name: "break-glass flag after email", args: []string{"login-link", "admin@example.com", "--break-glass"}, wantLink: &loginLinkCommand{email: "admin@example.com", breakGlass: true}}, + {name: "login link break-glass without email", args: []string{"login-link", "--break-glass"}, wantErr: true}, + {name: "login link unknown flag", args: []string{"login-link", "--force", "admin@example.com"}, wantErr: true}, + {name: "login link two emails", args: []string{"login-link", "a@example.com", "b@example.com"}, wantErr: true}, {name: "default healthcheck", args: []string{"healthcheck"}, wantDerived: true}, {name: "custom healthcheck", args: []string{"healthcheck", "http://fanout:8080/healthz"}, wantHealth: "http://fanout:8080/healthz"}, {name: "repair verify", args: []string{"repair", "verify"}, wantRepair: &repairCommand{action: "verify"}}, @@ -64,12 +69,15 @@ func TestParseCommandLine(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - showVersion, email, healthURL, derivedProbe, repair, err := parseCommandLine(test.args, io.Discard) + showVersion, loginLink, healthURL, derivedProbe, repair, err := parseCommandLine(test.args, io.Discard) if (err != nil) != test.wantErr { t.Fatalf("error = %v, wantErr %v", err, test.wantErr) } - if showVersion != test.wantVersion || email != test.wantEmail || healthURL != test.wantHealth || derivedProbe != test.wantDerived { - t.Fatalf("result = (%v, %q, %q, %v), want (%v, %q, %q, %v)", showVersion, email, healthURL, derivedProbe, test.wantVersion, test.wantEmail, test.wantHealth, test.wantDerived) + if showVersion != test.wantVersion || healthURL != test.wantHealth || derivedProbe != test.wantDerived { + t.Fatalf("result = (%v, %q, %v), want (%v, %q, %v)", showVersion, healthURL, derivedProbe, test.wantVersion, test.wantHealth, test.wantDerived) + } + if loginLink == nil != (test.wantLink == nil) || loginLink != nil && *loginLink != *test.wantLink { + t.Fatalf("login link = %#v, want %#v", loginLink, test.wantLink) } if repair == nil != (test.wantRepair == nil) || repair != nil && *repair != *test.wantRepair { t.Fatalf("repair = %#v, want %#v", repair, test.wantRepair) @@ -189,7 +197,7 @@ func TestCreateLoginLink(t *testing.T) { } var output bytes.Buffer - if err := createLoginLink(cfg, " ADMIN@example.com ", &output); err != nil { + if err := createLoginLink(cfg, " ADMIN@example.com ", false, &output); err != nil { t.Fatalf("createLoginLink: %v", err) } line := strings.TrimSpace(strings.Split(output.String(), "\n")[1]) @@ -219,6 +227,142 @@ func TestCreateLoginLink(t *testing.T) { } } +func breakGlassTestConfig(t *testing.T, role auth.Role, status auth.UserStatus) config.Config { + t.Helper() + cfg := config.Config{ + AuthMode: "oidc", + AuthCodeSecret: "0123456789abcdef0123456789abcdef", + DataDir: t.TempDir(), + Addr: ":7520", + PublicURL: "https://fanout.example.com", + } + if err := os.MkdirAll(cfg.ControlDir(), 0o755); err != nil { + t.Fatalf("MkdirAll: %v", err) + } + sqlite, err := store.NewSQLite(cfg.ControlSQLitePath()) + if err != nil { + t.Fatalf("NewSQLite: %v", err) + } + defer sqlite.Close() + users := auth.NewUserStore(sqlite.DB) + if _, err := users.CreateWithAudit("keeper@example.com", "", auth.RoleAdmin, auth.AuditEvent{EventType: "user.created", Outcome: "success"}); err != nil { + t.Fatalf("Create keeper: %v", err) + } + user, err := users.CreateWithAudit("user@example.com", "", auth.RoleAdmin, auth.AuditEvent{EventType: "user.created", Outcome: "success"}) + if err != nil { + t.Fatalf("Create user: %v", err) + } + if _, err := users.UpdateWithAudit(user.ID, nil, nil, &role, &status, auth.AuditEvent{EventType: "user.updated", Outcome: "success"}); err != nil { + t.Fatalf("Update user: %v", err) + } + return cfg +} + +func loginLinkState(t *testing.T, cfg config.Config) (links, issued, breakGlassIssued int) { + t.Helper() + sqlite, err := store.NewSQLite(cfg.ControlSQLitePath()) + if err != nil { + t.Fatalf("reopen SQLite: %v", err) + } + defer sqlite.Close() + if err := sqlite.DB.QueryRow(`SELECT COUNT(*) FROM verifications`).Scan(&links); err != nil { + t.Fatalf("count verifications: %v", err) + } + if err := sqlite.DB.QueryRow(`SELECT COUNT(*) FROM auth_audit_events WHERE event_type = 'login_link.issued'`).Scan(&issued); err != nil { + t.Fatalf("count issued: %v", err) + } + if err := sqlite.DB.QueryRow(`SELECT COUNT(*) FROM auth_audit_events WHERE event_type = 'login_link.break_glass_issued'`).Scan(&breakGlassIssued); err != nil { + t.Fatalf("count break-glass issued: %v", err) + } + return links, issued, breakGlassIssued +} + +func TestCreateBreakGlassLoginLinkForActiveAdministrator(t *testing.T) { + cfg := breakGlassTestConfig(t, auth.RoleAdmin, auth.UserStatusActive) + var output bytes.Buffer + if err := createLoginLink(cfg, "user@example.com", true, &output); err != nil { + t.Fatalf("createLoginLink: %v", err) + } + if !strings.Contains(output.String(), "break-glass") { + t.Fatalf("output = %q, want it to identify a break-glass link", output.String()) + } + loginURL, err := url.Parse(strings.TrimSpace(strings.Split(output.String(), "\n")[1])) + if err != nil { + t.Fatalf("parse URL: %v", err) + } + sqlite, err := store.NewSQLite(cfg.ControlSQLitePath()) + if err != nil { + t.Fatalf("reopen SQLite: %v", err) + } + defer sqlite.Close() + codes := auth.NewCodeStore(sqlite.DB, cfg.AuthCodeSecret) + if _, ok, err := codes.VerifyLoginLink(loginURL.Query().Get("login_token")); err != nil || ok { + t.Fatalf("VerifyLoginLink(break-glass) = (%v, %v), want (false, nil)", ok, err) + } + if email, ok, err := codes.VerifyBreakGlassLoginLink(loginURL.Query().Get("login_token")); err != nil || !ok || email != "user@example.com" { + t.Fatalf("VerifyBreakGlassLoginLink = (%q, %v, %v)", email, ok, err) + } + var issued, breakGlassIssued int + if err := sqlite.DB.QueryRow(`SELECT + COUNT(*) FILTER (WHERE event_type = 'login_link.issued'), + COUNT(*) FILTER (WHERE event_type = 'login_link.break_glass_issued') + FROM auth_audit_events`).Scan(&issued, &breakGlassIssued); err != nil { + t.Fatalf("query audit: %v", err) + } + if issued != 0 || breakGlassIssued != 1 { + t.Fatalf("issued = %d, break-glass issued = %d, want 0 and 1", issued, breakGlassIssued) + } +} + +func TestCreateBreakGlassLoginLinkRefusals(t *testing.T) { + const email = "user@example.com" + for _, tc := range []struct { + name string + role auth.Role + status auth.UserStatus + mutate func(*config.Config) + email string + wantErr string + }{ + {name: "viewer", role: auth.RoleViewer, status: auth.UserStatusActive, email: email, wantErr: "administrator"}, + {name: "operator", role: auth.RoleOperator, status: auth.UserStatusActive, email: email, wantErr: "administrator"}, + {name: "suspended administrator", role: auth.RoleAdmin, status: auth.UserStatusSuspended, email: email, wantErr: "suspended"}, + {name: "empty secret", role: auth.RoleAdmin, status: auth.UserStatusActive, email: email, mutate: func(c *config.Config) { c.AuthCodeSecret = "" }, wantErr: "FANOUT_AUTH_CODE_SECRET"}, + {name: "short secret", role: auth.RoleAdmin, status: auth.UserStatusActive, email: email, mutate: func(c *config.Config) { c.AuthCodeSecret = "short" }, wantErr: "FANOUT_AUTH_CODE_SECRET"}, + {name: "local mode", role: auth.RoleAdmin, status: auth.UserStatusActive, email: email, mutate: func(c *config.Config) { c.AuthMode = "local" }, wantErr: "oidc"}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := breakGlassTestConfig(t, tc.role, tc.status) + if tc.mutate != nil { + tc.mutate(&cfg) + } + var output bytes.Buffer + err := createLoginLink(cfg, tc.email, true, &output) + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want it to mention %q", err, tc.wantErr) + } + if output.Len() != 0 { + t.Fatalf("output = %q, want none", output.String()) + } + if links, issued, breakGlassIssued := loginLinkState(t, cfg); links != 0 || issued != 0 || breakGlassIssued != 0 { + t.Fatalf("state = %d links, %d issued, %d break-glass issued; want none", links, issued, breakGlassIssued) + } + }) + } +} + +func TestCreateLoginLinkWithoutFlagStillRefusesOIDCMode(t *testing.T) { + cfg := breakGlassTestConfig(t, auth.RoleAdmin, auth.UserStatusActive) + var output bytes.Buffer + err := createLoginLink(cfg, "user@example.com", false, &output) + if err == nil || err.Error() != "login links are available only in local auth mode" { + t.Fatalf("error = %v", err) + } + if links, issued, breakGlassIssued := loginLinkState(t, cfg); links != 0 || issued != 0 || breakGlassIssued != 0 { + t.Fatalf("state = %d links, %d issued, %d break-glass issued; want none", links, issued, breakGlassIssued) + } +} + func TestHealthcheckURL(t *testing.T) { for _, tc := range []struct{ addr, cert, want string }{ {"", "", "http://127.0.0.1:7520/healthz"}, diff --git a/docs/authentication.md b/docs/authentication.md index 81e58cce3..b4017e62e 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -46,7 +46,8 @@ Local mode requires only a 32-character `FANOUT_AUTH_CODE_SECRET`. SMTP is optional: when all SMTP settings are present, users can request email codes; without them, an operator with access to the control database can mint a login link. OIDC mode instead requires an HTTPS issuer, a client, and an HTTPS -`FANOUT_PUBLIC_URL`. +`FANOUT_PUBLIC_URL`; set `FANOUT_AUTH_CODE_SECRET` as well to keep +[break-glass recovery](#oidc-break-glass-recovery) available. After setup in local mode, send yourself a code if SMTP is configured and confirm it arrives. Credentials @@ -89,9 +90,35 @@ one URL to stderr. The URL expires after 15 minutes, works once, and writes a distinct `login_link.redeemed` audit event when used. Running it while Fanout is online is supported by the control database's WAL and busy-timeout settings. -Fix SMTP after regaining access if email-code login is expected. OIDC-mode -recovery remains at the identity provider or OIDC configuration layer; local -login links are unavailable in that mode. +Fix SMTP after regaining access if email-code login is expected. Ordinary +login links are unavailable in OIDC mode; use a break-glass link instead. + +### OIDC break-glass recovery + +When the identity provider is unavailable, an operator with access to the +control database can issue a one-time link for an active administrator: + +```sh +fanout login-link --break-glass admin@example.com +``` + +`FANOUT_AUTH_CODE_SECRET` must be set to at least 32 characters, on both the +command and the server, because it protects the stored credential. OIDC mode +does not require the secret at startup, so an installation that wants this +recovery path must set it and restart Fanout before the outage. Without it the +command fails with an error naming the variable and `/api/auth/link/verify` +stays disabled. + +The command refuses other roles, suspended users, and local mode. The link +expires after 15 minutes and works once. In OIDC mode `/api/auth/link/verify` +accepts only these links, refuses an ordinary login link without consuming it, +and re-checks that the account is still an active administrator. Issuing writes +a `login_link.break_glass_issued` audit event and redeeming writes a +`login_link.break_glass_redeemed` audit event. + +Fanout contacts the identity provider's discovery endpoint when the server +starts, and exits if that fails. Break-glass access therefore needs a server +that is already running; do not restart Fanout during the outage. ### User account API @@ -258,6 +285,7 @@ access, including browser sessions and OAuth tokens, through |---|---|---| | Setup URL | Creates the first administrator | One-time, expires in 1 hour | | Login URL | Authenticates one existing active local user | One-time, expires in 15 minutes; mint with `fanout login-link` | +| Break-glass URL | Authenticates one active administrator in OIDC mode | One-time, expires in 15 minutes; mint with `fanout login-link --break-glass` | | Browser session | Interactive access | Idle and absolute TTL; revoked on role, email, or status change | | Ingest token | OTLP ingest | Settings page | | Metrics token | `/metrics` scrape | `FANOUT_METRICS_TOKEN` | diff --git a/internal/api/auth.go b/internal/api/auth.go index e2fe08796..40b85b754 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -324,7 +324,12 @@ func (h *AuthHandler) Verify(c *echo.Context) error { } func (h *AuthHandler) LoginLink(c *echo.Context) error { - if strings.ToLower(strings.TrimSpace(h.cfg.AuthMode)) != "local" { + mode := strings.ToLower(strings.TrimSpace(h.cfg.AuthMode)) + // OIDC mode redeems break-glass links only, and only once the operator has + // configured the secret that protects them. Without it the route stays + // disabled exactly as it is for an OIDC install that never opted in. + breakGlass := mode == "oidc" && h.cfg.ValidateLoginLinkSecret() == nil + if mode != "local" && !breakGlass { return echo.NewHTTPError(http.StatusNotFound, "local login is disabled") } if !h.verifyIPLimiter.Allow(c.RealIP()) { @@ -337,13 +342,17 @@ func (h *AuthHandler) LoginLink(c *echo.Context) error { return echo.NewHTTPError(http.StatusBadRequest, "login token is required") } - email, ok, err := h.codes.VerifyLoginLink(strings.TrimSpace(req.Token)) + verifyLink, redeemedEvent, invalidReason := h.codes.VerifyLoginLink, auth.AuditEventType("login_link.redeemed"), "invalid_login_link" + if breakGlass { + verifyLink, redeemedEvent, invalidReason = h.codes.VerifyBreakGlassLoginLink, auth.AuditEventType("login_link.break_glass_redeemed"), "invalid_break_glass_link" + } + email, ok, err := verifyLink(strings.TrimSpace(req.Token)) if err != nil { slog.Error("auth: verify login link", "err", err) return echo.NewHTTPError(http.StatusInternalServerError, "failed to verify login link") } if !ok { - h.recordAudit(c, auth.AuditEvent{EventType: "login.failed", Outcome: "denied", TargetType: "email", Metadata: map[string]any{"reason": "invalid_login_link"}}) + h.recordAudit(c, auth.AuditEvent{EventType: "login.failed", Outcome: "denied", TargetType: "email", Metadata: map[string]any{"reason": invalidReason}}) jitter() return echo.NewHTTPError(http.StatusUnauthorized, "invalid or expired login link") } @@ -358,11 +367,18 @@ func (h *AuthHandler) LoginLink(c *echo.Context) error { jitter() return echo.NewHTTPError(http.StatusUnauthorized, "user not found or suspended") } + // Re-check the role here: the account may have changed since the link was + // issued, and break-glass access exists for administrators alone. + if breakGlass && user.Role != auth.RoleAdmin { + h.recordAudit(c, auth.AuditEvent{EventType: "login.failed", Outcome: "denied", TargetType: "user", TargetID: user.ID, Metadata: map[string]any{"reason": "break_glass_requires_admin"}}) + jitter() + return echo.NewHTTPError(http.StatusForbidden, "break-glass login requires an administrator") + } if err := h.establishSession(c, user); err != nil { slog.Error("auth: login link session establishment failed", "user_id", user.ID, "err", err) return echo.NewHTTPError(http.StatusInternalServerError, "failed to create session") } - h.recordAudit(c, auth.AuditEvent{ActorUserID: user.ID, EventType: "login_link.redeemed", Outcome: "success", TargetType: "user", TargetID: user.ID}) + h.recordAudit(c, auth.AuditEvent{ActorUserID: user.ID, EventType: redeemedEvent, Outcome: "success", TargetType: "user", TargetID: user.ID}) c.Response().Header().Set("Cache-Control", "no-store") return c.JSON(http.StatusOK, map[string]string{"status": "authenticated"}) } diff --git a/internal/api/auth_test.go b/internal/api/auth_test.go index a949981ba..910e100f4 100644 --- a/internal/api/auth_test.go +++ b/internal/api/auth_test.go @@ -753,3 +753,165 @@ func TestSetupConsumesTokenBeforeFalliblePostSetupWork(t *testing.T) { t.Fatalf("setup token state = %v, want unset: a committed administrator must not leave a live setup credential", got) } } + +const breakGlassTestSecret = "0123456789abcdef0123456789abcdef" + +func newBreakGlassTestServer(t *testing.T, secret string) *testAuthServer { + t.Helper() + return newTestAuthServerWith(t, config.Config{AuthMode: "oidc", AuthCodeSecret: secret}, auth.SMTPConfig{}) +} + +func (s *testAuthServer) redeemLink(token string) *httptest.ResponseRecorder { + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/auth/link/verify", strings.NewReader(`{"token":"`+token+`"}`)) + req.Header.Set("Content-Type", "application/json") + s.e.ServeHTTP(rec, req) + return rec +} + +func (s *testAuthServer) countAudit(t *testing.T, eventType string) int { + t.Helper() + var events int + if err := s.db.DB.QueryRow(`SELECT COUNT(*) FROM auth_audit_events WHERE event_type = ?`, eventType).Scan(&events); err != nil { + t.Fatalf("query audit: %v", err) + } + return events +} + +func hasSessionCookie(rec *httptest.ResponseRecorder) bool { + for _, cookie := range rec.Result().Cookies() { + if cookie.Name == "fanout_session" && cookie.Value != "" { + return true + } + } + return false +} + +func TestBreakGlassLinkAuthenticatesActiveAdministratorOnceInOIDCMode(t *testing.T) { + s := newBreakGlassTestServer(t, breakGlassTestSecret) + user, err := s.users.CreateWithAudit("admin@example.com", "", auth.RoleAdmin, auth.AuditEvent{EventType: "user.created", Outcome: "success"}) + if err != nil { + t.Fatalf("Create: %v", err) + } + token, err := s.codes.CreateBreakGlassLoginLink(user.Email) + if err != nil { + t.Fatalf("CreateBreakGlassLoginLink: %v", err) + } + first := s.redeemLink(token) + if first.Code != http.StatusOK || !hasSessionCookie(first) { + t.Fatalf("first redemption = %d %s", first.Code, first.Body.String()) + } + if second := s.redeemLink(token); second.Code != http.StatusUnauthorized || hasSessionCookie(second) { + t.Fatalf("second redemption = %d %s, want 401", second.Code, second.Body.String()) + } + if got := s.countAudit(t, "login_link.break_glass_redeemed"); got != 1 { + t.Fatalf("break-glass redeemed events = %d, want 1", got) + } + if got := s.countAudit(t, "login_link.redeemed"); got != 0 { + t.Fatalf("ordinary redeemed events = %d, want 0", got) + } +} + +func TestOIDCModeRefusesOrdinaryLoginLinkWithoutConsumingIt(t *testing.T) { + s := newBreakGlassTestServer(t, breakGlassTestSecret) + user, err := s.users.CreateWithAudit("admin@example.com", "", auth.RoleAdmin, auth.AuditEvent{EventType: "user.created", Outcome: "success"}) + if err != nil { + t.Fatalf("Create: %v", err) + } + token, err := s.codes.CreateLoginLink(user.Email) + if err != nil { + t.Fatalf("CreateLoginLink: %v", err) + } + if rec := s.redeemLink(token); rec.Code != http.StatusUnauthorized || hasSessionCookie(rec) { + t.Fatalf("ordinary link in OIDC mode = %d %s, want 401 without a session", rec.Code, rec.Body.String()) + } + if got := s.countAudit(t, "login.failed"); got != 1 { + t.Fatalf("login.failed events = %d, want 1", got) + } + if got := s.countAudit(t, "login_link.redeemed") + s.countAudit(t, "login_link.break_glass_redeemed"); got != 0 { + t.Fatalf("redeemed events = %d, want 0", got) + } + if _, ok, err := s.codes.VerifyLoginLink(token); err != nil || !ok { + t.Fatalf("ordinary link was consumed: (%v, %v)", ok, err) + } +} + +func TestBreakGlassLinkRefusesIneligibleUsersAtRedemption(t *testing.T) { + for _, tc := range []struct { + name string + role auth.Role + status auth.UserStatus + want int + }{ + {"viewer", auth.RoleViewer, auth.UserStatusActive, http.StatusForbidden}, + {"operator", auth.RoleOperator, auth.UserStatusActive, http.StatusForbidden}, + {"suspended administrator", auth.RoleAdmin, auth.UserStatusSuspended, http.StatusUnauthorized}, + } { + t.Run(tc.name, func(t *testing.T) { + s := newBreakGlassTestServer(t, breakGlassTestSecret) + // A second administrator keeps the last-admin guard out of the way. + if _, err := s.users.CreateWithAudit("keeper@example.com", "", auth.RoleAdmin, auth.AuditEvent{EventType: "user.created", Outcome: "success"}); err != nil { + t.Fatalf("Create keeper: %v", err) + } + user, err := s.users.CreateWithAudit("target@example.com", "", auth.RoleAdmin, auth.AuditEvent{EventType: "user.created", Outcome: "success"}) + if err != nil { + t.Fatalf("Create: %v", err) + } + // Issue while eligible: redemption must re-check the account's + // current state rather than trust the state at issue time. + token, err := s.codes.CreateBreakGlassLoginLink(user.Email) + if err != nil { + t.Fatalf("CreateBreakGlassLoginLink: %v", err) + } + role, status := tc.role, tc.status + if _, err := s.users.UpdateWithAudit(user.ID, nil, nil, &role, &status, auth.AuditEvent{EventType: "user.updated", Outcome: "success"}); err != nil { + t.Fatalf("Update: %v", err) + } + rec := s.redeemLink(token) + if rec.Code != tc.want || hasSessionCookie(rec) { + t.Fatalf("redemption = %d %s, want %d without a session", rec.Code, rec.Body.String(), tc.want) + } + if got := s.countAudit(t, "login_link.break_glass_redeemed"); got != 0 { + t.Fatalf("redeemed events = %d, want 0", got) + } + }) + } +} + +func TestOIDCModeWithoutUsableSecretKeepsLinkRouteDisabled(t *testing.T) { + for _, secret := range []string{"", "too-short"} { + s := newBreakGlassTestServer(t, secret) + user, err := s.users.CreateWithAudit("admin@example.com", "", auth.RoleAdmin, auth.AuditEvent{EventType: "user.created", Outcome: "success"}) + if err != nil { + t.Fatalf("Create: %v", err) + } + token, err := s.codes.CreateBreakGlassLoginLink(user.Email) + if err != nil { + t.Fatalf("CreateBreakGlassLoginLink: %v", err) + } + if rec := s.redeemLink(token); rec.Code != http.StatusNotFound || hasSessionCookie(rec) { + t.Fatalf("secret %q: redemption = %d %s, want 404", secret, rec.Code, rec.Body.String()) + } + if got := s.countAudit(t, "login.failed"); got != 0 { + t.Fatalf("secret %q: login.failed events = %d, want 0", secret, got) + } + if _, ok, err := s.codes.VerifyBreakGlassLoginLink(token); err != nil || !ok { + t.Fatalf("secret %q: link was consumed: (%v, %v)", secret, ok, err) + } + } +} + +func TestLocalModeRefusesBreakGlassLink(t *testing.T) { + s := newTestAuthServer(t) + user, err := s.users.CreateWithAudit("admin@example.com", "", auth.RoleAdmin, auth.AuditEvent{EventType: "user.created", Outcome: "success"}) + if err != nil { + t.Fatalf("Create: %v", err) + } + token, err := s.codes.CreateBreakGlassLoginLink(user.Email) + if err != nil { + t.Fatalf("CreateBreakGlassLoginLink: %v", err) + } + if rec := s.redeemLink(token); rec.Code != http.StatusUnauthorized || hasSessionCookie(rec) { + t.Fatalf("break-glass link in local mode = %d %s, want 401", rec.Code, rec.Body.String()) + } +} diff --git a/internal/auth/audit.go b/internal/auth/audit.go index 907f3f280..7fdc5b05c 100644 --- a/internal/auth/audit.go +++ b/internal/auth/audit.go @@ -54,7 +54,8 @@ func recordAudit(ctx context.Context, executor auditExecutor, event AuditEvent) if !validAuditValue(event.EventType, map[AuditEventType]struct{}{ "authorization.denied": {}, "identity.linked": {}, "ingest_key.rotated": {}, "login.failed": {}, "login.requested": {}, "login.succeeded": {}, "logout": {}, - "login_link.issued": {}, "login_link.redeemed": {}, "oauth_connection.revoked": {}, + "login_link.issued": {}, "login_link.redeemed": {}, + "login_link.break_glass_issued": {}, "login_link.break_glass_redeemed": {}, "oauth_connection.revoked": {}, "oidc.denied": {}, "role.changed": {}, "session.revoked": {}, "setup.completed": {}, "user.created": {}, "user.suspended": {}, "user.deleted": {}, "user.provisioned": {}, "user.updated": {}, }) { diff --git a/internal/auth/code.go b/internal/auth/code.go index 997170d1c..f34287bdd 100644 --- a/internal/auth/code.go +++ b/internal/auth/code.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "math/big" + "strings" "time" "github.com/labstack/fanout/internal/db/generated" @@ -23,8 +24,17 @@ const ( maxAttempts = 3 purposeEmailCode = "email_code" purposeLoginLink = "login_link" + // purposeBreakGlassLink marks a link minted by `fanout login-link + // --break-glass`. It is the only credential the OIDC-mode link route accepts, + // and ordinary link verification never matches it. + purposeBreakGlassLink = "break_glass_login_link" ) +// ErrCodeSecretRequired reports a sign-in credential operation attempted +// without FANOUT_AUTH_CODE_SECRET. An empty HMAC key would make stored hashes +// computable from the credential alone. +var ErrCodeSecretRequired = errors.New("auth: FANOUT_AUTH_CODE_SECRET is required for sign-in credentials") + // GenerateCode returns a random 6-digit code. func GenerateCode() (string, error) { n, err := rand.Int(rand.Reader, big.NewInt(1_000_000)) @@ -90,17 +100,34 @@ func (s *CodeStore) Create(email string) (string, error) { // CreateLoginLink stores a short-lived, single-use login link credential. func (s *CodeStore) CreateLoginLink(email string) (string, error) { + return s.createLink(email, purposeLoginLink) +} + +// CreateBreakGlassLoginLink stores a short-lived, single-use credential that +// only the OIDC-mode link route redeems. +func (s *CodeStore) CreateBreakGlassLoginLink(email string) (string, error) { + return s.createLink(email, purposeBreakGlassLink) +} + +func (s *CodeStore) createLink(email, purpose string) (string, error) { token, err := GenerateLoginLinkToken() if err != nil { return "", err } - if err := s.create(email, token, purposeLoginLink, loginLinkTTL); err != nil { + if err := s.create(email, token, purpose, loginLinkTTL); err != nil { return "", err } return token, nil } +func (s *CodeStore) secretMissing() bool { + return strings.TrimSpace(s.secret) == "" +} + func (s *CodeStore) create(email, credential, purpose string, ttl time.Duration) error { + if s.secretMissing() { + return ErrCodeSecretRequired + } hash := HashCode(credential, s.secret) id, err := appid.New() if err != nil { @@ -184,11 +211,21 @@ func (s *CodeStore) Verify(email, code string) (bool, error) { // email it was issued for. Login links are purpose-bound and cannot be used as // ordinary email verification codes. func (s *CodeStore) VerifyLoginLink(token string) (string, bool, error) { - if !secret.ValidSecret(token, "") { + return s.consumeLink(token, purposeLoginLink) +} + +// VerifyBreakGlassLoginLink atomically consumes a valid break-glass link and +// returns the email it was issued for. Ordinary login links never match. +func (s *CodeStore) VerifyBreakGlassLoginLink(token string) (string, bool, error) { + return s.consumeLink(token, purposeBreakGlassLink) +} + +func (s *CodeStore) consumeLink(token, purpose string) (string, bool, error) { + if s.secretMissing() || !secret.ValidSecret(token, "") { return "", false, nil } ctx := context.Background() - row, err := s.q.GetUnusedLoginLink(ctx, HashCode(token, s.secret)) + row, err := s.q.GetUnusedLoginLink(ctx, generated.GetUnusedLoginLinkParams{CodeHash: HashCode(token, s.secret), Purpose: purpose}) if errors.Is(err, sql.ErrNoRows) { return "", false, nil } @@ -202,7 +239,7 @@ func (s *CodeStore) VerifyLoginLink(token string) (string, bool, error) { if time.Now().After(expiresAt) { return "", false, nil } - result, err := s.db.ExecContext(ctx, `UPDATE verifications SET used = 1 WHERE id = ? AND purpose = ? AND used = 0`, row.ID, purposeLoginLink) + result, err := s.db.ExecContext(ctx, `UPDATE verifications SET used = 1 WHERE id = ? AND purpose = ? AND used = 0`, row.ID, purpose) if err != nil { return "", false, fmt.Errorf("auth: mark login link used: %w", err) } diff --git a/internal/auth/code_test.go b/internal/auth/code_test.go index a7e8eadab..ee8e3ff41 100644 --- a/internal/auth/code_test.go +++ b/internal/auth/code_test.go @@ -1,6 +1,7 @@ package auth import ( + "errors" "strings" "sync" "sync/atomic" @@ -262,3 +263,77 @@ func TestVerifyCapsConcurrentWrongAttempts(t *testing.T) { t.Fatalf("attempts = %d, want at most %d: each guess must reserve its attempt before the code is compared", attempts, maxAttempts) } } + +func TestBreakGlassLoginLinkIsPurposeBound(t *testing.T) { + s := newTestCodeStore(t) + breakGlass, err := s.CreateBreakGlassLoginLink("admin@example.com") + if err != nil { + t.Fatalf("CreateBreakGlassLoginLink: %v", err) + } + var stored string + if err := s.db.QueryRow(`SELECT purpose FROM verifications WHERE email = ?`, "admin@example.com").Scan(&stored); err != nil { + t.Fatalf("read stored link: %v", err) + } + if stored != purposeBreakGlassLink { + t.Fatalf("stored purpose = %q, want %q", stored, purposeBreakGlassLink) + } + if _, ok, err := s.VerifyLoginLink(breakGlass); err != nil || ok { + t.Fatalf("VerifyLoginLink(break-glass) = (%v, %v), want (false, nil)", ok, err) + } + email, ok, err := s.VerifyBreakGlassLoginLink(breakGlass) + if err != nil || !ok || email != "admin@example.com" { + t.Fatalf("VerifyBreakGlassLoginLink = (%q, %v, %v)", email, ok, err) + } + if _, ok, err := s.VerifyBreakGlassLoginLink(breakGlass); err != nil || ok { + t.Fatalf("second VerifyBreakGlassLoginLink = (%v, %v), want (false, nil)", ok, err) + } + + ordinary, err := s.CreateLoginLink("user@example.com") + if err != nil { + t.Fatalf("CreateLoginLink: %v", err) + } + if _, ok, err := s.VerifyBreakGlassLoginLink(ordinary); err != nil || ok { + t.Fatalf("VerifyBreakGlassLoginLink(ordinary) = (%v, %v), want (false, nil)", ok, err) + } + if _, ok, err := s.VerifyLoginLink(ordinary); err != nil || !ok { + t.Fatalf("ordinary link was consumed by the refused redemption: (%v, %v)", ok, err) + } +} + +func TestCodeStoreRefusesEmptySecret(t *testing.T) { + for _, value := range []string{"", " "} { + s := newTestCodeStore(t) + // A row hashed with the real secret proves verification stops at the + // missing secret rather than merely failing to find a match. + token, err := s.CreateBreakGlassLoginLink("seed@example.com") + if err != nil { + t.Fatalf("seed link: %v", err) + } + if _, err := s.db.Exec(`UPDATE verifications SET code_hash = ?`, HashCode(token, value)); err != nil { + t.Fatalf("rewrite hash: %v", err) + } + unkeyed := NewCodeStore(s.db, value) + if _, err := unkeyed.CreateLoginLink("a@example.com"); !errors.Is(err, ErrCodeSecretRequired) { + t.Fatalf("CreateLoginLink error = %v, want ErrCodeSecretRequired", err) + } + if _, err := unkeyed.CreateBreakGlassLoginLink("a@example.com"); !errors.Is(err, ErrCodeSecretRequired) { + t.Fatalf("CreateBreakGlassLoginLink error = %v, want ErrCodeSecretRequired", err) + } + if _, err := unkeyed.Create("a@example.com"); !errors.Is(err, ErrCodeSecretRequired) { + t.Fatalf("Create error = %v, want ErrCodeSecretRequired", err) + } + var written int + if err := s.db.QueryRow(`SELECT COUNT(*) FROM verifications WHERE email = ?`, "a@example.com").Scan(&written); err != nil { + t.Fatalf("count verifications: %v", err) + } + if written != 0 { + t.Fatalf("verifications written with secret %q = %d, want 0", value, written) + } + if _, ok, err := unkeyed.VerifyBreakGlassLoginLink(token); err != nil || ok { + t.Fatalf("VerifyBreakGlassLoginLink = (%v, %v), want (false, nil)", ok, err) + } + if _, ok, err := s.VerifyBreakGlassLoginLink(token); err != nil || ok { + t.Fatalf("empty-secret hash matched the real secret: (%v, %v)", ok, err) + } + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 74f2f5e42..018b9353e 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -163,7 +163,7 @@ type Config struct { // PublicURL sets the external browser origin, MCP token audience, and trusted MCP // request origin. Required for OIDC; HTTPS is required with MCP. PublicURL string `group:"server" env:"FANOUT_PUBLIC_URL"` - // AuthCodeSecret signs local sign-in codes; required in local mode with at least 32 characters. + // AuthCodeSecret signs sign-in codes and login links; needs at least 32 characters in local mode and to issue or redeem OIDC break-glass links. AuthCodeSecret string `group:"auth" env:"FANOUT_AUTH_CODE_SECRET" secret:"true"` // SelfSignup allows verified email addresses to create viewer accounts; requires local auth and SMTP. SelfSignup bool `group:"auth" env:"FANOUT_SELF_SIGNUP" default:"false"` @@ -328,8 +328,8 @@ func (c Config) Validate() error { return fmt.Errorf("FANOUT_SESSION_ABSOLUTE_TTL must be positive and at least FANOUT_SESSION_IDLE_TTL") } if authMode == "local" { - if len(strings.TrimSpace(c.AuthCodeSecret)) < 32 { - return fmt.Errorf("FANOUT_AUTH_CODE_SECRET must be at least 32 characters") + if err := c.ValidateLoginLinkSecret(); err != nil { + return err } } if anySet(c.SMTPHost, c.SMTPUser, c.SMTPPass, c.SMTPFrom) { @@ -419,6 +419,17 @@ func (c Config) Validate() error { return nil } +// ValidateLoginLinkSecret reports whether FANOUT_AUTH_CODE_SECRET can protect +// login links. Local mode requires this at startup. OIDC mode checks it only +// when a break-glass link is issued or redeemed, so OIDC installs that never +// set the secret keep starting. +func (c Config) ValidateLoginLinkSecret() error { + if len(strings.TrimSpace(c.AuthCodeSecret)) < 32 { + return fmt.Errorf("FANOUT_AUTH_CODE_SECRET must be at least 32 characters") + } + return nil +} + func (c Config) SecureCookies() bool { if c.TLSEnabled() { return true diff --git a/internal/config/config_test.go b/internal/config/config_test.go index ab31b48fb..020dabcf2 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -353,6 +353,32 @@ func TestValidate(t *testing.T) { } }) + t.Run("OIDC startup tolerates an unusable login-link secret", func(t *testing.T) { + c := valid + c.AuthMode = "oidc" + c.OIDCIssuerURL = "https://id.example.com" + c.OIDCClientID = "fanout" + c.OIDCClientSecret = "secret" + c.OIDCEmailClaim = "email" + c.OIDCEmailVerification = "required" + c.OIDCDefaultRole = "viewer" + c.PublicURL = "https://fanout.example.com" + for _, secret := range []string{"", "short"} { + c.AuthCodeSecret = secret + if err := c.Validate(); err != nil { + t.Fatalf("secret %q should not fail OIDC startup: %v", secret, err) + } + err := c.ValidateLoginLinkSecret() + if err == nil || !strings.Contains(err.Error(), "FANOUT_AUTH_CODE_SECRET") { + t.Fatalf("secret %q: ValidateLoginLinkSecret = %v, want an error naming the variable", secret, err) + } + } + c.AuthCodeSecret = strings.Repeat("x", 32) + if err := c.ValidateLoginLinkSecret(); err != nil { + t.Fatalf("32-character secret should be usable: %v", err) + } + }) + t.Run("OIDC verified email wildcard is explicit and valid", func(t *testing.T) { c := valid c.AuthMode = "oidc" diff --git a/internal/db/generated/codes.sql.go b/internal/db/generated/codes.sql.go index 853493f26..445b0ddae 100644 --- a/internal/db/generated/codes.sql.go +++ b/internal/db/generated/codes.sql.go @@ -79,19 +79,24 @@ func (q *Queries) GetLatestUnusedCode(ctx context.Context, arg GetLatestUnusedCo const getUnusedLoginLink = `-- name: GetUnusedLoginLink :one SELECT id, email, expires_at FROM verifications -WHERE code_hash = ? AND purpose = 'login_link' AND used = 0 +WHERE code_hash = ? AND purpose = ? AND used = 0 ORDER BY created_at DESC LIMIT 1 ` +type GetUnusedLoginLinkParams struct { + CodeHash string `json:"code_hash"` + Purpose string `json:"purpose"` +} + type GetUnusedLoginLinkRow struct { ID string `json:"id"` Email string `json:"email"` ExpiresAt string `json:"expires_at"` } -func (q *Queries) GetUnusedLoginLink(ctx context.Context, codeHash string) (GetUnusedLoginLinkRow, error) { - row := q.db.QueryRowContext(ctx, getUnusedLoginLink, codeHash) +func (q *Queries) GetUnusedLoginLink(ctx context.Context, arg GetUnusedLoginLinkParams) (GetUnusedLoginLinkRow, error) { + row := q.db.QueryRowContext(ctx, getUnusedLoginLink, arg.CodeHash, arg.Purpose) var i GetUnusedLoginLinkRow err := row.Scan(&i.ID, &i.Email, &i.ExpiresAt) return i, err diff --git a/internal/db/queries/codes.sql b/internal/db/queries/codes.sql index eae3aa5f2..3b72d9bb9 100644 --- a/internal/db/queries/codes.sql +++ b/internal/db/queries/codes.sql @@ -12,7 +12,7 @@ LIMIT 1; -- name: GetUnusedLoginLink :one SELECT id, email, expires_at FROM verifications -WHERE code_hash = ? AND purpose = 'login_link' AND used = 0 +WHERE code_hash = ? AND purpose = ? AND used = 0 ORDER BY created_at DESC LIMIT 1; diff --git a/site/src/content/docs/docs/concepts/authentication.mdx b/site/src/content/docs/docs/concepts/authentication.mdx index 0d9517660..9f832d212 100644 --- a/site/src/content/docs/docs/concepts/authentication.mdx +++ b/site/src/content/docs/docs/concepts/authentication.mdx @@ -128,7 +128,8 @@ docker exec fanout fanout login-link admin@example.com The URL is printed to stderr, expires in 15 minutes and works once. Issuance and redemption are audited. The command supports an online server but refuses -missing or suspended users, a missing control database and OIDC mode. +missing or suspended users, a missing control database and OIDC mode without +[`--break-glass`](#oidc-break-glass-recovery). Creating a local user without SMTP returns `201`, `invite_delivery: "not_configured"` and `login_link_required: true`. Mint a link @@ -138,7 +139,30 @@ SMTP fails delivery, the API reports an error. Repair SMTP after regaining acces If the only administrator is suspended or has an unusable address, stop Fanout and back up the control database. Repair that existing account's email or status in SQLite, preserving its ID and owned data. Restart and mint a login link for -the active account. OIDC recovery belongs at the provider or configuration layer. +the active account. + +## OIDC break-glass recovery + +If the identity provider is unavailable, run this with the server's environment +and data directory to issue a one-time link for an active administrator: + +```sh +fanout login-link --break-glass admin@example.com +# For Docker: +docker exec fanout fanout login-link --break-glass admin@example.com +``` + +Set `FANOUT_AUTH_CODE_SECRET` with at least 32 characters before you need this. +OIDC mode does not require it at startup, but without it the command fails and +the server keeps login links disabled. The server must also be running already: +Fanout contacts the provider's discovery endpoint at startup and exits if that +fails. + +The command refuses other roles, suspended users and local mode. The URL expires +in 15 minutes and works once. In OIDC mode, the server accepts only these links +and re-checks that the account is still an active administrator. Issuing and +redeeming write the distinct audit events `login_link.break_glass_issued` and +`login_link.break_glass_redeemed`. ## Review MCP connections diff --git a/site/src/content/docs/docs/guides/troubleshooting.mdx b/site/src/content/docs/docs/guides/troubleshooting.mdx index b55a9224f..3fd6edf51 100644 --- a/site/src/content/docs/docs/guides/troubleshooting.mdx +++ b/site/src/content/docs/docs/guides/troubleshooting.mdx @@ -153,7 +153,9 @@ docker exec fanout fanout login-link user@example.com ``` The link expires after 15 minutes, works once, and is recorded in the -authentication audit history. It is available in `local` auth mode only. +authentication audit history. It is available in `local` auth mode only; OIDC +installations use +[`--break-glass`](/docs/concepts/authentication#oidc-break-glass-recovery). A configured SMTP relay that fails delivery returns an error. See [account recovery](/docs/concepts/authentication#recover-local-sign-in) diff --git a/site/src/content/docs/docs/reference/cli.mdx b/site/src/content/docs/docs/reference/cli.mdx index e5f953481..02f3ddd36 100644 --- a/site/src/content/docs/docs/reference/cli.mdx +++ b/site/src/content/docs/docs/reference/cli.mdx @@ -16,6 +16,7 @@ status: preview | `fanout --version`, `fanout -v` | Print the build version to stdout and exit. | | `fanout -h`, `fanout --help` | Print usage to stderr and exit successfully. | | `fanout login-link ` | Mint a login URL for an existing active local user. | +| `fanout login-link --break-glass ` | Mint a one-time login URL for an active administrator in OIDC mode. | | `fanout healthcheck [url]` | Probe an explicit URL, or derive `/healthz` from listener settings. | | `fanout repair verify` | Validate every authoritative telemetry batch without changing it. | | `fanout repair quarantine --batch ` | Move one confirmed corrupt batch aside. `--batch` is required. | @@ -40,6 +41,20 @@ active user. It prints one URL to stderr. The URL expires in 15 minutes and works once. It can run while the server is online. See [account recovery](/docs/concepts/authentication#recover-local-sign-in). +### Break-glass links + +Use `--break-glass` when an OIDC installation's identity provider is unavailable: + +```sh +fanout login-link --break-glass admin@example.com +``` + +The flag requires OIDC auth mode, `FANOUT_AUTH_CODE_SECRET` with at least 32 +characters, and an active administrator. Other roles are refused. The URL +expires in 15 minutes and works once. Without the flag the command refuses OIDC +mode. See +[OIDC break-glass recovery](/docs/concepts/authentication#oidc-break-glass-recovery). + ## Health probes With no URL, `healthcheck` reads only `FANOUT_ADDR`, diff --git a/site/src/content/docs/docs/reference/configuration/auth.mdx b/site/src/content/docs/docs/reference/configuration/auth.mdx index a069e50ef..506d6eef3 100644 --- a/site/src/content/docs/docs/reference/configuration/auth.mdx +++ b/site/src/content/docs/docs/reference/configuration/auth.mdx @@ -39,7 +39,7 @@ Vendor credentials and endpoints keep the vendor's documented names. ### `FANOUT_AUTH_CODE_SECRET` -Signs local sign-in codes; required in local mode with at least 32 characters. +Signs sign-in codes and login links; needs at least 32 characters in local mode and to issue or redeem OIDC break-glass links. ### `FANOUT_AUTH_MODE` From b4486f82cabed6dda2af3d36ba8cfd08cb71a1ea Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Sun, 8 Nov 2026 08:39:54 -0800 Subject: [PATCH 2/3] fix(auth): harden break-glass redemption and diagnostics Warn at startup when OIDC mode has a FANOUT_AUTH_CODE_SECRET too short for break-glass links, without failing startup or logging the value. Make the audit write mandatory for break-glass redemption: when it fails, destroy the session and return 500. Ordinary links and OIDC login keep their best-effort audit. Give suspended or missing break-glass redemptions their own audit reason, and document that the verify route's per-client rate limit needs FANOUT_TRUSTED_PROXY_CIDRS behind a proxy. --- docs/authentication.md | 8 +- internal/api/auth.go | 31 ++++-- internal/api/auth_test.go | 102 +++++++++++++++++- internal/config/config.go | 3 + internal/config/config_test.go | 36 +++++++ .../docs/docs/concepts/authentication.mdx | 8 +- 6 files changed, 176 insertions(+), 12 deletions(-) diff --git a/docs/authentication.md b/docs/authentication.md index b4017e62e..d4bb3f474 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -114,7 +114,13 @@ expires after 15 minutes and works once. In OIDC mode `/api/auth/link/verify` accepts only these links, refuses an ordinary login link without consuming it, and re-checks that the account is still an active administrator. Issuing writes a `login_link.break_glass_issued` audit event and redeeming writes a -`login_link.break_glass_redeemed` audit event. +`login_link.break_glass_redeemed` audit event. If the redemption event cannot be +written, Fanout discards the session and the request fails; the link is spent, +so issue a new one. + +`/api/auth/link/verify` is rate limited per client address. Behind a reverse +proxy, set `FANOUT_TRUSTED_PROXY_CIDRS`; otherwise every request shares the +proxy's address and one limit, and other traffic can block recovery. Fanout contacts the identity provider's discovery endpoint when the server starts, and exits if that fails. Break-glass access therefore needs a server diff --git a/internal/api/auth.go b/internal/api/auth.go index 40b85b754..bd26dd542 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -342,9 +342,9 @@ func (h *AuthHandler) LoginLink(c *echo.Context) error { return echo.NewHTTPError(http.StatusBadRequest, "login token is required") } - verifyLink, redeemedEvent, invalidReason := h.codes.VerifyLoginLink, auth.AuditEventType("login_link.redeemed"), "invalid_login_link" + verifyLink, redeemedEvent, invalidReason, unavailableReason := h.codes.VerifyLoginLink, auth.AuditEventType("login_link.redeemed"), "invalid_login_link", "suspended_or_missing_login_link_user" if breakGlass { - verifyLink, redeemedEvent, invalidReason = h.codes.VerifyBreakGlassLoginLink, auth.AuditEventType("login_link.break_glass_redeemed"), "invalid_break_glass_link" + verifyLink, redeemedEvent, invalidReason, unavailableReason = h.codes.VerifyBreakGlassLoginLink, auth.AuditEventType("login_link.break_glass_redeemed"), "invalid_break_glass_link", "suspended_or_missing_break_glass_user" } email, ok, err := verifyLink(strings.TrimSpace(req.Token)) if err != nil { @@ -363,7 +363,7 @@ func (h *AuthHandler) LoginLink(c *echo.Context) error { return echo.NewHTTPError(http.StatusInternalServerError, "failed to complete login") } if errors.Is(err, auth.ErrUserNotFound) || user.Status != auth.UserStatusActive { - h.recordAudit(c, auth.AuditEvent{EventType: "login.failed", Outcome: "denied", TargetType: "email", Metadata: map[string]any{"reason": "suspended_or_missing_login_link_user"}}) + h.recordAudit(c, auth.AuditEvent{EventType: "login.failed", Outcome: "denied", TargetType: "email", Metadata: map[string]any{"reason": unavailableReason}}) jitter() return echo.NewHTTPError(http.StatusUnauthorized, "user not found or suspended") } @@ -378,7 +378,20 @@ func (h *AuthHandler) LoginLink(c *echo.Context) error { slog.Error("auth: login link session establishment failed", "user_id", user.ID, "err", err) return echo.NewHTTPError(http.StatusInternalServerError, "failed to create session") } - h.recordAudit(c, auth.AuditEvent{ActorUserID: user.ID, EventType: redeemedEvent, Outcome: "success", TargetType: "user", TargetID: user.ID}) + redeemed := auth.AuditEvent{ActorUserID: user.ID, EventType: redeemedEvent, Outcome: "success", TargetType: "user", TargetID: user.ID} + if breakGlass { + // Break-glass bypasses the identity provider, so a redemption that + // cannot be audited must not leave a usable session behind. + if err := h.writeAudit(c, redeemed); err != nil { + slog.Error("auth: break-glass redemption audit failed", "user_id", user.ID, "err", err) + if destroyErr := h.sessions.Destroy(c.Request().Context()); destroyErr != nil { + slog.Error("auth: break-glass session destroy failed", "user_id", user.ID, "err", destroyErr) + } + return echo.NewHTTPError(http.StatusInternalServerError, "failed to complete login") + } + } else { + h.recordAudit(c, redeemed) + } c.Response().Header().Set("Cache-Control", "no-store") return c.JSON(http.StatusOK, map[string]string{"status": "authenticated"}) } @@ -413,13 +426,17 @@ func (h *AuthHandler) Logout(c *echo.Context) error { } func (h *AuthHandler) recordAudit(c *echo.Context, event auth.AuditEvent) { + if err := h.writeAudit(c, event); err != nil { + slog.Error("authentication audit write failed", "event", event.EventType, "err", err) + } +} + +func (h *AuthHandler) writeAudit(c *echo.Context, event auth.AuditEvent) error { event.RemoteIP = c.RealIP() event.UserAgent = c.Request().UserAgent() ctx, cancel := auth.DetachedWriteContext(c.Request().Context()) defer cancel() - if err := h.audit.Record(ctx, event); err != nil { - slog.Error("authentication audit write failed", "event", event.EventType, "err", err) - } + return h.audit.Record(ctx, event) } func (h *AuthHandler) establishSession(c *echo.Context, user auth.User) error { diff --git a/internal/api/auth_test.go b/internal/api/auth_test.go index 910e100f4..223d7dc8b 100644 --- a/internal/api/auth_test.go +++ b/internal/api/auth_test.go @@ -778,6 +778,15 @@ func (s *testAuthServer) countAudit(t *testing.T, eventType string) int { return events } +func (s *testAuthServer) countFailedReason(t *testing.T, reason string) int { + t.Helper() + var events int + if err := s.db.DB.QueryRow(`SELECT COUNT(*) FROM auth_audit_events WHERE event_type = 'login.failed' AND json_extract(metadata_json, '$.reason') = ?`, reason).Scan(&events); err != nil { + t.Fatalf("query audit reason: %v", err) + } + return events +} + func hasSessionCookie(rec *httptest.ResponseRecorder) bool { for _, cookie := range rec.Result().Cookies() { if cookie.Name == "fanout_session" && cookie.Value != "" { @@ -842,10 +851,11 @@ func TestBreakGlassLinkRefusesIneligibleUsersAtRedemption(t *testing.T) { role auth.Role status auth.UserStatus want int + reason string }{ - {"viewer", auth.RoleViewer, auth.UserStatusActive, http.StatusForbidden}, - {"operator", auth.RoleOperator, auth.UserStatusActive, http.StatusForbidden}, - {"suspended administrator", auth.RoleAdmin, auth.UserStatusSuspended, http.StatusUnauthorized}, + {"viewer", auth.RoleViewer, auth.UserStatusActive, http.StatusForbidden, "break_glass_requires_admin"}, + {"operator", auth.RoleOperator, auth.UserStatusActive, http.StatusForbidden, "break_glass_requires_admin"}, + {"suspended administrator", auth.RoleAdmin, auth.UserStatusSuspended, http.StatusUnauthorized, "suspended_or_missing_break_glass_user"}, } { t.Run(tc.name, func(t *testing.T) { s := newBreakGlassTestServer(t, breakGlassTestSecret) @@ -874,10 +884,96 @@ func TestBreakGlassLinkRefusesIneligibleUsersAtRedemption(t *testing.T) { if got := s.countAudit(t, "login_link.break_glass_redeemed"); got != 0 { t.Fatalf("redeemed events = %d, want 0", got) } + if got := s.countFailedReason(t, tc.reason); got != 1 { + t.Fatalf("login.failed events with reason %q = %d, want 1", tc.reason, got) + } }) } } +func TestBreakGlassLinkForMissingUserHasDistinctAuditReason(t *testing.T) { + s := newBreakGlassTestServer(t, breakGlassTestSecret) + token, err := s.codes.CreateBreakGlassLoginLink("gone@example.com") + if err != nil { + t.Fatalf("CreateBreakGlassLoginLink: %v", err) + } + if rec := s.redeemLink(token); rec.Code != http.StatusUnauthorized || hasSessionCookie(rec) { + t.Fatalf("redemption = %d %s, want 401 without a session", rec.Code, rec.Body.String()) + } + if got := s.countFailedReason(t, "suspended_or_missing_break_glass_user"); got != 1 { + t.Fatalf("break-glass reason events = %d, want 1", got) + } + if got := s.countFailedReason(t, "suspended_or_missing_login_link_user"); got != 0 { + t.Fatalf("ordinary reason events = %d, want 0", got) + } +} + +func TestOrdinaryLoginLinkKeepsItsSuspendedAuditReason(t *testing.T) { + s := newTestAuthServer(t) + token, err := s.codes.CreateLoginLink("gone@example.com") + if err != nil { + t.Fatalf("CreateLoginLink: %v", err) + } + if rec := s.redeemLink(token); rec.Code != http.StatusUnauthorized { + t.Fatalf("redemption = %d %s, want 401", rec.Code, rec.Body.String()) + } + if got := s.countFailedReason(t, "suspended_or_missing_login_link_user"); got != 1 { + t.Fatalf("ordinary reason events = %d, want 1", got) + } +} + +func (s *testAuthServer) failAuditWrites(t *testing.T, eventType string) { + t.Helper() + if _, err := s.db.DB.Exec(`CREATE TRIGGER fail_audit BEFORE INSERT ON auth_audit_events WHEN NEW.event_type = '` + eventType + `' BEGIN SELECT RAISE(ABORT, 'audit unavailable'); END`); err != nil { + t.Fatalf("create audit failure trigger: %v", err) + } +} + +func (s *testAuthServer) countSessions(t *testing.T) int { + t.Helper() + var sessions int + if err := s.db.DB.QueryRow(`SELECT COUNT(*) FROM sessions`).Scan(&sessions); err != nil { + t.Fatalf("count sessions: %v", err) + } + return sessions +} + +func TestBreakGlassRedemptionFailsClosedWhenAuditWriteFails(t *testing.T) { + s := newBreakGlassTestServer(t, breakGlassTestSecret) + user, err := s.users.CreateWithAudit("admin@example.com", "", auth.RoleAdmin, auth.AuditEvent{EventType: "user.created", Outcome: "success"}) + if err != nil { + t.Fatalf("Create: %v", err) + } + token, err := s.codes.CreateBreakGlassLoginLink(user.Email) + if err != nil { + t.Fatalf("CreateBreakGlassLoginLink: %v", err) + } + s.failAuditWrites(t, "login_link.break_glass_redeemed") + rec := s.redeemLink(token) + if rec.Code != http.StatusInternalServerError || hasSessionCookie(rec) { + t.Fatalf("redemption = %d %s, want 500 without a session", rec.Code, rec.Body.String()) + } + if got := s.countSessions(t); got != 0 { + t.Fatalf("stored sessions = %d, want 0", got) + } +} + +func TestOrdinaryLoginLinkStillSucceedsWhenAuditWriteFails(t *testing.T) { + s := newTestAuthServer(t) + user, err := s.users.CreateWithAudit("user@example.com", "", auth.RoleViewer, auth.AuditEvent{EventType: "user.created", Outcome: "success"}) + if err != nil { + t.Fatalf("Create: %v", err) + } + token, err := s.codes.CreateLoginLink(user.Email) + if err != nil { + t.Fatalf("CreateLoginLink: %v", err) + } + s.failAuditWrites(t, "login_link.redeemed") + if rec := s.redeemLink(token); rec.Code != http.StatusOK || !hasSessionCookie(rec) { + t.Fatalf("redemption = %d %s, want 200 with a session", rec.Code, rec.Body.String()) + } +} + func TestOIDCModeWithoutUsableSecretKeepsLinkRouteDisabled(t *testing.T) { for _, secret := range []string{"", "too-short"} { s := newBreakGlassTestServer(t, secret) diff --git a/internal/config/config.go b/internal/config/config.go index 018b9353e..15d0f38ed 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -225,6 +225,9 @@ func (c Config) LogStartup() { if c.MetricsPublic { slog.Warn("Prometheus metrics are publicly accessible", "path", "/metrics") } + if strings.ToLower(strings.TrimSpace(c.AuthMode)) == "oidc" && c.AuthCodeSecret != "" && c.ValidateLoginLinkSecret() != nil { + slog.Warn("FANOUT_AUTH_CODE_SECRET is shorter than 32 characters; OIDC break-glass login links will be unavailable") + } if c.SelfSignup { slog.Info("self-signup is enabled", "role", appauth.RoleViewer) } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 020dabcf2..3959c95d1 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -1,6 +1,8 @@ package config import ( + "bytes" + "log/slog" "os" "path/filepath" "reflect" @@ -523,3 +525,37 @@ func TestSecureCookies(t *testing.T) { }) } } + +func TestLogStartupWarnsAboutUnusableBreakGlassSecret(t *testing.T) { + const shortSecret = "not-long-enough-value" + for _, tc := range []struct { + name string + mode string + secret string + want bool + }{ + {"oidc short", "oidc", shortSecret, true}, + {"oidc normalized mode short", " OIDC ", shortSecret, true}, + {"oidc unset", "oidc", "", false}, + {"oidc usable", "oidc", strings.Repeat("x", 32), false}, + {"local short", "local", shortSecret, false}, + } { + t.Run(tc.name, func(t *testing.T) { + var logs bytes.Buffer + previous := slog.Default() + slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil))) + t.Cleanup(func() { slog.SetDefault(previous) }) + + Config{AuthMode: tc.mode, AuthCodeSecret: tc.secret}.LogStartup() + + output := logs.String() + got := strings.Contains(output, "FANOUT_AUTH_CODE_SECRET") && strings.Contains(output, "break-glass") + if got != tc.want { + t.Fatalf("warning present = %v, want %v; logs: %s", got, tc.want, output) + } + if strings.Contains(output, shortSecret) { + t.Fatalf("logs contain the secret value: %s", output) + } + }) + } +} diff --git a/site/src/content/docs/docs/concepts/authentication.mdx b/site/src/content/docs/docs/concepts/authentication.mdx index 9f832d212..5fee3d208 100644 --- a/site/src/content/docs/docs/concepts/authentication.mdx +++ b/site/src/content/docs/docs/concepts/authentication.mdx @@ -162,7 +162,13 @@ The command refuses other roles, suspended users and local mode. The URL expires in 15 minutes and works once. In OIDC mode, the server accepts only these links and re-checks that the account is still an active administrator. Issuing and redeeming write the distinct audit events `login_link.break_glass_issued` and -`login_link.break_glass_redeemed`. +`login_link.break_glass_redeemed`. If the redemption event cannot be written, +Fanout discards the session and the request fails; the link is spent, so issue a +new one. + +`/api/auth/link/verify` is rate limited per client address. Behind a reverse +proxy, set `FANOUT_TRUSTED_PROXY_CIDRS`; otherwise every request shares the +proxy's address and one limit, and other traffic can block recovery. ## Review MCP connections From 4fd478a57fc0d9bc9cc7545e2422cf6febef455e Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Sun, 8 Nov 2026 08:43:25 -0800 Subject: [PATCH 3/3] fix(auth): audit break-glass redemption before creating a session Write the redemption audit event after eligibility checks and link consumption but before establishing a session, so an audit failure returns 500 with no session ever created. This removes the destroy path, which could still commit a session if the destroy itself failed. --- docs/authentication.md | 4 ++-- internal/api/auth.go | 19 +++++++++---------- internal/api/auth_test.go | 10 ++++++++++ .../docs/docs/concepts/authentication.mdx | 2 +- 4 files changed, 22 insertions(+), 13 deletions(-) diff --git a/docs/authentication.md b/docs/authentication.md index d4bb3f474..212a1a92a 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -115,8 +115,8 @@ accepts only these links, refuses an ordinary login link without consuming it, and re-checks that the account is still an active administrator. Issuing writes a `login_link.break_glass_issued` audit event and redeeming writes a `login_link.break_glass_redeemed` audit event. If the redemption event cannot be -written, Fanout discards the session and the request fails; the link is spent, -so issue a new one. +written, Fanout creates no session and the request fails; the link is spent, so +issue a new one. `/api/auth/link/verify` is rate limited per client address. Behind a reverse proxy, set `FANOUT_TRUSTED_PROXY_CIDRS`; otherwise every request shares the diff --git a/internal/api/auth.go b/internal/api/auth.go index bd26dd542..49261a0ef 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -374,22 +374,21 @@ func (h *AuthHandler) LoginLink(c *echo.Context) error { jitter() return echo.NewHTTPError(http.StatusForbidden, "break-glass login requires an administrator") } - if err := h.establishSession(c, user); err != nil { - slog.Error("auth: login link session establishment failed", "user_id", user.ID, "err", err) - return echo.NewHTTPError(http.StatusInternalServerError, "failed to create session") - } redeemed := auth.AuditEvent{ActorUserID: user.ID, EventType: redeemedEvent, Outcome: "success", TargetType: "user", TargetID: user.ID} if breakGlass { - // Break-glass bypasses the identity provider, so a redemption that - // cannot be audited must not leave a usable session behind. + // Break-glass bypasses the identity provider, so it is audited before + // any session exists. A session failure after this point leaves an + // audited redemption with no login, which is the safe direction. if err := h.writeAudit(c, redeemed); err != nil { slog.Error("auth: break-glass redemption audit failed", "user_id", user.ID, "err", err) - if destroyErr := h.sessions.Destroy(c.Request().Context()); destroyErr != nil { - slog.Error("auth: break-glass session destroy failed", "user_id", user.ID, "err", destroyErr) - } return echo.NewHTTPError(http.StatusInternalServerError, "failed to complete login") } - } else { + } + if err := h.establishSession(c, user); err != nil { + slog.Error("auth: login link session establishment failed", "user_id", user.ID, "err", err) + return echo.NewHTTPError(http.StatusInternalServerError, "failed to create session") + } + if !breakGlass { h.recordAudit(c, redeemed) } c.Response().Header().Set("Cache-Control", "no-store") diff --git a/internal/api/auth_test.go b/internal/api/auth_test.go index 223d7dc8b..21fe3186d 100644 --- a/internal/api/auth_test.go +++ b/internal/api/auth_test.go @@ -1,6 +1,7 @@ package api import ( + "database/sql" "encoding/json" "errors" "net/http" @@ -956,6 +957,15 @@ func TestBreakGlassRedemptionFailsClosedWhenAuditWriteFails(t *testing.T) { if got := s.countSessions(t); got != 0 { t.Fatalf("stored sessions = %d, want 0", got) } + // establishSession records the login first, so an untouched timestamp shows + // the audit failure stopped the request before any session was started. + var lastLogin sql.NullString + if err := s.db.DB.QueryRow(`SELECT logged_in_at FROM users WHERE id = ?`, user.ID).Scan(&lastLogin); err != nil { + t.Fatalf("query last login: %v", err) + } + if lastLogin.String != "" { + t.Fatalf("logged_in_at = %q, want no session establishment", lastLogin.String) + } } func TestOrdinaryLoginLinkStillSucceedsWhenAuditWriteFails(t *testing.T) { diff --git a/site/src/content/docs/docs/concepts/authentication.mdx b/site/src/content/docs/docs/concepts/authentication.mdx index 5fee3d208..cdceb77df 100644 --- a/site/src/content/docs/docs/concepts/authentication.mdx +++ b/site/src/content/docs/docs/concepts/authentication.mdx @@ -163,7 +163,7 @@ in 15 minutes and works once. In OIDC mode, the server accepts only these links and re-checks that the account is still an active administrator. Issuing and redeeming write the distinct audit events `login_link.break_glass_issued` and `login_link.break_glass_redeemed`. If the redemption event cannot be written, -Fanout discards the session and the request fails; the link is spent, so issue a +Fanout creates no session and the request fails; the link is spent, so issue a new one. `/api/auth/link/verify` is rate limited per client address. Behind a reverse