3973e4058d
Events can now have multiple users with distinct roles:
owner — manage collaborators, delete event, full access
editor — manage guests, tokens, CSV import, patch event
viewer — read-only access to everything
Schema (migration 0008)
- collaborator_role ENUM + event_collaborators + collaborator_invites
- Backfill: every existing events.host_id becomes an owner row
- EventRepo.Create seeds the owner row in the same transaction so
no future event can exist without one
Authz
- New requireRole(eventID, userID, minRole) helper. Non-members 404;
insufficient role 403. Replaces requireEventOwner across every
shared-role handler (events.get/update, guests CRUD, tokens issue/
rotate/bulk, csv preview/commit/template, activity, ws-ticket)
- events.delete + collaborator management stay owner-only
- GET /events lists every event the user has any role on
- /events/{id} response now embeds your_role for UI branching
Collaborator endpoints
- GET /events/{id}/collaborators (viewer+)
- POST /events/{id}/collaborators (owner) — sends invite email
- PATCH /events/{id}/collaborators/{user_id} (owner) — role change
- DELETE /events/{id}/collaborators/{user_id} (owner) — refuses last owner
- DELETE /events/{id}/collaborators/pending (owner) — cancel invite
- GET /invites/{token} (public) — preview summary
- POST /invites/{token}/accept (authed) — atomic accept
Invitations
- SHA-256 hashed in DB; raw value only lives in the email link
- 7-day TTL, single-use, email-bound (caller's email must match)
- New SendCollaboratorInvite on auth.EmailSender + Resend/SMTP/SES
senders + log stub; collaborator_invite.html/txt branded template
Frontend
- TeamCard.vue on the event detail page: lists collaborators with
inline role-change + remove, pending-invites with cancel, invite
modal (email + role). Owner-only actions hidden for editors/viewers
- /invites/[token] accept page: shows invite summary, prompts signup
or sign-in with pre-filled email, refuses mismatched accounts
Tests (all 6 pass on the existing testcontainers harness)
- backfill: legacy host gets owner role
- role enforcement: viewer can read, editor can write guests but not
delete/manage team, non-member 404s everywhere
- last-owner removal refused (400)
- shared events show up in collaborator's /events list
- invite flow: create → preview → accept → role granted → replay 410
- email mismatch on accept returns 403
- expired invite returns 410
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
385 lines
11 KiB
Go
385 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 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",
|
|
}})
|
|
}
|