test_outbound_url_ssrf_guards.py 30 KB

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