// 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}) }