Files
guestguard/internal/storage/access_logs.go
T
Kwaku Danso b873012191 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>
2026-05-19 21:33:57 +01:00

143 lines
3.6 KiB
Go

package storage
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
)
type AccessLogRepo struct {
pool *pgxpool.Pool
}
func NewAccessLogRepo(db *DB) *AccessLogRepo {
return &AccessLogRepo{pool: db.Pool}
}
type CreateAccessLogParams struct {
GuestID uuid.UUID
TokenID uuid.UUID
Fingerprint map[string]any
IPAddress string
}
func (r *AccessLogRepo) Create(ctx context.Context, p CreateAccessLogParams) (uuid.UUID, error) {
var fpJSON []byte
if p.Fingerprint != nil {
b, err := json.Marshal(p.Fingerprint)
if err != nil {
return uuid.Nil, fmt.Errorf("marshal fingerprint: %w", err)
}
fpJSON = b
}
var ip *string
if p.IPAddress != "" {
ip = &p.IPAddress
}
const q = `
INSERT INTO access_logs (guest_id, token_id, fingerprint, ip_address)
VALUES ($1, $2, $3, $4::inet)
RETURNING id
`
var id uuid.UUID
err := r.pool.QueryRow(ctx, q, p.GuestID, p.TokenID, fpJSON, ip).Scan(&id)
return id, err
}
type ApplyScoreParams struct {
AccessLogID uuid.UUID
Score int
Reasons []string
Flagged bool
}
// AccessCheckActivity is a scored access-log entry joined with the guest's
// name. Used by the activity-history endpoint so dashboards can show
// historical security checks (including blocked attempts) even when nobody
// was watching the live monitor at the time.
type AccessCheckActivity struct {
GuestID uuid.UUID
GuestName string
Score int
Reasons []string
Flagged bool
CreatedAt time.Time
}
// ListRecentScoredByEvent returns scored access-log entries for an event,
// newest first. Unscored entries (someone opened the page but the fraud
// engine hasn't replied yet) are excluded — they'd be noise on the feed.
func (r *AccessLogRepo) ListRecentScoredByEvent(ctx context.Context, eventID uuid.UUID, limit int) ([]AccessCheckActivity, error) {
if limit <= 0 || limit > 200 {
limit = 50
}
const q = `
SELECT a.guest_id, g.name, a.risk_score, a.risk_reasons, a.flagged, a.created_at
FROM access_logs a
JOIN guests g ON g.id = a.guest_id
WHERE g.event_id = $1 AND a.risk_score IS NOT NULL
ORDER BY a.created_at DESC
LIMIT $2
`
rows, err := r.pool.Query(ctx, q, eventID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []AccessCheckActivity
for rows.Next() {
var (
a AccessCheckActivity
reasons []string
score int16
)
if err := rows.Scan(&a.GuestID, &a.GuestName, &score, &reasons, &a.Flagged, &a.CreatedAt); err != nil {
return nil, err
}
a.Score = int(score)
a.Reasons = reasons
out = append(out, a)
}
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
SET risk_score = $2, risk_reasons = $3, flagged = $4
WHERE id = $1
`
tag, err := r.pool.Exec(ctx, q, p.AccessLogID, p.Score, p.Reasons, p.Flagged)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return errors.New("access_log not found")
}
return nil
}