Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(security): update pip's vendored urllib3 in Docker images (#7328)

LearningCircuitcefd9f94f49a
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index 9c234ed0ac..b1a110d5ac 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -10,6 +10,9 @@ updates:
exclude-paths:
- "requirements/ci-health.*"
- "requirements/gitleaks-tests.*"
+ # Reviewed by hand together with scripts/refresh_pip_urllib3.py, which
+ # looks for these exact wheel names; an automatic bump breaks the build.
+ - "requirements/pip-vendor-refresh.txt"
schedule:
interval: "weekly"
day: "monday"
@@ -45,6 +48,8 @@ updates:
directory: "/requirements"
exclude-paths:
- "bootstrap-*.txt"
+ # See the root pip entry: refreshed by hand with its build script.
+ - "pip-vendor-refresh.txt"
allow:
- dependency-type: "all"
schedule:
diff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.yml
index 58f5457fcf..bb7e3f55f3 100644
--- a/.github/workflows/docker-tests.yml
+++ b/.github/workflows/docker-tests.yml
@@ -110,6 +110,11 @@ jobs:
docker:
- 'Dockerfile'
- '.dockerignore'
+ # Build inputs the Dockerfile copies into the image stages.
+ - 'requirements/bootstrap-*.txt'
+ - 'requirements/pip-vendor-refresh.txt'
+ - 'scripts/refresh_pip_urllib3.py'
+ - 'tests/ci/standalone/verify_pip_vendor.py'
- 'scripts/ldr_entrypoint.sh'
- 'scripts/ollama_entrypoint.sh'
- 'pyproject.toml'
diff --git a/Dockerfile b/Dockerfile
index 4810f320d8..d34ed3a651 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -79,6 +79,18 @@ RUN apt-get update -o Acquire::Retries=3 && apt-get upgrade -y -o Acquire::Retri
COPY requirements/bootstrap-builder.txt /tmp/bootstrap-builder.txt
RUN pip3 install --no-cache-dir --require-hashes -r /tmp/bootstrap-builder.txt \
&& rm /tmp/bootstrap-builder.txt
+
+# pip 26.2.1 still vendors urllib3 2.7.0. Refresh it from reviewed wheels,
+# including ensurepip's seed wheel, until pip ships urllib3 >=2.8.0 (#7094).
+COPY requirements/pip-vendor-refresh.txt /tmp/pip-vendor-refresh.txt
+COPY scripts/refresh_pip_urllib3.py /tmp/refresh_pip_urllib3.py
+COPY tests/ci/standalone/verify_pip_vendor.py /tmp/verify_pip_vendor.py
+RUN python3 -m pip download --no-cache-dir --no-deps --only-binary=:all: \
+ --require-hashes -r /tmp/pip-vendor-refresh.txt -d /tmp/pip-vendor-input \
+ && python3 /tmp/refresh_pip_urllib3.py /tmp/pip-vendor-input /tmp/pip-vendor-output \
+ --install /tmp/verify_pip_vendor.py \
+ && rm -rf /tmp/pip-vendor-input /tmp/pip-vendor-output \
+ /tmp/pip-vendor-refresh.txt /tmp/refresh_pip_urllib3.py /tmp/verify_pip_vendor.py
# disable update check
ENV PDM_CHECK_UPDATE=false
# Increase PDM request timeout from default 15s to 120s for large packages (numpy, torch)
@@ -316,6 +328,17 @@ COPY requirements/bootstrap-runtime.txt /tmp/bootstrap-runtime.txt
RUN pip3 install --no-cache-dir --require-hashes -r /tmp/bootstrap-runtime.txt \
&& rm /tmp/bootstrap-runtime.txt
+# This independent root stage needs the same pip and ensurepip refresh.
+COPY requirements/pip-vendor-refresh.txt /tmp/pip-vendor-refresh.txt
+COPY scripts/refresh_pip_urllib3.py /tmp/refresh_pip_urllib3.py
+COPY tests/ci/standalone/verify_pip_vendor.py /tmp/verify_pip_vendor.py
+RUN python3 -m pip download --no-cache-dir --no-deps --only-binary=:all: \
+ --require-hashes -r /tmp/pip-vendor-refresh.txt -d /tmp/pip-vendor-input \
+ && python3 /tmp/refresh_pip_urllib3.py /tmp/pip-vendor-input /tmp/pip-vendor-output \
+ --install /tmp/verify_pip_vendor.py \
+ && rm -rf /tmp/pip-vendor-input /tmp/pip-vendor-output \
+ /tmp/pip-vendor-refresh.txt /tmp/refresh_pip_urllib3.py /tmp/verify_pip_vendor.py
+
# Install runtime dependencies for SQLCipher and WeasyPrint.
# `apt-get upgrade -y` is INTENTIONAL — see rationale on the builder-base
# upgrade (top of file). Trade reproducibility for always-fresh CVE patches.
diff --git a/changelog.d/+pip-vendored-urllib3.security.md b/changelog.d/+pip-vendored-urllib3.security.md
new file mode 100644
index 0000000000..042c2ba125
--- /dev/null
+++ b/changelog.d/+pip-vendored-urllib3.security.md
@@ -0,0 +1 @@
+Refresh pip's vendored urllib3 to 2.8.0 in the Docker build and runtime images, including the ensurepip seed wheel. This applies the upstream HTTPS-proxy TLS and chunked-response denial-of-service fixes while retaining pip's vendoring adaptations and updating its package inventory.
diff --git a/requirements/pip-vendor-refresh.txt b/requirements/pip-vendor-refresh.txt
new file mode 100644
index 0000000000..70044190ce
--- /dev/null
+++ b/requirements/pip-vendor-refresh.txt
@@ -0,0 +1,7 @@
+# Inputs for scripts/refresh_pip_urllib3.py. Download wheels only; the script
+# rebuilds pip with upstream urllib3 2.8.0 and retains pip's vendoring changes.
+# Remove this refresh when the bootstrap pip release vendors urllib3 >=2.8.0.
+pip==26.2.1 \
+ --hash=sha256:71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e
+urllib3==2.8.0 \
+ --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3
diff --git a/scripts/refresh_pip_urllib3.py b/scripts/refresh_pip_urllib3.py
new file mode 100644
index 0000000000..1a2c9f4160
--- /dev/null
+++ b/scripts/refresh_pip_urllib3.py
@@ -0,0 +1,274 @@
+"""Refresh pip's bundled urllib3 until pip releases its upstream update.
+
+Inputs are the unmodified, hash-verified PyPI wheels for pip 26.2.1 and
+urllib3 2.8.0. Preserve pip's namespace rewrites and disabled Brotli support,
+update its vendor manifest and CycloneDX SBOM, and regenerate wheel RECORD.
+The Docker build installs this wheel and also replaces ensurepip's copy so
+creating a venv cannot restore the vulnerable vendored urllib3 2.7.0.
+
+Upstream fixes: https://github.com/urllib3/urllib3/releases/tag/2.8.0
+Vendoring baseline: https://github.com/pypa/pip/tree/26.2.1/src/pip/_vendor
+Delete this helper and its Docker wiring when a pinned pip release carries
+urllib3 >=2.8.0. A changed input or ensurepip layout requires a new review.
+"""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import csv
+import hashlib
+import io
+import json
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo
+
+
+PIP_VERSION = "26.2.1"
+URLLIB3_VERSION = "2.8.0"
+PIP_WHEEL = f"pip-{PIP_VERSION}-py3-none-any.whl"
+URLLIB3_WHEEL = f"urllib3-{URLLIB3_VERSION}-py3-none-any.whl"
+INPUT_HASHES = {
+ PIP_WHEEL: "71138adf1f4ca900cdb7d289c21b7494329f2332b6d85f0e1c42108c0384ed3e",
+ URLLIB3_WHEEL: "0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3",
+}
+VENDOR = "pip/_vendor/"
+DIST_INFO = f"pip-{PIP_VERSION}.dist-info/"
+
+
+def verified_wheel(path: Path) -> dict[str, bytes]:
+ """Read only the exact reviewed input, before interpreting ZIP contents."""
+ expected = INPUT_HASHES.get(path.name)
+ data = path.read_bytes()
+ if expected is None or hashlib.sha256(data).hexdigest() != expected:
+ raise ValueError(f"unreviewed wheel: {path.name}")
+ with ZipFile(io.BytesIO(data)) as archive:
+ return {name: archive.read(name) for name in archive.namelist()}
+
+
+def replace_once(text: str, old: str, new: str, count: int = 1) -> str:
+ if text.count(old) != count:
+ raise ValueError(
+ f"vendoring source drift: expected {count} copies of {old!r}"
+ )
+ return text.replace(old, new)
+
+
+def vendored_sources(upstream: dict[str, bytes]) -> dict[str, bytes]:
+ """Apply the same seven-file vendoring delta pip uses for urllib3 2.7.0."""
+ files = {
+ VENDOR + name: content
+ for name, content in upstream.items()
+ if name.startswith("urllib3/") and not name.endswith("/")
+ }
+ # These rewrites include documentation examples, as pip's vendor tool does.
+ for name, count in (
+ ("poolmanager.py", 2),
+ ("util/request.py", 1),
+ ("util/timeout.py", 1),
+ ("util/url.py", 2),
+ ):
+ path = VENDOR + "urllib3/" + name
+ files[path] = replace_once(
+ files[path].decode(),
+ "import urllib3\n",
+ "from pip._vendor import urllib3\n",
+ count,
+ ).encode()
+ for name in ("util/url.py", "contrib/pyopenssl.py"):
+ path = VENDOR + "urllib3/" + name
+ files[path] = replace_once(
+ files[path].decode(),
+ "import idna\n",
+ "from pip._vendor import idna\n",
+ ).encode()
+ path = VENDOR + "urllib3/contrib/pyopenssl.py"
+ text = replace_once(
+ files[path].decode(),
+ "import urllib3.contrib.pyopenssl\n urllib3.contrib.pyopenssl.inject_into_urllib3()",
+ "import pip._vendor.urllib3.contrib.pyopenssl as pyopenssl\n pyopenssl.inject_into_urllib3()",
+ )
+ files[path] = text.encode()
+ path = VENDOR + "urllib3/contrib/emscripten/__init__.py"
+ text = replace_once(
+ files[path].decode(),
+ "import urllib3.connection\n",
+ "import pip._vendor.urllib3.connection as urllib3_connection\n",
+ )
+ text = replace_once(text, "urllib3.connection.", "urllib3_connection.", 3)
+ files[path] = text.encode()
+ # pip deliberately does not import ambient Brotli implementations.
+ for name, replacement in (
+ ("response.py", "brotli = None\n"),
+ ("util/request.py", ""),
+ ):
+ path = VENDOR + "urllib3/" + name
+ text = files[path].decode()
+ start = text.index("try:\n try:\n import brotlicffi")
+ end = text.index("\n\n", start)
+ text = text[:start] + replacement + text[end:]
+ files[path] = text.encode()
+ files[VENDOR + "urllib3/LICENSE.txt"] = upstream[
+ f"urllib3-{URLLIB3_VERSION}.dist-info/licenses/LICENSE.txt"
+ ]
+ return files
+
+
+def refreshed_contents(
+ pip: dict[str, bytes], urllib3: dict[str, bytes]
+) -> dict[str, bytes]:
+ files = {
+ name: content
+ for name, content in pip.items()
+ if not name.startswith(VENDOR + "urllib3/")
+ }
+ files.update(vendored_sources(urllib3))
+ files[DIST_INFO + "licenses/src/pip/_vendor/urllib3/LICENSE.txt"] = files[
+ VENDOR + "urllib3/LICENSE.txt"
+ ]
+ manifest, count = re.subn(
+ r"(?m)^(\s*)urllib3==2\.7\.0$",
+ rf"\g<1>urllib3=={URLLIB3_VERSION}",
+ files[VENDOR + "vendor.txt"].decode(),
+ )
+ if count != 1:
+ raise ValueError(
+ "pip's urllib3 vendor pin changed; review or remove the refresh"
+ )
+ files[VENDOR + "vendor.txt"] = manifest.encode()
+ sbom = json.loads(files[VENDOR + "bom.cdx.json"])
+ components = [
+ component
+ for component in sbom["components"]
+ if component["name"] == "urllib3"
+ ]
+ if len(components) != 1 or components[0]["version"] != "2.7.0":
+ raise ValueError("pip's urllib3 SBOM component changed")
+ old_ref = "pkg:pypi/[email protected]"
+ new_ref = f"pkg:pypi/urllib3@{URLLIB3_VERSION}"
+ component = components[0]
+ if component["bom-ref"] != old_ref or component["purl"] != old_ref:
+ raise ValueError("pip's urllib3 SBOM reference changed")
+ component.update(version=URLLIB3_VERSION, purl=new_ref)
+ component["bom-ref"] = new_ref
+ for dependency in sbom["dependencies"]:
+ if dependency["ref"] == old_ref:
+ dependency["ref"] = new_ref
+ if "dependsOn" in dependency:
+ dependency["dependsOn"] = [
+ new_ref if ref == old_ref else ref
+ for ref in dependency["dependsOn"]
+ ]
+ files[VENDOR + "bom.cdx.json"] = (
+ json.dumps(sbom, indent=2) + "\n"
+ ).encode()
+ record = DIST_INFO + "RECORD"
+ rows = io.StringIO(newline="")
+ writer = csv.writer(rows, lineterminator="\n")
+ for name, content in sorted(files.items()):
+ if name == record:
+ continue
+ digest = (
+ base64.urlsafe_b64encode(hashlib.sha256(content).digest())
+ .rstrip(b"=")
+ .decode()
+ )
+ writer.writerow((name, "sha256=" + digest, len(content)))
+ writer.writerow((record, "", ""))
+ files[record] = rows.getvalue().encode()
+ return files
+
+
+def build_wheel(inputs: Path, output: Path) -> Path:
+ files = refreshed_contents(
+ verified_wheel(inputs / PIP_WHEEL),
+ verified_wheel(inputs / URLLIB3_WHEEL),
+ )
+ output.mkdir(parents=True, exist_ok=True)
+ destination = output / PIP_WHEEL
+ if destination.resolve() == (inputs / PIP_WHEEL).resolve():
+ raise ValueError("output must not overwrite the reviewed input")
+ with ZipFile(destination, "w", compression=ZIP_DEFLATED) as archive:
+ for name, content in sorted(files.items()):
+ info = ZipInfo(name, date_time=(2026, 10, 11, 0, 0, 0))
+ info.compress_type = ZIP_DEFLATED
+ info.external_attr = 0o644 << 16
+ archive.writestr(info, content)
+ return destination
+
+
+def install(wheel: Path, verifier: Path) -> None:
+ verifier = verifier.resolve(strict=True)
+ import ensurepip
+ import pip
+
+ if pip.__version__ != PIP_VERSION or ensurepip.version() != PIP_VERSION:
+ raise ValueError(
+ "pip/ensurepip changed; review or remove the vendored refresh"
+ )
+ bundle = Path(ensurepip.__file__).parent / "_bundled" / PIP_WHEEL
+ # Refuse an alternative system-wheel layout or an unexpected bundle.
+ with ensurepip._get_pip_whl_path_ctx() as selected:
+ if selected.resolve() != bundle.resolve():
+ raise ValueError(
+ "ensurepip does not use the reviewed bundled-wheel layout"
+ )
+ if hashlib.sha256(bundle.read_bytes()).hexdigest() not in {
+ INPUT_HASHES[PIP_WHEEL],
+ hashlib.sha256(wheel.read_bytes()).hexdigest(),
+ }:
+ raise ValueError("ensurepip's bundled pip is not the reviewed wheel")
+ subprocess.run(
+ [
+ sys.executable,
+ "-I",
+ "-m",
+ "pip",
+ "install",
+ "--no-index",
+ "--no-deps",
+ "--no-cache-dir",
+ "--force-reinstall",
+ str(wheel),
+ ],
+ check=True,
+ )
+ shutil.copyfile(wheel, bundle)
+ # Fresh interpreters avoid trusting modules cached before reinstalling pip.
+ check = ["-I", str(verifier), URLLIB3_VERSION]
+ subprocess.run([sys.executable, *check], check=True)
+ subprocess.run(
+ [sys.executable, "-I", "-m", "pip", "debug", "--verbose"], check=True
+ )
+ with tempfile.TemporaryDirectory(prefix="pip-vendor-venv-") as directory:
+ subprocess.run(
+ [sys.executable, "-I", "-m", "venv", directory], check=True
+ )
+ subprocess.run(
+ [str(Path(directory) / "bin/python"), *check], check=True
+ )
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("inputs", type=Path)
+ parser.add_argument("output", type=Path)
+ parser.add_argument(
+ "--install",
+ type=Path,
+ metavar="VERIFIER",
+ help="install the wheel and run this standalone verifier in pip and a new venv",
+ )
+ args = parser.parse_args()
+ wheel = build_wheel(args.inputs, args.output)
+ if args.install is not None:
+ install(wheel, args.install)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/ci/standalone/verify_pip_vendor.py b/tests/ci/standalone/verify_pip_vendor.py
new file mode 100644
index 0000000000..9db6587b3b
--- /dev/null
+++ b/tests/ci/standalone/verify_pip_vendor.py
@@ -0,0 +1,148 @@
+"""Run real pip transport regressions during both Docker root-stage builds.
+
+Run in a fresh interpreter after installing the rebuilt pip, then again in a
+new ensurepip-created virtual environment. This is a standalone build probe,
+so the production root stage does not need pytest or application dependencies.
+The negative TLS setting below is input to a mocked connection; no network
+connection is made by these regression checks.
+"""
+
+import io
+import json
+import sys
+from pathlib import Path
+
+
+def verify_chunk_lines() -> None:
+ """Both chunk-size and trailer reads must reject oversized lines."""
+ import http.client
+
+ from pip._vendor.urllib3.exceptions import ProtocolError
+ from pip._vendor.urllib3.response import HTTPResponse
+
+ class Socket:
+ def __init__(self, data: bytes):
+ self.data = data
+
+ def makefile(self, *args, **kwargs):
+ return io.BytesIO(self.data)
+
+ def read(body: bytes) -> bytes:
+ raw = http.client.HTTPResponse(
+ Socket(
+ b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + body
+ ),
+ method="GET",
+ )
+ raw.begin()
+ response = HTTPResponse(
+ body=raw,
+ headers=dict(raw.headers.items()),
+ original_response=raw,
+ preload_content=False,
+ request_method="GET",
+ )
+ try:
+ return b"".join(response.read_chunked())
+ finally:
+ response.close()
+
+ if read(b"1\r\na\r\n0\r\n\r\n") != b"a":
+ raise RuntimeError("ordinary chunked decoding failed")
+ for body, message in (
+ (b"1" * 65537 + b"\r\n", "chunk size line exceeded"),
+ (
+ b"1\r\na\r\n0\r\n" + b"x" * 65537 + b"\r\n",
+ "chunk trailer line exceeded",
+ ),
+ ):
+ try:
+ read(body)
+ except ProtocolError as error:
+ if message not in str(error):
+ raise RuntimeError("unexpected chunk rejection") from error
+ else:
+ raise RuntimeError("oversized chunk line was accepted")
+
+
+def verify_deflate_eof() -> None:
+ """A raw Deflate stream with trailing input must finish bounded reads."""
+ import zlib
+
+ from pip._vendor.urllib3.response import DeflateDecoder
+
+ payload = b"hello" * 10
+ decoder = DeflateDecoder()
+ output = decoder.decompress(
+ zlib.compress(payload)[2:-4] + b"trailer", max_length=8
+ )
+ for _ in range(32):
+ if not decoder.has_unconsumed_tail:
+ break
+ output += decoder.decompress(b"", max_length=8)
+ if decoder.has_unconsumed_tail or output != payload:
+ raise RuntimeError(
+ "Deflate failed to finish at EOF or changed decoded content"
+ )
+
+
+def verify_proxy_policy() -> None:
+ """An origin's weaker TLS settings must not override proxy verification."""
+ import ssl
+ from collections import namedtuple
+ from unittest.mock import Mock, patch
+
+ from pip._vendor.urllib3 import connection
+ from pip._vendor.urllib3._base_connection import ProxyConfig
+
+ context = ssl.create_default_context()
+ config = ProxyConfig(context, False, None, None)
+ conn = connection.HTTPSConnection(
+ "origin.invalid",
+ cert_reqs=ssl.CERT_NONE,
+ ca_certs="/origin-only",
+ proxy_config=config,
+ )
+ wrapped = namedtuple("Wrapped", "socket is_verified")(Mock(), True)
+ with patch.object(
+ connection, "_ssl_wrap_socket_and_match_hostname", return_value=wrapped
+ ) as wrap:
+ conn._connect_tls_proxy("proxy.invalid", Mock())
+ policy = wrap.call_args.kwargs
+ if not (
+ policy["cert_reqs"] == ssl.CERT_REQUIRED
+ and policy["ssl_context"] is context
+ and policy["ca_certs"] is None
+ ):
+ raise RuntimeError("origin TLS configuration overrode the proxy policy")
+
+
+def verify_runtime(expected_version: str) -> None:
+ import pip
+ from pip._vendor import urllib3
+ from pip._vendor.urllib3.util.url import parse_url
+
+ if urllib3.__version__ != expected_version:
+ raise RuntimeError("installed pip did not load the refreshed urllib3")
+ if parse_url("https://bücher.example").host != "xn--bcher-kva.example":
+ raise RuntimeError("vendored IDNA import failed")
+ sbom = json.loads(
+ (Path(pip.__file__).parent / "_vendor/bom.cdx.json").read_text()
+ )
+ components = [
+ item for item in sbom["components"] if item["name"] == "urllib3"
+ ]
+ if len(components) != 1 or components[0]["version"] != urllib3.__version__:
+ raise RuntimeError(
+ "installed pip's SBOM disagrees with its urllib3 code"
+ )
+ verify_chunk_lines()
+ verify_deflate_eof()
+ verify_proxy_policy()
+ print(
+ "pip's urllib3 code, inventory and transport regression checks passed"
+ )
+
+
+if __name__ == "__main__":
+ verify_runtime(sys.argv[1])