Repository navigation
Stop trusting the client's redirect url for pull-through downloads #1429
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
gerrod3
wants to merge
4
commits into
pulp:main
Choose a base branch
from
gerrod3:t3/pull-through-signed-urls
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+539
−47
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b0a8856
Sign pull-through links instead of trusting the redirect url
gerrod3 fd55068
Use plain filename pull-through links when Redis is available
gerrod3 0a5906d
Key pull-through entries per project and refresh them on remote edits
gerrod3 18e94be
Bind signed pull-through links to the remote's listing and test witho…
gerrod3 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Fixed pull-through downloads trusting the upstream url given by the client; pull-through links are now signed and downloads are checked against the upstream sha256. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Fixed pip intermittently receiving a pull-through wheel instead of its metadata, or the reverse, when Redis caching is enabled. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,14 +12,16 @@ | |
| 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 | ||
| from packaging.requirements import Requirement | ||
| from packaging.utils import canonicalize_name | ||
| from packaging.utils import canonicalize_name, parse_sdist_filename, parse_wheel_filename | ||
| from packaging.version import InvalidVersion, parse | ||
| from pypi_simple import ACCEPT_JSON_PREFERRED, ProjectPage | ||
|
|
||
| from pulpcore.plugin.cache import SyncContentCache | ||
| from pulpcore.plugin.exceptions import TimeoutException | ||
| from pulpcore.plugin.models import Artifact, Remote, VulnerabilityReport | ||
| from pulpcore.plugin.util import get_domain | ||
|
|
@@ -35,6 +37,13 @@ | |
| 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" | ||
| _CACHE_TTL = settings.CACHE_SETTINGS["EXPIRES_TTL"] | ||
| # Outlive both the cached simple pages and their max-age in client caches, None never expires | ||
| PULL_THROUGH_TTL = None if _CACHE_TTL is None else _CACHE_TTL + 600 | ||
|
|
||
| PYPI_SIMPLE_V1_HTML = "application/vnd.pypi.simple.v1+html" | ||
| PYPI_SIMPLE_V1_JSON = "application/vnd.pypi.simple.v1+json" | ||
|
|
||
|
|
@@ -768,3 +777,117 @@ 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, like it clears its stored entries | ||
| 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): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. When you disable cache, a signed link still works after you change the remote (e.g. |
||
| """ | ||
| 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 url, includes or excludes | ||
| 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 | ||
|
|
||
|
|
||
| def _pull_through_key(remote, filename): | ||
| # Group entries per project so each expires on its own, falling back to the filename for | ||
| # legacy names that can't be parsed | ||
| try: | ||
| if filename.endswith(".whl"): | ||
| bucket = parse_wheel_filename(filename)[0] | ||
| else: | ||
| bucket = parse_sdist_filename(filename)[0] | ||
| except ValueError: | ||
| bucket = filename | ||
| return f"pulp_python:pull_through:{remote.pk}:{bucket}" | ||
|
|
||
|
|
||
| def store_pull_through_entries(remote, entries): | ||
| """ | ||
| Stores filename -> {url, sha256, metadata_sha256} entries of a remote in Redis. | ||
|
|
||
| Returns True if the entries were stored, so plain filename links can be used for them. | ||
| """ | ||
| if not settings.CACHE_ENABLED: | ||
| return False | ||
| if not entries: | ||
| return True | ||
| buckets = defaultdict(dict) | ||
| for filename, entry in entries.items(): | ||
| buckets[_pull_through_key(remote, filename)][filename] = json.dumps(entry) | ||
| try: | ||
| pipe = SyncContentCache().redis.pipeline(transaction=False) | ||
| for key, mapping in buckets.items(): | ||
| pipe.hset(key, mapping=mapping) | ||
| if PULL_THROUGH_TTL is not None: | ||
| pipe.expire(key, PULL_THROUGH_TTL) | ||
| pipe.execute() | ||
| except Exception as e: | ||
| log.warning("Failed to store pull-through entries: %s", e) | ||
| return False | ||
| return True | ||
|
|
||
|
|
||
| def clear_pull_through_entries(remote_pk): | ||
| """Deletes all the stored pull-through entries of a remote.""" | ||
| if not settings.CACHE_ENABLED: | ||
| return | ||
| try: | ||
| redis = SyncContentCache().redis | ||
| keys = list(redis.scan_iter(match=f"pulp_python:pull_through:{remote_pk}:*", count=1000)) | ||
| if keys: | ||
| redis.delete(*keys) | ||
| except Exception as e: | ||
| log.warning("Failed to clear pull-through entries: %s", e) | ||
|
|
||
|
|
||
| def lookup_pull_through_entry(remote, filename): | ||
| """ | ||
| Returns the upstream (url, sha256) for a file stored by store_pull_through_entries. | ||
|
|
||
| filename can be a stored package's filename or its PEP 658 metadata file. | ||
| """ | ||
| if not settings.CACHE_ENABLED: | ||
| return None | ||
| is_metadata = filename.endswith(".metadata") | ||
| filename = filename.removesuffix(".metadata") | ||
| try: | ||
| raw = SyncContentCache().redis.hget(_pull_through_key(remote, filename), filename) | ||
| except Exception as e: | ||
| log.warning("Failed to look up pull-through entry: %s", e) | ||
| return None | ||
| if not raw: | ||
| return None | ||
| entry = json.loads(raw) | ||
| if not is_metadata: | ||
| return entry["url"], entry.get("sha256") | ||
| if entry.get("metadata_sha256"): | ||
| return f"{entry['url']}.metadata", entry["metadata_sha256"] | ||
| return None | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.