feat(loyalty): Phase 1 production launch hardening
Some checks failed
CI / ruff (push) Successful in 18s
CI / pytest (push) Failing after 2h37m39s
CI / validate (push) Successful in 30s
CI / dependency-scanning (push) Successful in 32s
CI / docs (push) Has been skipped
CI / deploy (push) Has been skipped

Phase 1 of the loyalty production launch plan: config & security
hardening, dropped-data fix, DB integrity guards, rate limiting, and
constant-time auth compare. 362 tests pass.

- 1.4 Persist customer birth_date (new column + migration). Enrollment
  form was collecting it but the value was silently dropped because
  create_customer_for_enrollment never received it. Backfills existing
  customers without overwriting.
- 1.1 LOYALTY_GOOGLE_SERVICE_ACCOUNT_JSON validated at startup (file
  must exist and be readable; ~ expanded). Adds is_google_wallet_enabled
  and is_apple_wallet_enabled derived flags. Prod path documented as
  ~/apps/orion/google-wallet-sa.json.
- 1.5 CHECK constraints on loyalty_cards (points_balance, stamp_count
  non-negative) and loyalty_programs (min_purchase, points_per_euro,
  welcome_bonus non-negative; stamps_target >= 1). Mirrored as
  CheckConstraint in models. Pre-flight scan showed zero violations.
- 1.3 @rate_limit on store mutating endpoints: stamp 60/min,
  redeem/points-earn 30-60/min, void/adjust 20/min, pin unlock 10/min.
- 1.2 Constant-time hmac.compare_digest for Apple Wallet auth token
  (pulled forward from Phase 9 — code is safe whenever Apple ships).

See app/modules/loyalty/docs/production-launch-plan.md for the full
launch plan and remaining phases.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-09 23:36:34 +02:00
parent 27ac7f3e28
commit 4b56eb7ab1
20 changed files with 848 additions and 12 deletions

View File

@@ -2,9 +2,17 @@
import pytest
from app.modules.loyalty.exceptions import InvalidAppleAuthTokenException
from app.modules.loyalty.services.apple_wallet_service import AppleWalletService
class _FakeCard:
"""Lightweight card stub for verify_auth_token tests."""
def __init__(self, token: str | None) -> None:
self.apple_auth_token = token
@pytest.mark.unit
@pytest.mark.loyalty
class TestAppleWalletService:
@@ -16,3 +24,38 @@ class TestAppleWalletService:
def test_service_instantiation(self):
"""Service can be instantiated."""
assert self.service is not None
@pytest.mark.unit
@pytest.mark.loyalty
class TestVerifyAuthToken:
"""verify_auth_token must be constant-time and handle missing tokens."""
def setup_method(self):
self.service = AppleWalletService()
def test_correct_token_passes(self):
card = _FakeCard("correct-token-abc123")
# Should not raise
self.service.verify_auth_token(card, "ApplePass correct-token-abc123")
def test_wrong_token_raises(self):
card = _FakeCard("correct-token-abc123")
with pytest.raises(InvalidAppleAuthTokenException):
self.service.verify_auth_token(card, "ApplePass wrong-token-xyz")
def test_missing_authorization_header_raises(self):
card = _FakeCard("correct-token-abc123")
with pytest.raises(InvalidAppleAuthTokenException):
self.service.verify_auth_token(card, None)
def test_malformed_authorization_header_raises(self):
card = _FakeCard("correct-token-abc123")
with pytest.raises(InvalidAppleAuthTokenException):
self.service.verify_auth_token(card, "Bearer correct-token-abc123")
def test_card_with_no_stored_token_raises(self):
"""A card that never enrolled in Apple Wallet has no token to compare."""
card = _FakeCard(None)
with pytest.raises(InvalidAppleAuthTokenException):
self.service.verify_auth_token(card, "ApplePass anything")

View File

@@ -233,6 +233,80 @@ class TestResolveCustomerId:
db, customer_id=None, email=None, store_id=test_store.id
)
def test_resolve_persists_birthday_on_create(self, db, test_store):
"""Birthday provided at self-enrollment is saved on the new customer."""
from datetime import date
email = f"birthday-create-{uuid.uuid4().hex[:8]}@test.com"
result = self.service.resolve_customer_id(
db,
customer_id=None,
email=email,
store_id=test_store.id,
create_if_missing=True,
customer_name="Anna Test",
customer_birthday=date(1992, 6, 15),
)
customer = db.query(Customer).filter(Customer.id == result).first()
assert customer.birth_date == date(1992, 6, 15)
def test_resolve_backfills_birthday_on_existing_customer(
self, db, test_store
):
"""An existing customer without a birthday is backfilled from form."""
from datetime import date
email = f"backfill-{uuid.uuid4().hex[:8]}@test.com"
# Pre-create a customer with no birth_date
existing = self.service.resolve_customer_id(
db,
customer_id=None,
email=email,
store_id=test_store.id,
create_if_missing=True,
customer_name="No Birthday",
)
customer = db.query(Customer).filter(Customer.id == existing).first()
assert customer.birth_date is None
# Re-enroll with birthday — should backfill
self.service.resolve_customer_id(
db,
customer_id=None,
email=email,
store_id=test_store.id,
create_if_missing=True,
customer_birthday=date(1985, 3, 22),
)
db.refresh(customer)
assert customer.birth_date == date(1985, 3, 22)
def test_resolve_does_not_overwrite_existing_birthday(self, db, test_store):
"""Birthday already on the customer is not overwritten by form input."""
from datetime import date
email = f"no-overwrite-{uuid.uuid4().hex[:8]}@test.com"
# Create with original birthday
cid = self.service.resolve_customer_id(
db,
customer_id=None,
email=email,
store_id=test_store.id,
create_if_missing=True,
customer_birthday=date(1990, 1, 1),
)
# Re-enroll with a different birthday
self.service.resolve_customer_id(
db,
customer_id=None,
email=email,
store_id=test_store.id,
create_if_missing=True,
customer_birthday=date(2000, 1, 1),
)
customer = db.query(Customer).filter(Customer.id == cid).first()
assert customer.birth_date == date(1990, 1, 1)
@pytest.mark.unit
@pytest.mark.loyalty

View File

@@ -0,0 +1,99 @@
"""Tests for loyalty module configuration validators."""
import os
import pytest
from app.modules.loyalty.config import ModuleConfig
@pytest.mark.unit
@pytest.mark.loyalty
class TestGoogleWalletConfigValidator:
"""Validator must fail fast when the SA path is set but unreachable."""
def test_unset_path_is_allowed(self, monkeypatch):
"""Google Wallet config is optional — None passes."""
monkeypatch.delenv("LOYALTY_GOOGLE_SERVICE_ACCOUNT_JSON", raising=False)
monkeypatch.delenv("LOYALTY_GOOGLE_ISSUER_ID", raising=False)
cfg = ModuleConfig(_env_file=None)
assert cfg.google_service_account_json is None
assert cfg.is_google_wallet_enabled is False
def test_existing_file_passes(self, tmp_path, monkeypatch):
"""A real file path passes and is returned expanded."""
sa_file = tmp_path / "fake-sa.json"
sa_file.write_text("{}")
monkeypatch.setenv("LOYALTY_GOOGLE_SERVICE_ACCOUNT_JSON", str(sa_file))
monkeypatch.setenv("LOYALTY_GOOGLE_ISSUER_ID", "1234567890")
cfg = ModuleConfig(_env_file=None)
assert cfg.google_service_account_json == str(sa_file)
assert cfg.is_google_wallet_enabled is True
def test_missing_file_raises(self, tmp_path, monkeypatch):
"""A path that does not exist raises a clear error at import time."""
bogus = tmp_path / "does-not-exist.json"
monkeypatch.setenv("LOYALTY_GOOGLE_SERVICE_ACCOUNT_JSON", str(bogus))
with pytest.raises(ValueError, match="no file exists"):
ModuleConfig(_env_file=None)
def test_unreadable_file_raises(self, tmp_path, monkeypatch):
"""A path that exists but is not readable raises a clear error."""
sa_file = tmp_path / "no-read.json"
sa_file.write_text("{}")
os.chmod(sa_file, 0o000)
try:
monkeypatch.setenv(
"LOYALTY_GOOGLE_SERVICE_ACCOUNT_JSON", str(sa_file)
)
# Skip if running as root (root bypasses unix file perms)
if os.geteuid() == 0:
pytest.skip("Cannot test unreadable file as root")
with pytest.raises(ValueError, match="not readable"):
ModuleConfig(_env_file=None)
finally:
os.chmod(sa_file, 0o600)
def test_tilde_path_is_expanded(self, tmp_path, monkeypatch):
"""Leading ~ is expanded so deployments can use ~/apps/orion/..."""
# Plant the file at $HOME/.../fake-sa.json then reference via ~
home = tmp_path / "home"
home.mkdir()
sa_dir = home / "apps" / "orion"
sa_dir.mkdir(parents=True)
sa_file = sa_dir / "fake-sa.json"
sa_file.write_text("{}")
monkeypatch.setenv("HOME", str(home))
monkeypatch.setenv(
"LOYALTY_GOOGLE_SERVICE_ACCOUNT_JSON",
"~/apps/orion/fake-sa.json",
)
cfg = ModuleConfig(_env_file=None)
assert cfg.google_service_account_json == str(sa_file)
@pytest.mark.unit
@pytest.mark.loyalty
class TestAppleWalletEnabledFlag:
"""is_apple_wallet_enabled is a derived flag for the storefront UI."""
def test_disabled_when_unset(self, monkeypatch):
for var in (
"LOYALTY_APPLE_PASS_TYPE_ID",
"LOYALTY_APPLE_TEAM_ID",
"LOYALTY_APPLE_WWDR_CERT_PATH",
"LOYALTY_APPLE_SIGNER_CERT_PATH",
"LOYALTY_APPLE_SIGNER_KEY_PATH",
):
monkeypatch.delenv(var, raising=False)
cfg = ModuleConfig(_env_file=None)
assert cfg.is_apple_wallet_enabled is False
def test_enabled_when_all_set(self, monkeypatch):
monkeypatch.setenv("LOYALTY_APPLE_PASS_TYPE_ID", "pass.com.x.y")
monkeypatch.setenv("LOYALTY_APPLE_TEAM_ID", "ABCD1234")
monkeypatch.setenv("LOYALTY_APPLE_WWDR_CERT_PATH", "/tmp/wwdr.pem")
monkeypatch.setenv("LOYALTY_APPLE_SIGNER_CERT_PATH", "/tmp/signer.pem")
monkeypatch.setenv("LOYALTY_APPLE_SIGNER_KEY_PATH", "/tmp/signer.key")
cfg = ModuleConfig(_env_file=None)
assert cfg.is_apple_wallet_enabled is True

View File

@@ -32,6 +32,8 @@ class TestCardEnrollRequest:
def test_self_enrollment_fields(self):
"""Self-enrollment accepts name, phone, birthday."""
from datetime import date
req = CardEnrollRequest(
email="self@example.com",
customer_name="Jane Doe",
@@ -40,7 +42,36 @@ class TestCardEnrollRequest:
)
assert req.customer_name == "Jane Doe"
assert req.customer_phone == "+352123456"
assert req.customer_birthday == "1990-01-15"
assert req.customer_birthday == date(1990, 1, 15)
def test_birthday_in_future_rejected(self):
"""Future birthdays are rejected."""
from datetime import date, timedelta
import pytest
from pydantic import ValidationError
with pytest.raises(ValidationError, match="must be in the past"):
CardEnrollRequest(
email="self@example.com",
customer_birthday=(date.today() + timedelta(days=1)).isoformat(),
)
def test_birthday_implausible_age_rejected(self):
"""Birthdays implying impossible ages are rejected."""
import pytest
from pydantic import ValidationError
with pytest.raises(ValidationError, match="implausible age"):
CardEnrollRequest(
email="self@example.com",
customer_birthday="1800-01-01",
)
def test_birthday_omitted_is_valid(self):
"""Birthday is optional."""
req = CardEnrollRequest(email="self@example.com")
assert req.customer_birthday is None
@pytest.mark.unit