Add deployment tiers, self-service password reset, and Authelia SSO fixes
release gate / check (push) Failing after 7m28s
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:
@@ -0,0 +1,221 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
"github.com/andrew/superbrain/internal/scripts"
|
||||
)
|
||||
|
||||
// AUTH_MODE=oidc (core/federated shape): Authelia exclusively. Password
|
||||
// login, signup and password reset are refused at the API — hiding the web
|
||||
// UI alone must never be the barrier — while the trusted identity bridge
|
||||
// keeps working and provisions operators listed in ADMIN_EMAILS as ADMIN.
|
||||
func TestAuthModeOIDC(t *testing.T) {
|
||||
srv, d := testServerDB(t)
|
||||
t.Setenv("AUTH_MODE", "oidc")
|
||||
t.Setenv("OIDC_ISSUER", "https://auth.test")
|
||||
t.Setenv("OIDC_CLIENT_ID", "superbrain")
|
||||
t.Setenv("OIDC_CLIENT_SECRET", "test-secret")
|
||||
t.Setenv("SMTP_HOST", "mail.test")
|
||||
t.Setenv("SMTP_FROM", "superbrain@test")
|
||||
t.Setenv("ADMIN_EMAILS", "operator@superbrain.test")
|
||||
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
|
||||
|
||||
c.request("POST", "/api/auth/login", map[string]any{"email": "a@superbrain.test", "password": "a-long-test-password"}, 403)
|
||||
c.request("POST", "/api/signup", map[string]any{"email": "a@superbrain.test", "password": "a-long-test-password"}, 403)
|
||||
c.request("POST", "/api/password/forgot", map[string]any{"email": "a@superbrain.test"}, 403)
|
||||
c.request("POST", "/api/password/reset", map[string]any{"token": "x", "password": "brand-new-password"}, 403)
|
||||
|
||||
// The identity bridge still provisions. A fresh SSO user is USER...
|
||||
body := map[string]any{"issuer": "https://auth.test", "subject": "sub-user", "email": "someone@superbrain.test", "emailVerified": true}
|
||||
status, out := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body)
|
||||
if status != 200 {
|
||||
t.Fatalf("identity provision: wanted 200, got %d: %v", status, out)
|
||||
}
|
||||
if role := out["user"].(map[string]any)["role"]; role != "USER" {
|
||||
t.Fatalf("fresh SSO user role = %v, wanted USER", role)
|
||||
}
|
||||
// ...and an operator-listed email becomes ADMIN on first SSO login —
|
||||
// the only bootstrap path when password login is disabled.
|
||||
body = map[string]any{"issuer": "https://auth.test", "subject": "sub-operator", "email": "operator@superbrain.test", "emailVerified": true}
|
||||
status, out = postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body)
|
||||
if status != 200 {
|
||||
t.Fatalf("operator provision: wanted 200, got %d: %v", status, out)
|
||||
}
|
||||
if role := out["user"].(map[string]any)["role"]; role != "ADMIN" {
|
||||
t.Fatalf("ADMIN_EMAILS SSO user role = %v, wanted ADMIN", role)
|
||||
}
|
||||
|
||||
// Seed CLI with SEED_SUBJECT links an offline-provisioned operator
|
||||
// without any session (the chicken-and-egg escape hatch for this mode).
|
||||
t.Setenv("SEED_EMAIL", "seeded@superbrain.test")
|
||||
t.Setenv("SEED_SUBJECT", "sub-seeded")
|
||||
t.Setenv("SEED_PASSWORD", "")
|
||||
if err := scripts.Seed(context.Background(), d); err != nil {
|
||||
t.Fatalf("seed with subject: %v", err)
|
||||
}
|
||||
body = map[string]any{"issuer": "https://auth.test", "subject": "sub-seeded", "email": "seeded@superbrain.test", "emailVerified": true}
|
||||
if status, _ := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body); status != 200 {
|
||||
t.Fatalf("seeded subject login: wanted 200, got %d", status)
|
||||
}
|
||||
// Re-running the same seed is idempotent.
|
||||
if err := scripts.Seed(context.Background(), d); err != nil {
|
||||
t.Fatalf("seed must be idempotent: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A pre-existing PASSWORD account still refuses auto-link by email in oidc
|
||||
// mode (409); the operator links it offline via SEED_SUBJECT, after which
|
||||
// SSO resolves to the SAME local user — exactly the core-upgrade path.
|
||||
func TestAuthModeOIDCLinksExistingPasswordAccount(t *testing.T) {
|
||||
srv, d := testServerDB(t)
|
||||
// Create the password account while passwords still work.
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
|
||||
c.request("POST", "/api/signup", map[string]any{"email": "admin@superbrain.test", "password": "a-long-test-password"}, 201)
|
||||
c.request("POST", "/api/auth/login", map[string]any{"email": "admin@superbrain.test", "password": "a-long-test-password"}, 200)
|
||||
adminID := meID(c)
|
||||
|
||||
t.Setenv("AUTH_MODE", "oidc")
|
||||
t.Setenv("OIDC_ISSUER", "https://auth.test")
|
||||
t.Setenv("ADMIN_EMAILS", "")
|
||||
|
||||
body := map[string]any{"issuer": "https://auth.test", "subject": "sub-admin", "email": "admin@superbrain.test", "emailVerified": true}
|
||||
if status, _ := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body); status != 409 {
|
||||
t.Fatalf("password account must refuse email auto-link: wanted 409, got %d", status)
|
||||
}
|
||||
|
||||
t.Setenv("SEED_EMAIL", "admin@superbrain.test")
|
||||
t.Setenv("SEED_SUBJECT", "sub-admin")
|
||||
t.Setenv("SEED_PASSWORD", "")
|
||||
if err := scripts.Seed(context.Background(), d); err != nil {
|
||||
t.Fatalf("offline link: %v", err)
|
||||
}
|
||||
status, out := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body)
|
||||
if status != 200 {
|
||||
t.Fatalf("linked login: wanted 200, got %d: %v", status, out)
|
||||
}
|
||||
if got := out["user"].(map[string]any)["id"]; got != adminID {
|
||||
t.Fatalf("SSO resolved to %v, wanted the pre-existing local user %s", got, adminID)
|
||||
}
|
||||
|
||||
// The subject can never be re-pointed at another user by re-seeding.
|
||||
t.Setenv("SEED_EMAIL", "other@superbrain.test")
|
||||
if err := scripts.Seed(context.Background(), d); err == nil {
|
||||
t.Fatal("linking an already-linked subject to a different user must fail")
|
||||
}
|
||||
}
|
||||
|
||||
// AUTH_MODE=password (multi-tenant shape): signup/password login only. The
|
||||
// OIDC bridge is refused even with valid variables AND a valid service token,
|
||||
// and the status endpoint reports OIDC disabled so the UI hides Authelia.
|
||||
func TestAuthModePassword(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
t.Setenv("AUTH_MODE", "password")
|
||||
t.Setenv("OIDC_ISSUER", "https://auth.test")
|
||||
t.Setenv("OIDC_CLIENT_ID", "superbrain")
|
||||
t.Setenv("OIDC_CLIENT_SECRET", "test-secret")
|
||||
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
|
||||
c.request("POST", "/api/signup", map[string]any{"email": "tenant@superbrain.test", "password": "a-long-test-password"}, 201)
|
||||
c.request("POST", "/api/auth/login", map[string]any{"email": "tenant@superbrain.test", "password": "a-long-test-password"}, 200)
|
||||
|
||||
body := map[string]any{"issuer": "https://auth.test", "subject": "sub-x", "email": "x@superbrain.test", "emailVerified": true}
|
||||
if status, _ := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body); status != 403 {
|
||||
t.Fatalf("identity bridge in password mode: wanted 403, got %d", status)
|
||||
}
|
||||
|
||||
status := c.request("GET", "/api/auth/oidc/status", nil, 200)
|
||||
if status["enabled"] != false {
|
||||
t.Fatalf("oidc status must report disabled in password mode: %v", status)
|
||||
}
|
||||
}
|
||||
|
||||
// LinkExternal (the mechanism behind SEED_SUBJECT and POST
|
||||
// /api/admin/oidc-link) refuses to move a subject between users.
|
||||
func TestLinkExternalConflict(t *testing.T) {
|
||||
_, d := testServerDB(t)
|
||||
repo := db.NewUserRepo(d)
|
||||
ctx := context.Background()
|
||||
a, _ := repo.Create(ctx, &db.NewUserInput{ID: db.NewID(), Name: "A", Email: "a@superbrain.test", Password: "x", Role: "USER"})
|
||||
b, _ := repo.Create(ctx, &db.NewUserInput{ID: db.NewID(), Name: "B", Email: "b@superbrain.test", Password: "x", Role: "USER"})
|
||||
if err := repo.LinkExternal(ctx, a, "authelia", "sub-1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repo.LinkExternal(ctx, a, "authelia", "sub-1"); err != nil {
|
||||
t.Fatalf("relinking the same user must be idempotent: %v", err)
|
||||
}
|
||||
if err := repo.LinkExternal(ctx, b, "authelia", "sub-1"); err != db.ErrAccountLinked {
|
||||
t.Fatalf("subject move: wanted ErrAccountLinked, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TIER=core alone (no AUTH_MODE set) must behave exactly like the oidc
|
||||
// shape: the tier derives the mode end to end.
|
||||
func TestTierCoreDerivesOIDCOnly(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
t.Setenv("TIER", "core")
|
||||
t.Setenv("OIDC_ISSUER", "https://auth.test")
|
||||
t.Setenv("OIDC_CLIENT_ID", "superbrain")
|
||||
t.Setenv("OIDC_CLIENT_SECRET", "test-secret")
|
||||
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
|
||||
c.request("POST", "/api/auth/login", map[string]any{"email": "a@superbrain.test", "password": "a-long-test-password"}, 403)
|
||||
c.request("POST", "/api/signup", map[string]any{"email": "a@superbrain.test", "password": "a-long-test-password"}, 403)
|
||||
c.request("POST", "/api/password/forgot", map[string]any{"email": "a@superbrain.test"}, 403)
|
||||
|
||||
body := map[string]any{"issuer": "https://auth.test", "subject": "sub-tier", "email": "tier@superbrain.test", "emailVerified": true}
|
||||
if status, out := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body); status != 200 {
|
||||
t.Fatalf("identity provision on core tier: wanted 200, got %d: %v", status, out)
|
||||
}
|
||||
}
|
||||
|
||||
// TIER=multi alone must refuse the OIDC bridge even with real variables and
|
||||
// a valid service token, while signup and password login keep working.
|
||||
func TestTierMultiDerivesPasswordOnly(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
t.Setenv("TIER", "multi")
|
||||
t.Setenv("OIDC_ISSUER", "https://auth.test")
|
||||
t.Setenv("OIDC_CLIENT_ID", "superbrain")
|
||||
t.Setenv("OIDC_CLIENT_SECRET", "test-secret")
|
||||
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
|
||||
c.request("POST", "/api/signup", map[string]any{"email": "tenant@superbrain.test", "password": "a-long-test-password"}, 201)
|
||||
c.request("POST", "/api/auth/login", map[string]any{"email": "tenant@superbrain.test", "password": "a-long-test-password"}, 200)
|
||||
|
||||
body := map[string]any{"issuer": "https://auth.test", "subject": "sub-m", "email": "m@superbrain.test", "emailVerified": true}
|
||||
if status, _ := postOIDCIdentity(t, srv.URL, oidcServiceToken(t, "oidc-provision", time.Now().Add(time.Minute)), body); status != 403 {
|
||||
t.Fatalf("identity bridge on multi tier: wanted 403, got %d", status)
|
||||
}
|
||||
if status := c.request("GET", "/api/auth/oidc/status", nil, 200); status["enabled"] != false {
|
||||
t.Fatalf("oidc status must report disabled on multi tier: %v", status)
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit variables override tier defaults (the documented escape hatch):
|
||||
// TIER=core + AUTH_MODE=both re-enables password login, while signup stays
|
||||
// off until SIGNUP_ENABLED says otherwise.
|
||||
func TestTierExplicitOverride(t *testing.T) {
|
||||
srv, _ := testServerDB(t)
|
||||
t.Setenv("TIER", "core")
|
||||
t.Setenv("AUTH_MODE", "both")
|
||||
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
|
||||
// Signup stays off via the core-tier default...
|
||||
c.request("POST", "/api/signup", map[string]any{"email": "o@superbrain.test", "password": "a-long-test-password"}, 403)
|
||||
// ...until explicitly re-enabled.
|
||||
t.Setenv("SIGNUP_ENABLED", "1")
|
||||
c.request("POST", "/api/signup", map[string]any{"email": "o@superbrain.test", "password": "a-long-test-password"}, 201)
|
||||
c.request("POST", "/api/auth/login", map[string]any{"email": "o@superbrain.test", "password": "a-long-test-password"}, 200)
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/andrew/superbrain/internal/db"
|
||||
)
|
||||
|
||||
// fakeSMTP is a minimal loopback SMTP relay: it speaks just enough of the
|
||||
// protocol for internal/mailer (greeting, EHLO without extensions so no
|
||||
// STARTTLS/AUTH is attempted, MAIL/RCPT/DATA/QUIT) and records every
|
||||
// delivered message. Same fixture pattern as the CardDAV/IMAP fakes; the
|
||||
// harness sets INTEGRATIONS_ALLOW_PRIVATE=1 so netguard permits loopback.
|
||||
type fakeSMTP struct {
|
||||
t *testing.T
|
||||
ln net.Listener
|
||||
mu sync.Mutex
|
||||
msgs [][2]string // {envelope recipient, DATA payload}
|
||||
done chan struct{}
|
||||
close sync.Once
|
||||
}
|
||||
|
||||
func newFakeSMTP(t *testing.T) *fakeSMTP {
|
||||
t.Helper()
|
||||
ln, e := net.Listen("tcp", "127.0.0.1:0")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
f := &fakeSMTP{t: t, ln: ln, done: make(chan struct{})}
|
||||
go f.serve()
|
||||
t.Cleanup(func() { f.close.Do(func() { close(f.done); ln.Close() }) })
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fakeSMTP) serve() {
|
||||
for {
|
||||
conn, e := f.ln.Accept()
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
go f.handle(conn)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeSMTP) handle(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
r := bufio.NewReader(conn)
|
||||
say := func(s string) { conn.SetWriteDeadline(time.Now().Add(5 * time.Second)); conn.Write([]byte(s + "\r\n")) }
|
||||
say("220 fake ESMTP")
|
||||
var rcpt string
|
||||
inData := false
|
||||
var data strings.Builder
|
||||
for {
|
||||
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
|
||||
line, e := r.ReadString('\n')
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
if inData {
|
||||
if line == "." {
|
||||
inData = false
|
||||
f.mu.Lock()
|
||||
f.msgs = append(f.msgs, [2]string{rcpt, data.String()})
|
||||
f.mu.Unlock()
|
||||
data.Reset()
|
||||
say("250 OK queued")
|
||||
continue
|
||||
}
|
||||
data.WriteString(line + "\n")
|
||||
continue
|
||||
}
|
||||
up := strings.ToUpper(line)
|
||||
switch {
|
||||
case strings.HasPrefix(up, "EHLO"), strings.HasPrefix(up, "HELO"):
|
||||
say("250 fake") // single-line: no extensions advertised
|
||||
case strings.HasPrefix(up, "MAIL FROM"):
|
||||
say("250 OK")
|
||||
case strings.HasPrefix(up, "RCPT TO"):
|
||||
rcpt = strings.TrimSuffix(strings.TrimPrefix(line[strings.Index(line, ":")+1:], "<"), ">")
|
||||
say("250 OK")
|
||||
case up == "DATA":
|
||||
inData = true
|
||||
say("354 End data with <CR><LF>.<CR><LF>")
|
||||
case up == "QUIT":
|
||||
say("221 Bye")
|
||||
return
|
||||
case up == "RSET", up == "NOOP":
|
||||
say("250 OK")
|
||||
default:
|
||||
say("250 OK")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeSMTP) messages() [][2]string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([][2]string(nil), f.msgs...)
|
||||
}
|
||||
|
||||
// waitForMessage blocks until the fake has n messages (SMTP delivery is
|
||||
// synchronous from the handler's perspective, but the fake serves in its own
|
||||
// goroutines).
|
||||
func (f *fakeSMTP) waitForMessage(t *testing.T, n int) [2]string {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
msgs := f.messages()
|
||||
if len(msgs) >= n {
|
||||
return msgs[n-1]
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("fake SMTP received %d messages, wanted %d", len(f.messages()), n)
|
||||
return [2]string{}
|
||||
}
|
||||
|
||||
var resetLinkRx = regexp.MustCompile(`/reset-password\?token=([A-Za-z0-9_-]+)`)
|
||||
|
||||
func TestPasswordResetFlow(t *testing.T) {
|
||||
srv, d := testServerDB(t)
|
||||
smtp := newFakeSMTP(t)
|
||||
|
||||
host, port, _ := net.SplitHostPort(smtp.ln.Addr().String())
|
||||
t.Setenv("SMTP_HOST", host)
|
||||
t.Setenv("SMTP_PORT", port)
|
||||
t.Setenv("SMTP_FROM", "superbrain@superbrain.test")
|
||||
t.Setenv("NEXTAUTH_URL", "https://superbrain.test")
|
||||
|
||||
jar, _ := cookiejar.New(nil)
|
||||
alice := apiClient{t, &http.Client{Jar: jar}, srv.URL}
|
||||
alice.request("POST", "/api/signup", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 201)
|
||||
login := func(c apiClient, email, password string, status int) map[string]any {
|
||||
return c.request("POST", "/api/auth/login", map[string]any{"email": email, "password": password}, status)
|
||||
}
|
||||
first := login(alice, "alice@superbrain.test", "a-long-test-password", 200)
|
||||
firstVersion := int(first["tokenVersion"].(float64))
|
||||
|
||||
// Unknown address: the SAME 200 {"ok":true} body and no mail (review
|
||||
// SEC-4: no unauthenticated existence oracle).
|
||||
unknown := alice.request("POST", "/api/password/forgot", map[string]any{"email": "nobody@superbrain.test"}, 200)
|
||||
if len(unknown) != 1 || unknown["ok"] != true {
|
||||
t.Fatalf("forgot body for unknown address is distinguishable: %v", unknown)
|
||||
}
|
||||
// An OIDC-only (password-less) account must never receive a reset link:
|
||||
// setting a password would open a credential path around Authelia.
|
||||
oidcID := db.NewID()
|
||||
if _, e := db.NewUserRepo(d).Create(context.Background(), &db.NewUserInput{
|
||||
ID: oidcID, Name: "OIDC Only", Email: "oidc-only@superbrain.test", Role: "USER", External: true,
|
||||
}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
alice.request("POST", "/api/password/forgot", map[string]any{"email": "oidc-only@superbrain.test"}, 200)
|
||||
if msgs := smtp.messages(); len(msgs) != 0 {
|
||||
t.Fatalf("mail sent for unknown/OIDC-only addresses: %v", msgs)
|
||||
}
|
||||
|
||||
// Real request: one mail, link carries the token.
|
||||
alice.request("POST", "/api/password/forgot", map[string]any{"email": "alice@superbrain.test"}, 200)
|
||||
msg := smtp.waitForMessage(t, 1)
|
||||
if msg[0] != "alice@superbrain.test" {
|
||||
t.Fatalf("envelope recipient = %q", msg[0])
|
||||
}
|
||||
m := resetLinkRx.FindStringSubmatch(msg[1])
|
||||
if m == nil {
|
||||
t.Fatalf("no reset link in mail body:\n%s", msg[1])
|
||||
}
|
||||
token := m[1]
|
||||
if !strings.Contains(msg[1], "https://superbrain.test/reset-password") {
|
||||
t.Fatalf("reset link does not use NEXTAUTH_URL:\n%s", msg[1])
|
||||
}
|
||||
|
||||
// Password policy mirrors signup.
|
||||
alice.request("POST", "/api/password/reset", map[string]any{"token": token, "password": "short"}, 400)
|
||||
// The token survives a rejected attempt (it was never consumed).
|
||||
alice.request("POST", "/api/password/reset", map[string]any{"token": token, "password": strings.Repeat("x", 73)}, 400)
|
||||
alice.request("POST", "/api/password/reset", map[string]any{"token": "not-a-real-token", "password": "brand-new-password"}, 400)
|
||||
|
||||
// Successful reset: old password dies, new one works, and tokenVersion
|
||||
// bumps so every session minted before the reset is revoked (SEC-02).
|
||||
alice.request("POST", "/api/password/reset", map[string]any{"token": token, "password": "brand-new-password"}, 200)
|
||||
login(alice, "alice@superbrain.test", "a-long-test-password", 401)
|
||||
after := login(alice, "alice@superbrain.test", "brand-new-password", 200)
|
||||
if int(after["tokenVersion"].(float64)) != firstVersion+1 {
|
||||
t.Fatalf("tokenVersion = %v, wanted %d (reset must revoke prior sessions)", after["tokenVersion"], firstVersion+1)
|
||||
}
|
||||
// Single-use: replaying the consumed token fails.
|
||||
alice.request("POST", "/api/password/reset", map[string]any{"token": token, "password": "another-password-1"}, 400)
|
||||
login(alice, "alice@superbrain.test", "brand-new-password", 200)
|
||||
|
||||
// A fresh request supersedes outstanding tokens (newest link wins).
|
||||
alice.request("POST", "/api/password/forgot", map[string]any{"email": "alice@superbrain.test"}, 200)
|
||||
token2 := resetLinkRx.FindStringSubmatch(smtp.waitForMessage(t, 2)[1])[1]
|
||||
alice.request("POST", "/api/password/forgot", map[string]any{"email": "alice@superbrain.test"}, 200)
|
||||
token3 := resetLinkRx.FindStringSubmatch(smtp.waitForMessage(t, 3)[1])[1]
|
||||
alice.request("POST", "/api/password/reset", map[string]any{"token": token2, "password": "superseded-pass-1"}, 400)
|
||||
alice.request("POST", "/api/password/reset", map[string]any{"token": token3, "password": "final-password-1"}, 200)
|
||||
login(alice, "alice@superbrain.test", "final-password-1", 200)
|
||||
|
||||
// Expired tokens are rejected: age the stored row directly.
|
||||
alice.request("POST", "/api/password/forgot", map[string]any{"email": "alice@superbrain.test"}, 200)
|
||||
token4 := resetLinkRx.FindStringSubmatch(smtp.waitForMessage(t, 4)[1])[1]
|
||||
if _, e := d.Exec(`UPDATE "PasswordResetToken" SET "expiresAt"=now()-interval '1 minute'`); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
alice.request("POST", "/api/password/reset", map[string]any{"token": token4, "password": "too-late-pass-1"}, 400)
|
||||
}
|
||||
|
||||
func TestPasswordResetWithoutSMTP(t *testing.T) {
|
||||
srv := testServer(t)
|
||||
// No SMTP_HOST/SMTP_FROM configured: forgot reports a global 503 (a
|
||||
// deployment property, identical for every address — not an oracle).
|
||||
t.Setenv("SMTP_HOST", "")
|
||||
t.Setenv("SMTP_FROM", "")
|
||||
t.Setenv("NEXTAUTH_URL", "https://superbrain.test")
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c := apiClient{t, &http.Client{Jar: jar}, srv.URL}
|
||||
c.request("POST", "/api/signup", map[string]any{"email": "carol@superbrain.test", "password": "a-long-test-password"}, 201)
|
||||
c.request("POST", "/api/password/forgot", map[string]any{"email": "carol@superbrain.test"}, 503)
|
||||
c.request("POST", "/api/password/forgot", map[string]any{"email": "unknown@superbrain.test"}, 503)
|
||||
// Reset still validates tokens structurally even without SMTP config.
|
||||
c.request("POST", "/api/password/reset", map[string]any{"token": "x", "password": "brand-new-password"}, 400)
|
||||
}
|
||||
@@ -41,6 +41,10 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server {
|
||||
// 4.1 Auth and account (rate limited for non-loopback peers)
|
||||
mux.HandleFunc("POST /api/signup", auth.RateLimitSignup(auth.HandleSignup))
|
||||
mux.HandleFunc("POST /api/auth/login", auth.RateLimitLogin(auth.HandleLogin))
|
||||
// Self-service password reset (unauthenticated; enumeration-safe and
|
||||
// rate limited per effective client IP like signup).
|
||||
mux.HandleFunc("POST /api/password/forgot", auth.RateLimitForgot(auth.HandleForgotPassword))
|
||||
mux.HandleFunc("POST /api/password/reset", auth.RateLimitReset(auth.HandleResetPassword))
|
||||
mux.HandleFunc("GET /api/auth/", auth.HandleAuth) // csrf, callbacks, session, signout
|
||||
mux.HandleFunc("POST /api/auth/", auth.HandleAuth)
|
||||
mux.HandleFunc("GET /api/me", authed(auth.HandleMe))
|
||||
|
||||
Reference in New Issue
Block a user