test_outbound_url_ssrf_guards.py 28 KB

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