Coverage for services/testflight_client.py: 88.72%
103 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:21 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:21 +0000
1"""App Store Connect client — TestFlight external beta testers (SB-1314).
3Admins tick "iPhone beta" on an invite; the backend adds the invitee to the
4external TestFlight group so Apple emails them a TestFlight invitation.
6Auth is an ES256 JWT signed with an App Store Connect API key (.p8), minted
7per operation — one invite makes at most three calls, so caching buys nothing.
9Env:
10 ASC_KEY_ID — API key id (JWT `kid`)
11 ASC_ISSUER_ID — issuer id from App Store Connect (JWT `iss`)
12 ASC_PRIVATE_KEY — PEM contents of the .p8 (literal "\\n" accepted)
13 ASC_EXTERNAL_GROUP_ID — the external beta group testers are added to
14 ASC_APP_ID — the app's Apple id; defaults to 6820504545
16Mirrors apns_sender: never raises, and is a no-op until configured.
17"""
19from __future__ import annotations
21import os
22import time
23from dataclasses import dataclass
25import httpx
26import structlog
28logger = structlog.get_logger(__name__)
30BASE_URL = "https://api.appstoreconnect.apple.com"
31DEFAULT_APP_ID = "6820504545"
33# Apple rejects a token whose lifetime exceeds 20 minutes.
34TOKEN_LIFETIME_SECONDS = 15 * 60
36# Called inline from the invite request: keep it short.
37TIMEOUT_SECONDS = 10.0
39STATUS_ADDED = "added"
40STATUS_FAILED = "failed"
41STATUS_REMOVED = "removed"
44@dataclass
45class TesterResult:
46 status: str
47 tester_id: str | None = None
48 error: str | None = None
51def _private_key() -> str | None:
52 pem = os.getenv("ASC_PRIVATE_KEY")
53 if not pem:
54 return None
55 # Secret stores often flatten newlines to a literal "\n".
56 return pem.replace("\\n", "\n")
59def is_configured() -> bool:
60 """True if key id, issuer id, private key and group id are all set.
61 The backend boots without them; iPhone beta invites then record a failure.
62 """
63 return bool(
64 os.getenv("ASC_KEY_ID") and os.getenv("ASC_ISSUER_ID") and _private_key() and os.getenv("ASC_EXTERNAL_GROUP_ID")
65 )
68def get_app_id() -> str:
69 return os.getenv("ASC_APP_ID") or DEFAULT_APP_ID
72def _group_id() -> str:
73 return os.environ["ASC_EXTERNAL_GROUP_ID"]
76def _token(now: float | None = None) -> str:
77 """ES256 JWT for the App Store Connect API. Raises if unconfigured."""
78 import jwt # PyJWT; lazy, as in apns_sender
80 now = time.time() if now is None else now
81 pem = _private_key()
82 if not pem: 82 ↛ 83line 82 didn't jump to line 83 because the condition on line 82 was never true
83 raise RuntimeError("App Store Connect private key not available")
84 return jwt.encode(
85 {
86 "iss": os.environ["ASC_ISSUER_ID"],
87 "iat": int(now),
88 "exp": int(now) + TOKEN_LIFETIME_SECONDS,
89 "aud": "appstoreconnect-v1",
90 },
91 pem,
92 algorithm="ES256",
93 headers={"kid": os.environ["ASC_KEY_ID"], "typ": "JWT"},
94 )
97def _headers() -> dict[str, str]:
98 return {"Authorization": f"Bearer {_token()}", "Content-Type": "application/json"}
101def _error(response: httpx.Response) -> str:
102 """First error detail from an ASC error body, else the HTTP status."""
103 try:
104 errors = response.json().get("errors") or []
105 if errors: 105 ↛ 110line 105 didn't jump to line 110 because the condition on line 105 was always true
106 first = errors[0]
107 return f"HTTP {response.status_code}: {first.get('detail') or first.get('title') or first.get('code')}"
108 except Exception:
109 pass
110 return f"HTTP {response.status_code}"
113def _group_membership_body(tester_id: str) -> dict:
114 return {"data": [{"type": "betaTesters", "id": tester_id}]}
117def _find_tester_id(client: httpx.Client, email: str) -> str | None:
118 response = client.get(
119 f"{BASE_URL}/v1/betaTesters",
120 params={"filter[email]": email},
121 headers=_headers(),
122 )
123 if response.status_code != 200: 123 ↛ 124line 123 didn't jump to line 124 because the condition on line 123 was never true
124 raise RuntimeError(f"tester lookup failed: {_error(response)}")
125 data = response.json().get("data") or []
126 return data[0]["id"] if data else None
129def add_tester(
130 email: str,
131 first_name: str | None = None,
132 last_name: str | None = None,
133 *,
134 client: httpx.Client | None = None,
135) -> TesterResult:
136 """Add `email` to the external TestFlight group. Never raises.
138 Creates the tester with the group relationship; if Apple says the tester
139 already exists (409), looks them up by email and adds them to the group,
140 so re-inviting someone — or retrying — is safe.
141 """
142 if not is_configured():
143 return TesterResult(status=STATUS_FAILED, error="App Store Connect not configured")
144 if not email: 144 ↛ 145line 144 didn't jump to line 145 because the condition on line 144 was never true
145 return TesterResult(status=STATUS_FAILED, error="no TestFlight email")
147 group_id = _group_id()
148 attributes = {"email": email}
149 if first_name:
150 attributes["firstName"] = first_name
151 if last_name:
152 attributes["lastName"] = last_name
153 body = {
154 "data": {
155 "type": "betaTesters",
156 "attributes": attributes,
157 "relationships": {"betaGroups": {"data": [{"type": "betaGroups", "id": group_id}]}},
158 }
159 }
161 own_client = client is None
162 http = client or httpx.Client(timeout=TIMEOUT_SECONDS)
163 try:
164 response = http.post(f"{BASE_URL}/v1/betaTesters", json=body, headers=_headers())
165 if response.status_code in (200, 201):
166 tester_id = (response.json().get("data") or {}).get("id")
167 return TesterResult(status=STATUS_ADDED, tester_id=tester_id)
168 if response.status_code != 409:
169 return TesterResult(status=STATUS_FAILED, error=_error(response))
171 tester_id = _find_tester_id(http, email)
172 if not tester_id:
173 return TesterResult(status=STATUS_FAILED, error="tester exists but lookup by email found none")
174 added = http.post(
175 f"{BASE_URL}/v1/betaGroups/{group_id}/relationships/betaTesters",
176 json=_group_membership_body(tester_id),
177 headers=_headers(),
178 )
179 if added.status_code in (200, 201, 204): 179 ↛ 181line 179 didn't jump to line 181 because the condition on line 179 was always true
180 return TesterResult(status=STATUS_ADDED, tester_id=tester_id)
181 return TesterResult(status=STATUS_FAILED, tester_id=tester_id, error=_error(added))
182 except Exception as exc:
183 return TesterResult(status=STATUS_FAILED, error=str(exc))
184 finally:
185 if own_client:
186 http.close()
189def remove_tester(tester_id: str, *, client: httpx.Client | None = None) -> TesterResult:
190 """Remove a tester from the external group. Never raises."""
191 if not is_configured():
192 return TesterResult(status=STATUS_FAILED, tester_id=tester_id, error="App Store Connect not configured")
193 if not tester_id: 193 ↛ 194line 193 didn't jump to line 194 because the condition on line 193 was never true
194 return TesterResult(status=STATUS_FAILED, error="no tester id")
196 own_client = client is None
197 http = client or httpx.Client(timeout=TIMEOUT_SECONDS)
198 try:
199 # httpx.delete() takes no body; request() does.
200 response = http.request(
201 "DELETE",
202 f"{BASE_URL}/v1/betaGroups/{_group_id()}/relationships/betaTesters",
203 json=_group_membership_body(tester_id),
204 headers=_headers(),
205 )
206 if response.status_code in (200, 204):
207 return TesterResult(status=STATUS_REMOVED, tester_id=tester_id)
208 return TesterResult(status=STATUS_FAILED, tester_id=tester_id, error=_error(response))
209 except Exception as exc:
210 return TesterResult(status=STATUS_FAILED, tester_id=tester_id, error=str(exc))
211 finally:
212 if own_client:
213 http.close()