Files
guestguard/test/integration/auth_test.go
T
Kwaku Danso dbddf17e3b fix(rsvp): defend the edit flow against forwarded invitation links
When a guest submitted via their invitation and then forwarded the link
(or someone copied the URL), the recipient was shown the original guest's
response and a "Change my response" button. Two real problems:
  - Privacy leak: the original guest's reply was visible
  - Integrity: the recipient could silently overwrite the response

The fix is two layered defences plus a recovery path, matching the
industry pattern used by Eventbrite / Partiful / Lu.ma:

Backend
  - GET /access/{token} now compares the device fingerprint of the
    current request to the fingerprint stored on the existing RSVP.
    When they don't match, the rsvp field is omitted from the
    response and a new rsvp_submitted_elsewhere flag is set instead.
    The original guest's reply stays private.
  - PATCH /rsvp/{token} runs the same gate before scoring. A foreign
    device gets 403 with a hint to request an edit link.
  - The fingerprint check is intentionally narrow (user_agent only),
    so a guest jumping between Wi-Fi and mobile data on the same
    phone still sails through.

Recovery path
  - New POST /access/{token}/request-edit-link mints a short-lived
    edit nonce (Redis, 30-min TTL, SHA-256-hashed), then emails it
    to the guest's address on file via the existing EmailSender.
    Rate-limited to 3 per token per hour.
  - GET /access/{token}?edit=<nonce> and PATCH /rsvp with edit_nonce
    in the body both accept the nonce as a bypass for the
    same-device check. Lets the real guest edit from a new phone
    when their original device is gone.
  - New SendRSVPEditLink method on auth.EmailSender, implemented by
    every concrete sender (log stub / Resend / SMTP / SES), with a
    branded HTML+text template that explains the "we sent this
    because we didn't recognise the device" framing.

Frontend
  - rsvp/[token].vue learns the new "responded elsewhere" state.
    Renders "This invitation has already been used" + a
    "Send me an edit link" CTA when the access response says we
    have somewhere to deliver it. Empty-state copy reads "If you
    forwarded the link, please ask the original guest to reach
    out to the host".
  - When the URL carries ?edit=<nonce>, the page passes it on the
    /access call (so the backend unhides the RSVP), opens the edit
    form pre-populated, and forwards the nonce on PATCH.
  - Removed two leftover leaks from earlier — the page no longer
    shows internal "Risk score N · band" to confirmed or blocked
    guests; the blocked-attempt copy now reads "Something about
    this attempt looked off" rather than "suspicious access
    attempt".

Defensive nil-guard
  - The access handler's NATS publish goroutine now skips when
    deps.AccessPublisher is nil (matches the rsvp publisher's
    existing guard); without it the handler nil-panicked in tests
    that don't wire NATS.

Tests
  - TestFingerprintsSimilar (unit) covers the same-UA / different-UA
    / missing-UA matrix.
  - TestForwardedInvitationLinkDefence (integration) walks the full
    flow: submit from UA-A, hide on UA-B, request link, follow nonce
    from UA-B and edit, then verify a UA-C with a forged nonce is
    still refused.
  - Full integration suite passes (183.5s).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 15:09:07 +01:00

391 lines
11 KiB
Go

//go:build integration
package integration_test
import (
"bytes"
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/alchemistkay/guestguard/internal/api"
"github.com/alchemistkay/guestguard/internal/storage"
)
const authTestPassword = "correct-horse-battery-staple"
// recordingEmailSender captures the most recent verification / reset link so
// tests can finish the signup flow without a real inbox.
type recordingEmailSender struct {
verifyLink string
resetLink string
inviteLink string
}
func (s *recordingEmailSender) SendVerification(_ context.Context, _, _, link string) error {
s.verifyLink = link
return nil
}
func (s *recordingEmailSender) SendPasswordReset(_ context.Context, _, _, link string) error {
s.resetLink = link
return nil
}
func (s *recordingEmailSender) SendCollaboratorInvite(_ context.Context, _, _, _, _, link string) error {
s.inviteLink = link
return nil
}
func (s *recordingEmailSender) SendRSVPEditLink(_ context.Context, _, _, _, _ string) error {
// Block G follow-up — recording-only stub; we don't track the URL here
// because the dedicated forwarded-link test has its own capture sender.
return nil
}
func TestAuthFlow(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in -short mode")
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
t.Cleanup(cancel)
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
dsn := startPostgres(t, ctx)
db, err := storage.NewDB(ctx, dsn)
must(t, err, "connect db")
t.Cleanup(db.Close)
must(t, db.Migrate(ctx), "migrate")
emails := &recordingEmailSender{}
apiSrv, err := api.NewServer(api.ServerDeps{
Logger: logger,
DB: db,
TokenTTL: 24 * time.Hour,
JWTSecret: "test-secret-must-be-at-least-32-bytes-long-xx",
JWTIssuer: "guestguard-test",
AccessTokenTTL: 5 * time.Minute,
RefreshTokenTTL: 24 * time.Hour,
EmailVerificationTTL: 1 * time.Hour,
PasswordResetTTL: 1 * time.Hour,
PublicBaseURL: "http://localhost",
EmailSender: emails,
})
must(t, err, "build api server")
srv := httptest.NewServer(apiSrv.Handler())
t.Cleanup(srv.Close)
jar, _ := cookiejar.New(nil)
client := &http.Client{Jar: jar}
email := uniqueEmail(t)
t.Run("signup", func(t *testing.T) {
resp := post(t, client, srv.URL+"/auth/signup", map[string]string{
"email": email,
"name": "Auth Test",
"password": authTestPassword,
})
if resp.StatusCode != http.StatusCreated {
t.Fatalf("signup status: %d", resp.StatusCode)
}
resp.Body.Close()
if emails.verifyLink == "" {
t.Fatal("verification email not captured")
}
})
t.Run("login before verify is forbidden", func(t *testing.T) {
resp := post(t, client, srv.URL+"/auth/login", map[string]string{
"email": email,
"password": authTestPassword,
})
defer resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
body, _ := io.ReadAll(resp.Body)
t.Fatalf("expected 403, got %d: %s", resp.StatusCode, body)
}
})
t.Run("verify email", func(t *testing.T) {
token := tokenFromQuery(t, emails.verifyLink, "token")
resp := post(t, client, srv.URL+"/auth/verify-email", map[string]string{"token": token})
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
t.Fatalf("verify status: %d %s", resp.StatusCode, body)
}
})
t.Run("verify token replay rejected", func(t *testing.T) {
token := tokenFromQuery(t, emails.verifyLink, "token")
resp := post(t, client, srv.URL+"/auth/verify-email", map[string]string{"token": token})
resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("replay should be 400, got %d", resp.StatusCode)
}
})
var firstAccess string
t.Run("login returns access + refresh cookie", func(t *testing.T) {
resp := post(t, client, srv.URL+"/auth/login", map[string]string{
"email": email,
"password": authTestPassword,
})
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
t.Fatalf("login status: %d %s", resp.StatusCode, body)
}
var body struct {
AccessToken string `json:"access_token"`
}
must(t, json.NewDecoder(resp.Body).Decode(&body), "decode login")
if body.AccessToken == "" {
t.Fatal("missing access token")
}
firstAccess = body.AccessToken
assertRefreshCookieSet(t, srv.URL, jar)
})
t.Run("access token authorises /me", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, srv.URL+"/me", nil)
req.Header.Set("Authorization", "Bearer "+firstAccess)
resp, err := client.Do(req)
must(t, err, "GET /me")
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
t.Fatalf("/me status: %d %s", resp.StatusCode, body)
}
})
t.Run("refresh rotates tokens", func(t *testing.T) {
oldCookie := refreshCookieValue(t, srv.URL, jar)
resp := post(t, client, srv.URL+"/auth/refresh", nil)
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
t.Fatalf("refresh status: %d %s", resp.StatusCode, body)
}
var body struct {
AccessToken string `json:"access_token"`
}
must(t, json.NewDecoder(resp.Body).Decode(&body), "decode refresh")
if body.AccessToken == "" {
t.Fatal("missing new access token")
}
newCookie := refreshCookieValue(t, srv.URL, jar)
if newCookie == oldCookie {
t.Fatal("refresh did not rotate cookie")
}
// Replay of the old refresh token must be rejected and revoke the family.
jar2, _ := cookiejar.New(nil)
client2 := &http.Client{Jar: jar2}
setRefreshCookie(t, srv.URL, jar2, oldCookie)
replay := post(t, client2, srv.URL+"/auth/refresh", nil)
replay.Body.Close()
if replay.StatusCode != http.StatusUnauthorized {
t.Fatalf("old refresh replay should be 401, got %d", replay.StatusCode)
}
// And the family should be revoked: even the new (just-rotated) cookie
// no longer works.
familyReplay := post(t, client, srv.URL+"/auth/refresh", nil)
familyReplay.Body.Close()
if familyReplay.StatusCode != http.StatusUnauthorized {
t.Fatalf("family-revoked refresh should be 401, got %d", familyReplay.StatusCode)
}
})
// After family revocation, log back in to keep going.
resp := post(t, client, srv.URL+"/auth/login", map[string]string{
"email": email,
"password": authTestPassword,
})
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("second login: %d", resp.StatusCode)
}
t.Run("forgot-password emits link without leaking existence", func(t *testing.T) {
// Unknown email — still 202, no link sent.
emails.resetLink = ""
unknown := post(t, client, srv.URL+"/auth/forgot-password", map[string]string{
"email": "nobody-" + uuid.NewString() + "@guestguard.test",
})
unknown.Body.Close()
if unknown.StatusCode != http.StatusAccepted {
t.Fatalf("unknown forgot-password: %d", unknown.StatusCode)
}
if emails.resetLink != "" {
t.Fatal("reset link sent for unknown email")
}
known := post(t, client, srv.URL+"/auth/forgot-password", map[string]string{
"email": email,
})
known.Body.Close()
if known.StatusCode != http.StatusAccepted {
t.Fatalf("known forgot-password: %d", known.StatusCode)
}
if emails.resetLink == "" {
t.Fatal("reset link not captured")
}
})
t.Run("reset password invalidates sessions", func(t *testing.T) {
token := tokenFromPath(t, emails.resetLink, "/reset-password/")
newPw := "new-correct-horse-battery-staple"
resp := post(t, client, srv.URL+"/auth/reset-password", map[string]string{
"token": token,
"new_password": newPw,
})
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("reset status: %d", resp.StatusCode)
}
// Old password fails.
bad := post(t, client, srv.URL+"/auth/login", map[string]string{
"email": email,
"password": authTestPassword,
})
bad.Body.Close()
if bad.StatusCode != http.StatusUnauthorized {
t.Fatalf("old password should 401, got %d", bad.StatusCode)
}
// Existing refresh cookie should no longer work.
refresh := post(t, client, srv.URL+"/auth/refresh", nil)
refresh.Body.Close()
if refresh.StatusCode != http.StatusUnauthorized {
t.Fatalf("refresh after reset should 401, got %d", refresh.StatusCode)
}
// New password works.
ok := post(t, client, srv.URL+"/auth/login", map[string]string{
"email": email,
"password": newPw,
})
ok.Body.Close()
if ok.StatusCode != http.StatusOK {
t.Fatalf("new password login: %d", ok.StatusCode)
}
})
t.Run("logout revokes refresh", func(t *testing.T) {
resp := post(t, client, srv.URL+"/auth/logout", nil)
resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
t.Fatalf("logout status: %d", resp.StatusCode)
}
refresh := post(t, client, srv.URL+"/auth/refresh", nil)
refresh.Body.Close()
if refresh.StatusCode != http.StatusUnauthorized {
t.Fatalf("refresh after logout should 401, got %d", refresh.StatusCode)
}
})
t.Run("requireAuth rejects invalid bearer", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, srv.URL+"/me", nil)
req.Header.Set("Authorization", "Bearer not-a-real-jwt")
resp, err := client.Do(req)
must(t, err, "GET /me bad token")
resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("bad bearer should 401, got %d", resp.StatusCode)
}
})
}
// --- helpers ---
func uniqueEmail(t *testing.T) string {
t.Helper()
return "auth-" + uuid.NewString() + "@guestguard.test"
}
func post(t *testing.T, client *http.Client, url string, body any) *http.Response {
t.Helper()
var r io.Reader
if body != nil {
b, err := json.Marshal(body)
must(t, err, "marshal post body")
r = bytes.NewReader(b)
}
req, err := http.NewRequest(http.MethodPost, url, r)
must(t, err, "build post request")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := client.Do(req)
must(t, err, "do post "+url)
return resp
}
func tokenFromQuery(t *testing.T, link, key string) string {
t.Helper()
idx := strings.Index(link, key+"=")
if idx < 0 {
t.Fatalf("link missing %s: %s", key, link)
}
return link[idx+len(key)+1:]
}
func tokenFromPath(t *testing.T, link, prefix string) string {
t.Helper()
idx := strings.LastIndex(link, prefix)
if idx < 0 {
t.Fatalf("link missing prefix %s: %s", prefix, link)
}
return link[idx+len(prefix):]
}
func assertRefreshCookieSet(t *testing.T, baseURL string, jar http.CookieJar) {
t.Helper()
if refreshCookieValue(t, baseURL, jar) == "" {
t.Fatal("refresh cookie not set")
}
}
func refreshCookieValue(t *testing.T, baseURL string, jar http.CookieJar) string {
t.Helper()
// jar.Cookies needs a URL whose path matches the cookie's Path (/auth).
u := baseURL + "/auth/refresh"
parsed, err := url.Parse(u)
must(t, err, "parse url")
for _, c := range jar.Cookies(parsed) {
if c.Name == "gg_refresh" {
return c.Value
}
}
return ""
}
func setRefreshCookie(t *testing.T, baseURL string, jar http.CookieJar, value string) {
t.Helper()
parsed, err := url.Parse(baseURL + "/auth/refresh")
must(t, err, "parse url")
jar.SetCookies(parsed, []*http.Cookie{{
Name: "gg_refresh",
Value: value,
Path: "/auth",
}})
}