|
| 1 | +import socket |
| 2 | + |
| 3 | +import requests |
| 4 | + |
| 5 | +from gaia.web.client import PinnedIPAdapter |
| 6 | + |
| 7 | + |
| 8 | +class DummyInfo: |
| 9 | + def __init__(self, ip, port=80): |
| 10 | + # emulate socket.getaddrinfo return structure |
| 11 | + # (family, socktype, proto, canonname, sockaddr) |
| 12 | + self.entry = (socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port)) |
| 13 | + |
| 14 | + def __iter__(self): |
| 15 | + yield self.entry |
| 16 | + |
| 17 | + |
| 18 | +def test_ip_pinning_blocks_rebind_to_private_ip(monkeypatch): |
| 19 | + # simulate DNS rebind: first resolution returns public IP, second returns private |
| 20 | + calls = { |
| 21 | + "count": 0, |
| 22 | + } |
| 23 | + |
| 24 | + def fake_getaddrinfo(host, port, *args, **kwargs): |
| 25 | + calls["count"] += 1 |
| 26 | + if calls["count"] == 1: |
| 27 | + return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("203.0.113.10", port))] |
| 28 | + return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("10.0.0.5", port))] |
| 29 | + |
| 30 | + monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo) |
| 31 | + |
| 32 | + session = requests.Session() |
| 33 | + adapter = PinnedIPAdapter() |
| 34 | + session.mount("http://", adapter) |
| 35 | + |
| 36 | + resp = session.get("http://example.local/path") |
| 37 | + |
| 38 | + # Adapter should have rewritten the request URL to use the first resolved IP |
| 39 | + assert resp.request is not None |
| 40 | + assert "203.0.113.10" in resp.request.url |
| 41 | + # And the pinned cache should store the resolved IP |
| 42 | + key = ("example.local", 80) |
| 43 | + assert adapter._pinned_cache.get(key) == "203.0.113.10" |
| 44 | + |
| 45 | + |
| 46 | +def test_ip_pinning_prevents_dns_rebind(monkeypatch): |
| 47 | + # Ensure subsequent resolutions would return a different IP, but adapter |
| 48 | + # continues to use the pinned one from cache. |
| 49 | + states = {"calls": 0} |
| 50 | + |
| 51 | + def fake_getaddrinfo(host, port, *args, **kwargs): |
| 52 | + states["calls"] += 1 |
| 53 | + if states["calls"] == 1: |
| 54 | + return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("198.51.100.7", port))] |
| 55 | + # Rebind to loopback on later calls |
| 56 | + return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", port))] |
| 57 | + |
| 58 | + monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo) |
| 59 | + |
| 60 | + session = requests.Session() |
| 61 | + adapter = PinnedIPAdapter() |
| 62 | + session.mount("http://", adapter) |
| 63 | + |
| 64 | + # First request pins 198.51.100.7 |
| 65 | + r1 = session.get("http://example.local/first") |
| 66 | + assert "198.51.100.7" in r1.request.url |
| 67 | + |
| 68 | + # On second request, getaddrinfo would return 127.0.0.1, but adapter should |
| 69 | + # use the cached 198.51.100.7 |
| 70 | + r2 = session.get("http://example.local/second") |
| 71 | + assert "198.51.100.7" in r2.request.url |
0 commit comments