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
+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.