Coverage for app / services / dashboards / feeds.py: 90%

156 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""Outbound fetches for feed-backed widgets. 

2 

3Feed widgets show *exact* third-party data — a forecast, a set of headlines — 

4rather than a model's rendering of it. That means svc-core makes outbound 

5requests, which it otherwise never does, so everything here is deliberately 

6narrow: 

7 

8- Only http/https, only GET, one redirect hop at most. 

9- Every resolved address is checked against private, loopback, link-local and 

10 reserved ranges *before* connecting, so a user-supplied feed URL cannot be 

11 pointed at another service on the internal networks (SSRF). The check runs 

12 again on the redirect target. 

13- Hard caps on response size and time, so one hostile feed cannot exhaust the 

14 worker. 

15- An optional domain allowlist (``FEED_ALLOWED_DOMAINS``) for deployments that 

16 want feeds restricted to approved publishers. Empty means "any public host". 

17 

18svc-core reaches the internet on the dedicated ``feed-egress-network``; see 

19modules/docker-compose.yml. 

20""" 

21 

22from __future__ import annotations 

23 

24import ipaddress 

25import logging 

26import socket 

27from datetime import datetime, timezone 

28from typing import Any, Optional 

29from urllib.parse import urlparse 

30 

31import httpx 

32from defusedxml import ElementTree 

33 

34from app.common.settings import get_settings 

35 

36logger = logging.getLogger(__name__) 

37 

38#: Caps for any single feed fetch. 

39FETCH_TIMEOUT_SECONDS = 10.0 

40MAX_RESPONSE_BYTES = 2 * 1024 * 1024 

41USER_AGENT = "CHAIN-R-Dashboards/1.0 (+feed widget)" 

42 

43 

44class FeedError(RuntimeError): 

45 """A feed could not be fetched or understood.""" 

46 

47 

48# --------------------------------------------------------------------------- 

49# URL safety 

50# --------------------------------------------------------------------------- 

51 

52 

53def _is_public_address(host: str) -> bool: 

54 """Whether every address ``host`` resolves to is publicly routable. 

55 

56 All of them must be public: a hostname with both a public and a private 

57 A record would otherwise be a way in. 

58 """ 

59 try: 

60 infos = socket.getaddrinfo(host, None) 

61 except socket.gaierror as exc: 

62 raise FeedError(f"Could not resolve '{host}'.") from exc 

63 

64 if not infos: 

65 raise FeedError(f"Could not resolve '{host}'.") 

66 

67 for info in infos: 

68 address = info[4][0] 

69 try: 

70 ip = ipaddress.ip_address(address) 

71 except ValueError: 

72 return False 

73 if ( 

74 ip.is_private 

75 or ip.is_loopback 

76 or ip.is_link_local 

77 or ip.is_reserved 

78 or ip.is_multicast 

79 or ip.is_unspecified 

80 ): 

81 return False 

82 return True 

83 

84 

85def allowed_domains() -> list[str]: 

86 """The publisher domains ``FEED_ALLOWED_DOMAINS`` limits feeds to, or an 

87 empty list for any public host — what the board generator tells its 

88 model, so it does not propose a feed that is refused.""" 

89 raw = (getattr(get_settings(), "FEED_ALLOWED_DOMAINS", "") or "").strip() 

90 if not raw or raw == "*": 

91 return [] 

92 return [d for d in (e.strip().lower().lstrip(".") for e in raw.split(",")) if d] 

93 

94 

95def allowlisted_url(url: str) -> bool: 

96 """Whether ``url``'s host passes the allowlist (and nothing more: the 

97 address checks are :func:`validate_feed_url`'s, made before any fetch).""" 

98 host = urlparse(url).hostname 

99 return bool(host) and _allowlisted(host) 

100 

101 

102def _allowlisted(host: str) -> bool: 

103 """Whether ``host`` passes the configured publisher allowlist. 

104 

105 Empty or ``*`` means any public host. ``*`` exists because SSM cannot 

106 store an empty string, so a deployment that wants the default needs a 

107 real value that says so. 

108 """ 

109 raw = (getattr(get_settings(), "FEED_ALLOWED_DOMAINS", "") or "").strip() 

110 if not raw or raw == "*": 

111 return True 

112 host = host.lower() 

113 for entry in raw.split(","): 

114 domain = entry.strip().lower().lstrip(".") 

115 if domain and (host == domain or host.endswith(f".{domain}")): 

116 return True 

117 return False 

118 

119 

120def validate_feed_url(url: str) -> str: 

121 """Return ``url`` if it is safe to fetch, else raise :class:`FeedError`. 

122 

123 Called both when a widget's config is saved (so a bad URL is a 422 at edit 

124 time) and again before each fetch (so DNS that changes later is caught). 

125 """ 

126 parsed = urlparse(url) 

127 if parsed.scheme not in ("http", "https"): 

128 raise FeedError("Feed URLs must start with http:// or https://.") 

129 if not parsed.hostname: 

130 raise FeedError("That feed URL has no host.") 

131 

132 host = parsed.hostname 

133 if not _allowlisted(host): 

134 raise FeedError(f"'{host}' is not an approved feed source.") 

135 if not _is_public_address(host): 

136 raise FeedError( 

137 f"'{host}' resolves to a private address and cannot be fetched." 

138 ) 

139 return url 

140 

141 

142# --------------------------------------------------------------------------- 

143# Fetching 

144# --------------------------------------------------------------------------- 

145 

146 

147def fetch(url: str, *, params: Optional[dict] = None) -> httpx.Response: 

148 """GET ``url`` with every guard applied.""" 

149 validate_feed_url(url) 

150 

151 try: 

152 # Redirects are followed manually so the destination is re-validated; 

153 # httpx's own follow_redirects would bypass the SSRF check. 

154 with httpx.Client( 

155 timeout=FETCH_TIMEOUT_SECONDS, 

156 follow_redirects=False, 

157 headers={"User-Agent": USER_AGENT}, 

158 ) as client: 

159 response = client.get(url, params=params) 

160 

161 if response.is_redirect: 

162 location = response.headers.get("location") 

163 if not location: 

164 raise FeedError("The source redirected without a target.") 

165 target = str(httpx.URL(url).join(location)) 

166 validate_feed_url(target) 

167 response = client.get(target) 

168 

169 response.raise_for_status() 

170 except FeedError: 

171 raise 

172 except httpx.HTTPStatusError as exc: 

173 raise FeedError(f"The source returned {exc.response.status_code}.") from exc 

174 except httpx.HTTPError as exc: 

175 raise FeedError(f"Could not reach the source: {exc}") from exc 

176 

177 if len(response.content) > MAX_RESPONSE_BYTES: 

178 raise FeedError("The source returned too much data.") 

179 return response 

180 

181 

182# --------------------------------------------------------------------------- 

183# Weather — Open-Meteo 

184# 

185# Chosen because it needs no API key and no account, so a weather tile works 

186# out of the box rather than after a credential setup the user did not ask for. 

187# --------------------------------------------------------------------------- 

188 

189OPEN_METEO_URL = "https://api.open-meteo.com/v1/forecast" 

190 

191#: WMO weather codes → (label, icon key the frontend maps to a glyph). 

192WMO_CODES: dict[int, tuple[str, str]] = { 

193 0: ("Clear sky", "clear"), 

194 1: ("Mainly clear", "clear"), 

195 2: ("Partly cloudy", "partly-cloudy"), 

196 3: ("Overcast", "cloudy"), 

197 45: ("Fog", "fog"), 

198 48: ("Depositing rime fog", "fog"), 

199 51: ("Light drizzle", "drizzle"), 

200 53: ("Drizzle", "drizzle"), 

201 55: ("Dense drizzle", "drizzle"), 

202 56: ("Freezing drizzle", "sleet"), 

203 57: ("Dense freezing drizzle", "sleet"), 

204 61: ("Slight rain", "rain"), 

205 63: ("Rain", "rain"), 

206 65: ("Heavy rain", "rain"), 

207 66: ("Freezing rain", "sleet"), 

208 67: ("Heavy freezing rain", "sleet"), 

209 71: ("Slight snow", "snow"), 

210 73: ("Snow", "snow"), 

211 75: ("Heavy snow", "snow"), 

212 77: ("Snow grains", "snow"), 

213 80: ("Slight showers", "rain"), 

214 81: ("Showers", "rain"), 

215 82: ("Violent showers", "rain"), 

216 85: ("Snow showers", "snow"), 

217 86: ("Heavy snow showers", "snow"), 

218 95: ("Thunderstorm", "thunder"), 

219 96: ("Thunderstorm with hail", "thunder"), 

220 99: ("Thunderstorm with heavy hail", "thunder"), 

221} 

222 

223 

224def describe_weather_code(code: Any) -> tuple[str, str]: 

225 try: 

226 return WMO_CODES[int(code)] 

227 except (TypeError, ValueError, KeyError): 

228 return ("Unknown", "unknown") 

229 

230 

231def fetch_forecast( 

232 latitude: float, 

233 longitude: float, 

234 *, 

235 units: str = "metric", 

236 days: int = 5, 

237) -> dict: 

238 """A current-conditions + daily forecast payload for one location.""" 

239 metric = units != "imperial" 

240 params = { 

241 "latitude": latitude, 

242 "longitude": longitude, 

243 "current": "temperature_2m,apparent_temperature,relative_humidity_2m," 

244 "wind_speed_10m,weather_code,is_day", 

245 "daily": "weather_code,temperature_2m_max,temperature_2m_min," 

246 "precipitation_probability_max", 

247 "forecast_days": max(1, min(7, days)), 

248 "timezone": "auto", 

249 "temperature_unit": "celsius" if metric else "fahrenheit", 

250 "wind_speed_unit": "kmh" if metric else "mph", 

251 } 

252 

253 payload = fetch(OPEN_METEO_URL, params=params).json() 

254 current = payload.get("current") or {} 

255 daily = payload.get("daily") or {} 

256 

257 label, icon = describe_weather_code(current.get("weather_code")) 

258 days_out = [] 

259 dates = daily.get("time") or [] 

260 for index, date in enumerate(dates): 

261 day_label, day_icon = describe_weather_code( 

262 _at(daily.get("weather_code"), index) 

263 ) 

264 days_out.append( 

265 { 

266 "date": date, 

267 "label": day_label, 

268 "icon": day_icon, 

269 "max": _at(daily.get("temperature_2m_max"), index), 

270 "min": _at(daily.get("temperature_2m_min"), index), 

271 "precipitation_probability": _at( 

272 daily.get("precipitation_probability_max"), index 

273 ), 

274 } 

275 ) 

276 

277 return { 

278 "current": { 

279 "temperature": current.get("temperature_2m"), 

280 "feels_like": current.get("apparent_temperature"), 

281 "humidity": current.get("relative_humidity_2m"), 

282 "wind_speed": current.get("wind_speed_10m"), 

283 "label": label, 

284 "icon": icon, 

285 "is_day": bool(current.get("is_day", 1)), 

286 }, 

287 "days": days_out, 

288 "units": { 

289 "temperature": "°C" if metric else "°F", 

290 "wind_speed": "km/h" if metric else "mph", 

291 }, 

292 "timezone": payload.get("timezone"), 

293 "source": "Open-Meteo", 

294 "source_url": "https://open-meteo.com/", 

295 } 

296 

297 

298def _at(values: Any, index: int) -> Any: 

299 if isinstance(values, list) and 0 <= index < len(values): 

300 return values[index] 

301 return None 

302 

303 

304# --------------------------------------------------------------------------- 

305# RSS / Atom 

306# --------------------------------------------------------------------------- 

307 

308_ATOM_NS = "{http://www.w3.org/2005/Atom}" 

309 

310 

311def _text(node, *names: str) -> str: 

312 """First non-empty child text among ``names``, RSS or Atom.""" 

313 for name in names: 

314 for candidate in (name, f"{_ATOM_NS}{name}"): 

315 found = node.find(candidate) 

316 if found is not None and (found.text or "").strip(): 

317 return (found.text or "").strip() 

318 return "" 

319 

320 

321def _link(node) -> str: 

322 link = node.find("link") 

323 if link is not None: 

324 if (link.text or "").strip(): 

325 return (link.text or "").strip() 

326 # Atom puts the URL in an attribute, and may carry several rel types. 

327 for candidate in node.findall(f"{_ATOM_NS}link"): 

328 rel = candidate.get("rel", "alternate") 

329 if rel == "alternate" and candidate.get("href"): 

330 return candidate.get("href", "") 

331 return "" 

332 

333 

334def _strip_markup(value: str, limit: int = 300) -> str: 

335 """Feed summaries are frequently HTML; tiles want a plain-text excerpt.""" 

336 out, depth = [], 0 

337 for char in value: 

338 if char == "<": 

339 depth += 1 

340 elif char == ">": 

341 depth = max(0, depth - 1) 

342 elif depth == 0: 

343 out.append(char) 

344 text = " ".join("".join(out).split()) 

345 return text[:limit] 

346 

347 

348def parse_feed(xml: str, limit: int = 10) -> dict: 

349 """Normalise an RSS 2.0 or Atom document into feed + item dicts.""" 

350 try: 

351 root = ElementTree.fromstring(xml) 

352 except Exception as exc: # defusedxml raises several distinct types 

353 raise FeedError(f"That source is not a readable RSS or Atom feed: {exc}") 

354 

355 # Well-formed XML that is not a feed is the common mistake — pasting a 

356 # site's URL rather than its feed URL — so say that rather than "no items". 

357 root_tag = root.tag.split("}")[-1].lower() 

358 if root_tag not in ("rss", "feed", "rdf"): 

359 raise FeedError( 

360 "That URL is not an RSS or Atom feed. Look for the site's feed " 

361 "link (often /rss or /feed)." 

362 ) 

363 

364 channel = root.find("channel") 

365 container = channel if channel is not None else root 

366 

367 entries = container.findall("item") or root.findall(f"{_ATOM_NS}entry") 

368 if not entries: 

369 raise FeedError("That feed contains no items.") 

370 

371 items = [] 

372 for entry in entries[: max(1, min(50, limit))]: 

373 title = _text(entry, "title") or "Untitled" 

374 items.append( 

375 { 

376 "title": title[:300], 

377 "link": _link(entry), 

378 "published": _text(entry, "pubDate", "published", "updated", "date"), 

379 "summary": _strip_markup( 

380 _text(entry, "description", "summary", "subtitle") 

381 ), 

382 } 

383 ) 

384 

385 return { 

386 "feed_title": _text(container, "title") or "Feed", 

387 "feed_link": _link(container), 

388 "items": items, 

389 "fetched_at": datetime.now(timezone.utc).isoformat(), 

390 } 

391 

392 

393def fetch_feed(url: str, limit: int = 10) -> dict: 

394 """Fetch and parse an RSS/Atom feed.""" 

395 return parse_feed(fetch(url).text, limit)