Merge pull request #1752 from infinito-nexus/fix/utils/docker/registry-redirect-auth

fix(registry): keep the registry token on the registry host across redirects
This commit is contained in:
kevinveenbirkenbach authored and GitHub committed 2026-11-13 19:22:19 +01:00
commit 28d05e0183
3 files changed
+132 -50

No files matched your search

+104 -41
View File
@@ -6,6 +6,8 @@ import tempfile
import unittest
import unittest.mock as mock
import urllib.error
import urllib.request
import urllib.response
from email.message import Message
from pathlib import Path
@@ -65,7 +67,7 @@ def _http_error(code: int, headers=None) -> urllib.error.HTTPError:
class TestManifestExists(_IsolatedProbeCache):
def test_present_returns_true(self) -> None:
with mock.patch.object(
registry.urllib.request, "urlopen", return_value=_Resp(status=200)
registry.OPENER, "open", return_value=_Resp(status=200)
) as opened:
self.assertIs(registry.manifest_exists("postgres", "16"), True)
url = opened.call_args.args[0].full_url
@@ -74,26 +76,22 @@ class TestManifestExists(_IsolatedProbeCache):
)
def test_absent_returns_false(self) -> None:
with mock.patch.object(
registry.urllib.request, "urlopen", side_effect=_http_error(404)
):
with mock.patch.object(registry.OPENER, "open", side_effect=_http_error(404)):
self.assertIs(registry.manifest_exists("postgres", "999"), False)
def test_network_error_is_indeterminate(self) -> None:
with mock.patch.object(
registry.urllib.request, "urlopen", side_effect=urllib.error.URLError("x")
registry.OPENER, "open", side_effect=urllib.error.URLError("x")
):
self.assertIsNone(registry.manifest_exists("postgres", "16"))
def test_auth_wall_without_realm_is_indeterminate(self) -> None:
with mock.patch.object(
registry.urllib.request, "urlopen", side_effect=_http_error(401)
):
with mock.patch.object(registry.OPENER, "open", side_effect=_http_error(401)):
self.assertIsNone(registry.manifest_exists("quay.io/foo/bar", "1"))
def test_non_dockerhub_registry_host(self) -> None:
with mock.patch.object(
registry.urllib.request, "urlopen", return_value=_Resp(status=200)
registry.OPENER, "open", return_value=_Resp(status=200)
) as opened:
registry.manifest_exists("quay.io/keycloak/keycloak", "26.6.3")
url = opened.call_args.args[0].full_url
@@ -103,8 +101,8 @@ class TestManifestExists(_IsolatedProbeCache):
class TestManifestDigest(unittest.TestCase):
def test_a_malformed_content_digest_is_indeterminate(self) -> None:
with mock.patch.object(
registry.urllib.request,
"urlopen",
registry.OPENER,
"open",
return_value=_Resp(
status=200, headers={"Docker-Content-Digest": "sha256:/../../x"}
),
@@ -114,8 +112,8 @@ class TestManifestDigest(unittest.TestCase):
def test_returns_the_content_digest_of_a_head_request(self) -> None:
with mock.patch.object(
registry.urllib.request,
"urlopen",
registry.OPENER,
"open",
return_value=_Resp(status=200, headers={"Docker-Content-Digest": HEAD}),
) as opened:
digest = registry.manifest_digest("roundcube/roundcubemail", "1.7.5-apache")
@@ -131,29 +129,23 @@ class TestManifestDigest(unittest.TestCase):
)
def test_missing_tag_has_no_digest(self) -> None:
with mock.patch.object(
registry.urllib.request, "urlopen", side_effect=_http_error(404)
):
with mock.patch.object(registry.OPENER, "open", side_effect=_http_error(404)):
self.assertIsNone(registry.manifest_digest("postgres", "999"))
def test_rate_limit_has_no_digest(self) -> None:
with mock.patch.object(
registry.urllib.request, "urlopen", side_effect=_http_error(429)
):
with mock.patch.object(registry.OPENER, "open", side_effect=_http_error(429)):
self.assertIsNone(registry.manifest_digest("postgres", "16"))
def test_answer_without_digest_header_has_no_digest(self) -> None:
with mock.patch.object(
registry.urllib.request, "urlopen", return_value=_Resp(status=200)
):
with mock.patch.object(registry.OPENER, "open", return_value=_Resp(status=200)):
self.assertIsNone(registry.manifest_digest("postgres", "16"))
class TestFetchRegistryTags(unittest.TestCase):
def test_anonymous_tags(self) -> None:
with mock.patch.object(
registry.urllib.request,
"urlopen",
registry.OPENER,
"open",
return_value=_Resp(body=b'{"tags": ["1.0.0", "1.1.0"]}'),
):
self.assertEqual(
@@ -174,7 +166,7 @@ class TestFetchRegistryTags(unittest.TestCase):
raise _http_error(401, {"WWW-Authenticate": challenge})
return _Resp(body=b'{"tags": ["2.0.0"]}')
with mock.patch.object(registry.urllib.request, "urlopen", side_effect=_fake):
with mock.patch.object(registry.OPENER, "open", side_effect=_fake):
self.assertEqual(registry.fetch_registry_tags("ghcr.io/foo/bar"), ["2.0.0"])
def test_a_realm_other_than_https_is_never_opened(self) -> None:
@@ -183,8 +175,8 @@ class TestFetchRegistryTags(unittest.TestCase):
with (
self.subTest(realm=realm),
mock.patch.object(
registry.urllib.request,
"urlopen",
registry.OPENER,
"open",
side_effect=_http_error(401, challenge),
) as opened,
):
@@ -200,21 +192,19 @@ class TestFetchRegistryTags(unittest.TestCase):
body=b'{"tags": ["a"]}',
)
page2 = _Resp(body=b'{"tags": ["b"]}')
with mock.patch.object(
registry.urllib.request, "urlopen", side_effect=[page1, page2]
):
with mock.patch.object(registry.OPENER, "open", side_effect=[page1, page2]):
self.assertEqual(registry.fetch_registry_tags("foo"), ["a", "b"])
def test_network_failure_returns_empty(self) -> None:
with mock.patch.object(
registry.urllib.request, "urlopen", side_effect=urllib.error.URLError("x")
registry.OPENER, "open", side_effect=urllib.error.URLError("x")
):
self.assertEqual(registry.fetch_registry_tags("foo"), [])
def test_last_cursor_seeds_query(self) -> None:
with mock.patch.object(
registry.urllib.request,
"urlopen",
registry.OPENER,
"open",
return_value=_Resp(body=b'{"tags": ["v1.0.0"]}'),
) as opened:
self.assertEqual(
@@ -226,6 +216,83 @@ class TestFetchRegistryTags(unittest.TestCase):
url, "https://registry.gitlab.com/v2/foo/bar/tags/list?n=1000&last=v"
)
def _page(self, link: str) -> tuple[list[str], list[str]]:
pages = [
(200, _headers({"Link": f'<{link}>; rel="next"'}), b'{"tags": ["a"]}'),
(200, _headers(), b'{"tags": ["b"]}'),
]
with mock.patch.object(registry, "_request", side_effect=pages) as requested:
tags = registry.fetch_registry_tags("foo")
return tags, [call.args[0] for call in requested.call_args_list]
def test_a_link_next_on_the_registry_pages(self) -> None:
for link in ("/v2/library/foo/tags/list?last=a", _TAGS_NEXT):
with self.subTest(link=link):
self.assertEqual(self._page(link), (["a", "b"], [_TAGS, _TAGS_NEXT]))
def test_a_link_next_off_the_registry_stops_paging(self) -> None:
for link in (
"https://evil.example/v2/library/foo/tags/list?last=a",
"http://registry-1.docker.io/v2/library/foo/tags/list?last=a",
):
with self.subTest(link=link):
self.assertEqual(self._page(link), (["a"], [_TAGS]))
_TAGS = "https://registry-1.docker.io/v2/library/foo/tags/list?n=1000"
_TAGS_NEXT = "https://registry-1.docker.io/v2/library/foo/tags/list?last=a"
_BLOB = "https://registry-1.docker.io/v2/library/foo/blobs/sha256%3Aabc"
def _reply(req, status: int, headers=None, body: bytes = b""):
resp = urllib.response.addinfourl(
io.BytesIO(body), _headers(headers), req.full_url, status
)
resp.msg = "reply"
return resp
class TestBlobRedirect(unittest.TestCase):
def _fetch(self, location: str):
seen: list[tuple[str, str | None]] = []
def _open(_handler, req):
auth = req.get_header("Authorization")
seen.append((req.full_url, auth))
if req.full_url != _BLOB:
return _reply(req, 200, body=b'{"os": "linux"}')
if auth is None:
return _reply(req, 401)
return _reply(req, 307, {"Location": location})
with (
mock.patch.object(registry, "_bearer_token", return_value="tok"),
mock.patch.object(urllib.request.HTTPSHandler, "https_open", _open),
mock.patch.object(urllib.request.HTTPHandler, "http_open", _open),
):
return registry.fetch_blob("foo", "sha256:abc"), seen
def test_a_cross_host_redirect_drops_the_token(self) -> None:
blob, seen = self._fetch("https://cdn.example/blob")
self.assertEqual(blob, {"os": "linux"})
self.assertEqual(seen[-1], ("https://cdn.example/blob", None))
def test_a_same_host_redirect_keeps_the_token(self) -> None:
target = "https://registry-1.docker.io/v2/library/foo/blobs/sha256%3Adef"
blob, seen = self._fetch(target)
self.assertEqual(blob, {"os": "linux"})
self.assertEqual(seen[-1], (target, "Bearer tok"))
def test_a_redirect_off_https_is_refused(self) -> None:
for target in (
"http://registry-1.docker.io/v2/library/foo/blobs/sha256%3Adef",
"http://cdn.example/blob",
):
with self.subTest(target=target):
blob, seen = self._fetch(target)
self.assertIsNone(blob)
self.assertEqual([url for url, _auth in seen], [_BLOB, _BLOB])
_SINGLE = {
"config": {"size": 100},
@@ -330,21 +397,17 @@ class TestProbeOrder(_IsolatedProbeCache):
class TestFetchManifest(unittest.TestCase):
def test_non_dict_body_is_indeterminate(self) -> None:
with mock.patch.object(
registry.urllib.request, "urlopen", return_value=_Resp(body=b"[]")
):
with mock.patch.object(registry.OPENER, "open", return_value=_Resp(body=b"[]")):
self.assertIsNone(registry.fetch_manifest("img", "1"))
def test_rate_limited_is_indeterminate(self) -> None:
with mock.patch.object(
registry.urllib.request, "urlopen", side_effect=_http_error(429)
):
with mock.patch.object(registry.OPENER, "open", side_effect=_http_error(429)):
self.assertIsNone(registry.fetch_manifest("img", "1"))
def test_present_manifest_is_parsed(self) -> None:
with mock.patch.object(
registry.urllib.request,
"urlopen",
registry.OPENER,
"open",
return_value=_Resp(body=b'{"layers": []}'),
):
self.assertEqual(registry.fetch_manifest("img", "1"), {"layers": []})
+19
View File
@@ -0,0 +1,19 @@
from __future__ import annotations
import urllib.error
import urllib.request
from urllib.parse import urlparse
class HttpsRedirectHandler(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
target = urlparse(newurl)
if target.scheme != "https":
raise urllib.error.HTTPError(req.full_url, code, msg, headers, fp)
new = super().redirect_request(req, fp, code, msg, headers, newurl)
if target.netloc != urlparse(req.full_url).netloc:
new.remove_header("Authorization")
return new
OPENER = urllib.request.build_opener(HttpsRedirectHandler)
+9 -9
View File
@@ -24,11 +24,12 @@ import tempfile
import urllib.error
import urllib.request
from pathlib import Path
from urllib.parse import quote, urlencode, urlparse
from urllib.parse import quote, urlencode, urljoin, urlparse
from utils.docker.digest import valid_digest
from utils.docker.image.ref import DOCKER_HUB_REGISTRIES, split_registry_and_name
from utils.docker.mirror import mirror_image
from utils.docker.redirect import OPENER
_UA = "infinito-nexus-version-updater"
_UNKNOWN_PLATFORM = "unknown"
@@ -76,7 +77,7 @@ def _bearer_token(challenge: str, repo: str) -> str | None:
req = urllib.request.Request( # noqa: S310 - https request to a trusted registry host
f"{realm}?{urlencode(query)}", headers={"User-Agent": _UA}
)
with urllib.request.urlopen(req, timeout=15) as resp: # noqa: S310 - https request to a trusted registry host
with OPENER.open(req, timeout=15) as resp:
body = json.loads(resp.read().decode())
except (
urllib.error.URLError,
@@ -103,7 +104,7 @@ def _request(url: str, repo: str, method: str, accept: str | None):
headers["Authorization"] = f"Bearer {token}"
req = urllib.request.Request(url, headers=headers, method=method) # noqa: S310 - https request to a trusted registry host
try:
with urllib.request.urlopen(req, timeout=15) as resp: # noqa: S310 - https request to a trusted registry host
with OPENER.open(req, timeout=15) as resp:
return (
resp.status,
resp.headers,
@@ -153,12 +154,11 @@ def fetch_registry_tags(
match = _LINK_NEXT_RE.search(resp_headers.get("Link", "") or "")
if not match:
break
nxt = match.group(1)
if nxt.startswith("http"):
url = nxt
else:
parsed = urlparse(url)
url = f"{parsed.scheme}://{parsed.netloc}{nxt}"
nxt = urljoin(url, match.group(1))
target = urlparse(nxt)
if target.scheme != "https" or target.netloc != urlparse(url).netloc:
break
url = nxt
return tags