File size: 6,895 Bytes
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
"""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)


@pytest.mark.parametrize("overrides", [{"bundleId": "com.other.app"}, {"environment": "Production"},
                                       {"originalTransactionId": None}])
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")