Skip to content

Commit dfc1fb9

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. 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 ce93f4b commit dfc1fb9

6 files changed

Lines changed: 164 additions & 12 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.

‎pulp_python/app/models.py‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,13 @@
2020
from pulpcore.plugin.util import get_domain, get_domain_pk
2121

2222
from .utils import (
23+
PULL_THROUGH_PARAM,
2324
PYPI_LAST_SERIAL,
2425
PYPI_SERIAL_CONSTANT,
2526
artifact_to_python_content_data,
2627
canonicalize_name,
2728
python_content_to_json,
29+
unsign_pull_through_token,
2830
)
2931

3032
log = getLogger(__name__)
@@ -270,16 +272,32 @@ class PythonRemote(Remote, AutoAddObjPermsMixin):
270272
)
271273

272274
def get_remote_artifact_url(self, relative_path=None, request=None):
273-
"""Get url for remote_artifact"""
274-
if request and (url := request.query.get("redirect")):
275-
# This is a special case for pull-through caching
275+
"""Resolve content requests using the signed pull-through token."""
276+
if request is None:
277+
return super().get_remote_artifact_url(relative_path)
278+
if not (token := request.query.get(PULL_THROUGH_PARAM)):
279+
return None
280+
filename = PurePath(relative_path or "").name
281+
if resolved := unsign_pull_through_token(self, token, filename):
282+
url, sha256 = resolved
283+
if sha256:
284+
self.__dict__.setdefault("_pull_through_digests", {})[url] = sha256
276285
return url
277-
return super().get_remote_artifact_url(relative_path, request=request)
286+
return None
278287

279288
def get_remote_artifact_content_type(self, relative_path=None):
280289
"""Return PythonPackageContent."""
281290
return PythonPackageContent
282291

292+
def get_downloader(self, remote_artifact=None, url=None, download_factory=None, **kwargs):
293+
"""Validate pull-through downloads against the sha256 from their signed path."""
294+
digests = self.__dict__.get("_pull_through_digests", {})
295+
if remote_artifact and not remote_artifact.sha256:
296+
remote_artifact.sha256 = digests.get(remote_artifact.url)
297+
return super().get_downloader(
298+
remote_artifact=remote_artifact, url=url, download_factory=download_factory, **kwargs
299+
)
300+
283301
class Meta:
284302
default_related_name = "%(app_label)s_%(model_name)s"
285303
permissions = [

‎pulp_python/app/pypi/views.py‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
PYPI_SERIAL_CONSTANT,
4949
get_remote_package_filter,
5050
python_content_to_json,
51+
sign_pull_through_path,
5152
write_simple_detail,
5253
write_simple_index,
5354
)
@@ -250,9 +251,10 @@ def pull_through_package_simple(self, package, path, remote):
250251
def parse_package(release_package):
251252
parsed = urlparse(release_package.url)
252253
stripped_url = urlunsplit(chain(parsed[:3], ("", "")))
253-
redirect_path = f"{path}/{release_package.filename}?redirect={stripped_url}"
254-
d_url = urljoin(self.base_content_url, redirect_path)
255-
return release_package.filename, d_url, release_package.digests.get("sha256", "")
254+
sha256 = release_package.digests.get("sha256", "")
255+
pt_path = sign_pull_through_path(remote, release_package.filename, stripped_url, sha256)
256+
d_url = urljoin(self.base_content_url, f"{path}/{pt_path}")
257+
return release_package.filename, d_url, sha256
256258

257259
rfilter = get_remote_package_filter(remote)
258260
if not rfilter.filter_project(package):
@@ -286,7 +288,9 @@ def retrieve(self, request, path, package):
286288
normalized = canonicalize_name(package)
287289
releases = {}
288290
if self.distribution.remote:
289-
releases = self.pull_through_package_simple(normalized, path, self.distribution.remote)
291+
releases = self.pull_through_package_simple(
292+
normalized, path, self.distribution.remote.cast()
293+
)
290294
elif self.should_redirect(repo_version=repo_ver):
291295
return redirect(urljoin(self.base_content_url, f"{path}/simple/{normalized}/"))
292296
if content is not None:

‎pulp_python/app/utils.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import hashlib
12
import json
23
import os
34
import re
@@ -7,6 +8,7 @@
78

89
import pkginfo
910
from django.conf import settings
11+
from django.core import signing
1012
from jinja2 import Template
1113
from packaging.requirements import Requirement
1214
from packaging.utils import canonicalize_name
@@ -18,6 +20,9 @@
1820
"""TODO This serial constant is temporary until Python repositories implements serials"""
1921
PYPI_SERIAL_CONSTANT = 1000000000
2022

23+
PULL_THROUGH_PARAM = "pt"
24+
PULL_THROUGH_SALT = "pulp_python.pull_through"
25+
2126
simple_index_template = """<!DOCTYPE html>
2227
<html>
2328
<head>
@@ -491,3 +496,30 @@ def get_remote_package_filter(remote):
491496
rfilter = PackageIncludeFilter(remote)
492497
_remote_filters[remote.pulp_id] = (remote.pulp_last_updated, rfilter)
493498
return rfilter
499+
500+
501+
def _pull_through_signer(remote):
502+
# Changing what the remote lists invalidates its tokens.
503+
listing = json.dumps([remote.url, remote.includes, remote.excludes])
504+
salt = f"{PULL_THROUGH_SALT}:{remote.pk}:{hashlib.sha256(listing.encode()).hexdigest()}"
505+
return signing.Signer(salt=salt)
506+
507+
508+
def sign_pull_through_path(remote, filename, url, sha256=None):
509+
"""Return the content path carrying the signed upstream URL."""
510+
data = {"f": filename, "u": url}
511+
if sha256:
512+
data["s"] = sha256
513+
token = _pull_through_signer(remote).sign_object(data, compress=True)
514+
return f"{filename}?{PULL_THROUGH_PARAM}={token}"
515+
516+
517+
def unsign_pull_through_token(remote, token, filename):
518+
"""Return the upstream URL and SHA-256 for a valid token for this file."""
519+
try:
520+
data = _pull_through_signer(remote).unsign_object(token)
521+
except signing.BadSignature:
522+
return None
523+
if filename == data["f"]:
524+
return data["u"], data.get("s")
525+
return None

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

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import subprocess
2+
from hashlib import sha256
23
from random import sample
34
from urllib.parse import urljoin, urlsplit
45

@@ -53,7 +54,7 @@ def test_pull_through_simple(python_remote_factory, python_distribution_factory,
5354
assert len(project_page.packages) == 2
5455
for package in project_page.packages:
5556
assert package.filename in PYTHON_XS_FIXTURE_CHECKSUMS
56-
relative_path = f"{distro.base_path}/{package.filename}?redirect="
57+
relative_path = f"{distro.base_path}/{package.filename}?pt="
5758
assert urljoin(pulp_content_url, relative_path) in package.url
5859
assert PYTHON_XS_FIXTURE_CHECKSUMS[package.filename] == package.digests["sha256"]
5960

@@ -115,7 +116,7 @@ def test_pull_through_with_repo(
115116
url = urljoin(distro.base_url, "simple/aiohttp/")
116117
project_page = ProjectPage.from_response(requests.get(url), "aiohttp")
117118
for package in sample(project_page.packages, 3):
118-
assert "?redirect=" in package.url
119+
assert "?pt=" in package.url
119120
r = requests.get(package.url)
120121
assert r.status_code == 200
121122

@@ -153,12 +154,12 @@ def test_pull_through_local_only(
153154
url = f"{distro.base_url}simple/pulpcore/"
154155
r = requests.get(url)
155156
assert r.status_code == 200
156-
assert "?redirect=" not in r.text
157+
assert "?pt=" not in r.text
157158

158159
url = f"{distro.base_url}simple/shelf-reader/"
159160
r = requests.get(url)
160161
assert r.status_code == 200
161-
assert "?redirect=" in r.text
162+
assert "?pt=" in r.text
162163

163164
url = f"{distro.base_url}simple/pulp_python/"
164165
r = requests.get(url)
@@ -184,3 +185,29 @@ def test_pull_through_filtering_bad_names(python_remote_factory, python_distribu
184185
# Should have no packages with None version (they get filtered out)
185186
assert len(project_page.packages) > 0
186187
assert all(package.version is not None for package in project_page.packages)
188+
189+
190+
@pytest.mark.parallel
191+
def test_pull_through_rejects_bad_links(python_remote_factory, python_distribution_factory):
192+
"""Test that pull-through only downloads from a valid signed link."""
193+
remote = python_remote_factory(includes=["shelf-reader"])
194+
distro = python_distribution_factory(remote=remote.pulp_href)
195+
remote2 = python_remote_factory(includes=["shelf-reader"])
196+
distro2 = python_distribution_factory(remote=remote2.pulp_href)
197+
url = f"{distro.base_url}simple/shelf-reader/"
198+
199+
package1, package2 = ProjectPage.from_response(requests.get(url), "shelf-reader").packages
200+
token = package1.url.split("?pt=", 1)[1]
201+
202+
wrong_file_url = package2.url.split("?pt=", 1)[0] + f"?pt={token}"
203+
assert requests.get(wrong_file_url).status_code == 404
204+
205+
wrong_remote_url = package1.url.replace(f"/{distro.base_path}/", f"/{distro2.base_path}/")
206+
assert requests.get(wrong_remote_url).status_code == 404
207+
208+
unsigned_url = package1.url.split("?pt=", 1)[0]
209+
assert requests.get(unsigned_url).status_code == 404
210+
211+
response = requests.get(package1.url)
212+
assert response.status_code == 200
213+
assert sha256(response.content).hexdigest() == PYTHON_XS_FIXTURE_CHECKSUMS[package1.filename]
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
from types import SimpleNamespace
2+
from uuid import uuid4
3+
4+
import pytest
5+
6+
from pulp_python.app.utils import (
7+
PULL_THROUGH_PARAM,
8+
sign_pull_through_path,
9+
unsign_pull_through_token,
10+
)
11+
12+
FILENAME = "shelf_reader-0.1-py2-none-any.whl"
13+
URL = f"https://files.example.com/packages/ab/cd/{FILENAME}"
14+
15+
16+
def _remote(**kwargs):
17+
kwargs.setdefault("pk", uuid4())
18+
kwargs.setdefault("url", "https://pypi.org/")
19+
kwargs.setdefault("includes", [])
20+
kwargs.setdefault("excludes", [])
21+
return SimpleNamespace(**kwargs)
22+
23+
24+
def _token(remote, **kwargs):
25+
path = sign_pull_through_path(remote, FILENAME, URL, **kwargs)
26+
filename, token = path.split(f"?{PULL_THROUGH_PARAM}=")
27+
assert filename == FILENAME
28+
return token
29+
30+
31+
def test_round_trip():
32+
remote = _remote()
33+
token = _token(remote, sha256="a" * 64)
34+
35+
assert unsign_pull_through_token(remote, token, FILENAME) == (URL, "a" * 64)
36+
37+
38+
def test_rejects_other_remote():
39+
token = _token(_remote(), sha256="a" * 64)
40+
41+
assert unsign_pull_through_token(_remote(), token, FILENAME) is None
42+
43+
44+
@pytest.mark.parametrize(
45+
"changes",
46+
[{"url": "https://example.com/"}, {"includes": ["shelf-reader"]}, {"excludes": ["django"]}],
47+
)
48+
def test_rejects_changed_remote(changes):
49+
remote = _remote()
50+
token = _token(remote, sha256="a" * 64)
51+
52+
assert (
53+
unsign_pull_through_token(_remote(**{**vars(remote), **changes}), token, FILENAME) is None
54+
)
55+
56+
57+
def test_rejects_other_filename():
58+
remote = _remote()
59+
token = _token(remote, sha256="a" * 64)
60+
61+
assert unsign_pull_through_token(remote, token, "evil-1.0-py3-none-any.whl") is None
62+
63+
64+
def test_rejects_tampered_token():
65+
remote = _remote()
66+
token = _token(remote, sha256="a" * 64)
67+
tampered = token[:-1] + ("A" if token[-1] != "A" else "B")
68+
69+
assert unsign_pull_through_token(remote, tampered, FILENAME) is None
70+
assert unsign_pull_through_token(remote, "not-a-token", FILENAME) is None

0 commit comments

Comments
 (0)