feat: ship Tier 1 — auth, authz, rate limits, real notifications, CSV import, billing, backups/DR, privacy

Closes every block in docs/TIER1_PLAN.md from the Claude-scope side. The
homelab / cloud setup steps (SES verification, restore drill, lawyer-
drafted ToS) remain operator-owned but are unblocked.

Block A — Authentication
- Migration 0003: password_hash, email_verified, email_verification_tokens,
  password_reset_tokens, refresh_tokens (with replaced_by family chain).
- Bcrypt hasher, HS256 JWT signer, single-use refresh tokens with rotation
  + replay-detection (revokes the family on reuse).
- /auth/signup, /login, /refresh, /logout, /verify-email,
  /forgot-password, /reset-password — enumeration-safe.
- requireAuth middleware + GET /me.
- Frontend useAuth/useApi with auto-refresh-on-401, login/signup/verify/
  forgot/reset pages, route-guard middleware.

Block B — Authorisation
- EventRepo.GetForHost; Update/Delete scoped by host_id.
- All host routes behind requireAuth + ownership; cross-tenant returns
  404 (no enumeration). ?host_id removed.
- WS auth via short-lived single-use tickets (POST /auth/ws-ticket).
- Tests: TestCrossTenantIsolation — 9 probes.

Block C — Rate limiting
- Redis sliding-window via Lua (atomic ZADD+ZCARD+PEXPIRE).
- Per-route limits matching the plan (signup IP, login IP+email, RSVP/
  access by token, events/guests/tokens by user_id).
- 429 with Retry-After header and JSON body.
- Auth lockout: 5 failed logins → account locked, only password reset
  clears it.
- Frontend: useErrMessage normalises 429 + locked messaging.

Block D — Real notifications
- Migration 0004: provider_message_id, bounce_type, complained columns
  + unsubscribes (CITEXT) suppression table.
- Branded HTML + plaintext templates for verification, reset, invitation,
  confirmation, reminder. Per-page templates avoid html/template's
  contextual-escape collisions.
- Senders: SESv2, Twilio (SMS), SMTP (Mailpit-friendly), Resend HTTP.
- PickEmailSender priority Resend > SMTP > SES > Log — system boots
  cleanly in dev with Mailpit; production flips one env var.
- Webhook endpoints (Twilio status + SES SNS) — bounces add to suppression;
  signature verification stubbed pending creds.
- Auto-send: POST /tokens publishes invitation.send; notifier renders +
  delivers via the configured backend; suppression list honoured.
- Bulk + per-row invitation flow: POST /events/{id}/guests/invitations/bulk
  returns per-guest tokens so phone-only guests can be SMS'd manually.
- Unsubscribe: signed HMAC token (no TTL) + /unsubscribe/[token] page.
- WhatsApp Option A+: wa.me click-to-chat wizard with per-guest progress
  tracking, isLikelyE164 validation, edit-from-wizard.
- Token rotate (POST /tokens/rotate) invalidates the old URL — used by
  the regenerate-link flow.
- Mailpit added to docker-compose for dev inbox.

Block E — CSV import
- Streaming parser: tolerant header detection, UTF-8 BOM + UTF-16 LE/BE
  decoding, row-level validation, 5,000-row cap.
- Strict E.164 phone validation with helpful error message.
- POST /preview + /import + GET /template; preview UI on event page;
  atomic per-batch with dedup on existing emails.

Phone capture across UI
- PhoneInput component: country picker (~50 ISO codes) + national input +
  live E.164 preview + inline length validation.
- Used in Add Guest and Edit Guest modals. Smart paste-handling extracts
  country code from full E.164 strings.

Block F — Billing (Stripe)
- Migration 0005: subscriptions table (user_id → tier/status/period_end +
  Stripe customer/sub ids). Partial unique index keeps one granting sub
  per user.
- internal/billing: Tier + Limits model (Free 1/50, Pro 10/1000, Business
  ∞/5000), Stripe SDK wrapper with IgnoreAPIVersionMismatch for newer
  account API versions.
- /billing/checkout-session, /billing/portal, /billing/status,
  /webhooks/stripe (signature-verified, lifecycle events).
- Tier enforcement: 402 on POST /events, /guests, /import with
  {error, reason, tier, used, limit, upgrade_url} body.
- Frontend: useBilling composable, /dashboard/billing page (current plan,
  usage bars, tier cards), global UpgradeModal triggered by useApi's
  402 interceptor.
- Customer portal kept for self-service cancel/payment-method changes.

Block G — Backups & DR (application side)
- Every migration has a tested .down.sql.
- TestMigrationRoundtrip applies all ups → all downs → all ups against a
  fresh container; catches asymmetric down migrations.
- cmd/restore-verify: 28-check post-restore invariant tool (schema
  presence, no orphans across 10 FK relationships, email uniqueness,
  single-active subscription, row-count snapshot).
- docs/RUNBOOK_RESTORE.md: 9-step restore procedure with RTO/RPO
  targets, drill instructions, rollback path.

Block H — Privacy compliance (application side)
- Migration 0006: deleted_at + terms_accepted_at + privacy_policy_accepted_at
  on users. Partial index on email for live-only uniqueness.
- GET /me/data-export — synchronous JSON dump (user, events, guests,
  tokens, rsvps, access_logs, notifications).
- DELETE /me — soft-delete with PII scrub + refresh-token revocation;
  re-signup with same email works.
- POST /me/accept-terms — idempotent consent recording.
- Frontend /privacy + /terms placeholder pages with substantive (pending
  legal review) copy; footer links; signup terms checkbox; TermsGateModal
  for accounts created before the rollout; export + delete buttons on
  /dashboard/billing.

Tests
- All migrations verified up/down/up.
- Integration suite: TestE2EHappyPath, TestAuthFlow, TestCrossTenantIsolation,
  TestRateLimitSignup, TestLoginLockout, TestUnsubscribeFlow,
  TestSESBounceWebhook, TestTwilioStatusWebhook, TestCsvImportFlow,
  TestCsvImportAtomicRollback, TestBulkIssueInvitations, TestBulkIssueExplicitSubset,
  TestTokenIssuePublishesInvitation, TestTokenIssueWithoutGuestEmailSkipsInvitation,
  TestGuestUpdate, TestGuestDelete, TestTokenRotate, TestSMTPSenderAgainstMailpit,
  TestFreeTierEventLimit, TestFreeTierGuestLimit, TestBusinessTierBypassesLimits,
  TestDataExport, TestDeleteMe, TestAcceptTerms, TestMigrationRoundtrip.
  Full suite runs in ~120s against real Postgres + NATS + Redis + Mailpit.
- Unit suite green across internal/auth, internal/csvimport,
  internal/notification, internal/ratelimit, internal/domain.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Kwaku Danso
2026-05-16 23:54:22 +01:00
parent a0ed34f860
commit 59b8781659
124 changed files with 13702 additions and 445 deletions
+378
View File
@@ -0,0 +1,378 @@
//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
}
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 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",
}})
}