Spaces:
Running on T4
Running on T4
Download backend/app/integrations/app_store.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 8.51 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/integrations/app_store.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/backend/app/integrations/app_store.py
-
curl -L -o app_store.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/integrations/app_store.py
8.51 kB
| """App Store: verifies StoreKit 2 signed transactions and App Store Server Notifications V2. | |
| Both are JWS (ES256) whose x5c header carries leaf, intermediate and root certificates. We trust only the | |
| embedded Apple Root CA - G3: the intermediate must be issued by it, the leaf by the intermediate, all three must | |
| be in their validity window, and the leaf/intermediate must carry Apple's marker OIDs (as Apple's own library checks). | |
| """ | |
| import base64 | |
| from dataclasses import dataclass | |
| from datetime import UTC, datetime | |
| from functools import lru_cache | |
| from typing import Any | |
| import jwt | |
| from cryptography import x509 | |
| from cryptography.exceptions import InvalidSignature | |
| from cryptography.hazmat.primitives import hashes | |
| from app.core.config import get_settings | |
| # https://www.apple.com/certificateauthority/AppleRootCA-G3.cer | |
| # SHA-256 63:34:3A:BF:B8:9A:6A:03:EB:B5:7E:9B:3F:5F:A7:BE:7C:4F:5C:75:6F:30:17:B3:A8:C4:88:C3:65:3E:91:79 | |
| APPLE_ROOT_CA_G3_PEM = b"""-----BEGIN CERTIFICATE----- | |
| MIICQzCCAcmgAwIBAgIILcX8iNLFS5UwCgYIKoZIzj0EAwMwZzEbMBkGA1UEAwwS | |
| QXBwbGUgUm9vdCBDQSAtIEczMSYwJAYDVQQLDB1BcHBsZSBDZXJ0aWZpY2F0aW9u | |
| IEF1dGhvcml0eTETMBEGA1UECgwKQXBwbGUgSW5jLjELMAkGA1UEBhMCVVMwHhcN | |
| MTQwNDMwMTgxOTA2WhcNMzkwNDMwMTgxOTA2WjBnMRswGQYDVQQDDBJBcHBsZSBS | |
| b290IENBIC0gRzMxJjAkBgNVBAsMHUFwcGxlIENlcnRpZmljYXRpb24gQXV0aG9y | |
| aXR5MRMwEQYDVQQKDApBcHBsZSBJbmMuMQswCQYDVQQGEwJVUzB2MBAGByqGSM49 | |
| AgEGBSuBBAAiA2IABJjpLz1AcqTtkyJygRMc3RCV8cWjTnHcFBbZDuWmBSp3ZHtf | |
| TjjTuxxEtX/1H7YyYl3J6YRbTzBPEVoA/VhYDKX1DyxNB0cTddqXl5dvMVztK517 | |
| IDvYuVTZXpmkOlEKMaNCMEAwHQYDVR0OBBYEFLuw3qFYM4iapIqZ3r6966/ayySr | |
| MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2gA | |
| MGUCMQCD6cHEFl4aXTQY2e3v9GwOAEZLuN+yRhHFD/3meoyhpmvOwgPUnPWTxnS4 | |
| at+qIxUCMG1mihDK1A3UT82NQz60imOlM27jbdoXt2QfyFMm+YhidDkLF1vLUagM | |
| 6BgD56KyKA== | |
| -----END CERTIFICATE----- | |
| """ | |
| APPLE_ROOT_CA_G3_SHA256 = "63343abfb89a6a03ebb57e9b3f5fa7be7c4f5c756f3017b3a8c488c3653e9179" | |
| LEAF_MARKER_OID = x509.ObjectIdentifier("1.2.840.113635.100.6.11.1") | |
| INTERMEDIATE_MARKER_OID = x509.ObjectIdentifier("1.2.840.113635.100.6.2.1") | |
| class InvalidSignedData(Exception): | |
| """The JWS is malformed, not signed by Apple, or not for this app/environment.""" | |
| class AppleTransaction: | |
| original_transaction_id: str | |
| product_id: str | |
| expires_at: datetime | None | |
| revoked_at: datetime | None | |
| class AppleNotification: | |
| type: str | |
| subtype: str | None | |
| transaction: AppleTransaction | None | |
| grace_period_expires_at: datetime | None | |
| def _ms(value: Any) -> datetime | None: | |
| if value is None: | |
| return None | |
| try: | |
| return datetime.fromtimestamp(int(value) / 1000, UTC) | |
| except (TypeError, ValueError, OverflowError) as exc: | |
| raise InvalidSignedData("bad date") from exc | |
| def _has_extension(cert: x509.Certificate, oid: x509.ObjectIdentifier) -> bool: | |
| try: | |
| cert.extensions.get_extension_for_oid(oid) | |
| return True | |
| except x509.ExtensionNotFound: | |
| return False | |
| class JwsVerifier: | |
| """Verifies an x5c-signed ES256 JWS against a pinned root and returns its payload.""" | |
| def __init__(self, trusted_root: x509.Certificate): | |
| self.root = trusted_root | |
| self.root_fingerprint = trusted_root.fingerprint(hashes.SHA256()) | |
| def verify(self, token: str, now: datetime | None = None) -> dict[str, Any]: | |
| now = now or datetime.now(UTC) | |
| try: | |
| header = jwt.get_unverified_header(token) | |
| except jwt.PyJWTError as exc: | |
| raise InvalidSignedData("malformed JWS") from exc | |
| if header.get("alg") != "ES256": | |
| raise InvalidSignedData("unexpected algorithm") | |
| chain = header.get("x5c") | |
| if not isinstance(chain, list) or not 2 <= len(chain) <= 3: | |
| raise InvalidSignedData("missing certificate chain") | |
| try: | |
| certs = [x509.load_der_x509_certificate(base64.b64decode(c, validate=True)) for c in chain] | |
| except (ValueError, TypeError) as exc: | |
| raise InvalidSignedData("bad certificate") from exc | |
| if len(certs) == 3: | |
| # The root in the header is informational; it must be our pinned root, which is what we verify against. | |
| if certs[2].fingerprint(hashes.SHA256()) != self.root_fingerprint: | |
| raise InvalidSignedData("untrusted root") | |
| leaf, intermediate = certs[0], certs[1] | |
| try: | |
| leaf.verify_directly_issued_by(intermediate) | |
| intermediate.verify_directly_issued_by(self.root) | |
| except (InvalidSignature, ValueError, TypeError) as exc: | |
| raise InvalidSignedData("certificate chain does not verify") from exc | |
| for cert in (leaf, intermediate, self.root): | |
| if not cert.not_valid_before_utc <= now <= cert.not_valid_after_utc: | |
| raise InvalidSignedData("certificate outside its validity period") | |
| try: | |
| is_ca = intermediate.extensions.get_extension_for_class(x509.BasicConstraints).value.ca | |
| except x509.ExtensionNotFound: | |
| is_ca = False | |
| if not is_ca: | |
| raise InvalidSignedData("intermediate is not a CA") | |
| if not _has_extension(leaf, LEAF_MARKER_OID) or not _has_extension(intermediate, INTERMEDIATE_MARKER_OID): | |
| raise InvalidSignedData("missing Apple marker extensions") | |
| try: | |
| payload = jwt.decode(token, leaf.public_key(), algorithms=["ES256"], | |
| options={"verify_aud": False, "verify_iss": False}) | |
| except jwt.PyJWTError as exc: | |
| raise InvalidSignedData("bad signature") from exc | |
| if not isinstance(payload, dict): | |
| raise InvalidSignedData("bad payload") | |
| return payload | |
| class AppStoreClient: | |
| def __init__(self, *, bundle_id: str, environment: str, verifier: JwsVerifier): | |
| self.bundle_id = bundle_id | |
| self.environment = environment | |
| self.verifier = verifier | |
| def _check_app(self, payload: dict[str, Any]) -> None: | |
| if not self.bundle_id or payload.get("bundleId") != self.bundle_id: | |
| raise InvalidSignedData("wrong bundle id") | |
| if payload.get("environment") != self.environment: | |
| raise InvalidSignedData("wrong environment") | |
| def verify_signed_transaction(self, signed_transaction: str) -> AppleTransaction: | |
| payload = self.verifier.verify(signed_transaction) | |
| self._check_app(payload) | |
| original_id, product_id = payload.get("originalTransactionId"), payload.get("productId") | |
| if not original_id or not product_id: | |
| raise InvalidSignedData("missing transaction fields") | |
| return AppleTransaction( | |
| original_transaction_id=str(original_id), | |
| product_id=str(product_id), | |
| expires_at=_ms(payload.get("expiresDate")), | |
| revoked_at=_ms(payload.get("revocationDate")), | |
| ) | |
| def decode_notification(self, signed_payload: str) -> AppleNotification: | |
| payload = self.verifier.verify(signed_payload) | |
| data = payload.get("data") | |
| if not isinstance(payload.get("notificationType"), str): | |
| raise InvalidSignedData("missing notification type") | |
| transaction, grace = None, None | |
| if isinstance(data, dict): | |
| self._check_app(data) | |
| if data.get("signedTransactionInfo"): | |
| transaction = self.verify_signed_transaction(data["signedTransactionInfo"]) | |
| if data.get("signedRenewalInfo") and transaction is not None: | |
| renewal = self.verifier.verify(data["signedRenewalInfo"]) | |
| if str(renewal.get("originalTransactionId")) != transaction.original_transaction_id: | |
| raise InvalidSignedData("renewal info does not match the transaction") | |
| grace = _ms(renewal.get("gracePeriodExpiresDate")) | |
| return AppleNotification(type=payload["notificationType"], subtype=payload.get("subtype"), | |
| transaction=transaction, grace_period_expires_at=grace) | |
| def get_app_store() -> AppStoreClient: | |
| settings = get_settings() | |
| root = x509.load_pem_x509_certificate(APPLE_ROOT_CA_G3_PEM) | |
| if root.fingerprint(hashes.SHA256()).hex() != APPLE_ROOT_CA_G3_SHA256: | |
| raise RuntimeError("embedded Apple root certificate does not match its pinned fingerprint") | |
| return AppStoreClient(bundle_id=settings.apple_bundle_id, environment=settings.apple_environment, | |
| verifier=JwsVerifier(root)) | |