release gate / check (push) Failing after 6m56s
Transactional mail now goes out as the Superbrain HTML design
(internal/mailer/template.html, embedded verbatim) with a plain-text
alternative: multipart/alternative (plain first per RFC 2046), random
boundary, CRLF normalization and SMTP dot-stuffing. Render() fills the
{{placeholders}} with HTML-escaped values and removes optional sections
(CTA + fallback link, note block, footer links, address) when empty;
anchor drift fails the unit tests and degrades to plain text at send
time, never blocking delivery. Password reset gets the headline,
first-name greeting, "Choose a new password" button (Outlook VML
fallback) and expiry/single-use note; notification and agent emails
render title-as-headline with body paragraphs.
The template's footer links are now real pages:
- /help: public help center (10 topic sections + FAQ accordion), linked
from the login page.
- /unsubscribe?token=...: public confirmation page; the HMAC-signed user
id (notify.UnsubscribeToken, domain-separated, stable, no stored row)
IS the credential. POST /api/notifications/unsubscribe accepts the
RFC 8058 one-click shape (token in query, form body ignored) and the
browser JSON shape; it disables the user's enabled email channels and
pauses enabled agent email tasks addressed to their own email
(idempotent, re-enableable, per-client rate limited, audit logged).
- Email preferences deep-links to /settings?tab=notifications; Settings
now honors ?tab=<section> (unknown values fall back to profile).
notify.FooterLinks is the single eligibility point: preferences + help
whenever NEXTAUTH_URL is set; unsubscribe ONLY when the recipient is the
owner's own account email — third-party channel addresses and agent
recipients never receive a link that changes someone else's settings,
and transactional mail (password reset) never carries unsubscribe.
Owner-addressed mail also carries List-Unsubscribe +
List-Unsubscribe-Post headers.
Verified: Go build/vet/unit green; new TestUnsubscribeFlow integration
test pins footer + headers, blast radius (slack channel and third-party
task survive), one-click + JSON paths, idempotence, tampered tokens and
the third-party/transactional exclusions; notifications, phase-2,
password-reset and agent suites green; web lint/SSR-lint/build 0 errors;
full browser regressions pass; live smoke of /help, /unsubscribe states,
the settings deep-link auth gate and bad-token 400 through the proxy.
252 lines
8.4 KiB
Go
252 lines
8.4 KiB
Go
// 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"
|
|
"fmt"
|
|
"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"
|
|
minutes := int(resetTokenTTL.Minutes())
|
|
firstName := ""
|
|
if u.Name != nil {
|
|
if fields := strings.Fields(*u.Name); len(fields) > 0 {
|
|
firstName = fields[0]
|
|
}
|
|
}
|
|
content := mailer.Content{
|
|
Preheader: fmt.Sprintf("Choose a new password — the link expires in %d minutes.", minutes),
|
|
Headline: "Reset your password",
|
|
FirstName: firstName,
|
|
Body: "We received a request to reset your Superbrain password.\nClick the button below to choose a new one.",
|
|
CTAURL: link,
|
|
CTALabel: "Choose a new password",
|
|
Note: fmt.Sprintf("This link expires in %d minutes and can only be used once. "+
|
|
"If you didn't request a reset, you can ignore this email — your password stays unchanged.", minutes),
|
|
// Transactional mail: preferences and help, but deliberately NO
|
|
// unsubscribe — a reset link must never depend on notification
|
|
// preferences (base is non-empty here; checked above).
|
|
PreferencesURL: base + "/settings?tab=notifications",
|
|
HelpURL: base + "/help",
|
|
}
|
|
if e := mailer.SendTemplate(r.Context(), email, "Reset your Superbrain password", body, content); 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})
|
|
}
|