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

@@ -579,6 +579,16 @@ class CardService:
"""Reactivate a deactivated loyalty card."""
card = self.require_card(db, card_id)
card.is_active = True
# Create reactivation transaction for audit trail
transaction = LoyaltyTransaction(
merchant_id=card.merchant_id,
card_id=card.id,
transaction_type=TransactionType.CARD_REACTIVATED.value,
transaction_at=datetime.now(UTC),
)
db.add(transaction)
db.commit()
db.refresh(card)

View File

@@ -293,19 +293,35 @@ class PinService:
# No match found - record failed attempt on the first unlocked PIN only
# This limits blast radius to 1 lockout instead of N
# Use merchant-specific settings if available, fall back to global config
max_attempts = config.pin_max_failed_attempts
lockout_minutes = config.pin_lockout_minutes
if pins:
from app.modules.loyalty.models import LoyaltyProgram
program = db.query(LoyaltyProgram).filter(LoyaltyProgram.id == program_id).first()
if program:
from app.modules.loyalty.services.program_service import (
program_service as _ps,
)
merchant_settings = _ps.get_merchant_settings(db, program.merchant_id)
if merchant_settings:
max_attempts = merchant_settings.staff_pin_lockout_attempts
lockout_minutes = merchant_settings.staff_pin_lockout_minutes
locked_pin = None
remaining = None
for pin in pins:
if not pin.is_locked:
is_now_locked = pin.record_failed_attempt(
max_attempts=config.pin_max_failed_attempts,
lockout_minutes=config.pin_lockout_minutes,
max_attempts=max_attempts,
lockout_minutes=lockout_minutes,
)
if is_now_locked:
locked_pin = pin
else:
remaining = max(0, config.pin_max_failed_attempts - pin.failed_attempts)
remaining = max(0, max_attempts - pin.failed_attempts)
break # Only record on the first unlocked PIN
db.commit()

View File

@@ -101,6 +101,31 @@ class PointsService:
if settings and settings.require_order_reference and not order_reference:
raise OrderReferenceRequiredException()
# Idempotency guard: if same order_reference already earned points on this card, return existing result
if order_reference:
existing_tx = (
db.query(LoyaltyTransaction)
.filter(
LoyaltyTransaction.card_id == card.id,
LoyaltyTransaction.order_reference == order_reference,
LoyaltyTransaction.transaction_type == TransactionType.POINTS_EARNED.value,
)
.first()
)
if existing_tx:
return {
"success": True,
"message": "Points already earned for this order",
"points_earned": existing_tx.points_delta,
"points_per_euro": program.points_per_euro,
"purchase_amount_cents": existing_tx.purchase_amount_cents or purchase_amount_cents,
"card_id": card.id,
"card_number": card.card_number,
"points_balance": card.points_balance,
"total_points_earned": card.total_points_earned,
"store_id": existing_tx.store_id,
}
# Check minimum purchase amount
if program.minimum_purchase_cents > 0 and purchase_amount_cents < program.minimum_purchase_cents:
return {
@@ -263,10 +288,6 @@ class PointsService:
if points_required < program.minimum_redemption_points:
raise InvalidRewardException(reward_id)
# Check if enough points
if card.points_balance < points_required:
raise InsufficientPointsException(card.points_balance, points_required)
# Verify staff PIN if required
verified_pin = None
if program.require_staff_pin:
@@ -277,6 +298,10 @@ class PointsService:
# Re-fetch with row lock to prevent concurrent modification
card = card_service.get_card_for_update(db, card.id)
# Check balance AFTER acquiring lock to prevent TOCTOU race
if card.points_balance < points_required:
raise InsufficientPointsException(card.points_balance, points_required)
# Redeem points
now = datetime.now(UTC)
card.points_balance -= points_required
@@ -432,6 +457,7 @@ class PointsService:
now = datetime.now(UTC)
actual_voided = min(points_to_void, card.points_balance)
card.points_balance = max(0, card.points_balance - points_to_void)
card.total_points_voided += actual_voided
card.last_activity_at = now
# Create void transaction

View File

@@ -498,11 +498,8 @@ class ProgramService:
db.add(program)
db.flush()
# Create default merchant settings
settings = MerchantLoyaltySettings(
merchant_id=merchant_id,
)
db.add(settings)
# Create default merchant settings (idempotent — skips if already exists)
self.get_or_create_merchant_settings(db, merchant_id)
db.commit()
db.refresh(program)

View File

@@ -110,7 +110,10 @@ class StampService:
raise StaffPinRequiredException()
verified_pin = pin_service.verify_pin(db, program.id, staff_pin, store_id=store_id)
# Check cooldown
# Re-fetch with row lock to prevent concurrent modification
card = card_service.get_card_for_update(db, card.id)
# Check cooldown AFTER acquiring lock to prevent TOCTOU race
now = datetime.now(UTC)
if card.last_stamp_at:
cooldown_ends = card.last_stamp_at + timedelta(minutes=program.cooldown_minutes)
@@ -120,14 +123,11 @@ class StampService:
program.cooldown_minutes,
)
# Check daily limit
# Check daily limit AFTER acquiring lock
stamps_today = card_service.get_stamps_today(db, card.id)
if stamps_today >= program.max_daily_stamps:
raise DailyStampLimitException(program.max_daily_stamps, stamps_today)
# Re-fetch with row lock to prevent concurrent modification
card = card_service.get_card_for_update(db, card.id)
# Add the stamp
card.stamp_count += 1
card.total_stamps_earned += 1
@@ -241,10 +241,6 @@ class StampService:
if not program.is_active:
raise LoyaltyProgramInactiveException(program.id)
# Check if enough stamps
if card.stamp_count < program.stamps_target:
raise InsufficientStampsException(card.stamp_count, program.stamps_target)
# Verify staff PIN if required
verified_pin = None
if program.require_staff_pin:
@@ -255,6 +251,10 @@ class StampService:
# Re-fetch with row lock to prevent concurrent modification
card = card_service.get_card_for_update(db, card.id)
# Check stamp count AFTER acquiring lock to prevent TOCTOU race
if card.stamp_count < program.stamps_target:
raise InsufficientStampsException(card.stamp_count, program.stamps_target)
# Redeem stamps
now = datetime.now(UTC)
stamps_redeemed = program.stamps_target