-
Notifications
You must be signed in to change notification settings - Fork 10.2k
harden: bound HTTP reads and enforce strict redirects #3140
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
Open
PascalThuet
wants to merge
3
commits into
github:main
Choose a base branch
from
PascalThuet:split/bounded-http-reads
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.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
Some comments aren't visible on the classic Files Changed page.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| """Helpers for bounded HTTP downloads.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import NoReturn, TypeVar | ||
| from urllib.parse import urlparse | ||
|
|
||
|
|
||
| ErrorT = TypeVar("ErrorT", bound=Exception) | ||
|
|
||
| MAX_DOWNLOAD_BYTES = 50 * 1024 * 1024 | ||
| READ_CHUNK_SIZE = 1024 * 1024 | ||
|
|
||
| # Tighter ceiling for responses that are read fully into memory and parsed as | ||
| # JSON. The 50 MiB MAX_DOWNLOAD_BYTES default is sized for archive/payload | ||
| # downloads; JSON metadata responses are far smaller, so capping them close to | ||
| # their real size shrinks the memory-DoS surface and keeps the "too large" | ||
| # error reachable (rather than only triggering on tens of MiB). Pass it | ||
| # explicitly at each JSON call site so the intended bound is pinned there. | ||
| # METADATA covers fixed-shape single-object responses (an OAuth token, one | ||
| # release's metadata): a few KiB in practice, 1 MiB is already generous. | ||
| MAX_JSON_METADATA_BYTES = 1 * 1024 * 1024 | ||
|
|
||
|
|
||
| def is_https_or_localhost_http(url: str) -> bool: | ||
| """Return True if *url* is HTTPS, or HTTP limited to loopback hosts. | ||
|
|
||
| Shared scheme-safety predicate used by the auth HTTP redirect handler and | ||
| by the direct URL validations in the CLI download flows, so the rule (and | ||
| any future tightening of it) lives in one place. | ||
|
|
||
| A hostname is always required: a URL without one (e.g. ``https:///x``) | ||
| has no real target and is rejected regardless of scheme. | ||
|
|
||
| The loopback allowance is a deliberate *exact-string* match on | ||
| ``localhost`` / ``127.0.0.1`` / ``::1``, not an IP-range check: other | ||
| loopback addresses (e.g. ``127.0.0.2``) are intentionally not covered. | ||
| ``urlparse`` already lower-cases the hostname, so the comparison is | ||
| case-insensitive. | ||
| """ | ||
| parsed = urlparse(url) | ||
| if not parsed.hostname: | ||
| return False | ||
| is_localhost = parsed.hostname in ("localhost", "127.0.0.1", "::1") | ||
| return parsed.scheme == "https" or (parsed.scheme == "http" and is_localhost) | ||
|
|
||
|
|
||
| def _raise(error_type: type[ErrorT], message: str) -> NoReturn: | ||
| raise error_type(message) | ||
|
|
||
|
|
||
| def read_response_limited( | ||
| response, | ||
| *, | ||
| max_bytes: int = MAX_DOWNLOAD_BYTES, | ||
| error_type: type[ErrorT] = ValueError, | ||
| label: str = "download", | ||
| ) -> bytes: | ||
| """Read at most *max_bytes* from a response object. | ||
|
|
||
| ``response.read(n)`` is only guaranteed to return *up to* ``n`` bytes and may | ||
| return fewer even when more data is pending (e.g. chunked transfer encoding), | ||
| so a single ``read(max_bytes + 1)`` cannot enforce the bound on its own. Read | ||
| in a loop until EOF or until one byte past the limit has been accumulated. | ||
|
|
||
| *max_bytes* is keyword-only. It defaults to the module-wide | ||
| ``MAX_DOWNLOAD_BYTES`` (50 MiB) ceiling for archive/payload downloads; | ||
| callers with a tighter budget (e.g. small JSON responses) should pass an | ||
| explicit value so the intended bound is pinned at the call site rather than | ||
| tracking changes to the shared default. | ||
| """ | ||
| chunks: list[bytes] = [] | ||
| total = 0 | ||
| limit = max_bytes + 1 | ||
| while total < limit: | ||
| chunk = response.read(min(READ_CHUNK_SIZE, limit - total)) | ||
| if not chunk: | ||
| break | ||
| chunks.append(chunk) | ||
| total += len(chunk) | ||
| if total > max_bytes: | ||
| _raise(error_type, f"{label} exceeds maximum size of {max_bytes} bytes") | ||
| return b"".join(chunks) |
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
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 |
|---|---|---|
| @@ -1,15 +1,46 @@ | ||
| """HTTP test helpers shared by version-related CLI tests.""" | ||
|
|
||
| import io | ||
| import json | ||
| import urllib.request | ||
| from unittest.mock import MagicMock | ||
|
|
||
| import pytest | ||
|
|
||
|
|
||
| def mock_urlopen_response(payload: dict) -> MagicMock: | ||
| """Build a urlopen context-manager mock whose read returns JSON.""" | ||
| body = json.dumps(payload).encode("utf-8") | ||
| resp = MagicMock() | ||
| resp.read.return_value = body | ||
| resp.read.side_effect = io.BytesIO(body).read | ||
| cm = MagicMock() | ||
| cm.__enter__.return_value = resp | ||
| cm.__exit__.return_value = False | ||
| return cm | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def route_opener_open_through_urlopen(monkeypatch): | ||
| """Route build_opener().open through urllib.request.urlopen. | ||
|
|
||
| ``open_url(..., strict_redirects=True)`` fetches via | ||
| ``build_opener(...).open()``, which bypasses ``urllib.request.urlopen`` | ||
| — and with it the urlopen patches these test modules are built on. | ||
| Delegating ``open()`` to urlopen at call time keeps those patches | ||
| effective; the redirect handler's own behavior is covered by | ||
| ``TestRedirectStripping`` in test_authentication.py. | ||
|
|
||
| Import this fixture into a test module to activate it there. | ||
| """ | ||
|
|
||
| class _UrlopenDelegatingOpener: | ||
| def open(self, req, data=None, timeout=None): | ||
| if data is None: | ||
| return urllib.request.urlopen(req, timeout=timeout) | ||
| return urllib.request.urlopen(req, data=data, timeout=timeout) | ||
|
|
||
| monkeypatch.setattr( | ||
| urllib.request, | ||
| "build_opener", | ||
| lambda *handlers: _UrlopenDelegatingOpener(), | ||
| ) |
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
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.