Spaces:
Running on T4
Running on T4
Download backend/tests/unit/test_billing_app_store.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 6.9 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/tests/unit/test_billing_app_store.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/backend/tests/unit/test_billing_app_store.py
-
curl -L -o test_billing_app_store.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/tests/unit/test_billing_app_store.py
6.9 kB
| """Real JWS chain verification against a locally generated CA (injected as the trusted root).""" | |
| import base64 | |
| from datetime import UTC, datetime, timedelta | |
| import jwt | |
| import pytest | |
| from cryptography import x509 | |
| from cryptography.hazmat.primitives import hashes, serialization | |
| from cryptography.hazmat.primitives.asymmetric import ec | |
| from cryptography.x509.oid import NameOID | |
| from app.integrations.app_store import ( | |
| APPLE_ROOT_CA_G3_SHA256, | |
| INTERMEDIATE_MARKER_OID, | |
| LEAF_MARKER_OID, | |
| AppStoreClient, | |
| InvalidSignedData, | |
| JwsVerifier, | |
| get_app_store, | |
| ) | |
| NOW = datetime.now(UTC) | |
| BUNDLE = "com.example.app" | |
| def _cert(subject: str, key, issuer_cert, issuer_key, *, ca: bool, marker=None, not_after=None): | |
| name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, subject)]) | |
| builder = (x509.CertificateBuilder() | |
| .subject_name(name) | |
| .issuer_name(issuer_cert.subject if issuer_cert else name) | |
| .public_key(key.public_key()) | |
| .serial_number(x509.random_serial_number()) | |
| .not_valid_before(NOW - timedelta(days=1)) | |
| .not_valid_after(not_after or NOW + timedelta(days=365)) | |
| .add_extension(x509.BasicConstraints(ca=ca, path_length=None), critical=True)) | |
| if marker is not None: | |
| builder = builder.add_extension(x509.UnrecognizedExtension(marker, b"\x05\x00"), critical=False) | |
| return builder.sign(issuer_key or key, hashes.SHA256()) | |
| class Pki: | |
| def __init__(self, *, leaf_marker=LEAF_MARKER_OID, leaf_not_after=None): | |
| self.root_key = ec.generate_private_key(ec.SECP384R1()) | |
| self.root = _cert("Test Root", self.root_key, None, None, ca=True) | |
| self.int_key = ec.generate_private_key(ec.SECP384R1()) | |
| self.intermediate = _cert("Test Intermediate", self.int_key, self.root, self.root_key, ca=True, | |
| marker=INTERMEDIATE_MARKER_OID) | |
| self.leaf_key = ec.generate_private_key(ec.SECP256R1()) | |
| self.leaf = _cert("Test Leaf", self.leaf_key, self.intermediate, self.int_key, ca=False, | |
| marker=leaf_marker, not_after=leaf_not_after) | |
| def x5c(self) -> list[str]: | |
| return [base64.b64encode(c.public_bytes(serialization.Encoding.DER)).decode() | |
| for c in (self.leaf, self.intermediate, self.root)] | |
| def sign(self, payload: dict, *, x5c: list[str] | None = None) -> str: | |
| return jwt.encode(payload, self.leaf_key, algorithm="ES256", headers={"x5c": x5c or self.x5c()}) | |
| def _tx(**overrides) -> dict: | |
| return {"bundleId": BUNDLE, "environment": "Sandbox", "originalTransactionId": "2000000111", | |
| "transactionId": "2000000222", "productId": "pro_monthly", "type": "Auto-Renewable Subscription", | |
| "expiresDate": int((NOW + timedelta(days=30)).timestamp() * 1000), **overrides} | |
| def _client(pki: Pki) -> AppStoreClient: | |
| return AppStoreClient(bundle_id=BUNDLE, environment="Sandbox", verifier=JwsVerifier(pki.root)) | |
| def test_valid_transaction_is_decoded(): | |
| pki = Pki() | |
| tx = _client(pki).verify_signed_transaction(pki.sign(_tx(revocationDate=1_700_000_000_000))) | |
| assert tx.original_transaction_id == "2000000111" | |
| assert tx.product_id == "pro_monthly" | |
| assert abs((tx.expires_at - (NOW + timedelta(days=30))).total_seconds()) < 1 | |
| assert tx.revoked_at == datetime.fromtimestamp(1_700_000_000, UTC) | |
| def test_chain_from_another_root_is_rejected(): | |
| pki, other = Pki(), Pki() | |
| with pytest.raises(InvalidSignedData): | |
| _client(other).verify_signed_transaction(pki.sign(_tx())) | |
| def test_forged_root_in_header_is_rejected(): | |
| pki, attacker = Pki(), Pki() | |
| # Attacker's leaf and intermediate, with the trusted root appended to the header. | |
| forged = attacker.x5c()[:2] + [pki.x5c()[2]] | |
| with pytest.raises(InvalidSignedData): | |
| _client(pki).verify_signed_transaction(attacker.sign(_tx(), x5c=forged)) | |
| def test_tampered_payload_is_rejected(): | |
| pki = Pki() | |
| header, _, signature = pki.sign(_tx()).split(".") | |
| other_payload = pki.sign(_tx(productId="pro_yearly")).split(".")[1] | |
| with pytest.raises(InvalidSignedData): | |
| _client(pki).verify_signed_transaction(f"{header}.{other_payload}.{signature}") | |
| def test_non_es256_algorithm_is_rejected(): | |
| pki = Pki() | |
| token = jwt.encode(_tx(), "secret-secret-secret-secret-secret", algorithm="HS256", headers={"x5c": pki.x5c()}) | |
| with pytest.raises(InvalidSignedData): | |
| _client(pki).verify_signed_transaction(token) | |
| def test_wrong_app_or_missing_fields_are_rejected(overrides): | |
| pki = Pki() | |
| with pytest.raises(InvalidSignedData): | |
| _client(pki).verify_signed_transaction(pki.sign(_tx(**overrides))) | |
| def test_leaf_without_apple_marker_is_rejected(): | |
| pki = Pki(leaf_marker=None) | |
| with pytest.raises(InvalidSignedData): | |
| _client(pki).verify_signed_transaction(pki.sign(_tx())) | |
| def test_expired_leaf_is_rejected(): | |
| pki = Pki(leaf_not_after=NOW - timedelta(minutes=1)) | |
| with pytest.raises(InvalidSignedData): | |
| _client(pki).verify_signed_transaction(pki.sign(_tx())) | |
| def test_garbage_is_rejected(): | |
| pki = Pki() | |
| for token in ("", "not-a-jws", "a.b.c"): | |
| with pytest.raises(InvalidSignedData): | |
| _client(pki).verify_signed_transaction(token) | |
| def test_notification_decodes_nested_transaction_and_grace_period(): | |
| pki = Pki() | |
| grace = int((NOW + timedelta(days=40)).timestamp() * 1000) | |
| payload = {"notificationType": "DID_FAIL_TO_RENEW", "subtype": "GRACE_PERIOD", "data": { | |
| "bundleId": BUNDLE, "environment": "Sandbox", | |
| "signedTransactionInfo": pki.sign(_tx()), | |
| "signedRenewalInfo": pki.sign({"originalTransactionId": "2000000111", "gracePeriodExpiresDate": grace}), | |
| }} | |
| note = _client(pki).decode_notification(pki.sign(payload)) | |
| assert (note.type, note.subtype) == ("DID_FAIL_TO_RENEW", "GRACE_PERIOD") | |
| assert note.transaction.original_transaction_id == "2000000111" | |
| assert note.grace_period_expires_at == datetime.fromtimestamp(grace / 1000, UTC) | |
| def test_notification_with_nested_transaction_from_another_root_is_rejected(): | |
| pki, other = Pki(), Pki() | |
| payload = {"notificationType": "DID_RENEW", | |
| "data": {"bundleId": BUNDLE, "environment": "Sandbox", "signedTransactionInfo": other.sign(_tx())}} | |
| with pytest.raises(InvalidSignedData): | |
| _client(pki).decode_notification(pki.sign(payload)) | |
| def test_embedded_apple_root_matches_pinned_fingerprint(): | |
| client = get_app_store() | |
| assert client.verifier.root_fingerprint.hex() == APPLE_ROOT_CA_G3_SHA256 | |
| assert client.verifier.root.subject.rfc4514_string().endswith("CN=Apple Root CA - G3") | |