Coverage for notifications/fcm_sender.py: 96.44%

197 statements  

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

1"""FCM sender — native Android push (SB-1463). 

2 

3Firebase Cloud Messaging HTTP v1. Auth is a Google service account: we sign 

4an RS256 JWT with its private key, exchange it at the token endpoint for an 

5OAuth2 access token (OAuth 2.0 JWT bearer grant), and send with that. The 

6access token lasts an hour; it is cached and refreshed 5 minutes early. No 

7google-auth dependency — PyJWT + httpx are already here for APNs. 

8 

9Devices are addressed by Firebase Installation ID (Message.fid); FCM v1 has 

10deprecated Message.token in its favour. 

11 

12Env: 

13 FCM_SERVICE_ACCOUNT_JSON — the service-account key JSON, or 

14 FCM_SERVICE_ACCOUNT_PATH — path to that JSON file 

15 

16Mirrors apns_sender: never raises, returns the same SendResult, and reports 

17installations FCM says are gone as STATUS_EXPIRED so the caller deletes them. 

18Never logs or returns the service-account key or any token. 

19""" 

20 

21from __future__ import annotations 

22 

23import json 

24import os 

25import re 

26import threading 

27import time 

28from typing import Any 

29 

30import httpx 

31import structlog 

32 

33from notifications.web_push_sender import ( 

34 STATUS_EXPIRED, 

35 STATUS_FAILED, 

36 STATUS_SENT, 

37 SendResult, 

38) 

39 

40logger = structlog.get_logger(__name__) 

41 

42SCOPE = "https://www.googleapis.com/auth/firebase.messaging" 

43DEFAULT_TOKEN_URI = "https://oauth2.googleapis.com/token" 

44SEND_URL = "https://fcm.googleapis.com/v1/projects/{project_id}/messages:send" 

45GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer" 

46 

47# Lifetime of the signed assertion (Google's maximum). 

48ASSERTION_TTL_SECONDS = 60 * 60 

49 

50# Mint a new access token this long before the current one expires. 

51REFRESH_MARGIN_SECONDS = 5 * 60 

52 

53# After a failed token exchange, don't try again for this long — a fan-out 

54# would otherwise re-sign and re-POST once per device. 

55FAILED_EXCHANGE_BACKOFF_SECONDS = 30 

56 

57# How long FCM holds a message for an offline device. Same rationale as 

58# web_push_sender: a goal that arrives 5 minutes late is just noise. 

59MESSAGE_TTL = "60s" 

60 

61# Android notification channel the app creates for live-match alerts. 

62CHANNEL_ID = "live_scores" 

63 

64# FcmError.errorCode values meaning "this installation will never work here". 

65# SENDER_ID_MISMATCH is deliberately absent: it means our credentials or 

66# project are wrong, and pruning on it would wipe every device. 

67_EXPIRED_ERROR_CODES = frozenset({"UNREGISTERED", "UNREGISTERED_FID"}) 

68 

69# An INVALID_ARGUMENT only means a dead device when it names the address. 

70_DEVICE_ARGUMENT_RE = re.compile(r"registration token|installation id|\bfid\b", re.IGNORECASE) 

71 

72_REQUIRED_FIELDS = ("project_id", "client_email", "private_key") 

73 

74# _lock guards the cache only — never held across network I/O. 

75_lock = threading.Lock() 

76# Serialises refreshes so only one thread exchanges at a time. 

77_refresh_lock = threading.Lock() 

78_client_lock = threading.Lock() 

79# (access_token, expires_at, config key) 

80_cached_token: tuple[str, float, tuple[str, str]] | None = None 

81# (retry_after, config key) after a failed exchange 

82_failed_exchange: tuple[float, tuple[str, str]] | None = None 

83_client: httpx.Client | None = None 

84_warned_misconfigured = False 

85 

86 

87def _warn_misconfigured(source: str, reason: str) -> None: 

88 """One warning per process when FCM env is set but unusable. Never logs the value.""" 

89 global _warned_misconfigured 

90 if _warned_misconfigured: 

91 return 

92 _warned_misconfigured = True 

93 logger.warning("fcm.misconfigured", source=source, reason=reason) 

94 

95 

96def _service_account() -> dict[str, Any] | None: 

97 """Parsed service account from FCM_SERVICE_ACCOUNT_JSON, else the file at 

98 FCM_SERVICE_ACCOUNT_PATH. None unless it parses and has the fields we need. 

99 Silent when neither is set. 

100 """ 

101 source = "FCM_SERVICE_ACCOUNT_JSON" 

102 raw = os.getenv(source) 

103 if not raw: 

104 source = "FCM_SERVICE_ACCOUNT_PATH" 

105 path = os.getenv(source) 

106 if not path: 

107 return None 

108 try: 

109 with open(path) as fh: 

110 raw = fh.read() 

111 except (OSError, ValueError): 

112 _warn_misconfigured(source, "unreadable") 

113 return None 

114 try: 

115 # strict=False: secret stores sometimes turn "\n" escapes into raw newlines. 

116 info = json.loads(raw, strict=False) 

117 except ValueError: 

118 _warn_misconfigured(source, "invalid_json") 

119 return None 

120 if not isinstance(info, dict) or not all(isinstance(info.get(f), str) and info.get(f) for f in _REQUIRED_FIELDS): 

121 _warn_misconfigured(source, "missing_fields") 

122 return None 

123 # Secret stores sometimes double-escape, leaving a literal "\n" in the PEM. 

124 info["private_key"] = info["private_key"].replace("\\n", "\n") 

125 return info 

126 

127 

128def is_configured() -> bool: 

129 """True if a usable service account is available. Backend boots without 

130 one (FCM fan-out is a no-op until configured). 

131 """ 

132 return _service_account() is not None 

133 

134 

135def _get_client() -> httpx.Client: 

136 """Process-wide HTTP client, created lazily so a forked worker builds its own.""" 

137 global _client 

138 with _client_lock: 

139 if _client is None: 

140 _client = httpx.Client(timeout=10.0) 

141 return _client 

142 

143 

144def _sign_assertion(info: dict[str, Any], token_uri: str, now: float) -> str: 

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

146 

147 claims = { 

148 "iss": info["client_email"], 

149 "scope": SCOPE, 

150 "aud": token_uri, 

151 "iat": int(now), 

152 "exp": int(now) + ASSERTION_TTL_SECONDS, 

153 } 

154 headers = {"kid": info["private_key_id"]} if info.get("private_key_id") else None 

155 return jwt.encode(claims, info["private_key"], algorithm="RS256", headers=headers) 

156 

157 

158def _exchange(info: dict[str, Any], client: httpx.Client, now: float) -> tuple[str, float]: 

159 """One JWT-bearer exchange. Returns (access_token, expires_at); raises on failure.""" 

160 token_uri = info.get("token_uri") or DEFAULT_TOKEN_URI 

161 assertion = _sign_assertion(info, token_uri, now) 

162 response = client.post( 

163 token_uri, 

164 data={"grant_type": GRANT_TYPE, "assertion": assertion}, 

165 ) 

166 try: 

167 body = response.json() 

168 except Exception: 

169 body = None 

170 if not isinstance(body, dict): 

171 body = {} 

172 token = body.get("access_token") 

173 if response.status_code != 200 or not isinstance(token, str) or not token: 

174 # body["error"] is an OAuth error code (e.g. invalid_grant) — safe to surface. 

175 code = body.get("error") if isinstance(body.get("error"), str) else "" 

176 raise RuntimeError(f"FCM token exchange failed: HTTP {response.status_code} {code}".strip()) 

177 try: 

178 expires_in = float(body.get("expires_in") or ASSERTION_TTL_SECONDS) 

179 except (TypeError, ValueError): 

180 expires_in = float(ASSERTION_TTL_SECONDS) 

181 return token, now + expires_in 

182 

183 

184def _cached_for(config_key: tuple[str, str], now: float, margin: float) -> str | None: 

185 """Cached token for this config if it is valid for at least `margin` more seconds.""" 

186 with _lock: 

187 if _cached_token is not None: 

188 token, expires_at, cached_key = _cached_token 

189 if cached_key == config_key and now < expires_at - margin: 

190 return token 

191 return None 

192 

193 

194def _access_token( 

195 info: dict[str, Any], 

196 client: httpx.Client, 

197 now: float | None = None, 

198) -> str: 

199 """OAuth2 access token for the FCM scope, cached until 5 minutes before 

200 expiry. If a refresh fails, a cached token that has not actually expired 

201 is still used, and no new exchange is tried for 30 s. Raises when there 

202 is no usable token (callers turn that into a failed send). 

203 """ 

204 global _cached_token, _failed_exchange 

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

206 # A key rotation must not keep serving the old account's token. 

207 config_key = (info["client_email"], info["private_key"]) 

208 

209 fresh = _cached_for(config_key, now, REFRESH_MARGIN_SECONDS) 

210 if fresh: 

211 return fresh 

212 

213 with _refresh_lock: 

214 # Another thread may have refreshed while we waited. 

215 fresh = _cached_for(config_key, now, REFRESH_MARGIN_SECONDS) 

216 if fresh: 

217 return fresh 

218 

219 with _lock: 

220 backing_off = ( 

221 _failed_exchange is not None and _failed_exchange[1] == config_key and now < _failed_exchange[0] 

222 ) 

223 if backing_off: 

224 still_valid = _cached_for(config_key, now, 0) 

225 if still_valid: 

226 return still_valid 

227 raise RuntimeError("FCM token exchange failed recently; backing off") 

228 

229 try: 

230 token, expires_at = _exchange(info, client, now) 

231 except Exception: 

232 with _lock: 

233 _failed_exchange = (now + FAILED_EXCHANGE_BACKOFF_SECONDS, config_key) 

234 still_valid = _cached_for(config_key, now, 0) 

235 if still_valid: 

236 return still_valid 

237 raise 

238 

239 with _lock: 

240 _cached_token = (token, expires_at, config_key) 

241 _failed_exchange = None 

242 return token 

243 

244 

245def _invalidate_access_token() -> None: 

246 global _cached_token 

247 with _lock: 

248 _cached_token = None 

249 

250 

251def build_fcm_message(fid: str, payload: dict[str, Any]) -> dict[str, Any]: 

252 """Map the Web Push payload (title/body/tag/data) to an FCM v1 message. 

253 

254 data values must all be strings in FCM; matchId/eventType/url carry the 

255 app's tap handler to the match. android.notification.tag makes a repeat 

256 of the same (match, event) replace the earlier one in the shade. 

257 collapse_key is set too, but FCM only collapses data messages by it — 

258 these are notification messages, so tag is what dedupes on-device. 

259 """ 

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

261 message: dict[str, Any] = { 

262 "fid": fid, 

263 "notification": {"title": payload.get("title", ""), "body": payload.get("body", "")}, 

264 } 

265 fcm_data = {k: str(data[k]) for k in ("matchId", "eventType", "url") if data.get(k) is not None} 

266 if fcm_data: 266 ↛ 269line 266 didn't jump to line 269 because the condition on line 266 was always true

267 message["data"] = fcm_data 

268 

269 android_notification: dict[str, Any] = {"channel_id": CHANNEL_ID} 

270 android: dict[str, Any] = {"priority": "high", "ttl": MESSAGE_TTL, "notification": android_notification} 

271 tag = payload.get("tag") 

272 if tag: 

273 android["collapse_key"] = tag 

274 android_notification["tag"] = tag 

275 message["android"] = android 

276 return {"message": message} 

277 

278 

279def _error_info(response: httpx.Response) -> tuple[str | None, str | None, str]: 

280 """(errorCode from FcmError details, google.rpc status, message). 

281 

282 Tolerates any body shape — this runs inside send_fcm's never-raises contract. 

283 """ 

284 try: 

285 body = response.json() 

286 except Exception: 

287 return None, None, "" 

288 err = body.get("error") if isinstance(body, dict) else None 

289 if not isinstance(err, dict): 

290 return None, None, "" 

291 error_code = None 

292 details = err.get("details") 

293 if isinstance(details, list): 

294 for detail in details: 

295 code = detail.get("errorCode") if isinstance(detail, dict) else None 

296 if isinstance(code, str) and code: 

297 error_code = code 

298 break 

299 rpc_status = err.get("status") if isinstance(err.get("status"), str) else None 

300 message = err.get("message") if isinstance(err.get("message"), str) else "" 

301 return error_code, rpc_status, message 

302 

303 

304def _is_expired(http_status: int, error_code: str | None, rpc_status: str | None, message: str) -> bool: 

305 """Only FCM's explicit "this installation is gone" answers count. A bare 

306 404 or SENDER_ID_MISMATCH is a project/credential problem, not a dead device. 

307 """ 

308 if error_code in _EXPIRED_ERROR_CODES: 

309 return True 

310 # INVALID_ARGUMENT covers bad payloads too; only a bad address means drop it. 

311 if http_status == 400 and "INVALID_ARGUMENT" in (error_code, rpc_status): 

312 return bool(_DEVICE_ARGUMENT_RE.search(message or "")) 

313 return False 

314 

315 

316def send_fcm( 

317 device: dict[str, Any], 

318 payload: dict[str, Any], 

319 *, 

320 client: httpx.Client | None = None, 

321) -> SendResult: 

322 """Send a single FCM notification. Never raises. 

323 

324 device dict must include `fid`. payload is the Web Push payload built by 

325 the dispatcher — see build_fcm_message. A 401 drops the cached access 

326 token and retries once; 429/5xx fail without retry. 

327 """ 

328 info = _service_account() 

329 if info is None: 

330 return SendResult(status=STATUS_FAILED, error="FCM not configured") 

331 

332 fid = device.get("fid") 

333 if not fid: 

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

335 

336 try: 

337 http = client or _get_client() 

338 url = SEND_URL.format(project_id=info["project_id"]) 

339 body = build_fcm_message(fid, payload) 

340 response = None 

341 for _attempt in range(2): 

342 access_token = _access_token(info, http) 

343 response = http.post( 

344 url, 

345 json=body, 

346 headers={"authorization": f"Bearer {access_token}"}, 

347 ) 

348 if response.status_code != 401: 

349 break 

350 # Access token rejected (revoked, clock skew) — mint a fresh one. 

351 _invalidate_access_token() 

352 

353 http_status = response.status_code 

354 if http_status == 200: 

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

356 

357 error_code, rpc_status, message = _error_info(response) 

358 error = error_code or rpc_status or f"HTTP {http_status}" 

359 if _is_expired(http_status, error_code, rpc_status, message): 

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

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

362 except Exception as exc: 

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