Skip to content

Commit f1beab4

Browse files
krassowskiMUFFANUJ
andauthored
Backport of security patches to 4.6.x branch (#19185)
Fixes for: - GHSA-gx64-gj6p-pc4c - GHSA-89vp-jrxv-24w8 - GHSA-h5v5-8746-g7mm - GHSA-pppj-hq3g-57pj - GHSA-whvh-wf3x-g77j Slight departure from normal process due to GitHub private forks being broken, see jupyter/security#126. --------- Co-authored-by: Anuj Kumar Singh <[email protected]>
1 parent abdd427 commit f1beab4

14 files changed

Lines changed: 412 additions & 27 deletions

File tree

‎docs/source/extension/extension_dev.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,18 @@ const plugin: JupyterFrontEndPlugin<MyToken> = {
111111

112112
The `id` and `activate` fields are required and the other fields may be omitted. For more information about how to use the `requires`, `optional`, or `provides` fields, see {ref}`services`.
113113

114-
- `id` is a required unique string. The convention is to use the NPM extension package name, a colon, then a string identifying the plugin inside the extension.
114+
(plugin-id-convention)=
115+
116+
- `id` is a required unique string. The convention is to use the NPM
117+
extension package name, a colon, then a string identifying the plugin inside
118+
the extension, for example `my-extension:plugin`. JupyterLab treats the part
119+
before the first colon as the extension name when applying extension-level
120+
configuration such as enabling, disabling, deferring, or locking all plugins
121+
in that extension.
122+
The `jupyter/token-format` rule from
123+
[`@jupyter/eslint-plugin`](https://eslint-plugin.readthedocs.io/en/latest/rules/token-format/)
124+
can enforce the related `<package>:<TokenSymbol>` convention for token IDs
125+
used with `new Token(...)`.
115126
- `description` is an optional string. It allows to document the purpose of a plugin.
116127
- `autostart` indicates whether your plugin should be activated at application startup. Typically this should be `true`. If it is `false` or omitted, your plugin will be activated when any other plugin requests the token your plugin is providing.
117128
- `requires` and `optional` are lists of {ref}`tokens <tokens>` corresponding to services other plugins provide. These services will be given as arguments to the `activate` function when the plugin is activated. If a `requires` service is not registered with JupyterLab, an error will be thrown and the plugin will not be activated.

‎docs/source/user/extensions.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,19 @@ search result and the user is free to install any source extension. This is the
228228
To bring more security, you or your administrator can enable `blocklists` or `allowlists`
229229
mode. JupyterLab will check the extensions against the defined listings.
230230

231+
:::{note}
232+
In security-sensitive multi-user deployments, extension manager listings are not
233+
a substitute for isolating the JupyterLab server environment from user-controlled
234+
kernels. If users can import JupyterLab server internals such as
235+
`jupyterlab.extensions.pypi.PyPIExtensionManager` from a kernel, the kernel and
236+
server are sharing an environment that users may be able to modify outside the
237+
Extension Manager. Administrators should run the server in an environment users
238+
cannot modify, and may run kernels in separate user-writable environments. With
239+
that separation, installing packages in a kernel environment does not install
240+
extension code into the server environment. See JupyterHub's guidance on
241+
[isolating packages in a read-only environment](https://jupyterhub.readthedocs.io/en/latest/explanation/websecurity.html#isolate-packages-in-a-read-only-environment).
242+
:::
243+
231244
:::{warning}
232245
Only one mode at a time is allowed. If you or your server administrator configures
233246
both block and allow listings, the allow listing takes precedence.
@@ -390,12 +403,35 @@ Administrators may lock specific plugins with:
390403
jupyter labextension lock my-extension:plugin
391404
```
392405

406+
They may also add an extension-level lock by using the extension name without
407+
a plugin suffix:
408+
409+
```bash
410+
jupyter labextension lock my-extension
411+
```
412+
413+
JupyterLab identifies the extension for a plugin from the plugin ID prefix
414+
before the first colon. For example, `my-extension:plugin` is treated as a
415+
plugin in the `my-extension` extension. Extension-level locks therefore apply
416+
only to plugins whose IDs use the same prefix up to the colon, such as
417+
`my-extension:plugin` and `my-extension:other-plugin`. Extension authors should
418+
use the NPM extension package name, a colon, then a string identifying the
419+
plugin inside the extension, as described in the
420+
{ref}`plugin ID convention <plugin-id-convention>`, so
421+
administrators can lock or unlock all plugins in an extension consistently.
422+
393423
To unlock a locked plugin:
394424

395425
```bash
396426
jupyter labextension unlock my-extension:plugin
397427
```
398428

429+
To remove an extension-level lock:
430+
431+
```bash
432+
jupyter labextension unlock my-extension
433+
```
434+
399435
The locked plugins appear on the plugin list with a lock icon and cannot be enabled/disabled from the user interface:
400436

401437
```{image} ../images/plugin-manager-plugin-locked.png

‎jupyterlab/extensions/manager.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,8 @@ def _find_locked(self, plugins_or_extensions: list[str]) -> frozenset[str]:
235235
for plugin in plugins_or_extensions:
236236
if ":" in plugin:
237237
# check directly if this is a plugin identifier (has colon)
238-
if plugin in self.options.lock_rules:
238+
extension = plugin.split(":")[0]
239+
if plugin in self.options.lock_rules or extension in self.options.lock_rules:
239240
locked_subset.add(plugin)
240241
elif plugin in extensions_with_locked_plugins:
241242
# this is an extension - we need to check for >any< plugin
@@ -542,8 +543,8 @@ async def _is_allowed_by_listing(self, name: str) -> bool:
542543
return True
543544
if self._listings_cache is None:
544545
await self._fetch_listings()
545-
normalized = self._normalize_name(name)
546-
normalized_cache = {self._normalize_name(k) for k in self._listings_cache}
546+
normalized = self._canonicalize_name(name)
547+
normalized_cache = {self._canonicalize_name(k) for k in self._listings_cache}
547548
if self._listings_block_mode:
548549
return normalized not in normalized_cache
549550
else:
@@ -686,6 +687,10 @@ def _normalize_name(self, name: str) -> str:
686687
"""
687688
return name
688689

690+
def _canonicalize_name(self, name: str) -> str:
691+
"""Canonicalize extension name for listing policy comparisons."""
692+
return self._normalize_name(name)
693+
689694
async def _update_extensions_list(
690695
self, query: str | None = None, page: int = 1, per_page: int = 30
691696
) -> None:

‎jupyterlab/extensions/pypi.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@
3333
from packaging.version import parse as parse_version
3434
from traitlets import CFloat, CInt, Unicode, config, observe
3535

36+
try:
37+
from typing import override
38+
except ImportError:
39+
from typing_extensions import override
40+
3641
from jupyterlab._version import __version__
3742
from jupyterlab.extensions.manager import (
3843
ActionResult,
@@ -235,6 +240,7 @@ def metadata(self) -> ExtensionManagerMetadata:
235240
"""Extension manager metadata."""
236241
return ExtensionManagerMetadata("PyPI", True, sys.prefix)
237242

243+
@override
238244
async def is_install_allowed(self, name: str, version: str | None = None) -> bool:
239245
try:
240246
canonicalize_name(name, validate=True)
@@ -252,6 +258,11 @@ async def is_install_allowed(self, name: str, version: str | None = None) -> boo
252258
self.log.warning(f"Installation denied by allowlist/blocklist for {name}")
253259
return allowed
254260

261+
@override
262+
def _canonicalize_name(self, name: str) -> str:
263+
"""Canonicalize PyPI package names for listing policy comparisons."""
264+
return canonicalize_name(name)
265+
255266
async def get_latest_version(self, pkg: str) -> str | None:
256267
"""Return the latest available version for a given extension.
257268
@@ -498,7 +509,7 @@ async def install(self, name: str, version: Optional[str] = None) -> ActionResul
498509
Returns:
499510
The action result
500511
"""
501-
if not self.is_install_allowed(name, version):
512+
if not await self.is_install_allowed(name, version):
502513
# is_install_allowed will log the reason
503514
return ActionResult(status="error", message="install is not allowed")
504515

‎jupyterlab/labapp.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -867,7 +867,7 @@ def initialize_handlers(self): # noqa
867867
app_options=app_options,
868868
ext_options={
869869
"lock_rules": lock_rules,
870-
"all_locked": self.lock_all_plugins,
870+
"lock_all": self.lock_all_plugins,
871871
},
872872
parent=self,
873873
)

‎jupyterlab/tests/test_extensions.py‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
from jupyterlab.extensions import PyPIExtensionManager, ReadOnlyExtensionManager
1313
from jupyterlab.extensions.manager import (
14+
ActionResult,
1415
ExtensionManager,
1516
ExtensionPackage,
1617
PluginManager,
@@ -220,6 +221,22 @@ async def test_ExtensionManager_is_install_allowed_allowlist(mock_client):
220221
assert await manager.is_install_allowed("jupyterlab-evil") is False
221222

222223

224+
@pytest.mark.parametrize(
225+
"name",
226+
["jupyterlab-git", "JupyterLab-Git", "JupyterLab.Git", "jupyterlab_git"],
227+
)
228+
async def test_pypi_manager_allows_canonical_package_name_allowlist_matches(name):
229+
manager = PyPIExtensionManager(
230+
ext_options={"allowed_extensions_uris": {"http://dummy-allowed-extension"}}
231+
)
232+
manager._listings_cache = {"jupyterlab-git": {"name": "jupyterlab-git"}}
233+
if manager._listing_fetch is not None:
234+
manager._listing_fetch.stop()
235+
236+
assert await manager.is_install_allowed(name) is True
237+
assert await manager.is_install_allowed("jupyterlab-evil") is False
238+
239+
223240
@patch("tornado.httpclient.AsyncHTTPClient", new_callable=fake_client_factory)
224241
async def test_ExtensionManager_is_install_allowed_blocklist(mock_client):
225242
mock_client.body = json.dumps({"blocked_extensions": [{"name": "jupyterlab-evil"}]}).encode()
@@ -230,6 +247,48 @@ async def test_ExtensionManager_is_install_allowed_blocklist(mock_client):
230247
assert await manager.is_install_allowed("jupyterlab-git") is True
231248

232249

250+
@pytest.mark.parametrize(
251+
"name",
252+
["jupyterlab-git", "JupyterLab-Git", "JupyterLab.Git", "jupyterlab_git"],
253+
)
254+
async def test_handler_blocks_pypi_canonical_package_name_blocklist_matches(name):
255+
manager = PyPIExtensionManager(
256+
ext_options={"blocked_extensions_uris": {"http://dummy-blocked-extension"}}
257+
)
258+
manager._listings_cache = {"jupyterlab-git": {"name": "jupyterlab-git"}}
259+
if manager._listing_fetch is not None:
260+
manager._listing_fetch.stop()
261+
manager.install = AsyncMock(return_value=ActionResult(status="ok", needs_restart=[]))
262+
263+
handler = Mock()
264+
handler.current_user = "user"
265+
handler.get_json_body.return_value = {"cmd": "install", "extension_name": name}
266+
handler.manager = manager
267+
handler.set_status = Mock()
268+
handler.finish = Mock()
269+
270+
with pytest.raises(web.HTTPError) as exc_info:
271+
await ExtensionHandler.post(handler)
272+
assert exc_info.value.status_code == 422
273+
assert "was blocked" in exc_info.value.log_message
274+
manager.install.assert_not_called()
275+
276+
277+
async def test_pypi_manager_install_blocks_policy_denial_before_pip():
278+
manager = PyPIExtensionManager(
279+
ext_options={"blocked_extensions_uris": {"http://dummy-blocked-extension"}}
280+
)
281+
manager._listings_cache = {"jupyterlab-git": {"name": "jupyterlab-git"}}
282+
if manager._listing_fetch is not None:
283+
manager._listing_fetch.stop()
284+
285+
with patch("jupyterlab.extensions.pypi.run") as run_mock:
286+
result = await manager.install("JupyterLab.Git")
287+
288+
assert result == ActionResult(status="error", message="install is not allowed")
289+
run_mock.assert_not_called()
290+
291+
233292
@patch("tornado.httpclient.AsyncHTTPClient", new_callable=fake_client_factory)
234293
async def test_ExtensionManager_is_install_allowed_allowlist_takes_precedence(mock_client):
235294
mock_client.body = json.dumps(
@@ -579,6 +638,19 @@ async def test_pypi_manager_is_install_allowed_rejects_non_pypi_versions(version
579638
assert await manager.is_install_allowed("package", version) is expected
580639

581640

641+
async def test_pypi_manager_install_blocks_when_policy_denies():
642+
manager = PyPIExtensionManager()
643+
manager.is_install_allowed = AsyncMock(return_value=False)
644+
645+
with patch("jupyterlab.extensions.pypi.tornado.ioloop.IOLoop.current") as current_loop:
646+
result = await manager.install("jupyterlab-evil", "1.0.0")
647+
648+
assert result.status == "error"
649+
assert result.message == "install is not allowed"
650+
manager.is_install_allowed.assert_awaited_once_with("jupyterlab-evil", "1.0.0")
651+
current_loop.assert_not_called()
652+
653+
582654
async def test_handler_blocks_install_when_policy_denies():
583655
handler = Mock()
584656
handler.current_user = "user"

‎jupyterlab/tests/test_plugin_manager_handler.py‎

Lines changed: 79 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,17 @@
33

44
import json
55

6+
import pytest
67
from jupyterlab_server.config import get_static_page_config
8+
from tornado.httpclient import HTTPClientError
79

810
from jupyterlab.commands import get_app_info, lock_extension, unlock_extension
11+
from jupyterlab.extensions import manager as manager_module
912
from jupyterlab.extensions.manager import PluginManager
1013
from jupyterlab.handlers.plugin_manager_handler import PluginHandler, plugins_handler_path
1114

1215

13-
def plugin_handler_labapp(jp_serverapp, make_labserver_extension_app):
16+
def plugin_handler_labapp(jp_serverapp, make_labserver_extension_app, lock_all_plugins=False):
1417
app = make_labserver_extension_app()
1518
app._link_jupyter_server_extension(jp_serverapp)
1619

@@ -30,7 +33,7 @@ def plugin_handler_labapp(jp_serverapp, make_labserver_extension_app):
3033
"manager": PluginManager(
3134
ext_options={
3235
"lock_rules": lock_rules,
33-
"all_locked": False,
36+
"lock_all": lock_all_plugins,
3437
}
3538
)
3639
},
@@ -80,3 +83,77 @@ async def test_pluginHandler_unlock_extension(jp_serverapp, jp_fetch, make_labse
8083
payload = json.loads(response.body)
8184
assert response.code == 200
8285
assert payload["lockRules"] == []
86+
87+
88+
async def test_pluginHandler_lock_all_rejects_direct_post(
89+
jp_serverapp, jp_fetch, make_labserver_extension_app, monkeypatch
90+
):
91+
dispatched = []
92+
93+
def mock_disable_extension(plugin, app_options=None, level="sys_prefix"):
94+
dispatched.append(plugin)
95+
96+
monkeypatch.setattr(manager_module, "disable_extension", mock_disable_extension)
97+
98+
labapp = plugin_handler_labapp(
99+
jp_serverapp=jp_serverapp,
100+
make_labserver_extension_app=make_labserver_extension_app,
101+
lock_all_plugins=True,
102+
)
103+
labapp.initialize()
104+
105+
response = await jp_fetch("lab", "api", "plugins", method="GET")
106+
payload = json.loads(response.body)
107+
assert response.code == 200
108+
assert payload["allLocked"] is True
109+
110+
plugin = "@jupyterlab/apputils-extension:sanitizer"
111+
with pytest.raises(HTTPClientError) as e:
112+
await jp_fetch(
113+
"lab",
114+
"api",
115+
"plugins",
116+
method="POST",
117+
body=json.dumps({"cmd": "disable", "plugin_name": plugin}),
118+
)
119+
assert e.value.code == 500
120+
payload = json.loads(e.value.response.body)
121+
assert payload["status"] == "error"
122+
assert plugin in payload["message"]
123+
assert dispatched == []
124+
125+
126+
@pytest.mark.parametrize("cmd", ("disable", "enable"))
127+
async def test_pluginHandler_extension_lock_rejects_child_plugin_direct_post(
128+
jp_serverapp, jp_fetch, make_labserver_extension_app, monkeypatch, cmd
129+
):
130+
dispatched = []
131+
132+
def mock_toggle_extension(plugin, app_options=None, level="sys_prefix"):
133+
dispatched.append(plugin)
134+
135+
monkeypatch.setattr(manager_module, "disable_extension", mock_toggle_extension)
136+
monkeypatch.setattr(manager_module, "enable_extension", mock_toggle_extension)
137+
138+
extension = "@jupyterlab/apputils-extension"
139+
plugin = f"{extension}:sanitizer"
140+
lock_extension(extension)
141+
142+
labapp = plugin_handler_labapp(
143+
jp_serverapp=jp_serverapp, make_labserver_extension_app=make_labserver_extension_app
144+
)
145+
labapp.initialize()
146+
147+
with pytest.raises(HTTPClientError) as e:
148+
await jp_fetch(
149+
"lab",
150+
"api",
151+
"plugins",
152+
method="POST",
153+
body=json.dumps({"cmd": cmd, "plugin_name": plugin}),
154+
)
155+
assert e.value.code == 500
156+
payload = json.loads(e.value.response.body)
157+
assert payload["status"] == "error"
158+
assert plugin in payload["message"]
159+
assert dispatched == []

0 commit comments

Comments
 (0)