Files
Kwaku Danso 98678ff5a3 feat(tier2): finish the finish line — Block H follow-ups, Block G geolocation, cross-cutting
Three threads of work land here together to close out Tier 2.

### Block H follow-ups — day-of check-in
- Scanner is now an "open on your phone" magic-link flow. Hosts on
  desktop mint a scoped JWT via POST /events/{id}/scanner-ticket and
  render its URL into a QR; phone scans it and lands on /scanner with
  the ticket as bearer. The ticket carries Audience=scanner so it can
  never substitute for a session token.
- Plus-one confirmation at the door: scan → POST /check-in/preview to
  fetch guest + expected party size → confirm buttons ("Just them",
  "Party of N", custom) → POST /check-in. No more silent arrival_count=1.
- Offline scan queue: failed POSTs go into an IndexedDB store and drain
  on the 'online' event with poison-message protection.
- Day-of arrivals headline widget on the event overview, gated to the
  host's local calendar date so it doesn't dominate the page weeks out.
- Tab nav restyled with inline heroicons + scrollable segmented control;
  Check-in moves to the rightmost slot.
- PWA: manifest + service worker scoped to /scanner, generated 192/512
  icons (Go scripted renderer in scripts/gen-scanner-icons.go).
- Confirmation email QR was rendering broken because html/template
  rewrites data: URLs to #ZgotmplZ; mark the value as template.URL.
- Email "open your invitation" link 404'd because we had no token to
  put after /rsvp/. Threaded AccessLink through the RSVPConfirmed NATS
  event from the API at submit time.

### Block G remainder — geolocation + threshold preview
- Pluggable GeoResolver in the fraud engine (NullResolver, IPApiResolver
  for the free ip-api.com fallback, MaxMindResolver behind GG_GEOIP_DB_PATH).
  Wrapped in a Redis cache (30d TTL). Geo flows through both gRPC and
  NATS scoring paths.
- geo_jump scoring feature: >500km in <1h flags ("accessed from Lagos
  and Paris within 12 minutes"); >500km in <6h is a softer signal. The
  existing single-signal cap keeps a lone geo_jump in MEDIUM.
- FraudScored event carries geo_country/city/lat/lon; ApplyScore uses
  COALESCE so a later re-score without geo doesn't wipe earlier data.
- Threshold-slider live preview: GET /events/{id}/security/thresholds/preview
  returns band counts the host's existing access events would have
  fallen into under the proposed thresholds. Debounced (250ms) widget
  under the Advanced sliders so the host gets concrete feedback instead
  of guessing.

### Cross-cutting — audit, tier-gating, feature flags
- audit_log table + internal/audit.Recorder (async fire-and-forget on
  detached context so an audit blip never fails the real action). Wired
  into branding update, thresholds update, allowlist add/remove,
  collaborator invite/role-change/remove, message create/send-now/cancel.
- Tier-gating: extended billing.Limits with MaxCollaborators,
  CustomBranding, Scanner, Broadcasts. Free = none; Pro = 5 + all;
  Business = unlimited. Gates the scanner-ticket, message create,
  branding put, and collaborator invite endpoints with 402 +
  structured upgrade payload. Auto-reminders, fraud detection, and
  analytics deliberately stay on every tier — those are safety + visibility
  features, not upsell levers.
- Feature flags: feature_flags table + internal/flags.Store with 30s
  in-memory refresh, stable sha256(key + user_id) percent bucketing,
  unknown-key-defaults-on. Six Tier 2 flags pre-seeded. Three handlers
  (branding, broadcasts, scanner) check the kill switch ahead of the
  tier gate so ops can pull a feature back without a redeploy.

### Verified
- go test ./... + fraud-engine pytest (12/12 incl. 3 new geo_jump tests + 5
  new flags tests).
- docker compose build + up across api, fraud-engine, notifier, frontend.
- /health endpoints 200; migrations 0014 + 0015 applied; 6 flags
  seeded; audit_log table + partial indexes confirmed.
- Fraud-engine logs confirm geo resolver kind=CachedGeoResolver provider=auto.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 20:30:02 +01:00

400 lines
11 KiB
Go

package api
import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"github.com/alchemistkay/guestguard/internal/audit"
"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
audit *audit.Recorder
}
// --- 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(),
})
}
// GET /events/{id}/security/thresholds/preview?medium=&high=&block= — viewer+.
//
// Returns the band-counts that *would* result from applying the
// proposed thresholds to the event's recorded access scores. Powers the
// live "12 of your 47 access events would be flagged" widget under the
// sliders on the Gate tab, so a host moving the slider gets immediate
// concrete feedback instead of having to wait for new scans to land.
type thresholdsPreviewResponse struct {
Total int `json:"total"` // number of scored access logs we considered
Low int `json:"low"`
Medium int `json:"medium"`
High int `json:"high"`
Block int `json:"block"`
}
func (h *securityHandler) previewThresholds(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
}
// Parse the proposed thresholds out of the query string. Falling
// back to the event's stored thresholds when a value is missing
// means the frontend can ask "what would high=70 look like, with
// everything else as it is" without having to re-send the whole
// triple every time.
stored, _ := h.events.GetThresholds(r.Context(), eventID)
proposed := stored
if v, err := intQuery(r, "medium"); err == nil {
proposed.Medium = v
}
if v, err := intQuery(r, "high"); err == nil {
proposed.High = v
}
if v, err := intQuery(r, "block"); err == nil {
proposed.Block = v
}
if err := proposed.Valid(); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
scores, err := h.access.ScoresForEvent(r.Context(), eventID, 1000)
if err != nil {
h.logger.Error("preview thresholds: load scores", "err", err)
writeError(w, http.StatusInternalServerError, "failed to load access history")
return
}
out := thresholdsPreviewResponse{Total: len(scores)}
for _, s := range scores {
switch proposed.Band(s) {
case "block":
out.Block++
case "high":
out.High++
case "medium":
out.Medium++
default:
out.Low++
}
}
writeJSON(w, http.StatusOK, out)
}
// intQuery extracts a non-negative integer from ?<name>= on the
// request. Returns an error when missing or unparseable so the caller
// can decide whether to substitute a default.
func intQuery(r *http.Request, name string) (int, error) {
raw := r.URL.Query().Get(name)
if raw == "" {
return 0, errors.New("missing")
}
var v int
if _, err := fmt.Sscanf(raw, "%d", &v); err != nil {
return 0, err
}
if v < 0 || v > 100 {
return 0, errors.New("out of range")
}
return v, nil
}
// 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
}
h.audit.Record(r.Context(), audit.Params{
UserID: &hostID,
EventID: &eventID,
Action: "thresholds.update",
EntityType: "event",
TargetID: &eventID,
Metadata: map[string]any{
"medium": req.Medium,
"high": req.High,
"block": req.Block,
},
})
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
}
h.audit.Record(r.Context(), audit.Params{
UserID: &hostID,
EventID: &eventID,
Action: "allowlist.add",
EntityType: "allowlist",
Metadata: map[string]any{"cidr": canonical, "label": req.Label},
})
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
}
h.audit.Record(r.Context(), audit.Params{
UserID: &hostID,
EventID: &eventID,
Action: "allowlist.remove",
EntityType: "allowlist",
Metadata: map[string]any{"cidr": canonical},
})
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})
}