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
+32
View File
@@ -0,0 +1,32 @@
package auth
import (
"context"
"log/slog"
)
// EmailSender delivers transactional auth emails (verification, reset).
// Block A ships LogSender so dev environments work without Twilio/SES.
// Block D replaces this with a real SES-backed sender.
type EmailSender interface {
SendVerification(ctx context.Context, to, name, link string) error
SendPasswordReset(ctx context.Context, to, name, link string) error
}
type LogEmailSender struct {
Logger *slog.Logger
}
func (l LogEmailSender) SendVerification(_ context.Context, to, name, link string) error {
l.Logger.Info("auth email (stub): verification",
"to", to, "name", name, "link", link,
)
return nil
}
func (l LogEmailSender) SendPasswordReset(_ context.Context, to, name, link string) error {
l.Logger.Info("auth email (stub): password reset",
"to", to, "name", name, "link", link,
)
return nil
}
+95
View File
@@ -0,0 +1,95 @@
package auth
import (
"errors"
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
var (
ErrInvalidJWT = errors.New("invalid token")
ErrExpiredJWT = errors.New("token expired")
)
type AccessClaims struct {
UserID uuid.UUID `json:"sub_uuid"`
jwt.RegisteredClaims
}
type JWTSigner struct {
secret []byte
ttl time.Duration
issuer string
parser *jwt.Parser
}
func NewJWTSigner(secret string, ttl time.Duration, issuer string) (*JWTSigner, error) {
if len(secret) < 32 {
return nil, fmt.Errorf("jwt secret must be at least 32 bytes")
}
if ttl <= 0 {
return nil, fmt.Errorf("jwt ttl must be positive")
}
return &JWTSigner{
secret: []byte(secret),
ttl: ttl,
issuer: issuer,
parser: jwt.NewParser(
jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}),
jwt.WithIssuer(issuer),
jwt.WithExpirationRequired(),
),
}, nil
}
func (s *JWTSigner) Issue(userID uuid.UUID, now time.Time) (string, time.Time, error) {
exp := now.Add(s.ttl)
claims := AccessClaims{
UserID: userID,
RegisteredClaims: jwt.RegisteredClaims{
Issuer: s.issuer,
Subject: userID.String(),
IssuedAt: jwt.NewNumericDate(now),
NotBefore: jwt.NewNumericDate(now.Add(-1 * time.Second)),
ExpiresAt: jwt.NewNumericDate(exp),
ID: uuid.NewString(),
},
}
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := tok.SignedString(s.secret)
if err != nil {
return "", time.Time{}, err
}
return signed, exp, nil
}
func (s *JWTSigner) Parse(raw string) (*AccessClaims, error) {
claims := &AccessClaims{}
tok, err := s.parser.ParseWithClaims(raw, claims, func(t *jwt.Token) (any, error) {
return s.secret, nil
})
if err != nil {
if errors.Is(err, jwt.ErrTokenExpired) {
return nil, ErrExpiredJWT
}
return nil, ErrInvalidJWT
}
if !tok.Valid {
return nil, ErrInvalidJWT
}
if claims.UserID == uuid.Nil {
// Fallback for tokens that only carry Subject (defensive — we always
// set UserID on issue).
parsed, perr := uuid.Parse(claims.Subject)
if perr != nil {
return nil, ErrInvalidJWT
}
claims.UserID = parsed
}
return claims, nil
}
func (s *JWTSigner) TTL() time.Duration { return s.ttl }
+82
View File
@@ -0,0 +1,82 @@
package auth
import (
"errors"
"testing"
"time"
"github.com/google/uuid"
)
const testSecret = "test-secret-must-be-at-least-32-bytes-long-xx"
func TestJWTRoundTrip(t *testing.T) {
s, err := NewJWTSigner(testSecret, 5*time.Minute, "guestguard-test")
if err != nil {
t.Fatalf("signer: %v", err)
}
uid := uuid.New()
tok, exp, err := s.Issue(uid, time.Now())
if err != nil {
t.Fatalf("issue: %v", err)
}
if tok == "" {
t.Fatal("empty token")
}
if time.Until(exp) <= 0 {
t.Fatalf("expiry in past: %v", exp)
}
claims, err := s.Parse(tok)
if err != nil {
t.Fatalf("parse: %v", err)
}
if claims.UserID != uid {
t.Fatalf("user mismatch: got %s want %s", claims.UserID, uid)
}
}
func TestJWTExpired(t *testing.T) {
s, err := NewJWTSigner(testSecret, 1*time.Second, "guestguard-test")
if err != nil {
t.Fatalf("signer: %v", err)
}
tok, _, err := s.Issue(uuid.New(), time.Now().Add(-1*time.Hour))
if err != nil {
t.Fatalf("issue: %v", err)
}
if _, err := s.Parse(tok); !errors.Is(err, ErrExpiredJWT) {
t.Fatalf("expected ErrExpiredJWT, got %v", err)
}
}
func TestJWTTamper(t *testing.T) {
s, err := NewJWTSigner(testSecret, 5*time.Minute, "guestguard-test")
if err != nil {
t.Fatalf("signer: %v", err)
}
tok, _, _ := s.Issue(uuid.New(), time.Now())
// Flip a character in the signature segment.
tampered := tok[:len(tok)-1] + "a"
if tampered == tok {
tampered = tok[:len(tok)-1] + "b"
}
if _, err := s.Parse(tampered); !errors.Is(err, ErrInvalidJWT) {
t.Fatalf("expected ErrInvalidJWT, got %v", err)
}
}
func TestJWTSecretTooShort(t *testing.T) {
if _, err := NewJWTSigner("short", time.Minute, "x"); err == nil {
t.Fatal("expected error for short secret")
}
}
func TestOpaqueTokenHashStable(t *testing.T) {
raw, hash, err := NewOpaqueToken()
if err != nil {
t.Fatalf("mint: %v", err)
}
if got := HashOpaque(raw); got != hash {
t.Fatalf("hash mismatch: got %s want %s", got, hash)
}
}
+107
View File
@@ -0,0 +1,107 @@
package auth
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
// LockoutTracker counts consecutive failed logins per email and trips a
// lockout flag after a threshold. The lock is keyed by user_id (once we
// know it from the email) so that resetting the password — which we do via
// /auth/reset-password — can clear it cleanly.
//
// Why two keys? The failure counter must work even when the email maps to
// no user (otherwise an attacker probing addresses just gets unlimited
// tries). The lock flag only exists once we've matched an actual account.
type LockoutTracker struct {
client *redis.Client
threshold int
window time.Duration // how long failures linger before counters reset
prefix string
}
func NewLockoutTracker(client *redis.Client, threshold int, window time.Duration) *LockoutTracker {
return &LockoutTracker{
client: client,
threshold: threshold,
window: window,
prefix: "auth",
}
}
func (t *LockoutTracker) failKey(email string) string {
h := sha256.Sum256([]byte(strings.ToLower(strings.TrimSpace(email))))
return fmt.Sprintf("%s:login_fail:%s", t.prefix, hex.EncodeToString(h[:]))
}
func (t *LockoutTracker) lockKey(uid uuid.UUID) string {
return fmt.Sprintf("%s:locked:%s", t.prefix, uid.String())
}
// IsLocked reports whether the given user's account is currently locked.
func (t *LockoutTracker) IsLocked(ctx context.Context, uid uuid.UUID) (bool, error) {
if t == nil || t.client == nil {
return false, nil
}
v, err := t.client.Exists(ctx, t.lockKey(uid)).Result()
if err != nil {
return false, err
}
return v > 0, nil
}
// RecordFailure increments the failure counter for the email and, if it
// crosses the threshold, sets the lock flag for the given user id.
// Returns (locked, error). A nil userID is fine — the counter still ticks
// up so probing nonexistent accounts is also rate-limited.
func (t *LockoutTracker) RecordFailure(ctx context.Context, email string, userID *uuid.UUID) (bool, error) {
if t == nil || t.client == nil {
return false, nil
}
key := t.failKey(email)
n, err := t.client.Incr(ctx, key).Result()
if err != nil {
return false, err
}
if n == 1 {
_ = t.client.Expire(ctx, key, t.window).Err()
}
if int(n) >= t.threshold && userID != nil {
// Keep the lock until password reset clears it. 7-day fallback TTL
// so a permanently abandoned account doesn't pile up forever.
if err := t.client.Set(ctx, t.lockKey(*userID), "1", 7*24*time.Hour).Err(); err != nil {
return false, err
}
return true, nil
}
return false, nil
}
// ClearForUser drops both the lock flag and any in-flight failure counter
// for the user's email. Called from /auth/reset-password.
func (t *LockoutTracker) ClearForUser(ctx context.Context, uid uuid.UUID, email string) error {
if t == nil || t.client == nil {
return nil
}
pipe := t.client.Pipeline()
pipe.Del(ctx, t.lockKey(uid))
pipe.Del(ctx, t.failKey(email))
_, err := pipe.Exec(ctx)
return err
}
// ClearOnSuccess drops only the failure counter — used after a successful
// login to forgive prior typos.
func (t *LockoutTracker) ClearOnSuccess(ctx context.Context, email string) {
if t == nil || t.client == nil {
return
}
_ = t.client.Del(ctx, t.failKey(email)).Err()
}
+58
View File
@@ -0,0 +1,58 @@
package auth
import (
"errors"
"golang.org/x/crypto/bcrypt"
)
const bcryptCost = 12
var (
ErrPasswordMismatch = errors.New("password mismatch")
ErrPasswordTooShort = errors.New("password must be at least 8 characters")
ErrPasswordTooLong = errors.New("password must be at most 72 characters")
)
type PasswordHasher struct {
cost int
}
func NewPasswordHasher() *PasswordHasher {
return &PasswordHasher{cost: bcryptCost}
}
func (h *PasswordHasher) Hash(raw string) (string, error) {
if err := ValidatePassword(raw); err != nil {
return "", err
}
b, err := bcrypt.GenerateFromPassword([]byte(raw), h.cost)
if err != nil {
return "", err
}
return string(b), nil
}
func (h *PasswordHasher) Verify(hash, raw string) error {
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(raw)); err != nil {
if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
return ErrPasswordMismatch
}
return err
}
return nil
}
// ValidatePassword enforces a minimum length and the bcrypt-imposed maximum.
// bcrypt silently truncates inputs over 72 bytes, which would let a user set
// a 100-character password and successfully log in with the first 72; reject
// at the boundary instead.
func ValidatePassword(raw string) error {
if len(raw) < 8 {
return ErrPasswordTooShort
}
if len(raw) > 72 {
return ErrPasswordTooLong
}
return nil
}
+44
View File
@@ -0,0 +1,44 @@
package auth
import (
"errors"
"strings"
"testing"
)
func TestPasswordHasherRoundTrip(t *testing.T) {
h := NewPasswordHasher()
hash, err := h.Hash("correct-horse-battery-staple")
if err != nil {
t.Fatalf("hash: %v", err)
}
if hash == "" {
t.Fatal("empty hash")
}
if err := h.Verify(hash, "correct-horse-battery-staple"); err != nil {
t.Fatalf("verify correct: %v", err)
}
if err := h.Verify(hash, "wrong"); !errors.Is(err, ErrPasswordMismatch) {
t.Fatalf("verify wrong: got %v want ErrPasswordMismatch", err)
}
}
func TestPasswordValidation(t *testing.T) {
tests := []struct {
name string
pw string
want error
}{
{"too short", "1234567", ErrPasswordTooShort},
{"min length ok", "12345678", nil},
{"too long", strings.Repeat("a", 73), ErrPasswordTooLong},
{"max length ok", strings.Repeat("a", 72), nil},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := ValidatePassword(tc.pw); !errors.Is(got, tc.want) {
t.Fatalf("got %v want %v", got, tc.want)
}
})
}
}
+26
View File
@@ -0,0 +1,26 @@
package auth
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
)
// NewOpaqueToken returns a 32-byte URL-safe random token plus its SHA-256 hex
// digest. The raw value is shown once (in a link); only the digest is stored.
func NewOpaqueToken() (raw, hash string, err error) {
buf := make([]byte, 32)
if _, err := rand.Read(buf); err != nil {
return "", "", err
}
raw = base64.RawURLEncoding.EncodeToString(buf)
sum := sha256.Sum256([]byte(raw))
hash = hex.EncodeToString(sum[:])
return raw, hash, nil
}
func HashOpaque(raw string) string {
sum := sha256.Sum256([]byte(raw))
return hex.EncodeToString(sum[:])
}