feat(loyalty): production readiness round 2 — 12 security, integrity & correctness fixes
Some checks failed
CI / ruff (push) Successful in 12s
CI / validate (push) Successful in 27s
CI / dependency-scanning (push) Successful in 31s
CI / pytest (push) Failing after 3h14m58s
CI / docs (push) Has been cancelled
CI / deploy (push) Has been cancelled

Security:
- Fix TOCTOU race conditions: move balance/limit checks after row lock in redeem_points, add_stamp, redeem_stamps
- Add PIN ownership verification to update/delete/unlock store routes
- Gate adjust_points endpoint to merchant_owner role only

Data integrity:
- Track total_points_voided in void_points
- Add order_reference idempotency guard in earn_points

Correctness:
- Fix LoyaltyProgramAlreadyExistsException to use merchant_id parameter
- Add StorefrontProgramResponse excluding wallet IDs from public API
- Add bounds (±100000) to PointsAdjustRequest.points_delta

Audit & config:
- Add CARD_REACTIVATED transaction type with audit record
- Improve admin audit logging with actor identity and old values
- Use merchant-specific PIN lockout settings with global fallback
- Guard MerchantLoyaltySettings creation with get_or_create pattern

Tests: 27 new tests (265 total) covering all 12 items — unit and integration.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-16 23:37:23 +01:00
parent b6047f5b7d
commit 7d652716bb
20 changed files with 955 additions and 28 deletions

View File

@@ -372,3 +372,169 @@ class TestAdjustPoints:
assert result["success"] is True
assert result["points_balance"] == 0
# ============================================================================
# Item 1: TOCTOU Race Condition (redeem_points checks after lock)
# ============================================================================
@pytest.mark.unit
@pytest.mark.loyalty
class TestRedeemPointsTOCTOU:
"""Verify balance check happens after row lock."""
def setup_method(self):
self.service = PointsService()
def test_redeem_insufficient_after_lock(self, db, points_setup):
"""Balance check uses locked row state, not stale read."""
card = points_setup["card"]
store = points_setup["store"]
# Set balance to exactly the reward cost
card.points_balance = 100
db.commit()
# Should succeed — balance is exactly enough
result = self.service.redeem_points(
db, store_id=store.id, card_id=card.id, reward_id="r1",
)
assert result["success"] is True
assert result["points_balance"] == 0
# Second redemption should fail (balance is now 0 after lock)
with pytest.raises(InsufficientPointsException):
self.service.redeem_points(
db, store_id=store.id, card_id=card.id, reward_id="r1",
)
# ============================================================================
# Item 4: void_points updates total_points_voided
# ============================================================================
@pytest.mark.unit
@pytest.mark.loyalty
class TestVoidPointsTracking:
"""Verify void_points increments total_points_voided."""
def setup_method(self):
self.service = PointsService()
def test_void_updates_total_points_voided(self, db, points_setup):
"""total_points_voided is incremented on void."""
card = points_setup["card"]
store = points_setup["store"]
initial_voided = card.total_points_voided
self.service.void_points(
db, store_id=store.id, card_id=card.id, points_to_void=50,
)
db.refresh(card)
assert card.total_points_voided == initial_voided + 50
def test_void_caps_voided_at_balance(self, db, points_setup):
"""total_points_voided only counts actually voided amount (capped at balance)."""
card = points_setup["card"]
store = points_setup["store"]
# Set balance to 30, try to void 100
card.points_balance = 30
card.total_points_voided = 0
db.commit()
self.service.void_points(
db, store_id=store.id, card_id=card.id, points_to_void=100,
)
db.refresh(card)
assert card.total_points_voided == 30 # Only 30 was available
assert card.points_balance == 0
# ============================================================================
# Item 5: Duplicate order_reference guard
# ============================================================================
@pytest.mark.unit
@pytest.mark.loyalty
class TestEarnPointsIdempotency:
"""Verify duplicate order_reference returns existing result."""
def setup_method(self):
self.service = PointsService()
def test_duplicate_order_reference_returns_existing(self, db, points_setup):
"""Same order_reference returns existing result without double-earning."""
card = points_setup["card"]
store = points_setup["store"]
result1 = self.service.earn_points(
db,
store_id=store.id,
card_id=card.id,
purchase_amount_cents=1000,
order_reference="ORDER-DUP-001",
)
balance_after_first = result1["points_balance"]
result2 = self.service.earn_points(
db,
store_id=store.id,
card_id=card.id,
purchase_amount_cents=1000,
order_reference="ORDER-DUP-001",
)
# Second call should return same points_earned, balance unchanged
assert result2["points_earned"] == result1["points_earned"]
assert result2["points_balance"] == balance_after_first
assert result2["message"] == "Points already earned for this order"
def test_different_order_references_earn_separately(self, db, points_setup):
"""Different order_references earn points independently."""
card = points_setup["card"]
store = points_setup["store"]
result1 = self.service.earn_points(
db,
store_id=store.id,
card_id=card.id,
purchase_amount_cents=1000,
order_reference="ORDER-A",
)
result2 = self.service.earn_points(
db,
store_id=store.id,
card_id=card.id,
purchase_amount_cents=1000,
order_reference="ORDER-B",
)
assert result2["points_balance"] > result1["points_balance"]
assert result2["message"] == "Points earned successfully"
def test_no_order_reference_allows_multiple_earns(self, db, points_setup):
"""Without order_reference, multiple earns are allowed."""
card = points_setup["card"]
store = points_setup["store"]
result1 = self.service.earn_points(
db,
store_id=store.id,
card_id=card.id,
purchase_amount_cents=1000,
)
result2 = self.service.earn_points(
db,
store_id=store.id,
card_id=card.id,
purchase_amount_cents=1000,
)
assert result2["points_balance"] > result1["points_balance"]