Skip to content

Commit 935ee47

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 ac639c2 commit 935ee47

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
)
@@ -34,12 +35,14 @@
3435

3536
from .provenance import Provenance
3637
from .utils import (
38+
PULL_THROUGH_PARAM,
3739
PYPI_LAST_SERIAL,
3840
PYPI_SERIAL_CONSTANT,
3941
artifact_to_metadata_artifact,
4042
artifact_to_python_content_data,
4143
canonicalize_name,
4244
python_content_to_json,
45+
unsign_pull_through_token,
4346
)
4447

4548
log = getLogger(__name__)
@@ -357,30 +360,47 @@ class PythonRemote(Remote, AutoAddObjPermsMixin):
357360
vulnerabilities = models.BooleanField(default=False)
358361

359362
def get_remote_artifact_url(self, relative_path=None, request=None):
360-
"""Get url for remote_artifact"""
361-
if request and (url := request.query.get("redirect")):
362-
# This is a special case for pull-through caching
363-
# To handle PEP 658, it states that if the package has metadata available then it
364-
# should be found at the download URL + ".metadata". Thus if the request url ends with
365-
# ".metadata" then we need to add ".metadata" to the redirect url if not present.
366-
if relative_path:
367-
if relative_path.endswith(".metadata") and not url.endswith(".metadata"):
368-
url += ".metadata"
369-
# Handle special case for bug in pip (TODO file issue in pip) where it appends
370-
# ".metadata" to the redirect url instead of the request url
371-
if url.endswith(".metadata") and not relative_path.endswith(".metadata"):
372-
setattr(self, "_real_relative_path", url.rsplit("/", 1)[1])
363+
"""Get url for remote_artifact, content app requests need a signed pull-through token."""
364+
if request is None:
365+
return super().get_remote_artifact_url(relative_path)
366+
if not (token := request.query.get(PULL_THROUGH_PARAM)):
367+
return None
368+
filename = PurePath(relative_path or "").name
369+
# pip adds ".metadata" to the end of the url (the token) instead of the url path
370+
if token.endswith(".metadata"):
371+
token = token.removesuffix(".metadata")
372+
if not filename.endswith(".metadata"):
373+
filename = f"{filename}.metadata"
374+
setattr(self, "_real_relative_path", filename)
375+
if resolved := unsign_pull_through_token(self, token, filename):
376+
url, sha256 = resolved
377+
if sha256:
378+
self.__dict__.setdefault("_pull_through_digests", {})[url] = sha256
373379
return url
374-
return super().get_remote_artifact_url(relative_path, request=request)
380+
return None
375381

376382
def get_remote_artifact_content_type(self, relative_path=None):
377383
"""Return PythonPackageContent, except for metadata artifacts."""
378384
if hasattr(self, "_real_relative_path"):
379385
relative_path = getattr(self, "_real_relative_path")
380-
if relative_path and relative_path.endswith(".whl.metadata"):
386+
if relative_path and relative_path.endswith(".metadata"):
381387
return None
382388
return PythonPackageContent
383389

390+
def get_downloader(self, remote_artifact=None, url=None, download_factory=None, **kwargs):
391+
"""Validate pull-through downloads against the sha256 from their signed path."""
392+
digests = self.__dict__.get("_pull_through_digests", {})
393+
if remote_artifact and not remote_artifact.sha256:
394+
remote_artifact.sha256 = digests.get(remote_artifact.url)
395+
return super().get_downloader(
396+
remote_artifact=remote_artifact, url=url, download_factory=download_factory, **kwargs
397+
)
398+
399+
@hook(AFTER_UPDATE, when_any=["url", "includes", "excludes"], has_changed=True)
400+
def invalidate_pull_through_cache(self):
401+
"""Rebuild cached simple pages after the signed links they list are invalidated."""
402+
transaction.on_commit(self.invalidate_cache)
403+
384404
class Meta:
385405
default_related_name = "%(app_label)s_%(model_name)s"
386406
permissions = [

‎pulp_python/app/pypi/views.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
get_remote_package_filter,
5757
get_remote_simple_page,
5858
python_content_to_json,
59+
sign_pull_through_path,
5960
write_simple_detail,
6061
write_simple_detail_json,
6162
write_simple_index,
@@ -392,8 +393,14 @@ def pull_through_package_simple(self, package, path, remote):
392393
def parse_package(release_package):
393394
parsed = urlparse(release_package.url)
394395
stripped_url = urlunsplit(chain(parsed[:3], ("", "")))
395-
redirect_path = f"{path}/{release_package.filename}?redirect={stripped_url}"
396-
d_url = urljoin(self.base_content_url, redirect_path)
396+
pt_path = sign_pull_through_path(
397+
remote,
398+
release_package.filename,
399+
stripped_url,
400+
sha256=release_package.digests.get("sha256"),
401+
metadata_sha256=(release_package.metadata_digests or {}).get("sha256"),
402+
)
403+
d_url = urljoin(self.base_content_url, f"{path}/{pt_path}")
397404
return {
398405
"filename": release_package.filename,
399406
"url": d_url,
@@ -433,7 +440,8 @@ def retrieve(self, request, path, package):
433440
normalized = canonicalize_name(package)
434441
releases = {}
435442
if self.distribution.remote:
436-
releases = self.pull_through_package_simple(normalized, path, self.distribution.remote)
443+
remote = self.distribution.remote.cast()
444+
releases = self.pull_through_package_simple(normalized, path, remote)
437445
elif self.should_redirect(repo_version=repo_ver):
438446
return redirect(urljoin(self.base_content_url, f"{path}/simple/{normalized}/"))
439447
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
@@ -35,6 +36,10 @@
3536
SUPPORTED_METADATA_VERSIONS = ("1.0", "1.1", "1.2", "2.0", "2.1", "2.2", "2.3", "2.4", "2.5")
3637

3738
SIMPLE_API_VERSION = "1.1"
39+
40+
PULL_THROUGH_PARAM = "pt"
41+
PULL_THROUGH_SALT = "pulp_python.pull_through"
42+
3843
PYPI_SIMPLE_V1_HTML = "application/vnd.pypi.simple.v1+html"
3944
PYPI_SIMPLE_V1_JSON = "application/vnd.pypi.simple.v1+json"
4045

@@ -768,3 +773,40 @@ async def aget_remote_simple_page(package, remote, max_retries=1):
768773
else:
769774
page = ProjectPage.from_html(package, open(d.path, "rb").read(), base_url=url)
770775
return page
776+
777+
778+
def _pull_through_signer(remote):
779+
# Changing what the remote lists invalidates its tokens.
780+
listing = json.dumps([remote.url, remote.includes, remote.excludes])
781+
salt = f"{PULL_THROUGH_SALT}:{remote.pk}:{hashlib.sha256(listing.encode()).hexdigest()}"
782+
return signing.Signer(salt=salt)
783+
784+
785+
def sign_pull_through_path(remote, filename, url, sha256=None, metadata_sha256=None):
786+
"""Returns the content app path of a pull-through package, carrying its signed upstream url."""
787+
data = {"f": filename, "u": url}
788+
if sha256:
789+
data["s"] = sha256
790+
if metadata_sha256:
791+
data["m"] = metadata_sha256
792+
token = _pull_through_signer(remote).sign_object(data, compress=True)
793+
return f"{filename}?{PULL_THROUGH_PARAM}={token}"
794+
795+
796+
def unsign_pull_through_token(remote, token, filename):
797+
"""
798+
Returns the upstream (url, sha256) for a file of a signed pull-through token.
799+
800+
filename can be the signed package's filename or its PEP 658 metadata file. Returns None if
801+
the token is invalid, was signed for another remote or before its listing changed, or
802+
doesn't cover filename.
803+
"""
804+
try:
805+
data = _pull_through_signer(remote).unsign_object(token)
806+
except signing.BadSignature:
807+
return None
808+
if filename == data["f"]:
809+
return data["u"], data.get("s")
810+
if filename == f"{data['f']}.metadata" and data.get("m"):
811+
return f"{data['u']}.metadata", data["m"]
812+
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)