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:
Kwaku Danso
2026-05-19 21:33:57 +01:00
parent e5b187c575
commit b873012191
22 changed files with 1953 additions and 142 deletions
+280
View File
@@ -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})
}
+29
View File
@@ -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
View File
@@ -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 {
+25
View File
@@ -36,6 +36,31 @@ type Event struct {
Status EventStatus `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Per-event fraud-band thresholds (Tier 2 Block G). The defaults are
// set by the migration so events created pre-Block-G continue to use
// the previous global 30/60/85 boundaries until a host changes them.
FraudMediumThreshold int `json:"fraud_medium_threshold"`
FraudHighThreshold int `json:"fraud_high_threshold"`
FraudBlockThreshold int `json:"fraud_block_threshold"`
}
// Thresholds returns the event's fraud band trio as a single value the
// scoring path can pass around (or fall back to defaults if the row was
// loaded before this migration).
func (e *Event) Thresholds() FraudThresholds {
t := FraudThresholds{
Medium: e.FraudMediumThreshold,
High: e.FraudHighThreshold,
Block: e.FraudBlockThreshold,
}
// Treat zeros (or invalid orderings) as "host hasn't customised";
// fall back to defaults rather than wedge every score into the lowest
// band.
if t.Valid() != nil || t.Block == 0 {
return DefaultThresholds()
}
return t
}
var (
+125
View File
@@ -0,0 +1,125 @@
package domain
import (
"errors"
"net"
"time"
"github.com/google/uuid"
)
// Tier 2 Block G — per-event thresholds, allowlists, feedback.
// Default band boundaries — matches the previous hardcoded constants in
// the fraud engine so existing events behave identically until a host
// tweaks them. Mirrored on the events table as columns so a host can
// dial them up/down without touching code.
const (
DefaultFraudMediumThreshold = 30
DefaultFraudHighThreshold = 60
DefaultFraudBlockThreshold = 85
)
// FraudThresholds bundles the trio that controls band assignment for one
// event. Sent to the fraud engine on every Score call so the engine can
// apply the host's preference without a separate DB lookup.
type FraudThresholds struct {
Medium int `json:"medium"`
High int `json:"high"`
Block int `json:"block"`
}
// Valid sanity-checks the ordering. The frontend slider keeps these in
// order; this is a belt-and-braces server-side check.
func (t FraudThresholds) Valid() error {
if t.Medium < 0 || t.High > 100 || t.Block > 100 {
return ErrInvalidThresholds
}
if !(t.Medium <= t.High && t.High <= t.Block) {
return ErrInvalidThresholds
}
return nil
}
// DefaultThresholds returns the package defaults — useful when an event
// row hasn't been loaded yet (e.g. fallback in the scoring path).
func DefaultThresholds() FraudThresholds {
return FraudThresholds{
Medium: DefaultFraudMediumThreshold,
High: DefaultFraudHighThreshold,
Block: DefaultFraudBlockThreshold,
}
}
// Band maps a score to one of low/medium/high/block per the configured
// thresholds. Below medium → low; everything else picks the highest band
// the score crosses.
func (t FraudThresholds) Band(score int) string {
switch {
case score >= t.Block:
return "block"
case score >= t.High:
return "high"
case score >= t.Medium:
return "medium"
default:
return "low"
}
}
// Allowlist is one CIDR range that bypasses scoring entirely for the
// event. Hosts use this for known-good networks (office Wi-Fi, the
// venue's guest network, family routers). Score = 0, band = low,
// short-circuited before the fraud engine is even called.
type Allowlist struct {
EventID uuid.UUID `json:"event_id"`
CIDR string `json:"cidr"`
Label string `json:"label,omitempty"`
CreatedBy *uuid.UUID `json:"created_by,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
// ParseAllowlistCIDR validates and normalises a CIDR string. Single IPs
// are accepted and widened to /32 (IPv4) or /128 (IPv6). Returns the
// canonical string + the parsed *net.IPNet so the API layer can use both.
func ParseAllowlistCIDR(input string) (string, *net.IPNet, error) {
// Bare IP without /mask? Treat as a host route.
if ip := net.ParseIP(input); ip != nil {
if ip.To4() != nil {
input += "/32"
} else {
input += "/128"
}
}
_, ipnet, err := net.ParseCIDR(input)
if err != nil {
return "", nil, ErrInvalidCIDR
}
return ipnet.String(), ipnet, nil
}
// FraudFeedback is one host-back annotation on an access log: "this was
// fine despite the score" or "this really was suspicious". Seeds the
// future labelled-data ML model and lets hosts hide repeat false
// positives from their live monitor.
type FraudFeedback struct {
AccessLogID uuid.UUID `json:"access_log_id"`
Verdict string `json:"verdict"` // "legitimate" | "suspicious"
MarkedBy *uuid.UUID `json:"marked_by,omitempty"`
Note string `json:"note,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
func (f FraudFeedback) Valid() error {
if f.Verdict != "legitimate" && f.Verdict != "suspicious" {
return ErrInvalidVerdict
}
return nil
}
var (
ErrInvalidThresholds = errors.New("invalid thresholds (must satisfy 0 <= medium <= high <= block <= 100)")
ErrInvalidCIDR = errors.New("invalid CIDR — expected e.g. 203.0.113.0/24 or 2001:db8::/32")
ErrInvalidVerdict = errors.New("verdict must be 'legitimate' or 'suspicious'")
ErrAllowlistNotFound = errors.New("allowlist entry not found")
)
+86
View File
@@ -0,0 +1,86 @@
package domain
import "testing"
func TestThresholdsBand(t *testing.T) {
tt := DefaultThresholds() // 30/60/85
cases := map[int]string{
0: "low", 15: "low", 29: "low",
30: "medium", 45: "medium", 59: "medium",
60: "high", 70: "high", 84: "high",
85: "block", 99: "block", 100: "block",
}
for score, want := range cases {
if got := tt.Band(score); got != want {
t.Errorf("Band(%d) = %q, want %q", score, got, want)
}
}
}
func TestThresholdsValid(t *testing.T) {
ok := []FraudThresholds{
{0, 0, 0},
{30, 60, 85},
{10, 50, 90},
{50, 50, 50}, // equality at every boundary is allowed
{100, 100, 100},
}
for _, th := range ok {
if err := th.Valid(); err != nil {
t.Errorf("expected %+v to be valid, got %v", th, err)
}
}
bad := []FraudThresholds{
{60, 30, 85}, // medium > high
{30, 85, 60}, // high > block
{-1, 30, 60}, // negative
{30, 60, 101},
}
for _, th := range bad {
if err := th.Valid(); err == nil {
t.Errorf("expected %+v to be invalid", th)
}
}
}
func TestParseAllowlistCIDR(t *testing.T) {
cases := []struct {
in, want string
ok bool
}{
{"203.0.113.0/24", "203.0.113.0/24", true},
{"203.0.113.42", "203.0.113.42/32", true}, // bare IPv4 → /32
{"2001:db8::/32", "2001:db8::/32", true},
{"::1", "::1/128", true}, // bare IPv6 → /128
{"not-an-ip", "", false},
{"", "", false},
{"999.0.0.0/24", "", false},
}
for _, tc := range cases {
got, _, err := ParseAllowlistCIDR(tc.in)
if tc.ok {
if err != nil {
t.Errorf("ParseAllowlistCIDR(%q) unexpected err: %v", tc.in, err)
continue
}
if got != tc.want {
t.Errorf("ParseAllowlistCIDR(%q) = %q, want %q", tc.in, got, tc.want)
}
} else if err == nil {
t.Errorf("ParseAllowlistCIDR(%q) should have rejected", tc.in)
}
}
}
func TestFraudFeedbackValid(t *testing.T) {
for _, v := range []string{"legitimate", "suspicious"} {
if err := (FraudFeedback{Verdict: v}).Valid(); err != nil {
t.Errorf("verdict %q should be valid: %v", v, err)
}
}
for _, v := range []string{"", "fraud", "ok", "LEGITIMATE"} {
if err := (FraudFeedback{Verdict: v}).Valid(); err == nil {
t.Errorf("verdict %q should be invalid", v)
}
}
}
+15
View File
@@ -109,6 +109,21 @@ func (r *AccessLogRepo) ListRecentScoredByEvent(ctx context.Context, eventID uui
return out, rows.Err()
}
// BelongsToEvent reports whether the access log identified by `id` is
// attached (via guest) to `eventID`. Used by the feedback endpoint to
// stop a hostile editor on event A from marking event B's logs.
func (r *AccessLogRepo) BelongsToEvent(ctx context.Context, id, eventID uuid.UUID) (bool, error) {
var ok bool
err := r.pool.QueryRow(ctx, `
SELECT EXISTS (
SELECT 1 FROM access_logs a
JOIN guests g ON g.id = a.guest_id
WHERE a.id = $1 AND g.event_id = $2
)
`, id, eventID).Scan(&ok)
return ok, err
}
func (r *AccessLogRepo) ApplyScore(ctx context.Context, p ApplyScoreParams) error {
const q = `
UPDATE access_logs
+8 -7
View File
@@ -57,7 +57,7 @@ func (r *EventRepo) Create(ctx context.Context, p CreateEventParams) (*domain.Ev
const q = `
INSERT INTO events (host_id, name, slug, event_date, venue, max_capacity, settings, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
RETURNING id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at, fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
`
row := tx.QueryRow(ctx, q,
p.HostID, p.Name, p.Slug, p.EventDate, p.Venue, p.MaxCapacity, settingsJSON, p.Status,
@@ -86,7 +86,7 @@ func (r *EventRepo) Create(ctx context.Context, p CreateEventParams) (*domain.Ev
func (r *EventRepo) Get(ctx context.Context, id uuid.UUID) (*domain.Event, error) {
const q = `
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at, fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
FROM events WHERE id = $1
`
ev, err := scanEvent(r.pool.QueryRow(ctx, q, id))
@@ -104,7 +104,7 @@ func (r *EventRepo) Get(ctx context.Context, id uuid.UUID) (*domain.Event, error
// merging both cases we avoid leaking existence on cross-tenant lookups.
func (r *EventRepo) GetForHost(ctx context.Context, id, hostID uuid.UUID) (*domain.Event, error) {
const q = `
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at, fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
FROM events WHERE id = $1 AND host_id = $2
`
ev, err := scanEvent(r.pool.QueryRow(ctx, q, id, hostID))
@@ -131,7 +131,7 @@ func (r *EventRepo) ListForUser(ctx context.Context, userID uuid.UUID, collabEve
}
rows, err := r.pool.Query(ctx, `
SELECT DISTINCT
id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at, fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
FROM events
WHERE host_id = $1
OR id = ANY($2::uuid[])
@@ -167,14 +167,14 @@ func (r *EventRepo) List(ctx context.Context, hostID uuid.UUID, limit, offset in
)
if hostID == uuid.Nil {
rows, err = r.pool.Query(ctx, `
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at, fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
FROM events
ORDER BY created_at DESC
LIMIT $1 OFFSET $2
`, limit, offset)
} else {
rows, err = r.pool.Query(ctx, `
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at, fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
FROM events
WHERE host_id = $1
ORDER BY created_at DESC
@@ -239,7 +239,7 @@ func (r *EventRepo) update(ctx context.Context, id, hostID uuid.UUID, p UpdateEv
q += ` AND ($2::uuid IS NULL OR $2::uuid = host_id OR TRUE)`
}
q += `
RETURNING id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
RETURNING id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at, fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
`
var settingsJSON []byte
@@ -304,6 +304,7 @@ func scanEvent(s rowScanner) (*domain.Event, error) {
err := s.Scan(
&ev.ID, &ev.HostID, &ev.Name, &ev.Slug, &ev.EventDate, &ev.Venue,
&ev.MaxCapacity, &settingsJSON, &ev.Status, &ev.CreatedAt, &ev.UpdatedAt,
&ev.FraudMediumThreshold, &ev.FraudHighThreshold, &ev.FraudBlockThreshold,
)
if err != nil {
return nil, err
+242
View File
@@ -0,0 +1,242 @@
package storage
import (
"context"
"errors"
"strings"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/alchemistkay/guestguard/internal/domain"
)
// AllowlistRepo manages the per-event CIDR bypass list. Lookups happen
// before each fraud-engine call so they need to be cheap — the index on
// event_id keeps that O(log n) even on very busy events.
type AllowlistRepo struct {
pool *pgxpool.Pool
}
func NewAllowlistRepo(db *DB) *AllowlistRepo {
return &AllowlistRepo{pool: db.Pool}
}
// List returns every CIDR allowlisted for the event, newest first.
func (r *AllowlistRepo) List(ctx context.Context, eventID uuid.UUID) ([]domain.Allowlist, error) {
rows, err := r.pool.Query(ctx, `
SELECT event_id, ip_cidr::text, COALESCE(label, ''), created_by, created_at
FROM event_allowlists
WHERE event_id = $1
ORDER BY created_at DESC
`, eventID)
if err != nil {
return nil, err
}
defer rows.Close()
out := []domain.Allowlist{}
for rows.Next() {
var a domain.Allowlist
if err := rows.Scan(&a.EventID, &a.CIDR, &a.Label, &a.CreatedBy, &a.CreatedAt); err != nil {
return nil, err
}
out = append(out, a)
}
return out, rows.Err()
}
type AddAllowlistParams struct {
EventID uuid.UUID
CIDR string // pre-validated; ParseAllowlistCIDR canonicalised it
Label string
CreatedBy uuid.UUID
}
// Add inserts a row. A pre-existing (event_id, ip_cidr) returns
// ErrAllowlistExists so the API can render a friendly 409 instead of the
// raw Postgres unique-violation.
func (r *AllowlistRepo) Add(ctx context.Context, p AddAllowlistParams) (*domain.Allowlist, error) {
const q = `
INSERT INTO event_allowlists (event_id, ip_cidr, label, created_by)
VALUES ($1, $2::inet, NULLIF($3, ''), $4)
RETURNING event_id, ip_cidr::text, COALESCE(label, ''), created_by, created_at
`
var a domain.Allowlist
err := r.pool.QueryRow(ctx, q, p.EventID, p.CIDR, p.Label, p.CreatedBy).Scan(
&a.EventID, &a.CIDR, &a.Label, &a.CreatedBy, &a.CreatedAt,
)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return nil, ErrAllowlistExists
}
return nil, err
}
return &a, nil
}
// Remove deletes an allowlist entry. Returns ErrAllowlistNotFound if the
// (event, cidr) tuple doesn't exist.
func (r *AllowlistRepo) Remove(ctx context.Context, eventID uuid.UUID, cidr string) error {
tag, err := r.pool.Exec(ctx,
`DELETE FROM event_allowlists WHERE event_id = $1 AND ip_cidr = $2::inet`,
eventID, strings.TrimSpace(cidr))
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrAllowlistNotFound
}
return nil
}
// Matches reports whether the given IP falls inside any allowlisted CIDR
// for the event. Returns the matching label (if any) so the API can log
// "bypassed allowlist=Office Wi-Fi" instead of a bare boolean.
//
// We push the CIDR containment into Postgres via the inet `>>=` operator
// — much faster than streaming every row back to Go and matching there.
// One DB round-trip per access, indexed by event_id.
func (r *AllowlistRepo) Matches(ctx context.Context, eventID uuid.UUID, ip string) (bool, string, error) {
if ip == "" {
return false, "", nil
}
var label string
err := r.pool.QueryRow(ctx, `
SELECT COALESCE(label, '')
FROM event_allowlists
WHERE event_id = $1
AND ip_cidr >>= $2::inet
LIMIT 1
`, eventID, ip).Scan(&label)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return false, "", nil
}
// Invalid IP gets a Postgres error — treat as "doesn't match" so a
// malformed forwarded IP doesn't blow up the access path.
return false, "", nil
}
return true, label, nil
}
// --- thresholds ---
// GetThresholds returns the per-event fraud thresholds. Missing event
// surfaces as the global defaults — the caller normally has the event
// loaded already and doesn't need this method, but the fraud engine /
// access path can use it as a cheap lookup without re-loading the row.
func (r *EventRepo) GetThresholds(ctx context.Context, eventID uuid.UUID) (domain.FraudThresholds, error) {
var th domain.FraudThresholds
err := r.pool.QueryRow(ctx, `
SELECT fraud_medium_threshold, fraud_high_threshold, fraud_block_threshold
FROM events WHERE id = $1
`, eventID).Scan(&th.Medium, &th.High, &th.Block)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.DefaultThresholds(), domain.ErrEventNotFound
}
return domain.DefaultThresholds(), err
}
return th, nil
}
// UpdateThresholds patches the trio. Validation lives in the handler
// (host-facing error messages), but we keep the SQL guard rail with the
// ordering check duplicated at the DB level — a misbehaving client should
// never be able to write nonsense.
func (r *EventRepo) UpdateThresholds(ctx context.Context, eventID uuid.UUID, th domain.FraudThresholds) error {
if err := th.Valid(); err != nil {
return err
}
tag, err := r.pool.Exec(ctx, `
UPDATE events SET
fraud_medium_threshold = $2,
fraud_high_threshold = $3,
fraud_block_threshold = $4,
updated_at = now()
WHERE id = $1
`, eventID, th.Medium, th.High, th.Block)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrEventNotFound
}
return nil
}
// --- feedback ---
type FeedbackRepo struct {
pool *pgxpool.Pool
}
func NewFeedbackRepo(db *DB) *FeedbackRepo {
return &FeedbackRepo{pool: db.Pool}
}
type RecordFeedbackParams struct {
AccessLogID uuid.UUID
Verdict string // "legitimate" | "suspicious"
MarkedBy uuid.UUID
Note string
}
// Record upserts the verdict. Hosts sometimes change their mind ("oh,
// that was Aunty after all"); ON CONFLICT lets the second click win
// rather than 409-ing them.
func (r *FeedbackRepo) Record(ctx context.Context, p RecordFeedbackParams) (*domain.FraudFeedback, error) {
const q = `
INSERT INTO fraud_feedback (access_log_id, verdict, marked_by, note)
VALUES ($1, $2, $3, NULLIF($4, ''))
ON CONFLICT (access_log_id) DO UPDATE SET
verdict = EXCLUDED.verdict,
marked_by = EXCLUDED.marked_by,
note = EXCLUDED.note,
created_at = now()
RETURNING access_log_id, verdict, marked_by, COALESCE(note, ''), created_at
`
var f domain.FraudFeedback
err := r.pool.QueryRow(ctx, q, p.AccessLogID, p.Verdict, p.MarkedBy, p.Note).Scan(
&f.AccessLogID, &f.Verdict, &f.MarkedBy, &f.Note, &f.CreatedAt,
)
if err != nil {
return nil, err
}
return &f, nil
}
// ListForEvent returns every feedback row for access logs on the event,
// newest first. Powers the host's "I've reviewed these" filter on the
// Security tab and the future ML training pipeline.
func (r *FeedbackRepo) ListForEvent(ctx context.Context, eventID uuid.UUID) ([]domain.FraudFeedback, error) {
rows, err := r.pool.Query(ctx, `
SELECT f.access_log_id, f.verdict, f.marked_by, COALESCE(f.note, ''), f.created_at
FROM fraud_feedback f
JOIN access_logs a ON a.id = f.access_log_id
JOIN guests g ON g.id = a.guest_id
WHERE g.event_id = $1
ORDER BY f.created_at DESC
`, eventID)
if err != nil {
return nil, err
}
defer rows.Close()
out := []domain.FraudFeedback{}
for rows.Next() {
var f domain.FraudFeedback
if err := rows.Scan(&f.AccessLogID, &f.Verdict, &f.MarkedBy, &f.Note, &f.CreatedAt); err != nil {
return nil, err
}
out = append(out, f)
}
return out, rows.Err()
}
// ErrAllowlistExists is the storage-layer signal for a duplicate insert.
// Exposed here (not in domain) because the API layer is what cares about
// the 409 mapping — domain just sees "already exists".
var ErrAllowlistExists = errors.New("allowlist entry already exists")
@@ -0,0 +1,14 @@
DROP INDEX IF EXISTS idx_allowlists_event;
DROP TABLE IF EXISTS event_allowlists;
DROP TABLE IF EXISTS fraud_feedback;
ALTER TABLE access_logs
DROP COLUMN IF EXISTS geo_lon,
DROP COLUMN IF EXISTS geo_lat,
DROP COLUMN IF EXISTS geo_city,
DROP COLUMN IF EXISTS geo_country;
ALTER TABLE events
DROP COLUMN IF EXISTS fraud_block_threshold,
DROP COLUMN IF EXISTS fraud_high_threshold,
DROP COLUMN IF EXISTS fraud_medium_threshold;
@@ -0,0 +1,44 @@
-- Tier 2 Block G — smarter fraud detection.
--
-- Four schema additions:
-- 1. Per-event tunable thresholds. Defaults match the previous hardcoded
-- 30/60/85 band boundaries so existing events behave identically until
-- a host tweaks them.
-- 2. Geolocation columns on access_logs. The fraud engine fills these
-- asynchronously; nullable so logs from before this migration aren't
-- retroactively required to have geo data.
-- 3. fraud_feedback for the "this was legitimate / actually suspicious"
-- hostback. Seeds the future ML model and lets hosts silence specific
-- false positives.
-- 4. event_allowlists for CIDR-based bypass — the corporate-Wi-Fi and
-- family-router escape valve.
ALTER TABLE events
ADD COLUMN IF NOT EXISTS fraud_medium_threshold SMALLINT NOT NULL DEFAULT 30,
ADD COLUMN IF NOT EXISTS fraud_high_threshold SMALLINT NOT NULL DEFAULT 60,
ADD COLUMN IF NOT EXISTS fraud_block_threshold SMALLINT NOT NULL DEFAULT 85;
ALTER TABLE access_logs
ADD COLUMN IF NOT EXISTS geo_country TEXT,
ADD COLUMN IF NOT EXISTS geo_city TEXT,
ADD COLUMN IF NOT EXISTS geo_lat DOUBLE PRECISION,
ADD COLUMN IF NOT EXISTS geo_lon DOUBLE PRECISION;
CREATE TABLE IF NOT EXISTS fraud_feedback (
access_log_id UUID PRIMARY KEY REFERENCES access_logs(id) ON DELETE CASCADE,
verdict TEXT NOT NULL CHECK (verdict IN ('legitimate', 'suspicious')),
marked_by UUID REFERENCES users(id) ON DELETE SET NULL,
note TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS event_allowlists (
event_id UUID NOT NULL REFERENCES events(id) ON DELETE CASCADE,
ip_cidr INET NOT NULL,
label TEXT,
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (event_id, ip_cidr)
);
CREATE INDEX IF NOT EXISTS idx_allowlists_event ON event_allowlists(event_id);