Coverage for notifications/apns_sender.py: 94.37%

110 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 17:31 +0000

1"""APNs sender — native iOS push (SB-1236). 

2 

3Token-based auth: an ES256 provider JWT signed with the .p8 key from the 

4Apple developer account, sent over HTTP/2 (httpx + h2). Apple rejects a 

5provider token older than an hour and throttles one refreshed more often 

6than every 20 minutes, so it is cached and reused for 50. 

7 

8Env: 

9 APNS_KEY_ID — 10-char key id (JWT `kid`) 

10 APNS_TEAM_ID — 10-char team id (JWT `iss`) 

11 APNS_PRIVATE_KEY — PEM contents of the .p8, or 

12 APNS_PRIVATE_KEY_PATH — path to the .p8 

13 APNS_BUNDLE_ID — apns-topic; defaults to com.missingtable 

14 

15Mirrors web_push_sender: never raises, returns the same SendResult, and 

16reports tokens APNs says are gone as STATUS_EXPIRED so the caller deletes them. 

17""" 

18 

19from __future__ import annotations 

20 

21import json 

22import os 

23import threading 

24import time 

25from typing import Any 

26 

27import httpx 

28import structlog 

29 

30from notifications.web_push_sender import ( 

31 STATUS_EXPIRED, 

32 STATUS_FAILED, 

33 STATUS_SENT, 

34 SendResult, 

35) 

36 

37logger = structlog.get_logger(__name__) 

38 

39DEFAULT_BUNDLE_ID = "com.missingtable" 

40 

41HOST_SANDBOX = "api.sandbox.push.apple.com" 

42HOST_PRODUCTION = "api.push.apple.com" 

43 

44# Reuse the provider token for 50 minutes (Apple: < 60, refresh >= 20). 

45TOKEN_TTL_SECONDS = 50 * 60 

46 

47# apns-collapse-id is capped at 64 bytes by APNs. 

48COLLAPSE_ID_MAX_BYTES = 64 

49 

50# 400 reasons meaning "this token will never work here" — drop the device. 

51# Unregistered normally arrives as 410, which is expired regardless of reason. 

52_EXPIRED_REASONS = frozenset({"BadDeviceToken", "Unregistered", "DeviceTokenNotForTopic"}) 

53 

54# 403 reasons meaning our cached provider token is bad — mint a new one. 

55_PROVIDER_TOKEN_REASONS = frozenset({"ExpiredProviderToken", "InvalidProviderToken"}) 

56 

57_lock = threading.Lock() 

58_cached_token: tuple[str, float, tuple[str, str, str]] | None = None # (jwt, issued_at, config key) 

59_client: httpx.Client | None = None 

60 

61 

62def _private_key() -> str | None: 

63 """PEM from APNS_PRIVATE_KEY, else from the file at APNS_PRIVATE_KEY_PATH.""" 

64 pem = os.getenv("APNS_PRIVATE_KEY") 

65 if pem: 

66 # Secret stores often flatten newlines to a literal "\n". 

67 return pem.replace("\\n", "\n") 

68 path = os.getenv("APNS_PRIVATE_KEY_PATH") 

69 if path: 

70 try: 

71 with open(path) as fh: 

72 return fh.read() 

73 except OSError: 

74 return None 

75 return None 

76 

77 

78def is_configured() -> bool: 

79 """True if key id, team id and a private key are all available. Backend 

80 boots without them (APNs fan-out is a no-op until configured). 

81 """ 

82 return bool(os.getenv("APNS_KEY_ID") and os.getenv("APNS_TEAM_ID") and _private_key()) 

83 

84 

85def get_bundle_id() -> str: 

86 return os.getenv("APNS_BUNDLE_ID") or DEFAULT_BUNDLE_ID 

87 

88 

89def host_for(environment: str | None) -> str: 

90 """'production' → api.push.apple.com; anything else → sandbox.""" 

91 return HOST_PRODUCTION if environment == "production" else HOST_SANDBOX 

92 

93 

94def _provider_token(now: float | None = None) -> str: 

95 """ES256 provider JWT, cached for TOKEN_TTL_SECONDS. Raises if unconfigured.""" 

96 global _cached_token 

97 import jwt # PyJWT; lazy to keep the import surface tight at module load 

98 

99 now = time.time() if now is None else now 

100 key_id = os.environ["APNS_KEY_ID"] 

101 team_id = os.environ["APNS_TEAM_ID"] 

102 pem = _private_key() 

103 if not pem: 103 ↛ 104line 103 didn't jump to line 104 because the condition on line 103 was never true

104 raise RuntimeError("APNs private key not available") 

105 # A config change (key rotation) must not keep serving the old token. 

106 config_key = (key_id, team_id, pem) 

107 with _lock: 

108 if _cached_token is not None: 

109 token, issued_at, cached_key = _cached_token 

110 if cached_key == config_key and now - issued_at < TOKEN_TTL_SECONDS: 

111 return token 

112 token = jwt.encode( 

113 {"iss": team_id, "iat": int(now)}, 

114 pem, 

115 algorithm="ES256", 

116 headers={"kid": key_id}, 

117 ) 

118 _cached_token = (token, now, config_key) 

119 return token 

120 

121 

122def _invalidate_provider_token() -> None: 

123 global _cached_token 

124 with _lock: 

125 _cached_token = None 

126 

127 

128def _get_client() -> httpx.Client: 

129 """Process-wide HTTP/2 client. APNs wants connections reused, not reopened 

130 per notification. Created lazily so a forked worker builds its own. 

131 """ 

132 global _client 

133 with _lock: 

134 if _client is None: 

135 _client = httpx.Client(http2=True, timeout=10.0) 

136 return _client 

137 

138 

139def _collapse_id(tag: str | None) -> str | None: 

140 if not tag: 

141 return None 

142 encoded = tag.encode("utf-8")[:COLLAPSE_ID_MAX_BYTES] 

143 return encoded.decode("utf-8", errors="ignore") or None 

144 

145 

146def build_apns_payload(payload: dict[str, Any]) -> dict[str, Any]: 

147 """Map the Web Push payload (title/body/tag/data) to an APNs body. 

148 

149 aps.thread-id groups a match's notifications in Notification Center; 

150 matchId/eventType sit at the top level for the app's tap handler. 

151 """ 

152 data = payload.get("data") or {} 

153 aps: dict[str, Any] = { 

154 "alert": {"title": payload.get("title", ""), "body": payload.get("body", "")}, 

155 "sound": "default", 

156 } 

157 match_id = data.get("matchId") 

158 if match_id is not None: 

159 aps["thread-id"] = f"match-{match_id}" 

160 body: dict[str, Any] = {"aps": aps} 

161 if match_id is not None: 

162 body["matchId"] = match_id 

163 if data.get("eventType") is not None: 

164 body["eventType"] = data["eventType"] 

165 return body 

166 

167 

168def _reason(response: httpx.Response) -> str | None: 

169 try: 

170 return response.json().get("reason") 

171 except Exception: 

172 return None 

173 

174 

175def send_apns( 

176 device: dict[str, Any], 

177 payload: dict[str, Any], 

178 *, 

179 client: httpx.Client | None = None, 

180) -> SendResult: 

181 """Send a single APNs alert. Never raises. 

182 

183 device dict must include `device_token` and `environment`; `bundle_id` 

184 overrides APNS_BUNDLE_ID for the apns-topic. payload is the Web Push 

185 payload built by the dispatcher — see build_apns_payload. 

186 """ 

187 if not is_configured(): 

188 return SendResult(status=STATUS_FAILED, error="APNs not configured") 

189 

190 token = device.get("device_token") 

191 if not token: 

192 return SendResult(status=STATUS_FAILED, error="invalid device") 

193 

194 try: 

195 headers = { 

196 "authorization": f"bearer {_provider_token()}", 

197 "apns-topic": device.get("bundle_id") or get_bundle_id(), 

198 "apns-push-type": "alert", 

199 "apns-priority": "10", 

200 } 

201 collapse_id = _collapse_id(payload.get("tag")) 

202 if collapse_id: 

203 headers["apns-collapse-id"] = collapse_id 

204 

205 url = f"https://{host_for(device.get('environment'))}/3/device/{token}" 

206 response = (client or _get_client()).post( 

207 url, 

208 content=json.dumps(build_apns_payload(payload)), 

209 headers=headers, 

210 ) 

211 except Exception as exc: 

212 return SendResult(status=STATUS_FAILED, error=str(exc)) 

213 

214 http_status = response.status_code 

215 if http_status == 200: 

216 return SendResult(status=STATUS_SENT, http_status=http_status) 

217 

218 reason = _reason(response) 

219 error = reason or f"HTTP {http_status}" 

220 if http_status == 410 or (http_status == 400 and reason in _EXPIRED_REASONS): 

221 return SendResult(status=STATUS_EXPIRED, http_status=http_status, error=error) 

222 if http_status == 403 and reason in _PROVIDER_TOKEN_REASONS: 

223 # Next send mints a fresh provider token. 

224 _invalidate_provider_token() 

225 return SendResult(status=STATUS_FAILED, http_status=http_status, error=error)