Skip to content

Commit b2dd6da

Browse files
committed
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 and invalidate cached simple pages when the remote's listing changes. Extracted from #1429 for backporting. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Assisted By: OpenAI Codex (cherry picked from commit 8807ad9)
1 parent 6ab932c commit b2dd6da

6 files changed

Lines changed: 246 additions & 31 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Pull-through downloads now require signed package links and use the upstream SHA-256 when available. Refresh cached simple index pages to replace old unsigned links.

‎pulp_python/app/models.py‎

Lines changed: 36 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@
77
from django.conf import settings
88
from django.contrib.postgres.fields import ArrayField
99
from django.core.exceptions import ObjectDoesNotExist
10-
from django.db import models
10+
from django.db import models, transaction
1111
from django_lifecycle import (
12+
AFTER_UPDATE,
1213
BEFORE_SAVE,
1314
hook,
1415
)
@@ -27,12 +28,14 @@
2728

2829
from .provenance import Provenance
2930
from .utils import (
31+
PULL_THROUGH_PARAM,
3032
PYPI_LAST_SERIAL,
3133
PYPI_SERIAL_CONSTANT,
3234
artifact_to_metadata_artifact,
3335
artifact_to_python_content_data,
3436
canonicalize_name,
3537
python_content_to_json,
38+
unsign_pull_through_token,
3639
)
3740

3841
log = getLogger(__name__)
@@ -322,30 +325,47 @@ class PythonRemote(Remote, AutoAddObjPermsMixin):
322325
provenance = models.BooleanField(default=False)
323326

324327
def get_remote_artifact_url(self, relative_path=None, request=None):
325-
"""Get url for remote_artifact"""
326-
if request and (url := request.query.get("redirect")):
327-
# This is a special case for pull-through caching
328-
# To handle PEP 658, it states that if the package has metadata available then it
329-
# should be found at the download URL + ".metadata". Thus if the request url ends with
330-
# ".metadata" then we need to add ".metadata" to the redirect url if not present.
331-
if relative_path:
332-
if relative_path.endswith(".metadata") and not url.endswith(".metadata"):
333-
url += ".metadata"
334-
# Handle special case for bug in pip (TODO file issue in pip) where it appends
335-
# ".metadata" to the redirect url instead of the request url
336-
if url.endswith(".metadata") and not relative_path.endswith(".metadata"):
337-
setattr(self, "_real_relative_path", url.rsplit("/", 1)[1])
328+
"""Get url for remote_artifact, content app requests need a signed pull-through token."""
329+
if request is None:
330+
return super().get_remote_artifact_url(relative_path)
331+
if not (token := request.query.get(PULL_THROUGH_PARAM)):
332+
return None
333+
filename = PurePath(relative_path or "").name
334+
# pip adds ".metadata" to the end of the url (the token) instead of the url path
335+
if token.endswith(".metadata"):
336+
token = token.removesuffix(".metadata")
337+
if not filename.endswith(".metadata"):
338+
filename = f"{filename}.metadata"
339+
setattr(self, "_real_relative_path", filename)
340+
if resolved := unsign_pull_through_token(self, token, filename):
341+
url, sha256 = resolved
342+
if sha256:
343+
self.__dict__.setdefault("_pull_through_digests", {})[url] = sha256
338344
return url
339-
return super().get_remote_artifact_url(relative_path, request=request)
345+
return None
340346

341347
def get_remote_artifact_content_type(self, relative_path=None):
342348
"""Return PythonPackageContent, except for metadata artifacts."""
343349
if hasattr(self, "_real_relative_path"):
344350
relative_path = getattr(self, "_real_relative_path")
345-
if relative_path and relative_path.endswith(".whl.metadata"):
351+
if relative_path and relative_path.endswith(".metadata"):
346352
return None
347353
return PythonPackageContent
348354

355+
def get_downloader(self, remote_artifact=None, url=None, download_factory=None, **kwargs):
356+
"""Validate pull-through downloads against the sha256 from their signed path."""
357+
digests = self.__dict__.get("_pull_through_digests", {})
358+
if remote_artifact and not remote_artifact.sha256:
359+
remote_artifact.sha256 = digests.get(remote_artifact.url)
360+
return super().get_downloader(
361+
remote_artifact=remote_artifact, url=url, download_factory=download_factory, **kwargs
362+
)
363+
364+
@hook(AFTER_UPDATE, when_any=["url", "includes", "excludes"], has_changed=True)
365+
def invalidate_pull_through_cache(self):
366+
"""Rebuild cached simple pages after the signed links they list are invalidated."""
367+
transaction.on_commit(self.invalidate_cache)
368+
349369
class Meta:
350370
default_related_name = "%(app_label)s_%(model_name)s"
351371
permissions = [

‎pulp_python/app/pypi/views.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949
get_remote_package_filter,
5050
get_remote_simple_page,
5151
python_content_to_json,
52+
sign_pull_through_path,
5253
write_simple_detail,
5354
write_simple_detail_json,
5455
write_simple_index,
@@ -321,8 +322,14 @@ def pull_through_package_simple(self, package, path, remote):
321322
def parse_package(release_package):
322323
parsed = urlparse(release_package.url)
323324
stripped_url = urlunsplit(chain(parsed[:3], ("", "")))
324-
redirect_path = f"{path}/{release_package.filename}?redirect={stripped_url}"
325-
d_url = urljoin(self.base_content_url, redirect_path)
325+
pt_path = sign_pull_through_path(
326+
remote,
327+
release_package.filename,
328+
stripped_url,
329+
sha256=release_package.digests.get("sha256"),
330+
metadata_sha256=(release_package.metadata_digests or {}).get("sha256"),
331+
)
332+
d_url = urljoin(self.base_content_url, f"{path}/{pt_path}")
326333
return {
327334
"filename": release_package.filename,
328335
"url": d_url,
@@ -357,7 +364,8 @@ def retrieve(self, request, path, package):
357364
normalized = canonicalize_name(package)
358365
releases = {}
359366
if self.distribution.remote:
360-
releases = self.pull_through_package_simple(normalized, path, self.distribution.remote)
367+
remote = self.distribution.remote.cast()
368+
releases = self.pull_through_package_simple(normalized, path, remote)
361369
elif self.should_redirect(repo_version=repo_ver):
362370
return redirect(urljoin(self.base_content_url, f"{path}/simple/{normalized}/"))
363371
if content is not None:

‎pulp_python/app/utils.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import pkginfo
1313
from aiohttp.client_exceptions import ClientError
1414
from django.conf import settings
15+
from django.core import signing
1516
from django.db.models import F, FilteredRelation, Q
1617
from django.db.utils import IntegrityError
1718
from jinja2 import Template
@@ -33,6 +34,10 @@
3334
SUPPORTED_METADATA_VERSIONS = ("1.0", "1.1", "1.2", "2.0", "2.1", "2.2", "2.3", "2.4")
3435

3536
SIMPLE_API_VERSION = "1.1"
37+
38+
PULL_THROUGH_PARAM = "pt"
39+
PULL_THROUGH_SALT = "pulp_python.pull_through"
40+
3641
PYPI_SIMPLE_V1_HTML = "application/vnd.pypi.simple.v1+html"
3742
PYPI_SIMPLE_V1_JSON = "application/vnd.pypi.simple.v1+json"
3843

@@ -728,3 +733,40 @@ async def aget_remote_simple_page(package, remote, max_retries=1):
728733
else:
729734
page = ProjectPage.from_html(package, open(d.path, "rb").read(), base_url=url)
730735
return page
736+
737+
738+
def _pull_through_signer(remote):
739+
# Changing what the remote lists invalidates its tokens.
740+
listing = json.dumps([remote.url, remote.includes, remote.excludes])
741+
salt = f"{PULL_THROUGH_SALT}:{remote.pk}:{hashlib.sha256(listing.encode()).hexdigest()}"
742+
return signing.Signer(salt=salt)
743+
744+
745+
def sign_pull_through_path(remote, filename, url, sha256=None, metadata_sha256=None):
746+
"""Returns the content app path of a pull-through package, carrying its signed upstream url."""
747+
data = {"f": filename, "u": url}
748+
if sha256:
749+
data["s"] = sha256
750+
if metadata_sha256:
751+
data["m"] = metadata_sha256
752+
token = _pull_through_signer(remote).sign_object(data, compress=True)
753+
return f"{filename}?{PULL_THROUGH_PARAM}={token}"
754+
755+
756+
def unsign_pull_through_token(remote, token, filename):
757+
"""
758+
Returns the upstream (url, sha256) for a file of a signed pull-through token.
759+
760+
filename can be the signed package's filename or its PEP 658 metadata file. Returns None if
761+
the token is invalid, was signed for another remote or before its listing changed, or
762+
doesn't cover filename.
763+
"""
764+
try:
765+
data = _pull_through_signer(remote).unsign_object(token)
766+
except signing.BadSignature:
767+
return None
768+
if filename == data["f"]:
769+
return data["u"], data.get("s")
770+
if filename == f"{data['f']}.metadata" and data.get("m"):
771+
return f"{data['u']}.metadata", data["m"]
772+
return None

‎pulp_python/tests/functional/api/test_full_mirror.py‎

Lines changed: 75 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def test_pull_through_simple(python_remote_factory, python_distribution_factory,
5454
assert len(project_page.packages) == 2
5555
for package in project_page.packages:
5656
assert package.filename in PYTHON_XS_FIXTURE_CHECKSUMS
57-
relative_path = f"{distro.base_path}/{package.filename}?redirect="
57+
relative_path = f"{distro.base_path}/{package.filename}?pt="
5858
assert urljoin(pulp_content_url, relative_path) in package.url
5959
assert PYTHON_XS_FIXTURE_CHECKSUMS[package.filename] == package.digests["sha256"]
6060

@@ -134,7 +134,7 @@ def test_pull_through_with_repo(
134134
url = urljoin(distro.base_url, "simple/aiohttp/")
135135
project_page = ProjectPage.from_response(requests.get(url), "aiohttp")
136136
for package in sample(project_page.packages, 3):
137-
assert "?redirect=" in package.url
137+
assert "?pt=" in package.url
138138
r = requests.get(package.url)
139139
assert r.status_code == 200
140140

@@ -172,12 +172,12 @@ def test_pull_through_local_only(
172172
url = f"{distro.base_url}simple/pulpcore/"
173173
r = requests.get(url)
174174
assert r.status_code == 200
175-
assert "?redirect=" not in r.text
175+
assert "?pt=" not in r.text
176176

177177
url = f"{distro.base_url}simple/shelf-reader/"
178178
r = requests.get(url)
179179
assert r.status_code == 200
180-
assert "?redirect=" in r.text
180+
assert "?pt=" in r.text
181181

182182
url = f"{distro.base_url}simple/pulp_python/"
183183
r = requests.get(url)
@@ -210,9 +210,8 @@ def test_pull_through_metadata(python_remote_factory, python_distribution_factor
210210
"""
211211
Tests that metadata is correctly served when using pull-through.
212212
213-
So when requesting the metadata url according to PEP 658 you should just need to add .metadata
214-
to the end of the url path. Since pull-through includes a redirect query parameter we need to
215-
test adding .metadata to the end of the url path vs adding it to the end of redirect query.
213+
According to PEP 658 the metadata url is the package url with .metadata added to its path.
214+
pip and uv build it differently (string vs path append), both have to work.
216215
"""
217216
remote = python_remote_factory(includes=["pytz"])
218217
distro = python_distribution_factory(remote=remote.pulp_href)
@@ -226,20 +225,84 @@ def test_pull_through_metadata(python_remote_factory, python_distribution_factor
226225
assert package1.has_metadata
227226
assert package2.has_metadata
228227

229-
# The correct way to get the metadata url: add to path (uv does this)
228+
# Add to path (uv does this)
230229
parts1 = urlsplit(package1.url)
231230
url1 = urlunsplit((parts1[0], parts1[1], parts1[2] + ".metadata", parts1[3], parts1[4]))
232231
r = requests.get(url1)
233232
assert r.status_code == 200
234233
assert sha256(r.content).hexdigest() == package1.metadata_digests["sha256"]
235234

236-
# The incorrect way to get the metadata url: add to end of string (pip does this)
235+
# Add to end of string (pip does this)
237236
url2 = package2.url + ".metadata"
238237
r = requests.get(url2)
239238
assert r.status_code == 200
240239
assert sha256(r.content).hexdigest() == package2.metadata_digests["sha256"]
241240

242241

242+
@pytest.mark.parallel
243+
def test_pull_through_rejects_bad_links(python_remote_factory, python_distribution_factory):
244+
"""Tests that pull-through only downloads files from links signed for the distro's remote."""
245+
remote = python_remote_factory(includes=["shelf-reader"])
246+
distro = python_distribution_factory(remote=remote.pulp_href)
247+
remote2 = python_remote_factory(includes=["shelf-reader"])
248+
distro2 = python_distribution_factory(remote=remote2.pulp_href)
249+
250+
url = f"{distro.base_url}simple/shelf-reader/"
251+
package1, package2 = ProjectPage.from_response(requests.get(url), "shelf-reader").packages
252+
token1 = package1.url.split("?pt=")[1]
253+
254+
# Tampered token
255+
tampered = token1[:-1] + ("A" if token1[-1] != "A" else "B")
256+
r = requests.get(package1.url.replace(token1, tampered))
257+
assert r.status_code == 404
258+
259+
# Token used for another file
260+
r = requests.get(package2.url.replace(package2.url.split("?pt=")[1], token1))
261+
assert r.status_code == 404
262+
263+
# Token used on a distribution with another remote
264+
r = requests.get(package1.url.replace(f"/{distro.base_path}/", f"/{distro2.base_path}/"))
265+
assert r.status_code == 404
266+
267+
# Old unsigned redirect links
268+
upstream_url = urljoin(remote.url, "simple/shelf-reader/")
269+
upstream = ProjectPage.from_response(requests.get(upstream_url), "shelf-reader").packages[0]
270+
r = requests.get(f"{distro.base_url}{upstream.filename}?redirect={upstream.url}")
271+
assert r.status_code == 404
272+
273+
r = requests.get(package1.url)
274+
assert r.status_code == 200
275+
assert sha256(r.content).hexdigest() == package1.digests["sha256"]
276+
277+
278+
@pytest.mark.parallel
279+
def test_pull_through_signed_links_remote_update(
280+
python_bindings, python_remote_factory, python_distribution_factory, monitor_task
281+
):
282+
"""Tests that changing what the remote lists invalidates its signed pull-through links."""
283+
remote = python_remote_factory(includes=["shelf-reader"])
284+
distro = python_distribution_factory(remote=remote.pulp_href)
285+
286+
url = f"{distro.base_url}simple/shelf-reader/"
287+
package1, package2 = ProjectPage.from_response(requests.get(url), "shelf-reader").packages
288+
289+
# Other edits keep the links working
290+
body = {"download_concurrency": 5}
291+
monitor_task(python_bindings.RemotesPythonApi.partial_update(remote.pulp_href, body).task)
292+
r = requests.get(package1.url)
293+
assert r.status_code == 200
294+
assert sha256(r.content).hexdigest() == package1.digests["sha256"]
295+
296+
body = {"includes": ["shelf-reader", "aiohttp"]}
297+
monitor_task(python_bindings.RemotesPythonApi.partial_update(remote.pulp_href, body).task)
298+
assert requests.get(package2.url).status_code == 404
299+
packages = ProjectPage.from_response(requests.get(url), "shelf-reader").packages
300+
package2 = next(p for p in packages if p.filename == package2.filename)
301+
r = requests.get(package2.url)
302+
assert r.status_code == 200
303+
assert sha256(r.content).hexdigest() == package2.digests["sha256"]
304+
305+
243306
@pytest.mark.parallel
244307
def test_pull_through_metadata_with_repo(
245308
python_repo_factory,
@@ -257,7 +320,7 @@ def test_pull_through_metadata_with_repo(
257320
filename = "pip-26.0.1-py3-none-any.whl"
258321
package = next(p for p in project_page.packages if p.filename == filename)
259322
assert package.has_metadata
260-
assert "?redirect=" in package.url
323+
assert "?pt=" in package.url
261324

262325
# Retrieve the metadata and assert the content was not saved to the repository
263326
parts = urlsplit(package.url)
@@ -268,7 +331,7 @@ def test_pull_through_metadata_with_repo(
268331
project_page = ProjectPage.from_response(requests.get(pip_url), "pip")
269332
package = next(p for p in project_page.packages if p.filename == filename)
270333
assert package.has_metadata
271-
assert "?redirect=" in package.url
334+
assert "?pt=" in package.url
272335

273336
# Now retrieve the package and assert the content was saved with metadata
274337
r = requests.get(package.url)
@@ -281,7 +344,7 @@ def test_pull_through_metadata_with_repo(
281344
# Check the simple page is updated to point to the local repository
282345
project_page = ProjectPage.from_response(requests.get(pip_url), "pip")
283346
package = next(p for p in project_page.packages if p.filename == filename)
284-
assert "?redirect=" not in package.url
347+
assert "?pt=" not in package.url
285348
r = requests.get(package.metadata_url)
286349
assert r.status_code == 200
287350
assert sha256(r.content).hexdigest() == package.metadata_digests["sha256"]

0 commit comments

Comments
 (0)