Restart of Loop A (fresh review -> fix -> verify) findings from commit 5e967fa: - B1: sweep auto-refund treats Square PENDING refunds as NON-terminal (row stays pending, no gift-card clawback, refunds row inserted for payments AND till_sales, re-polls the deterministic sweepdup- key); Square-less pre-pass exempts square_refund_id IS NOT NULL rows - M4: terminal tip carve accounts for pending campaign discounts (headroom = total - pending - paid) so explicit tips aren't absorbed as service revenue; no-tip case stays a single record - max_redemptions TOCTOU closed with atomic conditional UPDATE ... RETURNING; exhausted-at-apply surfaces campaign_fully_redeemed - 2FA: verification code is single-use on the saved-card gate (VerifyForUser consume=true, interactive flows unaffected); new POST /api/user/2fa/code mints a fresh code for enabled users (RequireAuth + RequireNonGuest + mint cooldown + per-user limiter) - Refresh tokens: family_id + used_at columns; reuse of an already-rotated token revokes the ENTIRE family and inserts a refresh_token_reuse admin alert; rotation mints descendants in the same family - Frontend: 2FA code input + Request-a-new-code on all saved-card surfaces; admin modal keys code input to customer 2FA + 403 self-heal; tip-display note for pending discounts; 76 frontend tests - Verified: all 26 backend packages pass, frontend build+tests green, env-docs 41/41
107 lines
3.9 KiB
Go
107 lines
3.9 KiB
Go
//go:build test
|
|
|
|
package twofa
|
|
|
|
// Tests for the shared 2FA verification core (the package the payments
|
|
// card-access gate — B6/B10 — imports for real-challenge verification).
|
|
// The pepper provider is never registered here (handlers/user's build-tagged
|
|
// files register it), so Hash falls back to the legacy plain SHA-256 digest —
|
|
// which is exactly what the seeded pending-code hashes use.
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"testing"
|
|
"time"
|
|
|
|
"crussell/clock"
|
|
"crussell/db"
|
|
"crussell/testutils"
|
|
"crussell/testutils/fixtures"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func seedPending(t *testing.T, ctx context.Context, tx db.Querier, userID, code string) {
|
|
t.Helper()
|
|
_, err := tx.Exec(ctx, `UPDATE users
|
|
SET two_factor_method = 'email',
|
|
two_factor_pending_code_hash = $2,
|
|
two_factor_pending_code_expires = $3
|
|
WHERE id = $1`, userID, Hash(code), clock.Now().Add(10*time.Minute))
|
|
require.NoError(t, err)
|
|
}
|
|
|
|
func TestVerifyForUser_CorrectAndWrongCode(t *testing.T) {
|
|
ctx, tx := testutils.SetupTestTx(t)
|
|
|
|
// consume=false (interactive setup/disable path): a success keeps the
|
|
// pending code valid, so a wrong follow-up code reports ErrIncorrect.
|
|
userID, err := fixtures.CreateTestUser(tx)
|
|
require.NoError(t, err)
|
|
seedPending(t, ctx, tx, userID, "123456")
|
|
require.NoError(t, VerifyForUser(ctx, userID, "123456", false), "correct code must verify")
|
|
require.ErrorIs(t, VerifyForUser(ctx, userID, "999999", false), ErrIncorrect)
|
|
|
|
// consume=true (payments saved-card gate path): a success DESTROYS the
|
|
// pending code, so re-verifying the same code reports ErrMissingOrExpired
|
|
// — a verified code is single-use and cannot authorize a second charge.
|
|
userID2, err := fixtures.CreateTestUser(tx)
|
|
require.NoError(t, err)
|
|
seedPending(t, ctx, tx, userID2, "123456")
|
|
require.NoError(t, VerifyForUser(ctx, userID2, "123456", true), "correct code must verify")
|
|
require.ErrorIs(t, VerifyForUser(ctx, userID2, "123456", true), ErrMissingOrExpired, "a consumed code must be single-use")
|
|
var pendingHash sql.NullString
|
|
require.NoError(t, tx.QueryRow(ctx, "SELECT two_factor_pending_code_hash FROM users WHERE id = $1", userID2).Scan(&pendingHash))
|
|
require.False(t, pendingHash.Valid, "a consumed code must be NULLed in the DB")
|
|
}
|
|
|
|
func TestVerifyForUser_LockoutAndMissing(t *testing.T) {
|
|
ctx, tx := testutils.SetupTestTx(t)
|
|
userID, err := fixtures.CreateTestUser(tx)
|
|
require.NoError(t, err)
|
|
seedPending(t, ctx, tx, userID, "123456")
|
|
|
|
// Wrong code #1 → ErrIncorrect; four more reach the 5-attempt cap.
|
|
require.ErrorIs(t, VerifyForUser(ctx, userID, "999999", true), ErrIncorrect)
|
|
for i := 0; i < 4; i++ {
|
|
_ = VerifyForUser(ctx, userID, "999999", true)
|
|
}
|
|
require.ErrorIs(t, VerifyForUser(ctx, userID, "999999", true), ErrLockedOut)
|
|
|
|
// A fresh user with no pending code → ErrMissingOrExpired.
|
|
userID2, err := fixtures.CreateTestUser(tx)
|
|
require.NoError(t, err)
|
|
require.ErrorIs(t, VerifyForUser(ctx, userID2, "123456", true), ErrMissingOrExpired)
|
|
}
|
|
|
|
// TestVerifyForUser_AttemptStateMapPersists exercises the shared per-user
|
|
// attempt map directly (the state the payments gate shares with the interactive
|
|
// endpoints): the map is bounded and a locked-out record is never evicted.
|
|
func TestVerifyForUser_AttemptStateMapPersists(t *testing.T) {
|
|
t.Cleanup(func() {
|
|
MapMu.Lock()
|
|
Map = make(map[string]*AttemptState)
|
|
MaxTrackedAttempts = 10_000
|
|
MapMu.Unlock()
|
|
})
|
|
|
|
MapMu.Lock()
|
|
Map = make(map[string]*AttemptState)
|
|
MaxTrackedAttempts = 2
|
|
MapMu.Unlock()
|
|
|
|
// Fill the map with locked-out records; a new key must NOT evict one.
|
|
now := clock.Now()
|
|
for _, id := range []string{"victim_a", "victim_b"} {
|
|
st := &AttemptState{}
|
|
st.SetLastActive(now)
|
|
st.Count.Store(MaxAttempts)
|
|
Map[id] = st
|
|
}
|
|
_ = StateFor("new_user") // transient, untracked (map full of lockouts)
|
|
MapMu.Lock()
|
|
defer MapMu.Unlock()
|
|
require.Len(t, Map, 2, "locked-out records must survive the cap pressure")
|
|
}
|