test_url_safety.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. """Unit tests for the shared SSRF-data primitives (#1333).
  2. These primitives are imported by both ``_spoolman_helpers.assert_safe_spoolman_url``
  3. and ``_oidc_helpers.assert_safe_public_https_url``. Test them in isolation
  4. so a future change to one consumer doesn't accidentally drift the data.
  5. """
  6. import ipaddress
  7. import pytest
  8. from backend.app.api.routes._url_safety import (
  9. CLOUD_METADATA_IPS,
  10. NUMERIC_IP_RE,
  11. unwrap_ipv4_mapped,
  12. )
  13. def test_cloud_metadata_set_contains_known_endpoints():
  14. # Both v4 and v6 IMDS endpoints, plus Alibaba's variant.
  15. assert ipaddress.ip_address("169.254.169.254") in CLOUD_METADATA_IPS
  16. assert ipaddress.ip_address("100.100.100.200") in CLOUD_METADATA_IPS
  17. assert ipaddress.ip_address("fd00:ec2::254") in CLOUD_METADATA_IPS
  18. def test_cloud_metadata_set_is_frozen():
  19. # frozenset is the right immutable container — protects against
  20. # accidental mutation in tests/imports.
  21. assert isinstance(CLOUD_METADATA_IPS, frozenset)
  22. @pytest.mark.parametrize(
  23. "candidate",
  24. [
  25. "2130706433", # decimal-encoded 127.0.0.1
  26. "0x7f000001", # hex-encoded 127.0.0.1
  27. "0xFFFFFFFF", # uppercase hex
  28. "0",
  29. "4294967295", # max uint32
  30. ],
  31. )
  32. def test_numeric_ip_re_matches_encoded_forms(candidate):
  33. assert NUMERIC_IP_RE.match(candidate) is not None
  34. @pytest.mark.parametrize(
  35. "candidate",
  36. [
  37. "127.0.0.1", # dotted-decimal — not "numeric-encoded"
  38. "example.com",
  39. "spoolman.lan",
  40. "::1",
  41. "localhost",
  42. ],
  43. )
  44. def test_numeric_ip_re_rejects_normal_forms(candidate):
  45. assert NUMERIC_IP_RE.match(candidate) is None
  46. def test_unwrap_ipv4_mapped_unwraps_mapped_address():
  47. mapped = ipaddress.ip_address("::ffff:127.0.0.1")
  48. result = unwrap_ipv4_mapped(mapped)
  49. assert result == ipaddress.ip_address("127.0.0.1")
  50. assert isinstance(result, ipaddress.IPv4Address)
  51. def test_unwrap_ipv4_mapped_passes_through_pure_ipv4():
  52. addr = ipaddress.ip_address("8.8.8.8")
  53. assert unwrap_ipv4_mapped(addr) is addr
  54. def test_unwrap_ipv4_mapped_passes_through_pure_ipv6():
  55. addr = ipaddress.ip_address("2001:db8::1")
  56. assert unwrap_ipv4_mapped(addr) is addr