Files
minstrel/internal/api/auth_forgot_test.go
T
bvandeusenandClaude Opus 5.5 46194a609d
test-go / test (push) Successful in 1m29s
test-web / test (push) Successful in 1m37s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
test-go / integration (push) Canceled after 2m45s
release / Build signed APK (releases and dev) (push) Canceled after 3m40s
fix(auth): build password-reset links from an operator-set public address, never the Host header (M462 #4981)
buildResetURL used r.Host and r.TLS, so a forgot-password request with a
forged Host emailed the victim a real reset token on a link to the
attacker's server. Links now come only from network_settings.public_url
(migration 0062), and no reset email is sent while it is empty; the response
stays the same opaque 200 and the log says why.

The address is set on a new "Public address" card under Admin → Integrations,
which offers the page's own origin and warns while unset. PUT
/api/admin/network-settings takes either field alone, so the proxy card and
this one can't overwrite each other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 09:32:10 -04:00

159 lines
5.0 KiB
Go

package api
import (
"bytes"
"context"
"errors"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"git.fabledsword.com/bvandeusen/minstrel/internal/mailer"
"git.fabledsword.com/bvandeusen/minstrel/internal/netsettings"
)
// withPublicURL gives h a network-settings service holding url, restoring an
// empty value afterwards so other tests see the default.
func withPublicURL(t *testing.T, h *handlers, pool *pgxpool.Pool, url string) {
t.Helper()
ns, err := netsettings.New(context.Background(), pool, nil)
if err != nil {
t.Fatalf("netsettings: %v", err)
}
if err := ns.SetPublicURL(context.Background(), url); err != nil {
t.Fatalf("set public url: %v", err)
}
t.Cleanup(func() { _ = ns.SetPublicURL(context.Background(), "") })
h.netSettings = ns
}
// With no public URL set, a reset email is not sent at all, and the response
// is still the same opaque 200.
func TestForgotPassword_NoPublicURL_SendsNothing(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
fake := &mailer.FakeSender{}
h.mailer = fake
withPublicURL(t, h, pool, "")
user := seedUser(t, pool, "nourl", "pw", false)
if _, err := pool.Exec(context.Background(),
"UPDATE users SET email = 'nourl@example.com' WHERE id = $1", user.ID); err != nil {
t.Fatalf("seed email: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/api/auth/forgot-password",
bytes.NewReader([]byte(`{"email":"nourl@example.com"}`)))
rec := httptest.NewRecorder()
h.handleForgotPassword(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("status = %d, want 200", rec.Code)
}
if len(fake.Sent) != 0 {
t.Errorf("sent %d emails with no public URL set, want 0", len(fake.Sent))
}
}
func TestForgotPassword_KnownEmail_SendsMail(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
fake := &mailer.FakeSender{}
h.mailer = fake
withPublicURL(t, h, pool, "https://music.example.com")
user := seedUser(t, pool, "forgotuser", "pw", false)
if _, err := pool.Exec(context.Background(),
"UPDATE users SET email = 'forgot@example.com' WHERE id = $1", user.ID); err != nil {
t.Fatalf("seed email: %v", err)
}
body := `{"email":"forgot@example.com"}`
req := httptest.NewRequest(http.MethodPost, "/api/auth/forgot-password",
bytes.NewReader([]byte(body)))
// A forged Host must not reach the link: it comes from the public URL.
req.Host = "attacker.example.net"
rec := httptest.NewRecorder()
h.handleForgotPassword(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("status = %d, want 200", rec.Code)
}
if len(fake.Sent) != 1 {
t.Fatalf("Sent len = %d, want 1", len(fake.Sent))
}
got := fake.LastSent()
if got.To != "forgot@example.com" {
t.Errorf("To = %q, want forgot@example.com", got.To)
}
if !strings.Contains(got.TextBody, "https://music.example.com/reset-password/") {
t.Errorf("reset link not built from the public URL:\n%s", got.TextBody)
}
if strings.Contains(got.TextBody+got.HTMLBody, "attacker.example.net") {
t.Error("the request's Host header reached the emailed link")
}
// Token row was inserted.
var tokenCount int
if err := pool.QueryRow(context.Background(),
"SELECT count(*) FROM password_resets WHERE user_id = $1", user.ID).Scan(&tokenCount); err != nil {
t.Fatalf("verify token: %v", err)
}
if tokenCount == 0 {
t.Errorf("no password_resets row inserted")
}
}
func TestForgotPassword_UnknownEmail_Returns200_NoSend(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, _ := testHandlers(t)
fake := &mailer.FakeSender{}
h.mailer = fake
body := `{"email":"nonexistent@example.com"}`
req := httptest.NewRequest(http.MethodPost, "/api/auth/forgot-password",
bytes.NewReader([]byte(body)))
rec := httptest.NewRecorder()
h.handleForgotPassword(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("status = %d, want 200 (always; no enumeration)", rec.Code)
}
if len(fake.Sent) != 0 {
t.Errorf("Sent len = %d, want 0 for unknown email", len(fake.Sent))
}
}
func TestForgotPassword_MailerFailure_StillReturns200(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
fake := &mailer.FakeSender{FailNext: errors.New("simulated SMTP failure")}
h.mailer = fake
user := seedUser(t, pool, "mailfail", "pw", false)
if _, err := pool.Exec(context.Background(),
"UPDATE users SET email = 'mailfail@example.com' WHERE id = $1", user.ID); err != nil {
t.Fatalf("seed: %v", err)
}
body := `{"email":"mailfail@example.com"}`
req := httptest.NewRequest(http.MethodPost, "/api/auth/forgot-password",
bytes.NewReader([]byte(body)))
rec := httptest.NewRecorder()
h.handleForgotPassword(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("status = %d, want 200 (mailer failures don't propagate)", rec.Code)
}
}