Add deployment tiers, self-service password reset, and Authelia SSO fixes
release gate / check (push) Failing after 7m28s

Product tiers (decided 2026-10-26): TIER=core|multi is the deployment knob.
core (federated install, paying customers) derives AUTH_MODE=oidc with
signup/bootstrap off - Authelia is the only way in and accounts are
provisioned upstream (Superpanel -> LDAP -> Authelia). multi (hosted
self-service) derives AUTH_MODE=password: signup, password login and
SMTP-backed self-reset, with the OIDC bridge refused even when variables
are set. Explicit AUTH_MODE/SIGNUP_ENABLED/ALLOW_BOOTSTRAP_SIGNUP always
override the tier; invalid values fail startup instead of falling back.
Go enforces every gate at the API; the web UI mirrors it (conditional
credentials provider, SSO-only login page, signup/reset redirects).

Authelia-only bootstrap: ProvisionExternal grants ADMIN to ADMIN_EMAILS
addresses at first SSO login, and --seed accepts SEED_SUBJECT to link a
pre-existing password account offline - the only path when 409 'account
link required' meets a deployment where nobody can password-login to call
oidc-link.

Self-service password reset (multi tier): POST /api/password/forgot and
/api/password/reset with hashed single-use 30-minute tokens
(PasswordResetToken, migration 011 + schema.sql), enumeration-safe
identical 200s, per-IP rate limits, tokenVersion bump on success (all
prior sessions revoked), OIDC-only accounts excluded by design. New
internal/mailer sends via netguard+outbound budget; NETGUARD_TRUSTED_HOSTS
pins operator-chosen relays that resolve privately (split-horizon DNS)
without the blanket INTEGRATIONS_ALLOW_PRIVATE switch. Web gains
/forgot-password and /reset-password pages and a login-page link.

Federated install fixes: the Authelia client now registers a
claims_policy putting email in the ID token (production AccessDenied -
Auth.js builds OIDC profiles exclusively from ID-token claims), config is
validated before restarting the shared Authelia, uninstall removes the
claims block marker-safely, and generated .env switches to TIER=core with
a password-less admin seed.

Tests: tier derivation/override unit tests, mode and tier integration
tests (403 gates, bridge refusal, ADMIN_EMAILS promotion, offline link),
reset-flow integration tests against a loopback SMTP fake, netguard
trusted-host tests. Docs: RUNNING.md, web/docs/AUTHELIA.md section 7,
.env.example, STRATEGY.md.
This commit is contained in:
Andrew S Erwin
2026-10-26 12:28:43 -05:00
parent d7a2abc683
commit f372936894
33 changed files with 1879 additions and 64 deletions
+228
View File
@@ -0,0 +1,228 @@
// Self-service password reset: "forgot password" emails a single-use link,
// "reset" consumes it. Both endpoints are unauthenticated, so they follow
// the same rules as login/signup:
//
// - No account enumeration (review SEC-4 pattern): /forgot answers the
// identical 200 {"ok":true} whether or not the address exists, has a
// password, or the email actually went out. Delivery problems are logged
// for the operator, never surfaced per-address.
// - Tokens are 256-bit random values; only the SHA-256 hash is stored.
// A reset bumps tokenVersion, invalidating every session minted with
// the old password (review SEC-02 revocation semantics).
// - OIDC-only (password-less) accounts are deliberately excluded: handing
// them a password would open a credential path around Authelia that the
// provisioning bridge refuses to create by email match alone.
//
// Sending requires SMTP_HOST/SMTP_FROM (see internal/mailer); without them
// /forgot answers 503 — a global deployment property, not a per-account
// signal.
package auth
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"log"
"net/http"
"net/mail"
"strings"
"time"
"github.com/andrew/superbrain/internal/config"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/mailer"
)
const (
resetTokenTTL = 30 * time.Minute
resetTokenBytes = 32
forgotIPLimit = 5 // forgot-password requests per IP per window
forgotIPWindow = time.Hour
resetIPLimit = 10 // reset submissions per IP per window
resetIPWindow = time.Hour
maxResetTokenLen = 128
minResetPassword = 8 // mirrors signup
maxResetPasswordB = 72 // bcrypt input cap, mirrors signup
)
var (
forgotIPs = newLimiterStore()
resetIPs = newLimiterStore()
)
// RateLimitForgot and RateLimitReset cap the two unauthenticated reset
// endpoints per effective client IP. Like signup (and unlike login) they
// keep the loopback exemption for same-host consumers of the 127.0.0.1
// binding; a forwarded identity never earns it (review SEC-2).
func RateLimitForgot(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !isLoopback(r) {
if ok, retry := forgotIPs.allow(EffectiveClientIP(r), forgotIPLimit, forgotIPWindow, time.Now()); !ok {
tooManyRequests(w, retry)
return
}
}
next(w, r)
}
}
func RateLimitReset(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !isLoopback(r) {
if ok, retry := resetIPs.allow(EffectiveClientIP(r), resetIPLimit, resetIPWindow, time.Now()); !ok {
tooManyRequests(w, retry)
return
}
}
next(w, r)
}
}
// HandleForgotPassword accepts {"email": ...} and always answers 200
// {"ok":true} once the request is well-formed — the response must not
// distinguish registered, unregistered, or OIDC-only addresses.
//
// POST /api/password/forgot
func HandleForgotPassword(w http.ResponseWriter, r *http.Request) {
if !checkAuthRequest(w, r) {
return
}
// SSO-only deployments have no local passwords to reset; Authelia owns
// recovery there. Refuse before the SMTP check so the response does not
// vary with mail configuration.
if config.AuthMode() == "oidc" {
failure(w, 403, "Password reset is disabled on this server")
return
}
cfg := config.Load()
if !mailer.LoadConfig().Configured() {
// Global misconfiguration; identical for every address.
failure(w, 503, "Password reset is not available on this server")
return
}
base := strings.TrimRight(strings.TrimSpace(cfg.NextAuthURL), "/")
if base == "" {
log.Printf("password reset: NEXTAUTH_URL is unset; cannot build reset links")
failure(w, 503, "Password reset is not available on this server")
return
}
var req struct {
Email string `json:"email"`
}
if !decode(w, r, &req) {
return
}
email := strings.ToLower(strings.TrimSpace(req.Email))
// Every early exit below answers the same 200; only the operator log
// knows whether a mail went out.
okResponse := func() { writeJSON(w, 200, SignupResponse{true}) }
if email == "" {
okResponse()
return
}
if a, e := mail.ParseAddress(email); e != nil || a.Address != email || len(email) > maxSignupEmailLen {
okResponse()
return
}
u, e := db.NewUserRepo(db.FromContext(r.Context())).FindByEmail(r.Context(), email)
if e != nil {
if !errors.Is(e, db.ErrNotFound) {
log.Printf("password reset: user lookup failed: %v", e)
}
okResponse()
return
}
// Password-less (OIDC-provisioned) accounts are out of scope by design.
if u.Password == nil || *u.Password == "" {
log.Printf("password reset: ignored request for password-less account %s", email)
okResponse()
return
}
raw := make([]byte, resetTokenBytes)
if _, e := rand.Read(raw); e != nil {
log.Printf("password reset: token generation failed: %v", e)
okResponse()
return
}
token := base64.RawURLEncoding.EncodeToString(raw)
sum := sha256.Sum256([]byte(token))
repo := db.NewPasswordResetRepo(db.FromContext(r.Context()))
if e := repo.Create(r.Context(), u.ID, hex.EncodeToString(sum[:]), time.Now().Add(resetTokenTTL)); e != nil {
log.Printf("password reset: token store failed: %v", e)
okResponse()
return
}
link := base + "/reset-password?token=" + token
body := "We received a request to reset your Superbrain password.\n\n" +
"Open this link within " + resetTokenTTL.String() + " to choose a new password:\n\n" +
link + "\n\n" +
"If you did not request a reset, you can ignore this email; the link is\n" +
"single-use and your password stays unchanged.\n"
if e := mailer.Send(r.Context(), email, "Reset your Superbrain password", body); e != nil {
log.Printf("password reset: delivery to %s failed: %v", email, e)
}
okResponse()
}
// HandleResetPassword accepts {"token": ..., "password": ...}, consumes the
// token and sets the new bcrypt hash while invalidating existing sessions.
//
// POST /api/password/reset
func HandleResetPassword(w http.ResponseWriter, r *http.Request) {
if !checkAuthRequest(w, r) {
return
}
if config.AuthMode() == "oidc" {
failure(w, 403, "Password reset is disabled on this server")
return
}
var req struct {
Token string `json:"token"`
Password string `json:"password"`
}
if !decode(w, r, &req) {
return
}
token := strings.TrimSpace(req.Token)
if token == "" || len(token) > maxResetTokenLen {
failure(w, 400, "Invalid or expired token")
return
}
if len(req.Password) < minResetPassword {
failure(w, 400, "Password must be at least 8 characters")
return
}
if len(req.Password) > maxResetPasswordB {
failure(w, 400, "Password must be at most 72 bytes")
return
}
sum := sha256.Sum256([]byte(token))
userID, e := db.NewPasswordResetRepo(db.FromContext(r.Context())).Consume(r.Context(), hex.EncodeToString(sum[:]))
if e != nil {
if errors.Is(e, db.ErrNotFound) {
failure(w, 400, "Invalid or expired token")
return
}
failure(w, 500, "Database unavailable")
return
}
hash, e := bcryptHashImpl(req.Password)
if e != nil {
failure(w, 500, "Unable to hash password")
return
}
if e := db.NewUserRepo(db.FromContext(r.Context())).SetPassword(r.Context(), userID, hash); e != nil {
if errors.Is(e, db.ErrNotFound) {
failure(w, 400, "Invalid or expired token")
return
}
failure(w, 500, "Unable to reset password")
return
}
// Audited like role changes (review SEC-11): ids only, no secrets.
log.Printf("audit: password reset completed for user %s", userID)
writeJSON(w, 200, SignupResponse{true})
}