holoviz/panel · #9176
Stop silently retrying bundler downloads without certificate verification
doc/developer_guide/custom_models.md2 + / 0 −
@@ -356,3 +356,5 @@ The bundled resources have to be collected whenever they change, so rerun `pip i - A new model is added with a `__javascript_raw__` declaration or an existing model is updated - A new template with a `_resources` declaration is added or an existing template is updated - A CSS file in one of template directories (`panel/template/*/`) is added or modified++Bundling downloads the external resources over HTTPS and verifies their certificates. If you build behind a TLS-inspecting proxy, point `REQUESTS_CA_BUNDLE` or `SSL_CERT_FILE` at a CA bundle that trusts it. As a last resort, set `PANEL_BUNDLE_INSECURE=1` to disable certificate verification for the build.panel/compiler.py34 + / 9 −
@@ -11,6 +11,7 @@ import re import shutil import tarfile+import warnings import zipfile from concurrent.futures import ThreadPoolExecutor@@ -78,15 +79,39 @@ def _session(): return session +def _insecure_downloads():+ return os.environ.get('PANEL_BUNDLE_INSECURE', '').strip().lower() in ('1', 'true', 'yes')++ def _download(url):+ """+ Fetches a url, returning a (response, error) pair.++ Certificate verification is only disabled when PANEL_BUNDLE_INSECURE is+ set, for builds behind a TLS-inspecting proxy that cannot be given a CA+ bundle via REQUESTS_CA_BUNDLE or SSL_CERT_FILE.+ """+ kwargs = {}+ if _insecure_downloads():+ kwargs['verify'] = False+ warnings.warn(+ 'PANEL_BUNDLE_INSECURE is set, TLS certificate verification is '+ f'disabled for the download of {url}.', stacklevel=2+ ) try:- response, error = _session().get(url, timeout=10), None- except Exception:- try:- response, error = _session().get(url, verify=False, timeout=10), None- except Exception as e:- response, error = None, e- return response, error+ return _session().get(url, timeout=10, **kwargs), None+ except Exception as e:+ return None, e+++def _ssl_hint(error):+ if isinstance(error, requests.exceptions.SSLError):+ return (+ ' Certificate verification failed; point REQUESTS_CA_BUNDLE or '+ 'SSL_CERT_FILE at a CA bundle that trusts your proxy, or set '+ 'PANEL_BUNDLE_INSECURE=1 to disable verification.'+ )+ return '' # Regex to search and replace the sourceMappingURL@@ -208,7 +233,7 @@ def _write_license(spec, index): response, error = _download(f'{npm_cdn}/{spec}/package.json') if error or not response.ok: msg = f'Failed to fetch package metadata for {spec}, cannot determine its license.'- raise ConnectionError(msg) from error+ raise ConnectionError(msg + _ssl_hint(error)) from error meta = json.loads(response.content) name, version = meta.get('name', spec), meta.get('version', '') spdx = meta.get('license')@@ -280,7 +305,7 @@ def _write_bundled_files(name, files, explicit_dir=None, ext=None): response, error = _download(bundle_file) if error:- msg = f"Failed to fetch {name} dependency: {bundle_file}. Errored with {error}."+ msg = f"Failed to fetch {name} dependency: {bundle_file}. Errored with {error}.{_ssl_hint(error)}" raise ConnectionError(msg) from error if not response.ok: # A CDN answers a missing file with an error document and a 4xxpanel/tests/test_compiler.py52 + / 0 −
@@ -1,6 +1,9 @@ import json +from unittest import mock+ import pytest+import requests from bokeh.model import Model @@ -26,6 +29,55 @@ def clean_licenses(): compiler._LICENSE_SOURCES.clear() +@pytest.fixture+def session(monkeypatch):+ session = mock.Mock()+ monkeypatch.setattr(compiler, '_session', lambda: session)+ return session+++def test_download_returns_response(monkeypatch, session):+ monkeypatch.delenv('PANEL_BUNDLE_INSECURE', raising=False)+ response, error = compiler._download('https://example.com/a.js')+ assert response is session.get.return_value+ assert error is None+ session.get.assert_called_once_with('https://example.com/a.js', timeout=10)+++def test_download_does_not_retry_without_verification(monkeypatch, session):+ monkeypatch.delenv('PANEL_BUNDLE_INSECURE', raising=False)+ exc = requests.exceptions.SSLError('certificate verify failed')+ session.get.side_effect = exc+ response, error = compiler._download('https://example.com/a.js')+ assert response is None+ assert error is exc+ session.get.assert_called_once_with('https://example.com/a.js', timeout=10)+++@pytest.mark.parametrize('value', ['', '0', 'false', 'no', 'off'])+def test_download_verifies_for_falsy_insecure_env(monkeypatch, session, value):+ monkeypatch.setenv('PANEL_BUNDLE_INSECURE', value)+ compiler._download('https://example.com/a.js')+ session.get.assert_called_once_with('https://example.com/a.js', timeout=10)+++@pytest.mark.parametrize('value', ['1', 'true', 'True', 'YES'])+def test_download_insecure_env_disables_verification(monkeypatch, session, value):+ monkeypatch.setenv('PANEL_BUNDLE_INSECURE', value)+ with pytest.warns(UserWarning, match='certificate verification is disabled'):+ response, error = compiler._download('https://example.com/a.js')+ assert response is session.get.return_value+ assert error is None+ session.get.assert_called_once_with('https://example.com/a.js', timeout=10, verify=False)+++def test_write_bundled_files_hints_at_ca_bundle_on_ssl_error(monkeypatch):+ error = requests.exceptions.SSLError('certificate verify failed')+ monkeypatch.setattr(compiler, '_download', lambda url: (None, error))+ with pytest.raises(ConnectionError, match='REQUESTS_CA_BUNDLE.*PANEL_BUNDLE_INSECURE'):+ compiler._write_bundled_files('Bootstrap', [f'{NPM_CDN}/jquery@3.7.1/dist/jquery.min.js'])++ def test_write_bundled_files_skips_panel_cdn(no_download): compiler.write_bundled_files('Bootstrap', [f'{CDN_DIST}bundled/jquery/jquery.min.js'])