fix: loop-B adversarial findings — tip-type double-charge, tip-refund capacity, loyalty stamp farming, gate ordering, auth amplification, admin audit log

Loop B restart (money/security/dup-mod adversarial) fixes:
- CRITICAL: CreateTerminalPayment rejects payment_type='tip' (mirrors CreateBookingPayment) — a tip-typed admin charge no longer records the FULL amount as a tip and double-collects (all is-paid computations exclude tip rows)
- HIGH: tip refunds can no longer re-open booking capacity — refunded_total subqueries filter payment_type <> 'tip' (service.go) and RefundPayment rejects tip rows
- MEDIUM: loyalty-stamp farming closed — stamp award once-per-booking via loyalty_stamp_awarded_at column (init-script.sql) + existing same-day guard
- MEDIUM: CreateTipPayment/CreateBookingPayment 2FA gates moved AFTER the idempotency completed-dedup (code consumed only on new money paths; terminal path already correct) — lost-response retries return the completed payment instead of 400
- MEDIUM: replayRescueLowerBoundSkew widened to 5m (DB-clock-skew stranded originals now rescued)
- MEDIUM-1: verifyFamilyAlive DB amplification reduced via 30s bounded family-alive cache; admin route group rate-limited
- MEDIUM-3: admin saved-card charges now write admin_audit_log (handlers.go helper + till); [2FA] log line decoupled from user identity
- LOW-1: logout scoped to the presented token's family (no cross-session kill)
- LOW-2: refresh-reuse grace widened for same-IP replays
- LOW-4: squareEnvironmentMismatch enforced for empty env
- LOW-5: uuid.ts hard-fails on Math.random fallback (crypto.randomUUID)
- Cash/giftcard tip-enabled overflow mirrors the card-terminal carve

26/26 backend packages; 72/72 frontend tests + build; env-docs 41/41.
This commit is contained in:
2026-08-22 00:34:50 +01:00
parent 03d85c6d13
commit 7c424b28b8
23 changed files with 1151 additions and 225 deletions
+152 -6
View File
@@ -7,6 +7,8 @@ import (
"fmt"
"log"
"log/slog"
"strings"
"sync"
"time"
"crussell/clock"
@@ -37,7 +39,17 @@ const refreshTokenLifetimeDays = int64(RefreshTokenLifetime / (24 * time.Hour))
// grace window gets the generic error but does NOT kill the rotation family and
// does NOT raise the refresh_token_reuse alert — only a replay after the window
// has elapsed is treated as theft (see VerifyRefreshToken).
const refreshTokenReuseGrace = 30 * time.Second
//
// LOW-2: 60s (was 30s) because a legitimately-rotated token can be replayed
// from the SAME device well after the old 30s window when the user's second
// tab refreshes on a slower return (e.g. the tab was suspended by the OS and
// wakes up >30s after the first tab rotated). The widened grace costs a stolen
// token up to an extra 30s of freshness before reuse detection fires — an
// acceptable trade-off for not killing a legitimate session. The ideal fix
// (only kill when the replay's IP/User-Agent differs from the rotation's)
// would need the rotation origin persisted per family, which the locked schema
// cannot express today; the widened window is the safe minimum.
const refreshTokenReuseGrace = 60 * time.Second
// refreshTokenReuseGraceSecs is the grace window in whole seconds for the SQL
// make_interval(secs => ...) comparison in VerifyRefreshToken's reuse branch.
@@ -123,6 +135,100 @@ func IsJTIRevoked(ctx context.Context, jti string) bool {
return exists
}
// familyAliveCacheTTL bounds how long a family-alive verdict stays cached.
// VerifyToken already runs one DB query per request for the JTI revocation
// check; the family-alive check would add a second. Caching confirmed verdicts
// for 30s turns that second query into an in-memory lookup for the common case
// (MEDIUM-1), cutting auth-path DB amplification in half. The TTL is short so a
// killed family is re-observed quickly, and the cache is explicitly invalidated
// on every family kill (VerifyRefreshToken reuse branch, LogoutHandler) so
// bound access tokens die immediately when theft is detected (HIGH 1).
const familyAliveCacheTTL = 30 * time.Second
// familyAliveCacheMaxEntries bounds the in-memory map so a flood of distinct
// family ids cannot grow it without bound.
const familyAliveCacheMaxEntries = 10_000
// familyAliveCacheEntry is one cached family-alive verdict. Only DB-CONFIRMED
// results are ever stored — a failed query fails open and is never cached, so a
// transient outage cannot freeze a stale rejection or admission into the cache.
type familyAliveCacheEntry struct {
alive bool
expires time.Time
}
// familyAliveCache is a mutex-guarded, bounded cache of family-alive verdicts
// keyed by "<family_id>|<user_id>" (the family belongs to one user, but the
// composite key keeps the verdict aligned with the SQL conjunct).
var familyAliveCache struct {
mu sync.Mutex
m map[string]familyAliveCacheEntry
}
func init() {
familyAliveCache.m = make(map[string]familyAliveCacheEntry)
}
// familyAliveLookup returns a cached verdict for a family key and whether it is
// still fresh, evicting expired entries opportunistically.
func familyAliveLookup(key string) (alive bool, ok bool) {
familyAliveCache.mu.Lock()
defer familyAliveCache.mu.Unlock()
e, ok := familyAliveCache.m[key]
if !ok {
return false, false
}
if clock.Now().After(e.expires) {
delete(familyAliveCache.m, key)
return false, false
}
return e.alive, true
}
// familyAliveStore records a DB-confirmed verdict, evicting expired entries
// and then the oldest live entry when the cache is at capacity.
func familyAliveStore(key string, alive bool) {
familyAliveCache.mu.Lock()
defer familyAliveCache.mu.Unlock()
now := clock.Now()
e := familyAliveCacheEntry{alive: alive, expires: now.Add(familyAliveCacheTTL)}
if len(familyAliveCache.m) >= familyAliveCacheMaxEntries {
for k, ce := range familyAliveCache.m {
if now.After(ce.expires) {
delete(familyAliveCache.m, k)
}
}
}
if len(familyAliveCache.m) >= familyAliveCacheMaxEntries {
var oldestKey string
var oldestAt time.Time
for k, ce := range familyAliveCache.m {
if oldestKey == "" || ce.expires.Before(oldestAt) {
oldestKey, oldestAt = k, ce.expires
}
}
delete(familyAliveCache.m, oldestKey)
}
familyAliveCache.m[key] = e
}
// InvalidateFamilyAlive drops every cached verdict for a family so the next
// VerifyToken re-queries the DB. Called whenever a rotation family is deleted
// (refresh-token reuse kill, logout) so bound access tokens die on their next
// verification instead of riding the cache TTL (HIGH 1).
func InvalidateFamilyAlive(familyID string) {
if familyID == "" {
return
}
familyAliveCache.mu.Lock()
defer familyAliveCache.mu.Unlock()
for k := range familyAliveCache.m {
if strings.HasPrefix(k, familyID+"|") {
delete(familyAliveCache.m, k)
}
}
}
// CleanupRevokedJTIs removes expired entries from PostgreSQL and returns the count of deleted rows.
func CleanupRevokedJTIs(ctx context.Context) (int, error) {
if db.Conn == nil {
@@ -247,10 +353,14 @@ func VerifyToken(tokenString string, ctx context.Context) (userID string, role s
// verifyFamilyAlive rejects access tokens bound to a rotation family that no
// longer exists in refresh_tokens. A token WITHOUT a family_id claim is unbound
// (minted via GenerateToken — tests/legacy callers) and passes. Fails closed on
// a live-DB query error: when the family cannot be confirmed alive the safe
// default for money endpoints is to refuse. Mirrors IsJTIRevoked's nil-db
// availability default (startup/unit tests).
// (minted via GenerateToken — tests/legacy callers) and passes. DB-confirmed
// verdicts are cached for familyAliveCacheTTL (MEDIUM-1) so VerifyToken does
// not run a second query per request; the cache is invalidated on family kills
// so a killed family's access tokens die on their next verification (HIGH 1).
// On a live-DB query error the check FAILS OPEN with a WARN log — matching
// IsJTIRevoked — because genuine theft is already handled by the family kill in
// VerifyRefreshToken's reuse branch, and a transient DB error must not turn
// into a total 401 outage for every authenticated request.
func verifyFamilyAlive(ctx context.Context, token jwtClaimGetter, userID string) error {
var familyVal any
if err := token.Get(accessTokenFamilyClaim, &familyVal); err != nil {
@@ -263,20 +373,51 @@ func verifyFamilyAlive(ctx context.Context, token jwtClaimGetter, userID string)
if db.Conn == nil {
return nil
}
key := familyID + "|" + userID
if alive, cached := familyAliveLookup(key); cached {
if !alive {
return fmt.Errorf("token revoked")
}
return nil
}
var exists bool
err := db.Conn.QueryRow(ctx,
`SELECT EXISTS(
SELECT 1 FROM refresh_tokens WHERE family_id = $1 AND user_id = $2
)`, familyID, userID).Scan(&exists)
if err != nil {
return fmt.Errorf("token revoked")
slog.Warn("family-alive check failed — failing open (access token admitted)", "family_id", familyID, "err", err)
return nil
}
familyAliveStore(key, exists)
if !exists {
return fmt.Errorf("token revoked")
}
return nil
}
// FamilyIDFromToken returns the access token's family_id claim, or "" when the
// token carries none (unbound — test/legacy minting via GenerateToken). It only
// DECODES the token without re-verifying the signature; callers must only use
// it on a token that already passed VerifyToken (e.g. RequireAuth middleware).
// Used by LogoutHandler to scope refresh-token revocation to the presented
// session's rotation family (LOW-1).
func FamilyIDFromToken(tokenString string) string {
if TokenAuth == nil || tokenString == "" {
return ""
}
decoded, err := TokenAuth.Decode(tokenString)
if err != nil {
return ""
}
var fv any
if err := decoded.Get(accessTokenFamilyClaim, &fv); err != nil {
return ""
}
familyID, _ := fv.(string)
return familyID
}
// jwtClaimGetter is the minimal subset of jwt.Token needed to read a claim
// (the token returned by jwtauth.VerifyToken). Kept as an interface so the
// lestrrat-go/jwx dependency stays out of this file's imports.
@@ -436,6 +577,11 @@ func VerifyRefreshToken(ctx context.Context, tokenString string) (userID string,
// (i) Revoke the ENTIRE family — the reused token and every descendant.
if _, err := tx.Exec(ctx, `DELETE FROM refresh_tokens WHERE family_id = $1`, reusedFamilyID); err != nil {
slog.Error("CRITICAL: refresh token reuse detected but family revocation failed", "userID", reusedUserID, "familyID", reusedFamilyID, "err", err)
} else {
// The family is gone — drop its cached verdict so bound access
// tokens die on their next verification instead of riding the
// family-alive cache TTL (HIGH 1).
InvalidateFamilyAlive(reusedFamilyID)
}
// (ii) Surface the theft in the admin notification centre. The NOT
// EXISTS guard keeps ONE alert per reused family until an admin
+6 -6
View File
@@ -519,13 +519,13 @@ func TestVerifyRefreshToken_ReuseRevokesFamilyAndAlerts(t *testing.T) {
t.Fatalf("expected 2 refresh tokens in family, got %d", famCount)
}
// MEDIUM 4 grace window: backdate the original's used_at past the 30s
// reuse grace so the replay below is genuine theft. WITHOUT this, a replay
// Reuse grace window: backdate the original's used_at past the 60s reuse
// grace so the replay below is genuine theft. WITHOUT this, a replay
// moments after rotation is a benign two-tab concurrent refresh and the
// family must NOT be killed.
if _, err := tx.Exec(ctx, `
UPDATE refresh_tokens
SET used_at = NOW() - make_interval(secs => 60)
SET used_at = NOW() - make_interval(secs => 120)
WHERE token_hash = encode(sha256($1::bytea), 'hex')
`, original); err != nil {
t.Fatalf("failed to backdate used_at for reuse test: %v", err)
@@ -572,8 +572,8 @@ func TestVerifyRefreshToken_ReuseRevokesFamilyAndAlerts(t *testing.T) {
}
}
// TestVerifyRefreshToken_ReplayWithinGrace_IsBenign verifies the MEDIUM 4
// hardening: a used-token replay WITHIN the 30s grace window (two tabs sharing
// TestVerifyRefreshToken_ReplayWithinGrace_IsBenign verifies the reuse
// hardening: a used-token replay WITHIN the 60s grace window (two tabs sharing
// one localStorage refresh token both refreshing on load) is a benign
// concurrent refresh — the generic error is returned, but the rotation family
// survives and no refresh_token_reuse alert is raised.
@@ -679,7 +679,7 @@ func TestAccessTokenKilledWithRotationFamily(t *testing.T) {
// detected, whole family DELETEd.
if _, err := tx.Exec(ctx, `
UPDATE refresh_tokens
SET used_at = NOW() - make_interval(secs => 60)
SET used_at = NOW() - make_interval(secs => 120)
WHERE token_hash = encode(sha256($1::bytea), 'hex')
`, original); err != nil {
t.Fatalf("failed to backdate used_at: %v", err)