Skip to content

Commit 9c4f98e

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 <[email protected]> Assisted By: OpenAI Codex (cherry picked from commit 8807ad9)
1 parent 2bb1a9f commit 9c4f98e

6 files changed

Lines changed: 162 additions & 10 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,12 +20,14 @@
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
canonicalize_name,
2627
get_project_metadata_from_artifact,
2728
parse_project_metadata,
2829
python_content_to_json,
30+
unsign_pull_through_token,
2931
)
3032

3133
log = getLogger(__name__)
@@ -259,16 +261,32 @@ class PythonRemote(Remote, AutoAddObjPermsMixin):
259261
)
260262

261263
def get_remote_artifact_url(self, relative_path=None, request=None):
262-
"""Get url for remote_artifact"""
263-
if request and (url := request.query.get("redirect")):
264-
# This is a special case for pull-through caching
264+
"""Resolve content requests using the signed pull-through token."""
265+
if request is None:
266+
return super().get_remote_artifact_url(relative_path)
267+
if not (token := request.query.get(PULL_THROUGH_PARAM)):
268+
return None
269+
filename = PurePath(relative_path or "").name
270+
if resolved := unsign_pull_through_token(self, token, filename):
271+
url, sha256 = resolved
272+
if sha256:
273+
self.__dict__.setdefault("_pull_through_digests", {})[url] = sha256
265274
return url
266-
return super().get_remote_artifact_url(relative_path, request=request)
275+
return None
267276

268277
def get_remote_artifact_content_type(self, relative_path=None):
269278
"""Return PythonPackageContent."""
270279
return PythonPackageContent
271280

281+
def get_downloader(self, remote_artifact=None, url=None, download_factory=None, **kwargs):
282+
"""Validate pull-through downloads against the sha256 from their signed path."""
283+
digests = self.__dict__.get("_pull_through_digests", {})
284+
if remote_artifact and not remote_artifact.sha256:
285+
remote_artifact.sha256 = digests.get(remote_artifact.url)
286+
return super().get_downloader(
287+
remote_artifact=remote_artifact, url=url, download_factory=download_factory, **kwargs
288+
)
289+
272290
class Meta:
273291
default_related_name = "%(app_label)s_%(model_name)s"
274292
permissions = [

‎pulp_python/app/pypi/views.py‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
PYPI_LAST_SERIAL,
4545
PYPI_SERIAL_CONSTANT,
4646
python_content_to_json,
47+
sign_pull_through_path,
4748
write_simple_detail,
4849
write_simple_index,
4950
)
@@ -246,9 +247,10 @@ def parse_url(link):
246247
parsed = urlparse(link.url)
247248
digest, _, value = parsed.fragment.partition("=")
248249
stripped_url = urlunsplit(chain(parsed[:3], ("", "")))
249-
redirect = f"{path}/{link.text}?redirect={stripped_url}"
250-
d_url = urljoin(self.base_content_url, redirect)
251-
return link.text, d_url, value if digest == "sha256" else ""
250+
sha256 = value if digest == "sha256" else ""
251+
pt_path = sign_pull_through_path(remote, link.text, stripped_url, sha256)
252+
d_url = urljoin(self.base_content_url, f"{path}/{pt_path}")
253+
return link.text, d_url, sha256
252254

253255
url = remote.get_remote_artifact_url(f"simple/{package}/")
254256
kwargs = {}
@@ -272,7 +274,9 @@ def retrieve(self, request, path, package):
272274
normalized = canonicalize_name(package)
273275
if self.distribution.remote:
274276
if not repo_ver or not content.filter(name__normalize=normalized).exists():
275-
return self.pull_through_package_simple(normalized, path, self.distribution.remote)
277+
return self.pull_through_package_simple(
278+
normalized, path, self.distribution.remote.cast()
279+
)
276280
if self.should_redirect(repo_version=repo_ver):
277281
return redirect(urljoin(self.base_content_url, f"{path}/simple/{normalized}/"))
278282
packages = (

‎pulp_python/app/utils.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1+
import hashlib
12
import json
23
import shutil
34
import tempfile
45
from collections import defaultdict
56

67
import pkginfo
78
from django.conf import settings
9+
from django.core import signing
810
from jinja2 import Template
911
from packaging.utils import canonicalize_name
1012
from packaging.version import parse
@@ -13,6 +15,9 @@
1315
"""TODO This serial constant is temporary until Python repositories implements serials"""
1416
PYPI_SERIAL_CONSTANT = 1000000000
1517

18+
PULL_THROUGH_PARAM = "pt"
19+
PULL_THROUGH_SALT = "pulp_python.pull_through"
20+
1621
simple_index_template = """<!DOCTYPE html>
1722
<html>
1823
<head>
@@ -319,3 +324,30 @@ def write_simple_detail(project_name, project_packages, streamed=False):
319324
detail = Template(simple_detail_template, autoescape=True)
320325
context = {"project_name": project_name, "project_packages": project_packages}
321326
return detail.stream(**context) if streamed else detail.render(**context)
327+
328+
329+
def _pull_through_signer(remote):
330+
# Changing what the remote lists invalidates its tokens.
331+
listing = json.dumps([remote.url, remote.includes, remote.excludes])
332+
salt = f"{PULL_THROUGH_SALT}:{remote.pk}:{hashlib.sha256(listing.encode()).hexdigest()}"
333+
return signing.Signer(salt=salt)
334+
335+
336+
def sign_pull_through_path(remote, filename, url, sha256=None):
337+
"""Return the content path carrying the signed upstream URL."""
338+
data = {"f": filename, "u": url}
339+
if sha256:
340+
data["s"] = sha256
341+
token = _pull_through_signer(remote).sign_object(data, compress=True)
342+
return f"{filename}?{PULL_THROUGH_PARAM}={token}"
343+
344+
345+
def unsign_pull_through_token(remote, token, filename):
346+
"""Return the upstream URL and SHA-256 for a valid token for this file."""
347+
try:
348+
data = _pull_through_signer(remote).unsign_object(token)
349+
except signing.BadSignature:
350+
return None
351+
if filename == data["f"]:
352+
return data["u"], data.get("s")
353+
return None

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

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

45
import pytest
@@ -49,7 +50,7 @@ def test_pull_through_simple(python_remote_factory, python_distribution_factory,
4950
assert len(project_page.packages) == 2
5051
for package in project_page.packages:
5152
assert package.filename in PYTHON_XS_FIXTURE_CHECKSUMS
52-
relative_path = f"{distro.base_path}/{package.filename}?redirect="
53+
relative_path = f"{distro.base_path}/{package.filename}?pt="
5354
assert urljoin(pulp_content_url, relative_path) in package.url
5455
digests = package.get_digests()
5556
assert PYTHON_XS_FIXTURE_CHECKSUMS[package.filename] == digests["sha256"]
@@ -70,4 +71,30 @@ def test_pull_through_with_repo(
7071
assert len(project_page.packages) == 2
7172
for package in project_page.packages:
7273
assert package.filename in PYTHON_XS_FIXTURE_CHECKSUMS
73-
assert "?redirect=" not in package.url
74+
assert "?pt=" not in package.url
75+
76+
77+
@pytest.mark.parallel
78+
def test_pull_through_rejects_bad_links(python_remote_factory, python_distribution_factory):
79+
"""Test that pull-through only downloads from a valid signed link."""
80+
remote = python_remote_factory(url=PYPI_URL)
81+
distro = python_distribution_factory(remote=remote.pulp_href)
82+
remote2 = python_remote_factory(url=PYPI_URL)
83+
distro2 = python_distribution_factory(remote=remote2.pulp_href)
84+
url = f"{distro.base_url}simple/shelf-reader/"
85+
86+
package1, package2 = parse_repo_project_response("shelf-reader", requests.get(url)).packages
87+
token = package1.url.split("?pt=", 1)[1]
88+
89+
wrong_file_url = package2.url.split("?pt=", 1)[0] + f"?pt={token}"
90+
assert requests.get(wrong_file_url).status_code == 404
91+
92+
wrong_remote_url = package1.url.replace(f"/{distro.base_path}/", f"/{distro2.base_path}/")
93+
assert requests.get(wrong_remote_url).status_code == 404
94+
95+
unsigned_url = package1.url.split("?pt=", 1)[0]
96+
assert requests.get(unsigned_url).status_code == 404
97+
98+
response = requests.get(package1.url)
99+
assert response.status_code == 200
100+
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)