Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES/+pull-through-signed-urls.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +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.
52 changes: 36 additions & 16 deletions pulp_python/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db import models, transaction
from django_lifecycle import (
AFTER_UPDATE,
BEFORE_SAVE,
hook,
)
Expand All @@ -34,12 +35,14 @@

from .provenance import Provenance
from .utils import (
PULL_THROUGH_PARAM,
PYPI_LAST_SERIAL,
PYPI_SERIAL_CONSTANT,
artifact_to_metadata_artifact,
artifact_to_python_content_data,
canonicalize_name,
python_content_to_json,
unsign_pull_through_token,
)

log = getLogger(__name__)
Expand Down Expand Up @@ -352,30 +355,47 @@ class PythonRemote(Remote, AutoAddObjPermsMixin):
provenance = models.BooleanField(default=False)

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

def get_remote_artifact_content_type(self, relative_path=None):
"""Return PythonPackageContent, except for metadata artifacts."""
if hasattr(self, "_real_relative_path"):
relative_path = getattr(self, "_real_relative_path")
if relative_path and relative_path.endswith(".whl.metadata"):
if relative_path and relative_path.endswith(".metadata"):
return None
return PythonPackageContent

def get_downloader(self, remote_artifact=None, url=None, download_factory=None, **kwargs):
"""Validate pull-through downloads against the sha256 from their signed path."""
digests = self.__dict__.get("_pull_through_digests", {})
if remote_artifact and not remote_artifact.sha256:
remote_artifact.sha256 = digests.get(remote_artifact.url)
return super().get_downloader(
remote_artifact=remote_artifact, url=url, download_factory=download_factory, **kwargs
)

@hook(AFTER_UPDATE, when_any=["url", "includes", "excludes"], has_changed=True)
def invalidate_pull_through_cache(self):
"""Rebuild cached simple pages after the signed links they list are invalidated."""
transaction.on_commit(self.invalidate_cache)

class Meta:
default_related_name = "%(app_label)s_%(model_name)s"
permissions = [
Expand Down
14 changes: 11 additions & 3 deletions pulp_python/app/pypi/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
get_remote_package_filter,
get_remote_simple_page,
python_content_to_json,
sign_pull_through_path,
write_simple_detail,
write_simple_detail_json,
write_simple_index,
Expand Down Expand Up @@ -392,8 +393,14 @@ def pull_through_package_simple(self, package, path, remote):
def parse_package(release_package):
parsed = urlparse(release_package.url)
stripped_url = urlunsplit(chain(parsed[:3], ("", "")))
redirect_path = f"{path}/{release_package.filename}?redirect={stripped_url}"
d_url = urljoin(self.base_content_url, redirect_path)
pt_path = sign_pull_through_path(
remote,
release_package.filename,
stripped_url,
sha256=release_package.digests.get("sha256"),
metadata_sha256=(release_package.metadata_digests or {}).get("sha256"),
)
d_url = urljoin(self.base_content_url, f"{path}/{pt_path}")
return {
"filename": release_package.filename,
"url": d_url,
Expand Down Expand Up @@ -433,7 +440,8 @@ def retrieve(self, request, path, package):
normalized = canonicalize_name(package)
releases = {}
if self.distribution.remote:
releases = self.pull_through_package_simple(normalized, path, self.distribution.remote)
remote = self.distribution.remote.cast()
releases = self.pull_through_package_simple(normalized, path, remote)
elif self.should_redirect(repo_version=repo_ver):
return redirect(urljoin(self.base_content_url, f"{path}/simple/{normalized}/"))
if content is not None:
Expand Down
42 changes: 42 additions & 0 deletions pulp_python/app/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import pkginfo
from aiohttp.client_exceptions import ClientError
from django.conf import settings
from django.core import signing
from django.db.models import F, FilteredRelation, Q
from django.db.utils import IntegrityError
from jinja2 import Template
Expand All @@ -33,6 +34,10 @@
SUPPORTED_METADATA_VERSIONS = ("1.0", "1.1", "1.2", "2.0", "2.1", "2.2", "2.3", "2.4", "2.5")

SIMPLE_API_VERSION = "1.1"

PULL_THROUGH_PARAM = "pt"
PULL_THROUGH_SALT = "pulp_python.pull_through"

PYPI_SIMPLE_V1_HTML = "application/vnd.pypi.simple.v1+html"
PYPI_SIMPLE_V1_JSON = "application/vnd.pypi.simple.v1+json"

Expand Down Expand Up @@ -747,3 +752,40 @@ async def aget_remote_simple_page(package, remote, max_retries=1):
else:
page = ProjectPage.from_html(package, open(d.path, "rb").read(), base_url=url)
return page


def _pull_through_signer(remote):
# Changing what the remote lists invalidates its tokens.
listing = json.dumps([remote.url, remote.includes, remote.excludes])
salt = f"{PULL_THROUGH_SALT}:{remote.pk}:{hashlib.sha256(listing.encode()).hexdigest()}"
return signing.Signer(salt=salt)


def sign_pull_through_path(remote, filename, url, sha256=None, metadata_sha256=None):
"""Returns the content app path of a pull-through package, carrying its signed upstream url."""
data = {"f": filename, "u": url}
if sha256:
data["s"] = sha256
if metadata_sha256:
data["m"] = metadata_sha256
token = _pull_through_signer(remote).sign_object(data, compress=True)
return f"{filename}?{PULL_THROUGH_PARAM}={token}"


def unsign_pull_through_token(remote, token, filename):
"""
Returns the upstream (url, sha256) for a file of a signed pull-through token.

filename can be the signed package's filename or its PEP 658 metadata file. Returns None if
the token is invalid, was signed for another remote or before its listing changed, or
doesn't cover filename.
"""
try:
data = _pull_through_signer(remote).unsign_object(token)
except signing.BadSignature:
return None
if filename == data["f"]:
return data["u"], data.get("s")
if filename == f"{data['f']}.metadata" and data.get("m"):
return f"{data['u']}.metadata", data["m"]
return None
87 changes: 75 additions & 12 deletions pulp_python/tests/functional/api/test_full_mirror.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def test_pull_through_simple(python_remote_factory, python_distribution_factory,
assert len(project_page.packages) == 2
for package in project_page.packages:
assert package.filename in PYTHON_XS_FIXTURE_CHECKSUMS
relative_path = f"{distro.base_path}/{package.filename}?redirect="
relative_path = f"{distro.base_path}/{package.filename}?pt="
assert urljoin(pulp_content_url, relative_path) in package.url
assert PYTHON_XS_FIXTURE_CHECKSUMS[package.filename] == package.digests["sha256"]

Expand Down Expand Up @@ -134,7 +134,7 @@ def test_pull_through_with_repo(
url = urljoin(distro.base_url, "simple/aiohttp/")
project_page = ProjectPage.from_response(requests.get(url), "aiohttp")
for package in sample(project_page.packages, 3):
assert "?redirect=" in package.url
assert "?pt=" in package.url
r = requests.get(package.url)
assert r.status_code == 200

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

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

url = f"{distro.base_url}simple/pulp_python/"
r = requests.get(url)
Expand Down Expand Up @@ -210,9 +210,8 @@ def test_pull_through_metadata(python_remote_factory, python_distribution_factor
"""
Tests that metadata is correctly served when using pull-through.

So when requesting the metadata url according to PEP 658 you should just need to add .metadata
to the end of the url path. Since pull-through includes a redirect query parameter we need to
test adding .metadata to the end of the url path vs adding it to the end of redirect query.
According to PEP 658 the metadata url is the package url with .metadata added to its path.
pip and uv build it differently (string vs path append), both have to work.
"""
remote = python_remote_factory(includes=["pytz"])
distro = python_distribution_factory(remote=remote.pulp_href)
Expand All @@ -226,20 +225,84 @@ def test_pull_through_metadata(python_remote_factory, python_distribution_factor
assert package1.has_metadata
assert package2.has_metadata

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

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


@pytest.mark.parallel
def test_pull_through_rejects_bad_links(python_remote_factory, python_distribution_factory):
"""Tests that pull-through only downloads files from links signed for the distro's remote."""
remote = python_remote_factory(includes=["shelf-reader"])
distro = python_distribution_factory(remote=remote.pulp_href)
remote2 = python_remote_factory(includes=["shelf-reader"])
distro2 = python_distribution_factory(remote=remote2.pulp_href)

url = f"{distro.base_url}simple/shelf-reader/"
package1, package2 = ProjectPage.from_response(requests.get(url), "shelf-reader").packages
token1 = package1.url.split("?pt=")[1]

# Tampered token
tampered = token1[:-1] + ("A" if token1[-1] != "A" else "B")
r = requests.get(package1.url.replace(token1, tampered))
assert r.status_code == 404

# Token used for another file
r = requests.get(package2.url.replace(package2.url.split("?pt=")[1], token1))
assert r.status_code == 404

# Token used on a distribution with another remote
r = requests.get(package1.url.replace(f"/{distro.base_path}/", f"/{distro2.base_path}/"))
assert r.status_code == 404

# Old unsigned redirect links
upstream_url = urljoin(remote.url, "simple/shelf-reader/")
upstream = ProjectPage.from_response(requests.get(upstream_url), "shelf-reader").packages[0]
r = requests.get(f"{distro.base_url}{upstream.filename}?redirect={upstream.url}")
assert r.status_code == 404

r = requests.get(package1.url)
assert r.status_code == 200
assert sha256(r.content).hexdigest() == package1.digests["sha256"]


@pytest.mark.parallel
def test_pull_through_signed_links_remote_update(
python_bindings, python_remote_factory, python_distribution_factory, monitor_task
):
"""Tests that changing what the remote lists invalidates its signed pull-through links."""
remote = python_remote_factory(includes=["shelf-reader"])
distro = python_distribution_factory(remote=remote.pulp_href)

url = f"{distro.base_url}simple/shelf-reader/"
package1, package2 = ProjectPage.from_response(requests.get(url), "shelf-reader").packages

# Other edits keep the links working
body = {"download_concurrency": 5}
monitor_task(python_bindings.RemotesPythonApi.partial_update(remote.pulp_href, body).task)
r = requests.get(package1.url)
assert r.status_code == 200
assert sha256(r.content).hexdigest() == package1.digests["sha256"]

body = {"includes": ["shelf-reader", "aiohttp"]}
monitor_task(python_bindings.RemotesPythonApi.partial_update(remote.pulp_href, body).task)
assert requests.get(package2.url).status_code == 404
packages = ProjectPage.from_response(requests.get(url), "shelf-reader").packages
package2 = next(p for p in packages if p.filename == package2.filename)
r = requests.get(package2.url)
assert r.status_code == 200
assert sha256(r.content).hexdigest() == package2.digests["sha256"]


@pytest.mark.parallel
def test_pull_through_metadata_with_repo(
python_repo_factory,
Expand All @@ -257,7 +320,7 @@ def test_pull_through_metadata_with_repo(
filename = "pip-26.0.1-py3-none-any.whl"
package = next(p for p in project_page.packages if p.filename == filename)
assert package.has_metadata
assert "?redirect=" in package.url
assert "?pt=" in package.url

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

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