test_outbound_url_ssrf_guards.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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 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. "bambuddy_internal_url",
  211. # Guarded by assert_safe_spoolman_url at each consumer (spoolman.py,
  212. # location_service.py, inventory.py, spoolbuddy.py,
  213. # spoolman_inventory.py) rather than in the schema, keeping its
  214. # established user-facing "Spoolman URL ..." error wording.
  215. "spoolman_url",
  216. # Not an HTTP URL: ldap:// or ldaps://, handed to an LDAP client, never
  217. # to httpx. The LAN-service guard requires http/https and would reject
  218. # every valid value. It also cannot reach a cloud-metadata endpoint,
  219. # since IMDS only speaks HTTP.
  220. "ldap_server_url",
  221. }
  222. url_fields = {name for name in AppSettingsUpdate.model_fields if name.endswith("_url")}
  223. unguarded = url_fields - set(LAN_SERVICE_SETTINGS) - exempt
  224. assert not unguarded, (
  225. f"New outbound URL setting(s) {sorted(unguarded)} are not covered by a "
  226. f"SSRF guard. Add them to AppSettingsUpdate._LAN_SERVICE_URL_FIELDS (or "
  227. f"the public-internet guard), or add them to `exempt` above with a reason."
  228. )
  229. # ---------------------------------------------------------------------------
  230. # Notification providers: URL guard + no response-body echo
  231. # ---------------------------------------------------------------------------
  232. def _response(status: int = 500, body: str = "root:x:0:0:root:/root:/bin/bash") -> httpx.Response:
  233. return httpx.Response(status_code=status, text=body, request=httpx.Request("POST", "http://10.0.0.1/"))
  234. SECRET_BODY = "root:x:0:0:root:/root:/bin/bash"
  235. def test_opaque_failure_does_not_return_the_response_body():
  236. message = ns._opaque_http_failure(_response(), label="webhook endpoint")
  237. assert SECRET_BODY not in message
  238. assert "500" in message, "the status code is still useful and is not sensitive"
  239. assert "webhook endpoint" in message
  240. def test_opaque_failure_logs_the_body_for_the_operator(caplog):
  241. """The body stays available to whoever administers the host — via logs,
  242. not via the API response."""
  243. with caplog.at_level("DEBUG", logger=ns.__name__):
  244. ns._opaque_http_failure(_response(), label="ntfy server")
  245. assert SECRET_BODY in caplog.text
  246. @pytest.mark.parametrize(
  247. "provider_label",
  248. ["ntfy server", "Bark server", "Gotify server", "webhook endpoint", "Home Assistant endpoint"],
  249. )
  250. def test_user_supplied_host_providers_use_the_opaque_path(provider_label: str):
  251. """Guards the mapping itself: each user-supplied-host provider must route
  252. its HTTP failure through _opaque_http_failure rather than formatting the
  253. body inline."""
  254. src = inspect.getsource(ns)
  255. assert f'_opaque_http_failure(response, label="{provider_label}")' in src
  256. def test_no_user_supplied_host_provider_formats_the_body_inline():
  257. """Any remaining ``response.text[:200]`` must belong to a host-pinned provider.
  258. Pushover/Telegram/CallMeBot/Discord all target hardcoded hosts (Discord via
  259. a webhook-prefix allowlist), so there is no trust boundary to cross.
  260. """
  261. src = inspect.getsource(ns).split("\n")
  262. # _send_telegram_message is the api.telegram.org call itself (#3046);
  263. # _send_telegram wraps it.
  264. host_pinned = {
  265. "_send_callmebot",
  266. "_send_pushover",
  267. "_send_telegram",
  268. "_send_telegram_message",
  269. "_send_discord",
  270. }
  271. current = None
  272. offenders = []
  273. for line in src:
  274. match = re.match(r"\s+async def (_send_\w+)", line)
  275. if match:
  276. current = match.group(1)
  277. if "response.text[:200]" in line and current not in host_pinned:
  278. offenders.append(current)
  279. assert not offenders, (
  280. f"{offenders} echo the upstream response body but do not target a "
  281. f"hardcoded host. Route the failure through _opaque_http_failure."
  282. )
  283. @pytest.mark.parametrize("url", UNIVERSALLY_BLOCKED)
  284. def test_provider_url_guard_rejects_dangerous_targets(url: str):
  285. assert ns._assert_safe_provider_url(url, label="Webhook URL") is not None
  286. @pytest.mark.parametrize("url", LAN_ALLOWED)
  287. def test_provider_url_guard_permits_self_hosted_servers(url: str):
  288. assert ns._assert_safe_provider_url(url, label="ntfy server URL") is None
  289. @pytest.mark.asyncio
  290. @pytest.mark.parametrize(
  291. ("provider_type", "config"),
  292. [
  293. ("ntfy", {"server": "http://169.254.169.254", "topic": "t"}),
  294. ("bark", {"server": "http://169.254.169.254", "device_key": "k"}),
  295. ("gotify", {"server": "http://169.254.169.254", "app_token": "t"}),
  296. ("webhook", {"webhook_url": "http://169.254.169.254/latest/meta-data/"}),
  297. ],
  298. )
  299. async def test_test_config_refuses_metadata_targets_without_a_request(provider_type: str, config: dict, monkeypatch):
  300. """The end-to-end shape of the reported attack: an unsaved config aimed at
  301. IMDS via the test endpoint. It must be refused before any HTTP call."""
  302. called = False
  303. async def _fail_if_called(*_a, **_kw):
  304. nonlocal called
  305. called = True
  306. raise AssertionError("outbound request should not have been attempted")
  307. service = ns.NotificationService()
  308. monkeypatch.setattr(service, "_get_client", _fail_if_called)
  309. success, message = await service.send_test_notification(provider_type, config)
  310. assert success is False
  311. assert called is False
  312. assert "cloud metadata" in message
  313. # ---------------------------------------------------------------------------
  314. # Smart plugs: the same request-body-URL shape as the notification test endpoint
  315. # ---------------------------------------------------------------------------
  316. #
  317. # POST /smart-plugs/{ha,rest}/test-connection take their URL from the request
  318. # body and never persist it, so the schema-layer validator on ``ha_url`` does
  319. # not apply. Both are reachable with only ``SMART_PLUGS_CONTROL``, which the
  320. # default Operators group carries and which does NOT imply ``SETTINGS_UPDATE``
  321. # — identical to the notification case above.
  322. #
  323. # Both previously used hand-rolled checks that got the policy wrong in both
  324. # directions: the REST one rejected a literal ``127.0.0.1`` while allowing
  325. # every non-literal hostname, and the HA one matched three literal strings and
  326. # never parsed the hostname as an IP at all.
  327. @pytest.mark.parametrize("url", UNIVERSALLY_BLOCKED)
  328. def test_rest_plug_guard_rejects_dangerous_targets(url: str):
  329. assert RESTSmartPlugService._validate_url(url) is False
  330. @pytest.mark.parametrize("url", LAN_ALLOWED)
  331. def test_rest_plug_guard_permits_the_normal_self_hosted_topology(url: str):
  332. """Includes literal 127.0.0.1, which the previous implementation rejected
  333. while accepting the equivalent "localhost" — a plug bridge on the same
  334. host could only be configured by spelling it one particular way."""
  335. assert RESTSmartPlugService._validate_url(url) is True
  336. @pytest.mark.parametrize("url", UNIVERSALLY_BLOCKED)
  337. def test_ha_guard_rejects_dangerous_targets(url: str):
  338. assert HomeAssistantService._validate_url(url) is None
  339. @pytest.mark.parametrize("url", LAN_ALLOWED)
  340. def test_ha_guard_permits_the_normal_self_hosted_topology(url: str):
  341. assert HomeAssistantService._validate_url(url) is not None
  342. def test_ha_guard_still_normalises_the_url_it_returns():
  343. """Delegating the policy must not change what the caller gets back:
  344. scheme+host+port+path, with query and fragment dropped."""
  345. assert HomeAssistantService._validate_url("http://192.168.1.5:8123/base?x=1#f") == "http://192.168.1.5:8123/base"
  346. assert HomeAssistantService._validate_url("http://ha.lan") == "http://ha.lan"
  347. def test_ha_guard_keeps_ipv6_literals_bracketed():
  348. """urlparse strips the brackets off an IPv6 host; re-emitting it without
  349. them yields an unparseable URL that httpx cannot dial."""
  350. assert HomeAssistantService._validate_url("http://[fd00::1]:8123/api") == "http://[fd00::1]:8123/api"
  351. @pytest.mark.parametrize(
  352. "ip",
  353. [
  354. "169.254.169.254",
  355. "100.100.100.200",
  356. "fd00:ec2::254",
  357. "0.0.0.0", # nosec B104 — rejection fixture, not a bind address: the assertion below is that the guard refuses it
  358. "239.255.255.250",
  359. ],
  360. )
  361. def test_tasmota_guard_rejects_metadata_and_misuse_addresses(ip: str):
  362. """Tasmota keeps its own stricter rule (bare IP literals only, loopback
  363. rejected — a plug is always a separate LAN device), but must not miss the
  364. destinations that are dangerous regardless of topology."""
  365. assert TasmotaService._validate_ip(ip) is False
  366. @pytest.mark.parametrize("ip", ["::ffff:169.254.169.254", "::ffff:100.100.100.200"])
  367. def test_tasmota_guard_unwraps_ipv4_mapped_ipv6(ip: str):
  368. assert TasmotaService._validate_ip(ip) is False
  369. @pytest.mark.parametrize("ip", ["192.168.1.50", "10.0.0.7", "172.16.4.9"])
  370. def test_tasmota_guard_still_permits_a_normal_lan_plug(ip: str):
  371. assert TasmotaService._validate_ip(ip) is True
  372. @pytest.mark.parametrize("ip", ["127.0.0.1", "tasmota.local", "not-an-ip"])
  373. def test_tasmota_guard_keeps_failing_closed_on_non_lan_device_values(ip: str):
  374. """Deliberately stricter than the shared LAN guard, and unchanged here."""
  375. assert TasmotaService._validate_ip(ip) is False
  376. @pytest.mark.asyncio
  377. @pytest.mark.parametrize(
  378. "target",
  379. ["http://169.254.169.254/", "http://100.100.100.200/", "http://metadata.google.internal/"],
  380. )
  381. async def test_rest_test_connection_refuses_metadata_without_a_request(target: str, monkeypatch):
  382. """End-to-end shape of the reported attack, mirroring the notification
  383. test above: an unsaved URL aimed at IMDS via the test endpoint must be
  384. refused before any HTTP call is made."""
  385. def _fail_if_called(*_a, **_kw):
  386. raise AssertionError("outbound request should not have been attempted")
  387. monkeypatch.setattr(httpx, "AsyncClient", _fail_if_called)
  388. result = await RESTSmartPlugService().test_connection(target, "GET", None)
  389. assert result["success"] is False
  390. assert "cloud metadata" in result["error"]
  391. @pytest.mark.asyncio
  392. @pytest.mark.parametrize(
  393. "target",
  394. ["http://169.254.169.254", "http://100.100.100.200", "http://metadata.google.internal"],
  395. )
  396. async def test_ha_test_connection_refuses_metadata_without_a_request(target: str, monkeypatch):
  397. def _fail_if_called(*_a, **_kw):
  398. raise AssertionError("outbound request should not have been attempted")
  399. monkeypatch.setattr(httpx, "AsyncClient", _fail_if_called)
  400. result = await HomeAssistantService().test_connection(target, "token")
  401. assert result["success"] is False
  402. @pytest.mark.asyncio
  403. @pytest.mark.parametrize("target", ["http://169.254.169.254", "http://metadata.google.internal"])
  404. async def test_obico_test_connection_refuses_metadata_without_a_request(target: str, monkeypatch):
  405. """Same shape again: obico_ml_url is guarded when saved via settings, but
  406. this route takes the URL from the request body and echoes the response."""
  407. from backend.app.services.obico_detection import ObicoDetectionService
  408. def _fail_if_called(*_a, **_kw):
  409. raise AssertionError("outbound request should not have been attempted")
  410. monkeypatch.setattr(httpx, "AsyncClient", _fail_if_called)
  411. result = await ObicoDetectionService().test_connection(target)
  412. assert result["ok"] is False
  413. assert result["body"] is None
  414. assert "cloud metadata" in result["error"]
  415. # ---------------------------------------------------------------------------
  416. # Drift backstop, part 2: URLs that arrive in a request body
  417. # ---------------------------------------------------------------------------
  418. #
  419. # `test_every_url_setting_is_either_guarded_or_explicitly_exempt` above only
  420. # walks `AppSettingsUpdate`. That is why the notification test endpoint, and
  421. # then the two smart-plug test endpoints, each had to be found by hand: a URL
  422. # that arrives in a request body and is never persisted is not a settings
  423. # field, so nothing enumerated it. This walks the live route table instead.
  424. def _request_body_url_fields() -> set[tuple[str, str]]:
  425. """Every (model, field) pair on a mutating route whose body carries a URL."""
  426. from fastapi.routing import APIRoute
  427. from pydantic import BaseModel
  428. from backend.app.main import app
  429. found: set[tuple[str, str]] = set()
  430. for route in app.routes:
  431. if not isinstance(route, APIRoute) or not ({"POST", "PUT", "PATCH"} & set(route.methods or ())):
  432. continue
  433. for param in route.dependant.body_params:
  434. # FastAPI moved the resolved annotation from `type_` onto
  435. # `field_info.annotation`; read both so this can't silently
  436. # enumerate nothing (which would make the assertions vacuous).
  437. annotation = getattr(param, "type_", None)
  438. if annotation is None:
  439. annotation = getattr(getattr(param, "field_info", None), "annotation", None)
  440. if not (isinstance(annotation, type) and issubclass(annotation, BaseModel)):
  441. continue
  442. for field in annotation.model_fields:
  443. if field == "url" or field.endswith("_url"):
  444. found.add((annotation.__name__, field))
  445. return found
  446. # Guarded: the handler (or the service it calls) puts the value through one of
  447. # the two tiers before any request is issued.
  448. GUARDED_BODY_URLS = {
  449. ("AppSettingsUpdate", "bambu_studio_api_url"),
  450. ("AppSettingsUpdate", "ha_url"),
  451. ("AppSettingsUpdate", "obico_ml_url"),
  452. ("AppSettingsUpdate", "orcaslicer_api_url"),
  453. ("AppSettingsUpdate", "spoolman_url"), # assert_safe_spoolman_url at each consumer
  454. ("HATestConnectionRequest", "url"), # homeassistant._validate_url
  455. ("RESTTestConnectionRequest", "url"), # rest_smart_plug._validate_url
  456. ("TestConnectionRequest", "url"), # obico_detection.test_connection
  457. # Manyfold (#1471): manyfold.config.normalize_url applies the LAN tier on
  458. # save and test, and ManyfoldService._send re-checks every redirect hop.
  459. ("ManyfoldConfigUpdate", "url"),
  460. ("ManyfoldTestRequest", "url"),
  461. ("OIDCProviderCreate", "issuer_url"), # public tier, via schemas.auth
  462. ("OIDCProviderCreate", "icon_url"),
  463. ("OIDCProviderUpdate", "issuer_url"),
  464. ("OIDCProviderUpdate", "icon_url"),
  465. # Gitea/Forgejo derive their API base from this and request it with the
  466. # stored token, so it is a real fetch target — guarded in
  467. # github_backup._enforce_private_repo, which both POST and PATCH funnel through.
  468. ("GitHubBackupConfigCreate", "repository_url"),
  469. ("GitHubBackupConfigUpdate", "repository_url"),
  470. # SmartPlug{Create,Update} persist these; every read goes back out through
  471. # RESTSmartPlugService._send_request, which applies the same guard.
  472. ("SmartPlugCreate", "rest_on_url"),
  473. ("SmartPlugCreate", "rest_off_url"),
  474. ("SmartPlugCreate", "rest_status_url"),
  475. ("SmartPlugCreate", "rest_power_url"),
  476. ("SmartPlugCreate", "rest_energy_url"),
  477. ("SmartPlugUpdate", "rest_on_url"),
  478. ("SmartPlugUpdate", "rest_off_url"),
  479. ("SmartPlugUpdate", "rest_status_url"),
  480. ("SmartPlugUpdate", "rest_power_url"),
  481. ("SmartPlugUpdate", "rest_energy_url"),
  482. }
  483. # Not a destination Bambuddy requests — no guard applies.
  484. NOT_A_FETCH_TARGET = {
  485. ("AppSettingsUpdate", "external_url"), # Bambuddy's own address (see exempt list above)
  486. ("AppSettingsUpdate", "bambuddy_internal_url"),
  487. ("AppSettingsUpdate", "ldap_server_url"), # ldap://, handed to an LDAP client
  488. ("ProjectCreate", "url"), # stored link, rendered in the UI, never fetched
  489. ("ProjectUpdate", "url"),
  490. ("BOMItemCreate", "sourcing_url"), # stored supplier link, never fetched
  491. ("BOMItemUpdate", "sourcing_url"),
  492. ("MakerWorldResolveRequest", "url"), # parsed for a model id; fetches go to a pinned CDN allowlist
  493. ("DeviceRegisterRequest", "backend_url"), # the device's view of Bambuddy's own address
  494. ("HeartbeatRequest", "backend_url"),
  495. ("SystemConfigRequest", "backend_url"),
  496. ("ExternalLinkCreate", "url"), # sidebar link, rendered in the UI, never requested
  497. ("ExternalLinkUpdate", "url"),
  498. ("AppMessage", "url"), # an app's link, appended to the notification text; never requested
  499. ("FileUpdate", "external_url"), # library file link (#3077), rendered in the UI, never fetched
  500. ("MaintenanceTypeCreate", "wiki_url"), # documentation link surfaced in the UI/notifications
  501. ("MaintenanceTypeUpdate", "wiki_url"),
  502. ("ArchiveUpdate", "external_url"), # stored source link for the model, never fetched
  503. }
  504. # Genuinely unguarded, and deliberately recorded rather than quietly exempted.
  505. # These reach `external_camera.capture_frame`, which dials rtsp:// as well as
  506. # http(s):// — the LAN-service guard rejects any non-HTTP scheme, so wiring it
  507. # up as-is would break every RTSP camera. Closing these needs a scheme-aware
  508. # variant of the guard, not a one-line delegation.
  509. KNOWN_UNGUARDED_NEEDS_SCHEME_AWARE_GUARD = {
  510. ("PrinterCreate", "external_camera_url"),
  511. ("PrinterCreate", "external_camera_snapshot_url"),
  512. ("PrinterUpdate", "external_camera_url"),
  513. ("PrinterUpdate", "external_camera_snapshot_url"),
  514. }
  515. def test_the_route_walk_actually_finds_something():
  516. """Guards the guard. If FastAPI's internals move again and the walk starts
  517. returning nothing, both assertions below pass vacuously and the backstop
  518. silently stops working — which is the exact failure it exists to prevent."""
  519. found = _request_body_url_fields()
  520. assert ("RESTTestConnectionRequest", "url") in found
  521. assert ("HATestConnectionRequest", "url") in found
  522. assert len(found) > 20
  523. def test_every_request_body_url_is_classified():
  524. """A new URL-bearing request field can't land without a decision.
  525. Add it to GUARDED_BODY_URLS once the handler runs it through a guard, or
  526. to NOT_A_FETCH_TARGET with the reason it is never requested. Do not add
  527. anything to KNOWN_UNGUARDED_* without also raising it.
  528. """
  529. classified = GUARDED_BODY_URLS | NOT_A_FETCH_TARGET | KNOWN_UNGUARDED_NEEDS_SCHEME_AWARE_GUARD
  530. unclassified = _request_body_url_fields() - classified
  531. assert not unclassified, (
  532. f"Unclassified request-body URL field(s): {sorted(unclassified)}. Route the value "
  533. f"through a guard and list it in GUARDED_BODY_URLS, or list it in NOT_A_FETCH_TARGET "
  534. f"with the reason it is never fetched."
  535. )
  536. def test_classification_lists_do_not_drift_from_the_routes():
  537. """The reverse direction: a stale entry means a route was renamed or
  538. removed and the list was not updated, which would hide the next one."""
  539. actual = _request_body_url_fields()
  540. stale = (GUARDED_BODY_URLS | NOT_A_FETCH_TARGET | KNOWN_UNGUARDED_NEEDS_SCHEME_AWARE_GUARD) - actual
  541. assert not stale, f"Classification entries no longer match any route: {sorted(stale)}"