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