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>
This commit is contained in:
Kwaku Danso
2026-05-20 15:09:07 +01:00
parent b34715f152
commit dbddf17e3b
16 changed files with 893 additions and 25 deletions
+111
View File
@@ -0,0 +1,111 @@
package api
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
// RSVP-edit nonce store. When a guest revisits their invitation from a
// device that doesn't match the one they originally responded from, we
// hide their RSVP details from the access response so a forwarded link
// can't leak (or alter) their reply. They can request a one-time edit
// link sent to their email/SMS; that link carries a short-lived nonce
// stored here.
//
// We store sha256(raw) so a database snapshot of Redis doesn't give an
// attacker working nonces; the raw value only ever lives in the email
// link the guest receives.
const (
editNonceTTL = 30 * time.Minute
editNonceKeyPrefix = "gg:rsvp_edit:"
)
type editNonceStore struct {
rdb *redis.Client
}
// newEditNonceStore returns nil when Redis isn't configured — the calling
// handler treats nil as "edit-link flow disabled" and falls back to the
// strict same-device rule.
func newEditNonceStore(rdb *redis.Client) *editNonceStore {
if rdb == nil {
return nil
}
return &editNonceStore{rdb: rdb}
}
// Mint creates a fresh nonce bound to guestID, stores its hash with a
// 30-minute TTL, and returns the raw value for embedding in the email
// link. Hex-encoded so it survives URL transit without further escaping.
func (s *editNonceStore) Mint(ctx context.Context, guestID uuid.UUID) (raw string, err error) {
if s == nil {
return "", errors.New("edit nonce store not configured")
}
buf := make([]byte, 24)
if _, err := rand.Read(buf); err != nil {
return "", err
}
raw = hex.EncodeToString(buf)
sum := sha256.Sum256([]byte(raw))
key := editNonceKeyPrefix + hex.EncodeToString(sum[:])
if err := s.rdb.Set(ctx, key, guestID.String(), editNonceTTL).Err(); err != nil {
return "", err
}
return raw, nil
}
// Verify reports whether raw is a still-valid nonce for guestID.
// Doesn't consume the nonce; expiry happens naturally via TTL so the
// guest can refresh the edit page or briefly close + reopen the link
// during the half-hour window without losing their session.
func (s *editNonceStore) Verify(ctx context.Context, raw string, guestID uuid.UUID) (bool, error) {
if s == nil || raw == "" {
return false, nil
}
sum := sha256.Sum256([]byte(raw))
key := editNonceKeyPrefix + hex.EncodeToString(sum[:])
val, err := s.rdb.Get(ctx, key).Result()
if err != nil {
if errors.Is(err, redis.Nil) {
return false, nil
}
return false, err
}
return val == guestID.String(), nil
}
// fingerprintsSimilar reports whether two device fingerprints look like
// the same browser. The check is intentionally narrow: just `user_agent`,
// because it's the strongest signal of "same browser" and the one least
// affected by normal day-to-day variation (changing networks, switching
// rooms, etc).
//
// Conservative-by-default: when either side lacks a user_agent string we
// return false, which causes the access handler to hide the RSVP. The
// legitimate guest in that edge case can still recover via the
// request-edit-link flow.
//
// Two fingerprints with the same user_agent but different IPs are
// considered the same device. This is on purpose: a guest jumping
// between Wi-Fi and mobile data is the same person on the same phone.
// The Gate's full scoring (run on submit/edit, not on access) catches
// the more sophisticated mismatches.
func fingerprintsSimilar(stored, current map[string]any) bool {
if stored == nil || current == nil {
return false
}
s, _ := stored["user_agent"].(string)
c, _ := current["user_agent"].(string)
if s == "" || c == "" {
return false
}
return s == c
}
+52
View File
@@ -0,0 +1,52 @@
package api
import "testing"
func TestFingerprintsSimilar(t *testing.T) {
const ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_2) AppleWebKit/605"
other := "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537"
tests := []struct {
name string
stored, current map[string]any
want bool
}{
{
name: "identical UA, different IPs counts as same device",
stored: map[string]any{"user_agent": ua, "accept_language": "en"},
current: map[string]any{"user_agent": ua, "accept_language": "fr"},
want: true,
},
{
name: "different UA never matches",
stored: map[string]any{"user_agent": ua},
current: map[string]any{"user_agent": other},
want: false,
},
{
name: "missing UA on current side is treated as mismatch",
stored: map[string]any{"user_agent": ua},
current: map[string]any{},
want: false,
},
{
name: "missing UA on stored side is treated as mismatch",
stored: map[string]any{},
current: map[string]any{"user_agent": ua},
want: false,
},
{
name: "both nil is mismatch (conservative default)",
stored: nil,
current: nil,
want: false,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := fingerprintsSimilar(tc.stored, tc.current); got != tc.want {
t.Errorf("fingerprintsSimilar = %v, want %v", got, tc.want)
}
})
}
}
+38
View File
@@ -34,6 +34,7 @@ type rsvpHandler struct {
rsvps *storage.RSVPRepo
accessLogs *storage.AccessLogRepo
allowlist *storage.AllowlistRepo
editNonces *editNonceStore
scorer fraudScorer
pub rsvpPublisher
}
@@ -43,6 +44,12 @@ type submitRSVPRequest struct {
PlusOnes int `json:"plus_ones"`
DietaryNotes *string `json:"dietary_notes"`
Fingerprint map[string]any `json:"fingerprint"`
// EditNonce is the short-lived value carried back from the magic
// edit link the guest received by email. It bypasses the
// same-device check on PATCH so a guest who jumped to a new phone
// can still edit their RSVP. Empty on POST and on edits from the
// original device.
EditNonce string `json:"edit_nonce,omitempty"`
}
type submitRSVPResponse struct {
@@ -117,6 +124,13 @@ func (h *rsvpHandler) submit(w http.ResponseWriter, r *http.Request) {
// PATCH /rsvp/{token} — revise an existing RSVP. Same fraud check as POST.
// The prior state is snapshotted into rsvp_revisions inside Update; edits
// past MaxRSVPEdits return 429.
//
// As of the forwarded-link defence: a PATCH is only accepted when either
// (a) the current device fingerprint matches the one stored on the
// existing RSVP, or (b) the caller presented a valid edit nonce in the
// request body. Otherwise we refuse with 403 + a hint to request an edit
// link — this stops anyone the original guest forwarded the link to from
// quietly altering the response.
func (h *rsvpHandler) edit(w http.ResponseWriter, r *http.Request) {
tk, ok := h.loadValidToken(w, r)
if !ok {
@@ -136,6 +150,28 @@ func (h *rsvpHandler) edit(w http.ResponseWriter, r *http.Request) {
return
}
// Forwarded-link gate. Load the existing RSVP (if any) so we can
// compare device fingerprints; absent RSVP means this is a quirky
// PATCH-before-POST flow that Update will 404 below anyway.
if existing, err := h.rsvps.GetByGuest(r.Context(), guest.ID); err == nil && existing != nil {
current := mergeFingerprint(req.Fingerprint, collectFingerprint(r))
if !fingerprintsSimilar(existing.DeviceFingerprint, current) {
// Bypass via edit nonce delivered to the guest's email.
bypassed := false
if h.editNonces != nil && req.EditNonce != "" {
if ok, _ := h.editNonces.Verify(r.Context(), req.EditNonce, guest.ID); ok {
bypassed = true
}
}
if !bypassed {
writeError(w, http.StatusForbidden,
"this invitation looks like it's being opened from a different device; "+
"please request an edit link from the previous screen")
return
}
}
}
decision, fingerprint, ip, ok := h.scoreAccess(w, r, event, guest, tk, req.Fingerprint)
if !ok {
return
@@ -238,6 +274,7 @@ type decodedRSVPRequest struct {
PlusOnes int
DietaryNotes *string
Fingerprint map[string]any
EditNonce string
}
func decodeSubmitRSVP(w http.ResponseWriter, r *http.Request) (decodedRSVPRequest, bool) {
@@ -260,6 +297,7 @@ func decodeSubmitRSVP(w http.ResponseWriter, r *http.Request) (decodedRSVPReques
PlusOnes: req.PlusOnes,
DietaryNotes: req.DietaryNotes,
Fingerprint: req.Fingerprint,
EditNonce: req.EditNonce,
}, true
}
+11
View File
@@ -102,6 +102,7 @@ func NewServer(deps ServerDeps) (*Server, error) {
analyticsRepo := storage.NewAnalyticsRepo(deps.DB)
brandingRepo := storage.NewBrandingRepo(deps.DB)
allowlistRepo := storage.NewAllowlistRepo(deps.DB)
editNonces := newEditNonceStore(deps.Redis)
feedbackRepo := storage.NewFeedbackRepo(deps.DB)
// Branding image store. Empty UploadsDir leaves it nil and the upload
@@ -194,6 +195,8 @@ func NewServer(deps ServerDeps) (*Server, error) {
rsvps: rsvpRepo,
collabs: collabRepo,
branding: brandingRepo,
editNonces: editNonces,
emails: emails,
gen: auth.NewGenerator(),
ttl: deps.TokenTTL,
pub: deps.AccessPublisher,
@@ -208,6 +211,7 @@ func NewServer(deps ServerDeps) (*Server, error) {
rsvps: rsvpRepo,
accessLogs: accessRepo,
allowlist: allowlistRepo,
editNonces: editNonces,
scorer: deps.FraudScorer,
pub: deps.RSVPPublisher,
},
@@ -443,6 +447,13 @@ func (s *Server) Handler() http.Handler {
// Block B: .ics download. Same rate-limit class as /access since the
// payload is similarly cheap and the abuse profile is identical (one
// token per attacker).
// Forwarded-link defence: when a guest opens their invitation from a
// device the original RSVP wasn't submitted from, /access hides the
// reply. This endpoint mints a short-lived edit nonce and emails it
// so the real guest can recover from a new phone / new laptop.
mux.Handle("POST /access/{token}/request-edit-link",
rl("rsvp_edit_request", 3, time.Hour, pathKey("token"), http.HandlerFunc(s.tokens.requestEditLink)))
mux.Handle("GET /access/{token}/calendar.ics",
rl("calendar_ics", 60, time.Hour, pathKey("token"), http.HandlerFunc(s.tokens.calendar)))
mux.Handle("POST /rsvp/{token}",
+166 -24
View File
@@ -36,6 +36,8 @@ type tokenHandler struct {
rsvps *storage.RSVPRepo
collabs *storage.CollaboratorRepo
branding *storage.BrandingRepo
editNonces *editNonceStore
emails auth.EmailSender
gen *auth.Generator
ttl time.Duration
pub accessPublisher
@@ -412,7 +414,22 @@ type accessResponse struct {
// RSVP is the guest's current submission, if any. Populated so the RSVP
// page can show an edit form instead of a fresh submit form when the
// guest revisits their invitation link (Tier 2 Block A).
//
// As of the forwarded-link defence (Tier 2 Block G follow-up): this is
// only populated when the current device looks like the device that
// originally submitted, OR when the caller presented a valid edit nonce.
// A forwarded-link recipient sees a nil RSVP + RSVPSubmittedElsewhere=true
// instead, so the original guest's response stays private and unmodifiable.
RSVP *domain.RSVP `json:"rsvp,omitempty"`
// RSVPSubmittedElsewhere signals "there's an RSVP on file but we're
// hiding it because this looks like a different device". The frontend
// renders a "this invitation has already been responded to" view +
// (when CanRequestEditLink) a "send me an edit link" CTA.
RSVPSubmittedElsewhere bool `json:"rsvp_submitted_elsewhere,omitempty"`
// CanRequestEditLink reports whether we have a way to deliver an edit
// link to the guest (email or phone on file). When false the only
// path is for the guest to contact the host directly.
CanRequestEditLink bool `json:"can_request_edit_link,omitempty"`
// Calendar holds the add-to-calendar deep-links and the .ics download
// path so the frontend renders four ready-to-click buttons after a
// successful RSVP. (Tier 2 Block B.)
@@ -469,23 +486,25 @@ func (h *tokenHandler) access(w http.ResponseWriter, r *http.Request) {
h.logger.Error("create access log", "err", err)
}
go func(evt natspub.AccessAttempted) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := h.pub.PublishAccessAttempted(ctx, evt); err != nil {
h.logger.Error("publish access.attempted", "err", err, "guest_id", evt.GuestID)
}
}(natspub.AccessAttempted{
EventID: event.ID,
GuestID: guest.ID,
TokenID: tk.ID,
AccessLogID: accessLogID,
Fingerprint: fingerprint,
IPAddress: ip,
UserAgent: r.UserAgent(),
Referrer: r.Referer(),
OccurredAt: time.Now().UTC(),
})
if h.pub != nil {
go func(evt natspub.AccessAttempted) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := h.pub.PublishAccessAttempted(ctx, evt); err != nil {
h.logger.Error("publish access.attempted", "err", err, "guest_id", evt.GuestID)
}
}(natspub.AccessAttempted{
EventID: event.ID,
GuestID: guest.ID,
TokenID: tk.ID,
AccessLogID: accessLogID,
Fingerprint: fingerprint,
IPAddress: ip,
UserAgent: r.UserAgent(),
Referrer: r.Referer(),
OccurredAt: time.Now().UTC(),
})
}
var brandingPayload *domain.Branding
if h.branding != nil {
@@ -518,17 +537,140 @@ func (h *tokenHandler) access(w http.ResponseWriter, r *http.Request) {
}
}
// Forwarded-link defence (Tier 2 Block G follow-up). If a previous
// submission exists, only surface its details when the current
// device looks like the one that submitted, OR when the caller
// presented a valid edit nonce in ?edit=<nonce>. Anything else gets
// the "responded elsewhere" view — no leak, no edit.
rsvpPayload := existingRSVP
var rsvpSubmittedElsewhere, canRequestEditLink bool
if existingRSVP != nil && !fingerprintsSimilar(existingRSVP.DeviceFingerprint, fingerprint) {
bypassed := false
if nonce := r.URL.Query().Get("edit"); nonce != "" && h.editNonces != nil {
if ok, _ := h.editNonces.Verify(r.Context(), nonce, guest.ID); ok {
bypassed = true
}
}
if !bypassed {
rsvpPayload = nil
rsvpSubmittedElsewhere = true
canRequestEditLink =
h.editNonces != nil &&
((guest.Email != nil && *guest.Email != "") ||
(guest.Phone != nil && *guest.Phone != ""))
}
}
writeJSON(w, http.StatusOK, accessResponse{
Guest: guest,
Event: event,
Token: tk,
AccessLog: accessLogID,
RSVP: existingRSVP,
Calendar: h.calendarLinks(event, raw),
Branding: brandingPayload,
Guest: guest,
Event: event,
Token: tk,
AccessLog: accessLogID,
RSVP: rsvpPayload,
RSVPSubmittedElsewhere: rsvpSubmittedElsewhere,
CanRequestEditLink: canRequestEditLink,
Calendar: h.calendarLinks(event, raw),
Branding: brandingPayload,
})
}
// requestEditLinkResponse is the wire shape of POST /access/{token}/request-edit-link.
type requestEditLinkResponse struct {
// Channel hints at where the link went so the frontend can render
// "Sent to your email" vs. "Sent by SMS" feedback. Empty when the
// store/sender wasn't configured (dev environments without email
// wired up — the frontend should still treat that as success).
Channel string `json:"channel,omitempty"`
}
// POST /access/{token}/request-edit-link — public, token-scoped. When a
// guest opens their invitation from an unfamiliar device the regular
// access response hides their RSVP. This endpoint lets them prove email
// or phone ownership instead: we mint a short-lived edit nonce and
// deliver it to the address on file.
//
// Rate limit lives on the route registration (3 per hour per token).
// The endpoint itself stays generous about the response — we never
// reveal whether a token has an RSVP attached, just whether the request
// itself was acceptable.
func (h *tokenHandler) requestEditLink(w http.ResponseWriter, r *http.Request) {
raw := r.PathValue("token")
if err := auth.ValidateFormat(raw); err != nil {
writeError(w, http.StatusBadRequest, "malformed token")
return
}
tk, err := h.tokens.GetByHash(r.Context(), auth.HashToken(raw))
if err != nil {
if errors.Is(err, domain.ErrTokenNotFound) {
writeError(w, http.StatusNotFound, "token not found")
return
}
writeError(w, http.StatusInternalServerError, "failed to load token")
return
}
if err := tk.IsValid(time.Now().UTC()); err != nil {
writeError(w, http.StatusGone, err.Error())
return
}
guest, err := h.guests.Get(r.Context(), tk.GuestID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to load guest")
return
}
if h.editNonces == nil {
// Redis isn't wired up; the feature is disabled. Tell the caller
// honestly rather than pretending we sent something.
writeError(w, http.StatusServiceUnavailable, "edit-link delivery isn't configured for this environment")
return
}
// Only attempt delivery when there's somewhere to deliver to. Without
// email or phone on file the request is a 404 — we don't have a
// secure channel for the nonce.
hasEmail := guest.Email != nil && *guest.Email != ""
if !hasEmail {
// Phone-only delivery is a future enhancement (Twilio path is
// wired for the broader notifier; not for synchronous edit links
// yet). For now treat as no-channel.
writeError(w, http.StatusNotFound, "no email on file for this guest")
return
}
nonce, err := h.editNonces.Mint(r.Context(), guest.ID)
if err != nil {
h.logger.Error("mint edit nonce", "err", err, "guest_id", guest.ID)
writeError(w, http.StatusInternalServerError, "failed to issue edit link")
return
}
// Resolve the event name for the email. Best-effort: if the lookup
// fails we still send a link, just with a generic fallback.
eventName := "your event"
if event, err := h.events.Get(r.Context(), guest.EventID); err == nil {
eventName = event.Name
}
link := h.editLink(raw, nonce)
if h.emails != nil {
if err := h.emails.SendRSVPEditLink(r.Context(), *guest.Email, guest.Name, eventName, link); err != nil {
h.logger.Warn("send rsvp edit link", "err", err, "guest_id", guest.ID)
// Don't 500 — the nonce already exists in Redis, and we've
// logged the link in the dev stub. A 202-ish behaviour:
// "accepted; delivery might be best-effort".
}
}
writeJSON(w, http.StatusAccepted, requestEditLinkResponse{Channel: "email"})
}
func (h *tokenHandler) editLink(rawToken, nonce string) string {
base := h.publicBaseURL
if base == "" {
base = "http://localhost:3000"
}
return base + "/rsvp/" + rawToken + "?edit=" + nonce
}
// calendarLinks renders the three provider URLs + .ics path for the event.
// The raw access token is embedded in the .ics path so the download endpoint
// stays public (no auth) while still scoped to a single invitation.