From 4160575eaad65d1d994b1f2f7d396511cc85471c Mon Sep 17 00:00:00 2001 From: Gerrod Ubben Date: Mon, 23 Nov 2026 10:45:09 -0500 Subject: [PATCH] Sign pull-through package links Require signed tokens for upstream pull-through downloads and bind them to the remote's listing and package filename. Pass upstream SHA-256 digests to the downloader when available. Extracted from #1429 for backporting. Co-authored-by: Claude Opus 5.5 Assisted By: OpenAI Codex (cherry picked from commit 8807ad9d56ac01efe4aebf882eec9e7939fef783) --- CHANGES/+pull-through-signed-urls.bugfix | 1 + pulp_python/app/models.py | 26 +++++-- pulp_python/app/pypi/views.py | 12 ++-- pulp_python/app/utils.py | 32 +++++++++ .../tests/functional/api/test_full_mirror.py | 31 +++++++- pulp_python/tests/unit/test_pull_through.py | 70 +++++++++++++++++++ 6 files changed, 162 insertions(+), 10 deletions(-) create mode 100644 CHANGES/+pull-through-signed-urls.bugfix create mode 100644 pulp_python/tests/unit/test_pull_through.py diff --git a/CHANGES/+pull-through-signed-urls.bugfix b/CHANGES/+pull-through-signed-urls.bugfix new file mode 100644 index 000000000..c9b42ad93 --- /dev/null +++ b/CHANGES/+pull-through-signed-urls.bugfix @@ -0,0 +1 @@ +Pull-through downloads now require signed package links and use the upstream SHA-256 when available. diff --git a/pulp_python/app/models.py b/pulp_python/app/models.py index b3ecbf645..45b6d525c 100644 --- a/pulp_python/app/models.py +++ b/pulp_python/app/models.py @@ -20,12 +20,14 @@ from pulpcore.plugin.util import get_domain, get_domain_pk from .utils import ( + PULL_THROUGH_PARAM, PYPI_LAST_SERIAL, PYPI_SERIAL_CONSTANT, canonicalize_name, get_project_metadata_from_artifact, parse_project_metadata, python_content_to_json, + unsign_pull_through_token, ) log = getLogger(__name__) @@ -259,16 +261,32 @@ class PythonRemote(Remote, AutoAddObjPermsMixin): ) def get_remote_artifact_url(self, relative_path=None, request=None): - """Get url for remote_artifact""" - if request and (url := request.query.get("redirect")): - # This is a special case for pull-through caching + """Resolve content requests using the signed pull-through token.""" + if request is None: + return super().get_remote_artifact_url(relative_path) + if not (token := request.query.get(PULL_THROUGH_PARAM)): + return None + filename = PurePath(relative_path or "").name + if resolved := unsign_pull_through_token(self, token, filename): + url, sha256 = resolved + if sha256: + self.__dict__.setdefault("_pull_through_digests", {})[url] = sha256 return url - return super().get_remote_artifact_url(relative_path, request=request) + return None def get_remote_artifact_content_type(self, relative_path=None): """Return PythonPackageContent.""" return PythonPackageContent + def get_downloader(self, remote_artifact=None, url=None, download_factory=None, **kwargs): + """Validate pull-through downloads against the sha256 from their signed path.""" + digests = self.__dict__.get("_pull_through_digests", {}) + if remote_artifact and not remote_artifact.sha256: + remote_artifact.sha256 = digests.get(remote_artifact.url) + return super().get_downloader( + remote_artifact=remote_artifact, url=url, download_factory=download_factory, **kwargs + ) + class Meta: default_related_name = "%(app_label)s_%(model_name)s" permissions = [ diff --git a/pulp_python/app/pypi/views.py b/pulp_python/app/pypi/views.py index 0febe553f..9675755ff 100644 --- a/pulp_python/app/pypi/views.py +++ b/pulp_python/app/pypi/views.py @@ -44,6 +44,7 @@ PYPI_LAST_SERIAL, PYPI_SERIAL_CONSTANT, python_content_to_json, + sign_pull_through_path, write_simple_detail, write_simple_index, ) @@ -246,9 +247,10 @@ def parse_url(link): parsed = urlparse(link.url) digest, _, value = parsed.fragment.partition("=") stripped_url = urlunsplit(chain(parsed[:3], ("", ""))) - redirect = f"{path}/{link.text}?redirect={stripped_url}" - d_url = urljoin(self.base_content_url, redirect) - return link.text, d_url, value if digest == "sha256" else "" + sha256 = value if digest == "sha256" else "" + pt_path = sign_pull_through_path(remote, link.text, stripped_url, sha256) + d_url = urljoin(self.base_content_url, f"{path}/{pt_path}") + return link.text, d_url, sha256 url = remote.get_remote_artifact_url(f"simple/{package}/") kwargs = {} @@ -272,7 +274,9 @@ def retrieve(self, request, path, package): normalized = canonicalize_name(package) if self.distribution.remote: if not repo_ver or not content.filter(name__normalize=normalized).exists(): - return self.pull_through_package_simple(normalized, path, self.distribution.remote) + return self.pull_through_package_simple( + normalized, path, self.distribution.remote.cast() + ) if self.should_redirect(repo_version=repo_ver): return redirect(urljoin(self.base_content_url, f"{path}/simple/{normalized}/")) packages = ( diff --git a/pulp_python/app/utils.py b/pulp_python/app/utils.py index 28ca0de52..661cfe4a1 100644 --- a/pulp_python/app/utils.py +++ b/pulp_python/app/utils.py @@ -1,3 +1,4 @@ +import hashlib import json import shutil import tempfile @@ -5,6 +6,7 @@ import pkginfo from django.conf import settings +from django.core import signing from jinja2 import Template from packaging.utils import canonicalize_name from packaging.version import parse @@ -13,6 +15,9 @@ """TODO This serial constant is temporary until Python repositories implements serials""" PYPI_SERIAL_CONSTANT = 1000000000 +PULL_THROUGH_PARAM = "pt" +PULL_THROUGH_SALT = "pulp_python.pull_through" + simple_index_template = """ @@ -319,3 +324,30 @@ def write_simple_detail(project_name, project_packages, streamed=False): detail = Template(simple_detail_template, autoescape=True) context = {"project_name": project_name, "project_packages": project_packages} return detail.stream(**context) if streamed else detail.render(**context) + + +def _pull_through_signer(remote): + # Changing what the remote lists invalidates its tokens. + listing = json.dumps([remote.url, remote.includes, remote.excludes]) + salt = f"{PULL_THROUGH_SALT}:{remote.pk}:{hashlib.sha256(listing.encode()).hexdigest()}" + return signing.Signer(salt=salt) + + +def sign_pull_through_path(remote, filename, url, sha256=None): + """Return the content path carrying the signed upstream URL.""" + data = {"f": filename, "u": url} + if sha256: + data["s"] = sha256 + token = _pull_through_signer(remote).sign_object(data, compress=True) + return f"{filename}?{PULL_THROUGH_PARAM}={token}" + + +def unsign_pull_through_token(remote, token, filename): + """Return the upstream URL and SHA-256 for a valid token for this file.""" + try: + data = _pull_through_signer(remote).unsign_object(token) + except signing.BadSignature: + return None + if filename == data["f"]: + return data["u"], data.get("s") + return None diff --git a/pulp_python/tests/functional/api/test_full_mirror.py b/pulp_python/tests/functional/api/test_full_mirror.py index 00ee39796..56e0d1f75 100644 --- a/pulp_python/tests/functional/api/test_full_mirror.py +++ b/pulp_python/tests/functional/api/test_full_mirror.py @@ -1,4 +1,5 @@ import subprocess +from hashlib import sha256 from urllib.parse import urljoin, urlsplit import pytest @@ -49,7 +50,7 @@ def test_pull_through_simple(python_remote_factory, python_distribution_factory, assert len(project_page.packages) == 2 for package in project_page.packages: assert package.filename in PYTHON_XS_FIXTURE_CHECKSUMS - relative_path = f"{distro.base_path}/{package.filename}?redirect=" + relative_path = f"{distro.base_path}/{package.filename}?pt=" assert urljoin(pulp_content_url, relative_path) in package.url digests = package.get_digests() assert PYTHON_XS_FIXTURE_CHECKSUMS[package.filename] == digests["sha256"] @@ -70,4 +71,30 @@ def test_pull_through_with_repo( assert len(project_page.packages) == 2 for package in project_page.packages: assert package.filename in PYTHON_XS_FIXTURE_CHECKSUMS - assert "?redirect=" not in package.url + assert "?pt=" not in package.url + + +@pytest.mark.parallel +def test_pull_through_rejects_bad_links(python_remote_factory, python_distribution_factory): + """Test that pull-through only downloads from a valid signed link.""" + remote = python_remote_factory(url=PYPI_URL) + distro = python_distribution_factory(remote=remote.pulp_href) + remote2 = python_remote_factory(url=PYPI_URL) + distro2 = python_distribution_factory(remote=remote2.pulp_href) + url = f"{distro.base_url}simple/shelf-reader/" + + package1, package2 = parse_repo_project_response("shelf-reader", requests.get(url)).packages + token = package1.url.split("?pt=", 1)[1] + + wrong_file_url = package2.url.split("?pt=", 1)[0] + f"?pt={token}" + assert requests.get(wrong_file_url).status_code == 404 + + wrong_remote_url = package1.url.replace(f"/{distro.base_path}/", f"/{distro2.base_path}/") + assert requests.get(wrong_remote_url).status_code == 404 + + unsigned_url = package1.url.split("?pt=", 1)[0] + assert requests.get(unsigned_url).status_code == 404 + + response = requests.get(package1.url) + assert response.status_code == 200 + assert sha256(response.content).hexdigest() == PYTHON_XS_FIXTURE_CHECKSUMS[package1.filename] diff --git a/pulp_python/tests/unit/test_pull_through.py b/pulp_python/tests/unit/test_pull_through.py new file mode 100644 index 000000000..b3ac866ba --- /dev/null +++ b/pulp_python/tests/unit/test_pull_through.py @@ -0,0 +1,70 @@ +from types import SimpleNamespace +from uuid import uuid4 + +import pytest + +from pulp_python.app.utils import ( + PULL_THROUGH_PARAM, + sign_pull_through_path, + unsign_pull_through_token, +) + +FILENAME = "shelf_reader-0.1-py2-none-any.whl" +URL = f"https://files.example.com/packages/ab/cd/{FILENAME}" + + +def _remote(**kwargs): + kwargs.setdefault("pk", uuid4()) + kwargs.setdefault("url", "https://pypi.org/") + kwargs.setdefault("includes", []) + kwargs.setdefault("excludes", []) + return SimpleNamespace(**kwargs) + + +def _token(remote, **kwargs): + path = sign_pull_through_path(remote, FILENAME, URL, **kwargs) + filename, token = path.split(f"?{PULL_THROUGH_PARAM}=") + assert filename == FILENAME + return token + + +def test_round_trip(): + remote = _remote() + token = _token(remote, sha256="a" * 64) + + assert unsign_pull_through_token(remote, token, FILENAME) == (URL, "a" * 64) + + +def test_rejects_other_remote(): + token = _token(_remote(), sha256="a" * 64) + + assert unsign_pull_through_token(_remote(), token, FILENAME) is None + + +@pytest.mark.parametrize( + "changes", + [{"url": "https://example.com/"}, {"includes": ["shelf-reader"]}, {"excludes": ["django"]}], +) +def test_rejects_changed_remote(changes): + remote = _remote() + token = _token(remote, sha256="a" * 64) + + assert ( + unsign_pull_through_token(_remote(**{**vars(remote), **changes}), token, FILENAME) is None + ) + + +def test_rejects_other_filename(): + remote = _remote() + token = _token(remote, sha256="a" * 64) + + assert unsign_pull_through_token(remote, token, "evil-1.0-py3-none-any.whl") is None + + +def test_rejects_tampered_token(): + remote = _remote() + token = _token(remote, sha256="a" * 64) + tampered = token[:-1] + ("A" if token[-1] != "A" else "B") + + assert unsign_pull_through_token(remote, tampered, FILENAME) is None + assert unsign_pull_through_token(remote, "not-a-token", FILENAME) is None