feat(tier2): smarter fraud detection — Block G
Per-event fraud tuning. Hosts can now dial the medium / high / block
boundaries, allowlist trusted networks, and feed verdicts back on
flagged accesses — the seed corpus for a future ML model.
Schema (migration 0011)
- events.fraud_{medium,high,block}_threshold default 30/60/85 so
existing events behave identically until a host changes them
- access_logs.geo_{country,city,lat,lon} for future enrichment
- fraud_feedback table — verdict ('legitimate' | 'suspicious') + note,
PK on access_log_id so re-mark is an upsert
- event_allowlists table — (event_id, ip_cidr) primary key, inet column
so containment checks use the native >>= operator (indexed lookup)
Domain
- FraudThresholds with Valid() + Band() helpers; Default trio echoed
through GET responses so the frontend doesn't duplicate constants
- ParseAllowlistCIDR accepts bare IPs (auto-widens to /32 or /128) and
canonicalises the output (203.0.113.42 → 203.0.113.42/32)
- Event.Thresholds() falls back to defaults if columns weren't
populated yet, so the API never wedges every score into "low"
Storage
- AllowlistRepo: List / Add / Remove + Matches() — the latter pushes
CIDR containment into Postgres rather than streaming rows back
- FeedbackRepo: Record (upserts) + ListForEvent (joined through guests)
- EventRepo.GetThresholds + UpdateThresholds, plus the threshold
columns baked into scanEvent so every event load carries them
- AccessLogRepo.BelongsToEvent — stops a hostile editor on event A
from marking event B's access logs
API
- GET/PUT /events/{id}/security/thresholds (viewer/editor)
- GET/POST/DELETE /events/{id}/security/allowlist
- POST /events/{id}/access-logs/{log_id}/feedback (editor)
- GET /events/{id}/security/feedback
- RSVP scoring path: allowlist short-circuit fires before the fraud
engine; the engine's score is then re-banded against the event's
thresholds (engine.Risk becomes advisory — API is the source of
truth for "what counts as block here")
- CORS Allow-Methods already includes PUT (Block D fix)
Fraud engine
- Single-signal cap: it now takes ≥2 sub-scores of ≥70 to push the
final into HIGH. Fixes the well-known "second visit with a slightly
shifted fingerprint scores 60+" false positive
- Engine band remains advisory; API re-bands using per-event
thresholds before deciding to block
Frontend
- SecurityCard.vue: visual band ribbon (proportional to thresholds),
three sliders with mutual clamping so dragging medium past high
pushes high (not an invalid ordering), reset-to-defaults button,
CIDR allowlist with inline add + per-row remove, verdict-history
inbox. Toast feedback on save/add/remove
- "Security" tab added to the event-detail tab nav (5th tab,
right of Analytics)
- Viewer role hides write affordances; server enforces too
Tests
- Domain: ThresholdsBand, ThresholdsValid, ParseAllowlistCIDR (bare
IP widening + traversal/typo rejection), FraudFeedbackValid
- Integration: thresholds round-trip + invalid ordering rejection,
allowlist CRUD + duplicate 409 + invalid CIDR 400 + IP auto-widen,
feedback record + upsert + cross-tenant 404 + invalid verdict 400,
viewer can read / editor can write / outsider gets 404
- Full integration suite green (315.8s, all 36 top-level tests pass)
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,280 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/alchemistkay/guestguard/internal/domain"
|
||||
"github.com/alchemistkay/guestguard/internal/storage"
|
||||
)
|
||||
|
||||
// securityHandler bundles the Tier 2 Block G endpoints: per-event fraud
|
||||
// thresholds, the CIDR allowlist, and the fraud-feedback inbox.
|
||||
type securityHandler struct {
|
||||
logger *slog.Logger
|
||||
events *storage.EventRepo
|
||||
collabs *storage.CollaboratorRepo
|
||||
allowlist *storage.AllowlistRepo
|
||||
feedback *storage.FeedbackRepo
|
||||
access *storage.AccessLogRepo
|
||||
}
|
||||
|
||||
// --- thresholds ---
|
||||
|
||||
type thresholdsResponse struct {
|
||||
domain.FraudThresholds
|
||||
// Defaults are echoed so the slider can show "reset" affordances
|
||||
// without a hardcoded duplicate in the frontend.
|
||||
Defaults domain.FraudThresholds `json:"defaults"`
|
||||
}
|
||||
|
||||
// GET /events/{id}/security/thresholds — viewer+.
|
||||
func (h *securityHandler) getThresholds(w http.ResponseWriter, r *http.Request) {
|
||||
hostID, ok := hostFromContext(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
eventID, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
th, err := h.events.GetThresholds(r.Context(), eventID)
|
||||
if err != nil && !errors.Is(err, domain.ErrEventNotFound) {
|
||||
writeError(w, http.StatusInternalServerError, "failed to load thresholds")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, thresholdsResponse{
|
||||
FraudThresholds: th,
|
||||
Defaults: domain.DefaultThresholds(),
|
||||
})
|
||||
}
|
||||
|
||||
// PUT /events/{id}/security/thresholds — editor+.
|
||||
func (h *securityHandler) putThresholds(w http.ResponseWriter, r *http.Request) {
|
||||
hostID, ok := hostFromContext(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
eventID, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
|
||||
return
|
||||
}
|
||||
var req domain.FraudThresholds
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid json")
|
||||
return
|
||||
}
|
||||
if err := req.Valid(); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if err := h.events.UpdateThresholds(r.Context(), eventID, req); err != nil {
|
||||
if errors.Is(err, domain.ErrEventNotFound) {
|
||||
writeError(w, http.StatusNotFound, "event not found")
|
||||
return
|
||||
}
|
||||
h.logger.Error("update thresholds", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "failed to update thresholds")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, thresholdsResponse{
|
||||
FraudThresholds: req,
|
||||
Defaults: domain.DefaultThresholds(),
|
||||
})
|
||||
}
|
||||
|
||||
// --- allowlist ---
|
||||
|
||||
type addAllowlistRequest struct {
|
||||
CIDR string `json:"cidr"`
|
||||
Label string `json:"label"`
|
||||
}
|
||||
|
||||
// GET /events/{id}/security/allowlist — viewer+.
|
||||
func (h *securityHandler) listAllowlist(w http.ResponseWriter, r *http.Request) {
|
||||
hostID, ok := hostFromContext(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
eventID, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
entries, err := h.allowlist.List(r.Context(), eventID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list allowlist")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"entries": entries})
|
||||
}
|
||||
|
||||
// POST /events/{id}/security/allowlist — editor+.
|
||||
func (h *securityHandler) addAllowlist(w http.ResponseWriter, r *http.Request) {
|
||||
hostID, ok := hostFromContext(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
eventID, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
|
||||
return
|
||||
}
|
||||
var req addAllowlistRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid json")
|
||||
return
|
||||
}
|
||||
canonical, _, err := domain.ParseAllowlistCIDR(req.CIDR)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
entry, err := h.allowlist.Add(r.Context(), storage.AddAllowlistParams{
|
||||
EventID: eventID,
|
||||
CIDR: canonical,
|
||||
Label: req.Label,
|
||||
CreatedBy: hostID,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrAllowlistExists) {
|
||||
writeError(w, http.StatusConflict, "that CIDR is already allowlisted")
|
||||
return
|
||||
}
|
||||
h.logger.Error("add allowlist", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "failed to add allowlist entry")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, entry)
|
||||
}
|
||||
|
||||
// DELETE /events/{id}/security/allowlist?cidr=... — editor+. CIDR comes in
|
||||
// on the query string so the URL stays RESTful without route-encoding the
|
||||
// slash in the path.
|
||||
func (h *securityHandler) removeAllowlist(w http.ResponseWriter, r *http.Request) {
|
||||
hostID, ok := hostFromContext(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
eventID, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
|
||||
return
|
||||
}
|
||||
cidr := r.URL.Query().Get("cidr")
|
||||
if cidr == "" {
|
||||
writeError(w, http.StatusBadRequest, "cidr query parameter required")
|
||||
return
|
||||
}
|
||||
canonical, _, err := domain.ParseAllowlistCIDR(cidr)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if err := h.allowlist.Remove(r.Context(), eventID, canonical); err != nil {
|
||||
if errors.Is(err, domain.ErrAllowlistNotFound) {
|
||||
writeError(w, http.StatusNotFound, "allowlist entry not found")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "failed to remove allowlist entry")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// --- feedback ---
|
||||
|
||||
type feedbackRequest struct {
|
||||
Verdict string `json:"verdict"` // "legitimate" | "suspicious"
|
||||
Note string `json:"note"`
|
||||
}
|
||||
|
||||
// POST /events/{id}/access-logs/{log_id}/feedback — editor+. Records the
|
||||
// host's verdict on a specific access log. We re-verify the log belongs
|
||||
// to the event (a hostile editor on event A shouldn't be able to mark
|
||||
// event B's logs).
|
||||
func (h *securityHandler) recordFeedback(w http.ResponseWriter, r *http.Request) {
|
||||
hostID, ok := hostFromContext(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
eventID, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
|
||||
return
|
||||
}
|
||||
logID, ok := parseIDParam(w, r, "log_id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// Confirm the access log is on this event.
|
||||
belongs, err := h.access.BelongsToEvent(r.Context(), logID, eventID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to verify access log")
|
||||
return
|
||||
}
|
||||
if !belongs {
|
||||
writeError(w, http.StatusNotFound, "access log not found")
|
||||
return
|
||||
}
|
||||
|
||||
var req feedbackRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid json")
|
||||
return
|
||||
}
|
||||
if err := (domain.FraudFeedback{Verdict: req.Verdict}).Valid(); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
f, err := h.feedback.Record(r.Context(), storage.RecordFeedbackParams{
|
||||
AccessLogID: logID,
|
||||
Verdict: req.Verdict,
|
||||
MarkedBy: hostID,
|
||||
Note: req.Note,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("record feedback", "err", err)
|
||||
writeError(w, http.StatusInternalServerError, "failed to record feedback")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, f)
|
||||
}
|
||||
|
||||
// GET /events/{id}/security/feedback — viewer+.
|
||||
func (h *securityHandler) listFeedback(w http.ResponseWriter, r *http.Request) {
|
||||
hostID, ok := hostFromContext(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
eventID, ok := parseIDParam(w, r, "id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
fb, err := h.feedback.ListForEvent(r.Context(), eventID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list feedback")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"feedback": fb})
|
||||
}
|
||||
@@ -33,6 +33,7 @@ type rsvpHandler struct {
|
||||
events *storage.EventRepo
|
||||
rsvps *storage.RSVPRepo
|
||||
accessLogs *storage.AccessLogRepo
|
||||
allowlist *storage.AllowlistRepo
|
||||
scorer fraudScorer
|
||||
pub rsvpPublisher
|
||||
}
|
||||
@@ -322,6 +323,26 @@ func (h *rsvpHandler) scoreAccess(
|
||||
h.logger.Error("create access log", "err", err)
|
||||
}
|
||||
|
||||
// Block G: allowlist short-circuit. If the request IP matches a CIDR
|
||||
// the host has explicitly trusted (office Wi-Fi, family network), we
|
||||
// skip the fraud engine entirely — score 0, low band. Best-effort:
|
||||
// any error reading the allowlist falls through to normal scoring so a
|
||||
// dropped DB connection doesn't lock guests out of an event.
|
||||
if h.allowlist != nil {
|
||||
if matched, label, err := h.allowlist.Matches(r.Context(), event.ID, ip); err == nil && matched {
|
||||
reason := "allowlisted"
|
||||
if label != "" {
|
||||
reason = "allowlisted: " + label
|
||||
}
|
||||
return fraud.Decision{
|
||||
Score: 0,
|
||||
Risk: "low",
|
||||
Reasons: []string{reason},
|
||||
Used: true,
|
||||
}, fingerprint, ip, true
|
||||
}
|
||||
}
|
||||
|
||||
decision := h.scorer.Score(r.Context(), fraud.ScoreInput{
|
||||
EventID: event.ID,
|
||||
GuestID: guest.ID,
|
||||
@@ -332,6 +353,14 @@ func (h *rsvpHandler) scoreAccess(
|
||||
UserAgent: r.UserAgent(),
|
||||
Referrer: r.Referer(),
|
||||
})
|
||||
|
||||
// Block G: re-band the score using this event's thresholds. The
|
||||
// engine's `Risk` field becomes advisory; the API is the source of
|
||||
// truth for "what counts as block here". This lets a strict-event
|
||||
// host set Block=70 while a casual-event host sets it to 95 without
|
||||
// touching the engine.
|
||||
decision.Risk = event.Thresholds().Band(decision.Score)
|
||||
|
||||
if fraud.IsBlock(decision) {
|
||||
writeJSON(w, http.StatusForbidden, submitRSVPResponse{
|
||||
Decision: decision,
|
||||
|
||||
+31
-1
@@ -41,6 +41,7 @@ type Server struct {
|
||||
analytics *analyticsHandler
|
||||
branding *brandingHandler
|
||||
uploads *uploadHandler
|
||||
security *securityHandler
|
||||
}
|
||||
|
||||
type ServerDeps struct {
|
||||
@@ -100,6 +101,8 @@ func NewServer(deps ServerDeps) (*Server, error) {
|
||||
inviteRepo := storage.NewInviteRepo(deps.DB)
|
||||
analyticsRepo := storage.NewAnalyticsRepo(deps.DB)
|
||||
brandingRepo := storage.NewBrandingRepo(deps.DB)
|
||||
allowlistRepo := storage.NewAllowlistRepo(deps.DB)
|
||||
feedbackRepo := storage.NewFeedbackRepo(deps.DB)
|
||||
|
||||
// Branding image store. Empty UploadsDir leaves it nil and the upload
|
||||
// + serve handlers report 503, so the rest of the service keeps
|
||||
@@ -204,6 +207,7 @@ func NewServer(deps ServerDeps) (*Server, error) {
|
||||
events: eventRepo,
|
||||
rsvps: rsvpRepo,
|
||||
accessLogs: accessRepo,
|
||||
allowlist: allowlistRepo,
|
||||
scorer: deps.FraudScorer,
|
||||
pub: deps.RSVPPublisher,
|
||||
},
|
||||
@@ -259,6 +263,14 @@ func NewServer(deps ServerDeps) (*Server, error) {
|
||||
logger: deps.Logger,
|
||||
store: imageStore,
|
||||
},
|
||||
security: &securityHandler{
|
||||
logger: deps.Logger,
|
||||
events: eventRepo,
|
||||
collabs: collabRepo,
|
||||
allowlist: allowlistRepo,
|
||||
feedback: feedbackRepo,
|
||||
access: accessRepo,
|
||||
},
|
||||
collabs: &collaboratorHandler{
|
||||
logger: deps.Logger,
|
||||
events: eventRepo,
|
||||
@@ -356,6 +368,24 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.Handle("GET /events/{id}/analytics/export.csv",
|
||||
authed(http.HandlerFunc(s.analytics.exportCSV)))
|
||||
|
||||
// Block G — smarter fraud detection. Per-event thresholds, CIDR
|
||||
// allowlists, and the verdict feedback inbox. Reads are viewer+;
|
||||
// writes are editor+ (matches the rest of the event-edit surface).
|
||||
mux.Handle("GET /events/{id}/security/thresholds",
|
||||
authed(http.HandlerFunc(s.security.getThresholds)))
|
||||
mux.Handle("PUT /events/{id}/security/thresholds",
|
||||
authed(http.HandlerFunc(s.security.putThresholds)))
|
||||
mux.Handle("GET /events/{id}/security/allowlist",
|
||||
authed(http.HandlerFunc(s.security.listAllowlist)))
|
||||
mux.Handle("POST /events/{id}/security/allowlist",
|
||||
authed(http.HandlerFunc(s.security.addAllowlist)))
|
||||
mux.Handle("DELETE /events/{id}/security/allowlist",
|
||||
authed(http.HandlerFunc(s.security.removeAllowlist)))
|
||||
mux.Handle("GET /events/{id}/security/feedback",
|
||||
authed(http.HandlerFunc(s.security.listFeedback)))
|
||||
mux.Handle("POST /events/{id}/access-logs/{log_id}/feedback",
|
||||
authed(http.HandlerFunc(s.security.recordFeedback)))
|
||||
|
||||
// Block D — event branding. Reads are viewer+; PUT is editor+. The
|
||||
// upload endpoint is gated by auth only (any signed-in user can mint
|
||||
// an image URL; the URL is no use without an event they can edit
|
||||
@@ -470,7 +500,7 @@ func corsMiddleware(next http.Handler) http.Handler {
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
w.Header().Set("Vary", "Origin")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Device-Fingerprint")
|
||||
}
|
||||
if r.Method == http.MethodOptions {
|
||||
|
||||
Reference in New Issue
Block a user