Skip to content

Commit 85ff833

Browse files
authored
Merge pull request #1490 from gerrod3/patchback/backports/3.13/8807ad9d56ac01efe4aebf882eec9e7939fef783/pr-1484
[3.13] Sign pull-through package links
2 parents 9c9b1ec + 74df450 commit 85ff833

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,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__)
@@ -251,16 +253,32 @@ class PythonRemote(Remote, AutoAddObjPermsMixin):
251253
)
252254

253255
def get_remote_artifact_url(self, relative_path=None, request=None):
254-
"""Get url for remote_artifact"""
255-
if request and (url := request.query.get("redirect")):
256-
# This is a special case for pull-through caching
256+
"""Resolve content requests using the signed pull-through token."""
257+
if request is None:
258+
return super().get_remote_artifact_url(relative_path)
259+
if not (token := request.query.get(PULL_THROUGH_PARAM)):
260+
return None
261+
filename = PurePath(relative_path or "").name
262+
if resolved := unsign_pull_through_token(self, token, filename):
263+
url, sha256 = resolved
264+
if sha256:
265+
self.__dict__.setdefault("_pull_through_digests", {})[url] = sha256
257266
return url
258-
return super().get_remote_artifact_url(relative_path, request=request)
267+
return None
259268

260269
def get_remote_artifact_content_type(self, relative_path=None):
261270
"""Return PythonPackageContent."""
262271
return PythonPackageContent
263272

273+
def get_downloader(self, remote_artifact=None, url=None, download_factory=None, **kwargs):
274+
"""Validate pull-through downloads against the sha256 from their signed path."""
275+
digests = self.__dict__.get("_pull_through_digests", {})
276+
if remote_artifact and not remote_artifact.sha256:
277+
remote_artifact.sha256 = digests.get(remote_artifact.url)
278+
return super().get_downloader(
279+
remote_artifact=remote_artifact, url=url, download_factory=download_factory, **kwargs
280+
)
281+
264282
class Meta:
265283
default_related_name = "%(app_label)s_%(model_name)s"
266284
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
)
@@ -247,9 +248,10 @@ def parse_url(link):
247248
parsed = urlparse(link.url)
248249
digest, _, value = parsed.fragment.partition("=")
249250
stripped_url = urlunsplit(chain(parsed[:3], ("", "")))
250-
redirect = f"{path}/{link.text}?redirect={stripped_url}"
251-
d_url = urljoin(self.base_content_url, redirect)
252-
return link.text, d_url, value if digest == "sha256" else ""
251+
sha256 = value if digest == "sha256" else ""
252+
pt_path = sign_pull_through_path(remote, link.text, stripped_url, sha256)
253+
d_url = urljoin(self.base_content_url, f"{path}/{pt_path}")
254+
return link.text, d_url, sha256
253255

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

‎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.utils import canonicalize_name
1214
from packaging.version import parse
@@ -15,6 +17,9 @@
1517
"""TODO This serial constant is temporary until Python repositories implements serials"""
1618
PYPI_SERIAL_CONSTANT = 1000000000
1719

20+
PULL_THROUGH_PARAM = "pt"
21+
PULL_THROUGH_SALT = "pulp_python.pull_through"
22+
1823
simple_index_template = """<!DOCTYPE html>
1924
<html>
2025
<head>
@@ -363,3 +368,30 @@ def write_simple_detail(project_name, project_packages, streamed=False):
363368
detail = Template(simple_detail_template, autoescape=True)
364369
context = {"project_name": project_name, "project_packages": project_packages}
365370
return detail.stream(**context) if streamed else detail.render(**context)
371+
372+
373+
def _pull_through_signer(remote):
374+
# Changing what the remote lists invalidates its tokens.
375+
listing = json.dumps([remote.url, remote.includes, remote.excludes])
376+
salt = f"{PULL_THROUGH_SALT}:{remote.pk}:{hashlib.sha256(listing.encode()).hexdigest()}"
377+
return signing.Signer(salt=salt)
378+
379+
380+
def sign_pull_through_path(remote, filename, url, sha256=None):
381+
"""Return the content path carrying the signed upstream URL."""
382+
data = {"f": filename, "u": url}
383+
if sha256:
384+
data["s"] = sha256
385+
token = _pull_through_signer(remote).sign_object(data, compress=True)
386+
return f"{filename}?{PULL_THROUGH_PARAM}={token}"
387+
388+
389+
def unsign_pull_through_token(remote, token, filename):
390+
"""Return the upstream URL and SHA-256 for a valid token for this file."""
391+
try:
392+
data = _pull_through_signer(remote).unsign_object(token)
393+
except signing.BadSignature:
394+
return None
395+
if filename == data["f"]:
396+
return data["u"], data.get("s")
397+
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
assert PYTHON_XS_FIXTURE_CHECKSUMS[package.filename] == package.digests["sha256"]
5556

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