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:
@@ -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 (
|
||||
|
||||
@@ -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")
|
||||
)
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user