test_outbound_url_ssrf_guards.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. """Outbound-URL SSRF policy: two tiers, applied consistently.
  2. Bambuddy makes outbound HTTP requests to hosts the operator configures. Which
  3. policy applies is a property of the *service*, not the caller:
  4. - LAN-service (Spoolman, ntfy, Bark, webhooks, Home Assistant, Obico ML, the
  5. slicer sidecars) — loopback and RFC-1918 MUST stay reachable, because
  6. self-hosting those next to Bambuddy is the normal topology. Blocking them
  7. would break most installs, which is why a blanket private-IP blocklist is
  8. the wrong fix here.
  9. - Public-internet (OIDC issuer and icon URLs) — a private address cannot be a
  10. real IdP, so it is a probe.
  11. Both tiers reject what is dangerous under any topology: non-HTTP schemes,
  12. numeric-encoded IPs, cloud-metadata endpoints, multicast/unspecified, and
  13. IPv4-mapped IPv6 encodings of the above.
  14. The separate concern covered here is *response-body echo*. Notification
  15. provider URLs are writable by anyone holding ``NOTIFICATIONS_CREATE`` — which
  16. the default Operators group carries and which does NOT imply
  17. ``SETTINGS_UPDATE`` — and ``POST /notifications/test-config`` takes the URL
  18. from the request body without persisting it. Returning the upstream body there
  19. made an intended reachability check into an authenticated read primitive
  20. against anything the process can reach. Providers whose host Bambuddy pins
  21. (Pushover, Telegram, CallMeBot, Discord) may still echo, since the caller
  22. cannot influence the destination.
  23. """
  24. from __future__ import annotations
  25. import inspect
  26. import re
  27. import httpx
  28. import pytest
  29. from backend.app.api.routes._oidc_helpers import assert_safe_public_https_url
  30. from backend.app.api.routes._spoolman_helpers import assert_safe_spoolman_url
  31. from backend.app.api.routes._url_safety import assert_safe_lan_service_url
  32. from backend.app.schemas.auth import OIDCProviderCreate, OIDCProviderUpdate
  33. from backend.app.schemas.settings import LAN_SERVICE_URL_SETTINGS, AppSettingsUpdate
  34. from backend.app.services import notification_service as ns
  35. from backend.app.services.homeassistant import HomeAssistantService
  36. from backend.app.services.rest_smart_plug import RESTSmartPlugService
  37. from backend.app.services.tasmota import TasmotaService
  38. # Dangerous under any topology — both tiers must reject all of these.
  39. UNIVERSALLY_BLOCKED = [
  40. "file:///etc/passwd",
  41. "gopher://127.0.0.1:6379/_INFO",
  42. "ftp://internal.example.com/",
  43. "http://169.254.169.254/latest/meta-data/",
  44. "http://100.100.100.200/",
  45. "http://[fd00:ec2::254]/",
  46. "http://2130706433/",
  47. "http://0x7f000001/",
  48. "http://[::ffff:169.254.169.254]/",
  49. "http://0.0.0.0/",
  50. "http://239.255.255.250/",
  51. # The DNS-name form of the same target. Neither tier resolves hostnames,
  52. # but these are a fixed literal set, so matching them costs no lookup.
  53. "http://metadata.google.internal/",
  54. "http://METADATA.GOOGLE.INTERNAL/computeMetadata/v1/",
  55. "http://metadata.goog/",
  56. ]
  57. # The normal self-hosted topology — the LAN tier must permit all of these.
  58. LAN_ALLOWED = [
  59. "http://127.0.0.1:7912/",
  60. "http://localhost:3003",
  61. "http://192.168.1.50:8123",
  62. "http://10.0.0.7:3333",
  63. "http://172.16.4.9:8080",
  64. "https://ntfy.example.com/",
  65. "http://spoolman.lan:7912",
  66. ]
  67. # ---------------------------------------------------------------------------
  68. # The LAN-service tier
  69. # ---------------------------------------------------------------------------
  70. @pytest.mark.parametrize("url", UNIVERSALLY_BLOCKED)
  71. def test_lan_tier_rejects_universally_dangerous_targets(url: str):
  72. with pytest.raises(ValueError):
  73. assert_safe_lan_service_url(url, label="Test URL")
  74. @pytest.mark.parametrize("url", LAN_ALLOWED)
  75. def test_lan_tier_permits_the_normal_self_hosted_topology(url: str):
  76. """A blanket private-IP block here would break most real installs."""
  77. assert_safe_lan_service_url(url, label="Test URL")
  78. def test_lan_tier_names_the_field_in_its_error():
  79. with pytest.raises(ValueError, match="ntfy server URL"):
  80. assert_safe_lan_service_url("file:///etc/passwd", label="ntfy server URL")
  81. def test_spoolman_wrapper_keeps_its_user_facing_wording():
  82. """The wording is asserted by pre-existing tests; delegation must not change it."""
  83. with pytest.raises(ValueError, match="^Spoolman URL must use http or https$"):
  84. assert_safe_spoolman_url("file:///etc/passwd")
  85. with pytest.raises(ValueError, match="^Spoolman URL must not point to a cloud metadata endpoint$"):
  86. assert_safe_spoolman_url("http://169.254.169.254/")
  87. # ---------------------------------------------------------------------------
  88. # The public-internet tier
  89. # ---------------------------------------------------------------------------
  90. @pytest.mark.parametrize("url", UNIVERSALLY_BLOCKED)
  91. def test_public_tier_rejects_universally_dangerous_targets(url: str):
  92. with pytest.raises(ValueError):
  93. assert_safe_public_https_url(url)
  94. @pytest.mark.parametrize(
  95. "url",
  96. [
  97. "https://127.0.0.1/",
  98. "https://192.168.1.5/",
  99. "https://10.1.2.3/",
  100. "https://[fe80::1]/",
  101. "https://[::ffff:127.0.0.1]/",
  102. "http://accounts.google.com/", # scheme must be https
  103. ],
  104. )
  105. def test_public_tier_additionally_rejects_private_and_plain_http(url: str):
  106. with pytest.raises(ValueError):
  107. assert_safe_public_https_url(url)
  108. # ---------------------------------------------------------------------------
  109. # OIDC issuer_url — the encoding bypasses the hand-rolled validator missed
  110. # ---------------------------------------------------------------------------
  111. @pytest.mark.parametrize(
  112. "url",
  113. [
  114. "https://2130706433/", # decimal-encoded 127.0.0.1
  115. "https://0x7f000001/", # hex-encoded 127.0.0.1
  116. "https://[::ffff:127.0.0.1]/", # IPv4-mapped loopback
  117. "https://[::ffff:169.254.169.254]/", # IPv4-mapped IMDS
  118. "https://0.0.0.0/",
  119. "https://239.255.255.250/",
  120. "https://169.254.169.254/",
  121. "https://127.0.0.1/",
  122. "https://192.168.1.5/",
  123. "http://idp.example.com/",
  124. ],
  125. )
  126. def test_issuer_url_rejects_encoded_and_private_targets(url: str):
  127. with pytest.raises(ValueError):
  128. OIDCProviderCreate(
  129. name="SSO",
  130. issuer_url=url,
  131. client_id="cid",
  132. client_secret="secret",
  133. )
  134. def test_issuer_url_update_is_guarded_too():
  135. """The update path matters most: it can change the issuer while the stored
  136. client_secret stays, which is the shape that would exfiltrate a real secret."""
  137. with pytest.raises(ValueError):
  138. OIDCProviderUpdate(issuer_url="https://[::ffff:127.0.0.1]/")
  139. def test_issuer_url_error_names_the_field_not_the_icon():
  140. with pytest.raises(ValueError, match="issuer_url"):
  141. OIDCProviderUpdate(issuer_url="https://127.0.0.1/")
  142. def test_a_real_idp_still_validates():
  143. provider = OIDCProviderCreate(
  144. name="SSO",
  145. issuer_url="https://accounts.google.com",
  146. client_id="cid",
  147. client_secret="secret",
  148. )
  149. assert provider.issuer_url == "https://accounts.google.com"
  150. # ---------------------------------------------------------------------------
  151. # Settings URLs
  152. # ---------------------------------------------------------------------------
  153. # Imported from the schema rather than duplicated, so the backstop below cannot
  154. # silently disagree with what is actually validated.
  155. LAN_SERVICE_SETTINGS = LAN_SERVICE_URL_SETTINGS
  156. @pytest.mark.parametrize("field", LAN_SERVICE_SETTINGS)
  157. @pytest.mark.parametrize("url", UNIVERSALLY_BLOCKED)
  158. def test_settings_urls_reject_dangerous_targets(field: str, url: str):
  159. with pytest.raises(ValueError):
  160. AppSettingsUpdate(**{field: url})
  161. @pytest.mark.parametrize("field", LAN_SERVICE_SETTINGS)
  162. @pytest.mark.parametrize("url", LAN_ALLOWED)
  163. def test_settings_urls_permit_lan_hosts(field: str, url: str):
  164. assert AppSettingsUpdate(**{field: url})
  165. @pytest.mark.parametrize("field", LAN_SERVICE_SETTINGS)
  166. @pytest.mark.parametrize("empty", ["", " "])
  167. def test_settings_urls_accept_empty_meaning_not_configured(field: str, empty: str):
  168. """Empty is the documented "fall back to the env var" value for all four."""
  169. assert AppSettingsUpdate(**{field: empty})
  170. @pytest.mark.parametrize("field", LAN_SERVICE_SETTINGS)
  171. @pytest.mark.parametrize(
  172. "legacy",
  173. [
  174. "192.168.1.10:3333", # urlparse: scheme='', netloc='', hostname=None
  175. "localhost:3003", # urlparse: scheme='localhost' (!), hostname=None
  176. "obico.local:3333", # same trap, with dots
  177. "192.168.1.10",
  178. ],
  179. )
  180. def test_settings_urls_do_not_newly_reject_scheme_less_legacy_values(field: str, legacy: str):
  181. """Compatibility guard, not an endorsement.
  182. The settings inputs are plain text with no scheme enforcement, so values
  183. like these are already in the wild. They are inert — httpx raises
  184. UnsupportedProtocol, so no request is issued — and they were storable
  185. before the validator existed. Rejecting them now would block saves of
  186. unrelated fields bundled in the same request (the Obico panel auto-saves
  187. obico_ml_url alongside every other Obico setting).
  188. """
  189. assert AppSettingsUpdate(**{field: legacy})
  190. @pytest.mark.parametrize("field", LAN_SERVICE_SETTINGS)
  191. def test_settings_urls_still_reject_a_real_non_http_scheme(field: str):
  192. """The leniency above is scoped to strings that are not URLs at all."""
  193. with pytest.raises(ValueError):
  194. AppSettingsUpdate(**{field: "file:///etc/passwd"})
  195. def test_every_url_setting_is_either_guarded_or_explicitly_exempt():
  196. """CI backstop: a new outbound-URL setting can't land unvalidated.
  197. Any new ``*_url`` field on AppSettingsUpdate must be added to the
  198. validator's field tuple or listed as exempt here with a reason. This
  199. catches the failure mode the original report correctly identified — guards
  200. added per-incident rather than to the whole class of fields.
  201. """
  202. exempt = {
  203. # Bambuddy's own public address, not a destination it requests. It is
  204. # rendered into notification bodies and OIDC redirect URIs, and handed
  205. # to Obico's ML server as the `img` parameter for that server to fetch
  206. # (obico_detection.py builds `{external_url}/api/v1/obico/cached-frame/
  207. # {nonce}`). Pointing it at a private address only breaks Bambuddy's own
  208. # links; it cannot make Bambuddy request anything it otherwise wouldn't.
  209. "external_url",
  210. # Guarded by assert_safe_spoolman_url at each consumer (spoolman.py,
  211. # location_service.py, inventory.py, spoolbuddy.py,
  212. # spoolman_inventory.py) rather than in the schema, keeping its
  213. # established user-facing "Spoolman URL ..." error wording.
  214. "spoolman_url",
  215. # Not an HTTP URL: ldap:// or ldaps://, handed to an LDAP client, never
  216. # to httpx. The LAN-service guard requires http/https and would reject
  217. # every valid value. It also cannot reach a cloud-metadata endpoint,
  218. # since IMDS only speaks HTTP.
  219. "ldap_server_url",
  220. }
  221. url_fields = {name for name in AppSettingsUpdate.model_fields if name.endswith("_url")}
  222. unguarded = url_fields - set(LAN_SERVICE_SETTINGS) - exempt
  223. assert not unguarded, (
  224. f"New outbound URL setting(s) {sorted(unguarded)} are not covered by a "
  225. f"SSRF guard. Add them to AppSettingsUpdate._LAN_SERVICE_URL_FIELDS (or "
  226. f"the public-internet guard), or add them to `exempt` above with a reason."
  227. )
  228. # ---------------------------------------------------------------------------
  229. # Notification providers: URL guard + no response-body echo
  230. # ---------------------------------------------------------------------------
  231. def _response(status: int = 500, body: str = "root:x:0:0:root:/root:/bin/bash") -> httpx.Response:
  232. return httpx.Response(status_code=status, text=body, request=httpx.Request("POST", "http://10.0.0.1/"))
  233. SECRET_BODY = "root:x:0:0:root:/root:/bin/bash"
  234. def test_opaque_failure_does_not_return_the_response_body():
  235. message = ns._opaque_http_failure(_response(), label="webhook endpoint")
  236. assert SECRET_BODY not in message
  237. assert "500" in message, "the status code is still useful and is not sensitive"
  238. assert "webhook endpoint" in message
  239. def test_opaque_failure_logs_the_body_for_the_operator(caplog):
  240. """The body stays available to whoever administers the host — via logs,
  241. not via the API response."""
  242. with caplog.at_level("DEBUG", logger=ns.__name__):
  243. ns._opaque_http_failure(_response(), label="ntfy server")
  244. assert SECRET_BODY in caplog.text
  245. @pytest.mark.parametrize(
  246. "provider_label",
  247. ["ntfy server", "Bark server", "webhook endpoint", "Home Assistant endpoint"],
  248. )
  249. def test_user_supplied_host_providers_use_the_opaque_path(provider_label: str):
  250. """Guards the mapping itself: each user-supplied-host provider must route
  251. its HTTP failure through _opaque_http_failure rather than formatting the
  252. body inline."""
  253. src = inspect.getsource(ns)
  254. assert f'_opaque_http_failure(response, label="{provider_label}")' in src
  255. def test_no_user_supplied_host_provider_formats_the_body_inline():
  256. """Any remaining ``response.text[:200]`` must belong to a host-pinned provider.
  257. Pushover/Telegram/CallMeBot/Discord all target hardcoded hosts (Discord via
  258. a webhook-prefix allowlist), so there is no trust boundary to cross.
  259. """
  260. src = inspect.getsource(ns).split("\n")
  261. host_pinned = {"_send_callmebot", "_send_pushover", "_send_telegram", "_send_discord"}
  262. current = None
  263. offenders = []
  264. for line in src:
  265. match = re.match(r"\s+async def (_send_\w+)", line)
  266. if match:
  267. current = match.group(1)
  268. if "response.text[:200]" in line and current not in host_pinned:
  269. offenders.append(current)
  270. assert not offenders, (
  271. f"{offenders} echo the upstream response body but do not target a "
  272. f"hardcoded host. Route the failure through _opaque_http_failure."
  273. )
  274. @pytest.mark.parametrize("url", UNIVERSALLY_BLOCKED)
  275. def test_provider_url_guard_rejects_dangerous_targets(url: str):
  276. assert ns._assert_safe_provider_url(url, label="Webhook URL") is not None
  277. @pytest.mark.parametrize("url", LAN_ALLOWED)
  278. def test_provider_url_guard_permits_self_hosted_servers(url: str):
  279. assert ns._assert_safe_provider_url(url, label="ntfy server URL") is None
  280. @pytest.mark.asyncio
  281. @pytest.mark.parametrize(
  282. ("provider_type", "config"),
  283. [
  284. ("ntfy", {"server": "http://169.254.169.254", "topic": "t"}),
  285. ("bark", {"server": "http://169.254.169.254", "device_key": "k"}),
  286. ("webhook", {"webhook_url": "http://169.254.169.254/latest/meta-data/"}),
  287. ],
  288. )
  289. async def test_test_config_refuses_metadata_targets_without_a_request(provider_type: str, config: dict, monkeypatch):
  290. """The end-to-end shape of the reported attack: an unsaved config aimed at
  291. IMDS via the test endpoint. It must be refused before any HTTP call."""
  292. called = False
  293. async def _fail_if_called(*_a, **_kw):
  294. nonlocal called
  295. called = True
  296. raise AssertionError("outbound request should not have been attempted")
  297. service = ns.NotificationService()
  298. monkeypatch.setattr(service, "_get_client", _fail_if_called)
  299. success, message = await service.send_test_notification(provider_type, config)
  300. assert success is False
  301. assert called is False
  302. assert "cloud metadata" in message
  303. # ---------------------------------------------------------------------------
  304. # Smart plugs: the same request-body-URL shape as the notification test endpoint
  305. # ---------------------------------------------------------------------------
  306. #
  307. # POST /smart-plugs/{ha,rest}/test-connection take their URL from the request
  308. # body and never persist it, so the schema-layer validator on ``ha_url`` does
  309. # not apply. Both are reachable with only ``SMART_PLUGS_CONTROL``, which the
  310. # default Operators group carries and which does NOT imply ``SETTINGS_UPDATE``
  311. # — identical to the notification case above.
  312. #
  313. # Both previously used hand-rolled checks that got the policy wrong in both
  314. # directions: the REST one rejected a literal ``127.0.0.1`` while allowing
  315. # every non-literal hostname, and the HA one matched three literal strings and
  316. # never parsed the hostname as an IP at all.
  317. @pytest.mark.parametrize("url", UNIVERSALLY_BLOCKED)
  318. def test_rest_plug_guard_rejects_dangerous_targets(url: str):
  319. assert RESTSmartPlugService._validate_url(url) is False
  320. @pytest.mark.parametrize("url", LAN_ALLOWED)
  321. def test_rest_plug_guard_permits_the_normal_self_hosted_topology(url: str):
  322. """Includes literal 127.0.0.1, which the previous implementation rejected
  323. while accepting the equivalent "localhost" — a plug bridge on the same
  324. host could only be configured by spelling it one particular way."""
  325. assert RESTSmartPlugService._validate_url(url) is True
  326. @pytest.mark.parametrize("url", UNIVERSALLY_BLOCKED)
  327. def test_ha_guard_rejects_dangerous_targets(url: str):
  328. assert HomeAssistantService._validate_url(url) is None
  329. @pytest.mark.parametrize("url", LAN_ALLOWED)
  330. def test_ha_guard_permits_the_normal_self_hosted_topology(url: str):
  331. assert HomeAssistantService._validate_url(url) is not None
  332. def test_ha_guard_still_normalises_the_url_it_returns():
  333. """Delegating the policy must not change what the caller gets back:
  334. scheme+host+port+path, with query and fragment dropped."""
  335. assert HomeAssistantService._validate_url("http://192.168.1.5:8123/base?x=1#f") == "http://192.168.1.5:8123/base"
  336. assert HomeAssistantService._validate_url("http://ha.lan") == "http://ha.lan"
  337. def test_ha_guard_keeps_ipv6_literals_bracketed():
  338. """urlparse strips the brackets off an IPv6 host; re-emitting it without
  339. them yields an unparseable URL that httpx cannot dial."""
  340. assert HomeAssistantService._validate_url("http://[fd00::1]:8123/api") == "http://[fd00::1]:8123/api"
  341. @pytest.mark.parametrize(
  342. "ip",
  343. [
  344. "169.254.169.254",
  345. "100.100.100.200",
  346. "fd00:ec2::254",
  347. "0.0.0.0", # nosec B104 — rejection fixture, not a bind address: the assertion below is that the guard refuses it
  348. "239.255.255.250",
  349. ],
  350. )
  351. def test_tasmota_guard_rejects_metadata_and_misuse_addresses(ip: str):
  352. """Tasmota keeps its own stricter rule (bare IP literals only, loopback
  353. rejected — a plug is always a separate LAN device), but must not miss the
  354. destinations that are dangerous regardless of topology."""
  355. assert TasmotaService._validate_ip(ip) is False
  356. @pytest.mark.parametrize("ip", ["::ffff:169.254.169.254", "::ffff:100.100.100.200"])
  357. def test_tasmota_guard_unwraps_ipv4_mapped_ipv6(ip: str):
  358. assert TasmotaService._validate_ip(ip) is False
  359. @pytest.mark.parametrize("ip", ["192.168.1.50", "10.0.0.7", "172.16.4.9"])
  360. def test_tasmota_guard_still_permits_a_normal_lan_plug(ip: str):
  361. assert TasmotaService._validate_ip(ip) is True
  362. @pytest.mark.parametrize("ip", ["127.0.0.1", "tasmota.local", "not-an-ip"])
  363. def test_tasmota_guard_keeps_failing_closed_on_non_lan_device_values(ip: str):
  364. """Deliberately stricter than the shared LAN guard, and unchanged here."""
  365. assert TasmotaService._validate_ip(ip) is False
  366. @pytest.mark.asyncio
  367. @pytest.mark.parametrize(
  368. "target",
  369. ["http://169.254.169.254/", "http://100.100.100.200/", "http://metadata.google.internal/"],
  370. )
  371. async def test_rest_test_connection_refuses_metadata_without_a_request(target: str, monkeypatch):
  372. """End-to-end shape of the reported attack, mirroring the notification
  373. test above: an unsaved URL aimed at IMDS via the test endpoint must be
  374. refused before any HTTP call is made."""
  375. def _fail_if_called(*_a, **_kw):
  376. raise AssertionError("outbound request should not have been attempted")
  377. monkeypatch.setattr(httpx, "AsyncClient", _fail_if_called)
  378. result = await RESTSmartPlugService().test_connection(target, "GET", None)
  379. assert result["success"] is False
  380. assert "cloud metadata" in result["error"]
  381. @pytest.mark.asyncio
  382. @pytest.mark.parametrize(
  383. "target",
  384. ["http://169.254.169.254", "http://100.100.100.200", "http://metadata.google.internal"],
  385. )
  386. async def test_ha_test_connection_refuses_metadata_without_a_request(target: str, monkeypatch):
  387. def _fail_if_called(*_a, **_kw):
  388. raise AssertionError("outbound request should not have been attempted")
  389. monkeypatch.setattr(httpx, "AsyncClient", _fail_if_called)
  390. result = await HomeAssistantService().test_connection(target, "token")
  391. assert result["success"] is False
  392. @pytest.mark.asyncio
  393. @pytest.mark.parametrize("target", ["http://169.254.169.254", "http://metadata.google.internal"])
  394. async def test_obico_test_connection_refuses_metadata_without_a_request(target: str, monkeypatch):
  395. """Same shape again: obico_ml_url is guarded when saved via settings, but
  396. this route takes the URL from the request body and echoes the response."""
  397. from backend.app.services.obico_detection import ObicoDetectionService
  398. def _fail_if_called(*_a, **_kw):
  399. raise AssertionError("outbound request should not have been attempted")
  400. monkeypatch.setattr(httpx, "AsyncClient", _fail_if_called)
  401. result = await ObicoDetectionService().test_connection(target)
  402. assert result["ok"] is False
  403. assert result["body"] is None
  404. assert "cloud metadata" in result["error"]
  405. # ---------------------------------------------------------------------------
  406. # Drift backstop, part 2: URLs that arrive in a request body
  407. # ---------------------------------------------------------------------------
  408. #
  409. # `test_every_url_setting_is_either_guarded_or_explicitly_exempt` above only
  410. # walks `AppSettingsUpdate`. That is why the notification test endpoint, and
  411. # then the two smart-plug test endpoints, each had to be found by hand: a URL
  412. # that arrives in a request body and is never persisted is not a settings
  413. # field, so nothing enumerated it. This walks the live route table instead.
  414. def _request_body_url_fields() -> set[tuple[str, str]]:
  415. """Every (model, field) pair on a mutating route whose body carries a URL."""
  416. from fastapi.routing import APIRoute
  417. from pydantic import BaseModel
  418. from backend.app.main import app
  419. found: set[tuple[str, str]] = set()
  420. for route in app.routes:
  421. if not isinstance(route, APIRoute) or not ({"POST", "PUT", "PATCH"} & set(route.methods or ())):
  422. continue
  423. for param in route.dependant.body_params:
  424. # FastAPI moved the resolved annotation from `type_` onto
  425. # `field_info.annotation`; read both so this can't silently
  426. # enumerate nothing (which would make the assertions vacuous).
  427. annotation = getattr(param, "type_", None)
  428. if annotation is None:
  429. annotation = getattr(getattr(param, "field_info", None), "annotation", None)
  430. if not (isinstance(annotation, type) and issubclass(annotation, BaseModel)):
  431. continue
  432. for field in annotation.model_fields:
  433. if field == "url" or field.endswith("_url"):
  434. found.add((annotation.__name__, field))
  435. return found
  436. # Guarded: the handler (or the service it calls) puts the value through one of
  437. # the two tiers before any request is issued.
  438. GUARDED_BODY_URLS = {
  439. ("AppSettingsUpdate", "bambu_studio_api_url"),
  440. ("AppSettingsUpdate", "ha_url"),
  441. ("AppSettingsUpdate", "obico_ml_url"),
  442. ("AppSettingsUpdate", "orcaslicer_api_url"),
  443. ("AppSettingsUpdate", "spoolman_url"), # assert_safe_spoolman_url at each consumer
  444. ("HATestConnectionRequest", "url"), # homeassistant._validate_url
  445. ("RESTTestConnectionRequest", "url"), # rest_smart_plug._validate_url
  446. ("TestConnectionRequest", "url"), # obico_detection.test_connection
  447. ("OIDCProviderCreate", "issuer_url"), # public tier, via schemas.auth
  448. ("OIDCProviderCreate", "icon_url"),
  449. ("OIDCProviderUpdate", "issuer_url"),
  450. ("OIDCProviderUpdate", "icon_url"),
  451. # Gitea/Forgejo derive their API base from this and request it with the
  452. # stored token, so it is a real fetch target — guarded in
  453. # github_backup._enforce_private_repo, which both POST and PATCH funnel through.
  454. ("GitHubBackupConfigCreate", "repository_url"),
  455. ("GitHubBackupConfigUpdate", "repository_url"),
  456. # SmartPlug{Create,Update} persist these; every read goes back out through
  457. # RESTSmartPlugService._send_request, which applies the same guard.
  458. ("SmartPlugCreate", "rest_on_url"),
  459. ("SmartPlugCreate", "rest_off_url"),
  460. ("SmartPlugCreate", "rest_status_url"),
  461. ("SmartPlugCreate", "rest_power_url"),
  462. ("SmartPlugCreate", "rest_energy_url"),
  463. ("SmartPlugUpdate", "rest_on_url"),
  464. ("SmartPlugUpdate", "rest_off_url"),
  465. ("SmartPlugUpdate", "rest_status_url"),
  466. ("SmartPlugUpdate", "rest_power_url"),
  467. ("SmartPlugUpdate", "rest_energy_url"),
  468. }
  469. # Not a destination Bambuddy requests — no guard applies.
  470. NOT_A_FETCH_TARGET = {
  471. ("AppSettingsUpdate", "external_url"), # Bambuddy's own address (see exempt list above)
  472. ("AppSettingsUpdate", "ldap_server_url"), # ldap://, handed to an LDAP client
  473. ("ProjectCreate", "url"), # stored link, rendered in the UI, never fetched
  474. ("ProjectUpdate", "url"),
  475. ("BOMItemCreate", "sourcing_url"), # stored supplier link, never fetched
  476. ("BOMItemUpdate", "sourcing_url"),
  477. ("MakerWorldResolveRequest", "url"), # parsed for a model id; fetches go to a pinned CDN allowlist
  478. ("DeviceRegisterRequest", "backend_url"), # the device's view of Bambuddy's own address
  479. ("HeartbeatRequest", "backend_url"),
  480. ("SystemConfigRequest", "backend_url"),
  481. ("ExternalLinkCreate", "url"), # sidebar link, rendered in the UI, never requested
  482. ("ExternalLinkUpdate", "url"),
  483. ("MaintenanceTypeCreate", "wiki_url"), # documentation link surfaced in the UI/notifications
  484. ("MaintenanceTypeUpdate", "wiki_url"),
  485. ("ArchiveUpdate", "external_url"), # stored source link for the model, never fetched
  486. }
  487. # Genuinely unguarded, and deliberately recorded rather than quietly exempted.
  488. # These reach `external_camera.capture_frame`, which dials rtsp:// as well as
  489. # http(s):// — the LAN-service guard rejects any non-HTTP scheme, so wiring it
  490. # up as-is would break every RTSP camera. Closing these needs a scheme-aware
  491. # variant of the guard, not a one-line delegation.
  492. KNOWN_UNGUARDED_NEEDS_SCHEME_AWARE_GUARD = {
  493. ("PrinterCreate", "external_camera_url"),
  494. ("PrinterCreate", "external_camera_snapshot_url"),
  495. ("PrinterUpdate", "external_camera_url"),
  496. ("PrinterUpdate", "external_camera_snapshot_url"),
  497. }
  498. def test_the_route_walk_actually_finds_something():
  499. """Guards the guard. If FastAPI's internals move again and the walk starts
  500. returning nothing, both assertions below pass vacuously and the backstop
  501. silently stops working — which is the exact failure it exists to prevent."""
  502. found = _request_body_url_fields()
  503. assert ("RESTTestConnectionRequest", "url") in found
  504. assert ("HATestConnectionRequest", "url") in found
  505. assert len(found) > 20
  506. def test_every_request_body_url_is_classified():
  507. """A new URL-bearing request field can't land without a decision.
  508. Add it to GUARDED_BODY_URLS once the handler runs it through a guard, or
  509. to NOT_A_FETCH_TARGET with the reason it is never requested. Do not add
  510. anything to KNOWN_UNGUARDED_* without also raising it.
  511. """
  512. classified = GUARDED_BODY_URLS | NOT_A_FETCH_TARGET | KNOWN_UNGUARDED_NEEDS_SCHEME_AWARE_GUARD
  513. unclassified = _request_body_url_fields() - classified
  514. assert not unclassified, (
  515. f"Unclassified request-body URL field(s): {sorted(unclassified)}. Route the value "
  516. f"through a guard and list it in GUARDED_BODY_URLS, or list it in NOT_A_FETCH_TARGET "
  517. f"with the reason it is never fetched."
  518. )
  519. def test_classification_lists_do_not_drift_from_the_routes():
  520. """The reverse direction: a stale entry means a route was renamed or
  521. removed and the list was not updated, which would hide the next one."""
  522. actual = _request_body_url_fields()
  523. stale = (GUARDED_BODY_URLS | NOT_A_FETCH_TARGET | KNOWN_UNGUARDED_NEEDS_SCHEME_AWARE_GUARD) - actual
  524. assert not stale, f"Classification entries no longer match any route: {sorted(stale)}"