Skip to content

Commit 3e300f3

Browse files
committed
cursor comments
1 parent 546036a commit 3e300f3

5 files changed

Lines changed: 190 additions & 42 deletions

File tree

‎federation/scripts/add-peer.sh‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ done
3636
if [[ "${DISCOVER}" -eq 1 ]]; then
3737
DISCOVER_SCRIPT="${FEDERATION_ROOT}/scripts/lib/discover_peer_well_known.py"
3838
require_file "${DISCOVER_SCRIPT}"
39+
DISCOVER_OUTPUT=""
40+
if ! DISCOVER_OUTPUT="$(python3 "${DISCOVER_SCRIPT}" "${PEER_FQDN}")"; then
41+
die "discover failed for https://${PEER_FQDN}/.well-known/sds-federation.json"
42+
fi
3943
while IFS= read -r line; do
4044
key="${line%%=*}"
4145
value="${line#*=}"
@@ -47,7 +51,7 @@ if [[ "${DISCOVER}" -eq 1 ]]; then
4751
sync_service_url) PEER_SYNC="${value}" ;;
4852
*) die "unexpected discover output: ${line}" ;;
4953
esac
50-
done < <(python3 "${DISCOVER_SCRIPT}" "${PEER_FQDN}")
54+
done <<< "${DISCOVER_OUTPUT}"
5155
info "Discovered peer identity from https://${PEER_FQDN}/.well-known/sds-federation.json"
5256
fi
5357

‎gateway/sds_gateway/api_methods/federation/registry_application_review.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ def approve_registry_application(
8686
"reviewed_by",
8787
"reviewed_at",
8888
"rejected_reason",
89+
"updated_at",
8990
]
9091
if application.verified_well_known:
9192
update_fields.extend(
@@ -116,7 +117,13 @@ def reject_registry_application(
116117
application.reviewed_at = timezone.now()
117118
application.rejected_reason = (reason or "").strip()
118119
application.save(
119-
update_fields=["status", "reviewed_by", "reviewed_at", "rejected_reason"]
120+
update_fields=[
121+
"status",
122+
"reviewed_by",
123+
"reviewed_at",
124+
"rejected_reason",
125+
"updated_at",
126+
]
120127
)
121128
return ReviewResult(
122129
ok=True, message=f"Rejected application for {application.fqdn}."

‎gateway/sds_gateway/api_methods/federation/registry_application_verify.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,12 @@ def apply_verification_result(
7777
message: str,
7878
well_known: dict[str, Any] | None = None,
7979
) -> VerifyResult:
80-
update_fields = ["status", "last_verification_error", "verification_attempts"]
80+
update_fields = [
81+
"status",
82+
"last_verification_error",
83+
"verification_attempts",
84+
"updated_at",
85+
]
8186

8287
application.verification_attempts += 1
8388
if ok:

‎gateway/sds_gateway/api_methods/federation/registry_verify_fetch.py‎

Lines changed: 116 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
from __future__ import annotations
44

5+
import http.client
56
import ipaddress
7+
import json
68
import re
79
import socket
810
from typing import Any
@@ -30,6 +32,9 @@
3032
_COULD_NOT_FETCH_WELL_KNOWN = "Could not fetch well-known JSON."
3133
_WELL_KNOWN_INVALID_JSON = "Well-known response was not valid JSON."
3234
_WELL_KNOWN_NOT_OBJECT = "Well-known response was not a JSON object."
35+
_HTTP_SUCCESS_STATUS_MIN = 200
36+
_HTTP_SUCCESS_STATUS_MAX = 299
37+
_NO_PINNED_ADDRESSES = "no pinned addresses to connect"
3338

3439

3540
class RegistryVerifyFetchError(Exception):
@@ -47,8 +52,8 @@ def _is_lab_self_fetch(fqdn: str) -> bool:
4752
return bool(site_fqdn) and _normalized_host(fqdn) == site_fqdn
4853

4954

50-
def validate_applicant_hostname_for_verify(fqdn: str) -> None:
51-
"""Reject private, link-local, and non-public resolved targets."""
55+
def _resolve_global_addresses_for_verify(fqdn: str) -> list[str]:
56+
"""Resolve once; reject private targets; return global address strings."""
5257
host = _normalized_host(fqdn)
5358
if not host or "%" in host or "/" in host or "@" in host or ":" in host:
5459
raise RegistryVerifyFetchError(_INVALID_APPLICANT_HOSTNAME)
@@ -61,7 +66,7 @@ def validate_applicant_hostname_for_verify(fqdn: str) -> None:
6166
else:
6267
if not literal.is_global:
6368
raise RegistryVerifyFetchError(_APPLICANT_HOSTNAME_NOT_ALLOWED)
64-
return
69+
return [str(literal)]
6570

6671
try:
6772
infos = socket.getaddrinfo(host, 443, type=socket.SOCK_STREAM)
@@ -72,10 +77,87 @@ def validate_applicant_hostname_for_verify(fqdn: str) -> None:
7277
if not infos:
7378
raise RegistryVerifyFetchError(_COULD_NOT_RESOLVE_HOSTNAME)
7479

80+
addresses: list[str] = []
7581
for *_, sockaddr in infos:
7682
addr = ipaddress.ip_address(sockaddr[0])
7783
if not addr.is_global:
7884
raise RegistryVerifyFetchError(_APPLICANT_HOSTNAME_NOT_ALLOWED)
85+
addresses.append(sockaddr[0])
86+
return list(dict.fromkeys(addresses))
87+
88+
89+
def validate_applicant_hostname_for_verify(fqdn: str) -> None:
90+
"""Reject private, link-local, and non-public resolved targets."""
91+
_resolve_global_addresses_for_verify(fqdn)
92+
93+
94+
class _PinnedHTTPSConnection(http.client.HTTPSConnection):
95+
"""TLS to ``host`` while TCP connects to a pre-validated address."""
96+
97+
def __init__(self, host: str, pinned_address: str, *, timeout: float) -> None:
98+
self._pinned_address = pinned_address
99+
super().__init__(host, port=443, timeout=timeout)
100+
101+
def connect(self) -> None:
102+
self.sock = self._create_connection(
103+
(self._pinned_address, self.port),
104+
self.timeout,
105+
self.source_address,
106+
)
107+
server_hostname = self._tunnel_host or self.host
108+
self.sock = self._context.wrap_socket(
109+
self.sock, server_hostname=server_hostname
110+
)
111+
112+
113+
def _read_response_body_limited(
114+
response: http.client.HTTPResponse,
115+
max_bytes: int,
116+
) -> bytes:
117+
chunks: list[bytes] = []
118+
total = 0
119+
while True:
120+
chunk = response.read(8192)
121+
if not chunk:
122+
break
123+
total += len(chunk)
124+
if total > max_bytes:
125+
raise RegistryVerifyFetchError(_WELL_KNOWN_TOO_LARGE)
126+
chunks.append(chunk)
127+
return b"".join(chunks)
128+
129+
130+
def _pinned_https_get(
131+
url: str,
132+
hostname: str,
133+
pinned_addresses: list[str],
134+
timeout: int,
135+
) -> tuple[int, bytes]:
136+
"""GET over HTTPS using only addresses from verify DNS resolution."""
137+
parsed = urlparse(url)
138+
path = parsed.path or "/"
139+
if parsed.query:
140+
path = f"{path}?{parsed.query}"
141+
142+
last_error: BaseException | None = None
143+
for pinned in pinned_addresses:
144+
conn = _PinnedHTTPSConnection(hostname, pinned, timeout=timeout)
145+
try:
146+
conn.request("GET", path, headers={"Accept": "application/json"})
147+
response = conn.getresponse()
148+
body = _read_response_body_limited(response, _MAX_RESPONSE_BYTES)
149+
except RegistryVerifyFetchError:
150+
raise
151+
except (OSError, TimeoutError, http.client.HTTPException) as exc:
152+
last_error = exc
153+
else:
154+
return response.status, body
155+
finally:
156+
conn.close()
157+
158+
if last_error is not None:
159+
raise last_error
160+
raise OSError(_NO_PINNED_ADDRESSES)
79161

80162

81163
def fetch_well_known_json(
@@ -84,29 +166,46 @@ def fetch_well_known_json(
84166
) -> dict[str, Any]:
85167
"""GET applicant well-known JSON (HTTPS; local lab may use internal HTTP)."""
86168
url = resolve_well_known_fetch_url(fqdn)
169+
expected_host = _normalized_host(fqdn)
170+
pinned_addresses: list[str] | None = None
87171
if not _is_lab_self_fetch(fqdn):
88-
validate_applicant_hostname_for_verify(fqdn)
172+
pinned_addresses = _resolve_global_addresses_for_verify(fqdn)
89173
parsed = urlparse(url)
90-
expected_host = _normalized_host(fqdn)
91174
if (
92175
parsed.scheme != "https"
93176
or _normalized_host(parsed.hostname or "") != expected_host
94177
):
95178
raise RegistryVerifyFetchError(_INVALID_VERIFY_FETCH_URL)
96179

97180
try:
98-
response = requests.get(
99-
url,
100-
timeout=timeout,
101-
allow_redirects=False,
102-
headers={"Accept": "application/json"},
103-
)
104-
response.raise_for_status()
105-
content = response.content
106-
if len(content) > _MAX_RESPONSE_BYTES:
107-
raise RegistryVerifyFetchError(_WELL_KNOWN_TOO_LARGE)
108-
payload = response.json()
109-
except requests.RequestException:
181+
if pinned_addresses is not None:
182+
status, content = _pinned_https_get(
183+
url,
184+
expected_host,
185+
pinned_addresses,
186+
timeout,
187+
)
188+
if status < _HTTP_SUCCESS_STATUS_MIN or status > _HTTP_SUCCESS_STATUS_MAX:
189+
http_error_msg = f"HTTP {status}"
190+
raise requests.HTTPError(http_error_msg)
191+
else:
192+
response = requests.get(
193+
url,
194+
timeout=timeout,
195+
allow_redirects=False,
196+
headers={"Accept": "application/json"},
197+
)
198+
response.raise_for_status()
199+
content = response.content
200+
if len(content) > _MAX_RESPONSE_BYTES:
201+
raise RegistryVerifyFetchError(_WELL_KNOWN_TOO_LARGE)
202+
payload = json.loads(content)
203+
except (
204+
requests.RequestException,
205+
OSError,
206+
TimeoutError,
207+
http.client.HTTPException,
208+
):
110209
logger.warning(
111210
"registry verify HTTP failed fqdn={} url={}",
112211
fqdn,

‎gateway/sds_gateway/api_methods/tests/test_registry_verify_fetch.py‎

Lines changed: 55 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
from unittest.mock import patch
66

77
import pytest
8-
import requests
98
from django.test import override_settings
109

1110
from sds_gateway.api_methods.federation.registry_verify_fetch import (
@@ -29,46 +28,80 @@ def test_rejects_loopback_literal_ip() -> None:
2928
validate_applicant_hostname_for_verify("127.0.0.1")
3029

3130

32-
@patch(
33-
"sds_gateway.api_methods.federation.registry_verify_fetch.socket.getaddrinfo",
34-
return_value=[(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("10.0.0.5", 443))],
35-
)
3631
def test_rejects_private_resolved_ip() -> None:
37-
with pytest.raises(RegistryVerifyFetchError, match="not allowed"):
32+
with (
33+
patch(
34+
"sds_gateway.api_methods.federation.registry_verify_fetch.socket.getaddrinfo",
35+
return_value=[
36+
(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("10.0.0.5", 443)),
37+
],
38+
),
39+
pytest.raises(RegistryVerifyFetchError, match="not allowed"),
40+
):
3841
validate_applicant_hostname_for_verify("evil.example.edu")
3942

4043

4144
@override_settings(ADMIN_CONSOLE_ENV="production", SDS_SITE_FQDN="sds.crc.nd.edu")
42-
@patch("sds_gateway.api_methods.federation.registry_verify_fetch.requests.get")
45+
@patch(
46+
"sds_gateway.api_methods.federation.registry_verify_fetch._pinned_https_get",
47+
return_value=(200, b'{"fqdn":"public.example.edu"}'),
48+
)
4349
@patch(
4450
"sds_gateway.api_methods.federation.registry_verify_fetch.socket.getaddrinfo",
4551
return_value=[
4652
(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443)),
4753
],
4854
)
49-
def test_fetch_disables_redirects(mock_get: MagicMock) -> None:
50-
response = MagicMock()
51-
response.content = b'{"fqdn":"public.example.edu"}'
52-
response.json.return_value = {"fqdn": "public.example.edu"}
53-
response.raise_for_status = MagicMock()
54-
mock_get.return_value = response
55-
55+
def test_fetch_uses_pinned_https(
56+
mock_getaddrinfo: MagicMock,
57+
mock_pinned_get: MagicMock,
58+
) -> None:
5659
payload = fetch_well_known_json("public.example.edu")
5760
assert payload["fqdn"] == "public.example.edu"
58-
assert mock_get.call_args.kwargs["allow_redirects"] is False
61+
mock_pinned_get.assert_called_once()
62+
assert mock_pinned_get.call_args.args[2] == ["93.184.216.34"]
5963

6064

6165
@override_settings(ADMIN_CONSOLE_ENV="production", SDS_SITE_FQDN="sds.crc.nd.edu")
62-
@patch("sds_gateway.api_methods.federation.registry_verify_fetch.requests.get")
63-
def test_fetch_error_message_is_generic(mock_get: MagicMock) -> None:
64-
mock_get.side_effect = requests.ConnectionError("connection refused")
66+
@patch(
67+
"sds_gateway.api_methods.federation.registry_verify_fetch.socket.getaddrinfo",
68+
)
69+
def test_fetch_dns_rebind_does_not_use_second_resolution(
70+
mock_getaddrinfo: MagicMock,
71+
) -> None:
72+
mock_getaddrinfo.return_value = [
73+
(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443)),
74+
]
75+
76+
with patch(
77+
"sds_gateway.api_methods.federation.registry_verify_fetch._pinned_https_get",
78+
return_value=(200, b'{"fqdn":"public.example.edu"}'),
79+
) as mock_pinned_get:
80+
fetch_well_known_json("public.example.edu")
81+
82+
assert mock_getaddrinfo.call_count == 1
83+
mock_pinned_get.assert_called_once_with(
84+
"https://public.example.edu/.well-known/sds-federation.json",
85+
"public.example.edu",
86+
["93.184.216.34"],
87+
30,
88+
)
89+
90+
91+
@override_settings(ADMIN_CONSOLE_ENV="production", SDS_SITE_FQDN="sds.crc.nd.edu")
92+
@patch(
93+
"sds_gateway.api_methods.federation.registry_verify_fetch.socket.getaddrinfo",
94+
return_value=[
95+
(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443)),
96+
],
97+
)
98+
def test_fetch_error_message_is_generic(mock_getaddrinfo: MagicMock) -> None:
6599
with (
66100
patch(
67-
"sds_gateway.api_methods.federation.registry_verify_fetch.socket.getaddrinfo",
68-
return_value=[
69-
(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443)),
70-
],
101+
"sds_gateway.api_methods.federation.registry_verify_fetch._pinned_https_get",
102+
side_effect=OSError("connection refused"),
71103
),
72104
pytest.raises(RegistryVerifyFetchError, match="Could not fetch"),
73105
):
74106
fetch_well_known_json("public.example.edu")
107+
assert mock_getaddrinfo.called

0 commit comments

Comments
 (0)