package http import ( "bufio" "context" "net" "net/http" "net/http/cookiejar" "regexp" "strings" "sync" "testing" "time" "gitea.federated.computer/Federated_Computer/brain/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 .") 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) }