From cd84175921f2d1d3008b3184ca1caf22e18ea17d Mon Sep 17 00:00:00 2001 From: krassowski <5832902+krassowski@users.noreply.github.com> Date: Tue, 13 Feb 2024 11:57:40 +0000 Subject: [PATCH] Add `JUPYTER_SERVER_ALLOW_UNAUTHENTICATED_ACCESS` env variable --- jupyter_server/serverapp.py | 14 +++++++++++++- tests/test_serverapp.py | 20 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/jupyter_server/serverapp.py b/jupyter_server/serverapp.py index 9433214989..1f4510d91f 100644 --- a/jupyter_server/serverapp.py +++ b/jupyter_server/serverapp.py @@ -1275,10 +1275,12 @@ def _deprecated_password_config(self, change: t.Any) -> None: """, ) + _allow_unauthenticated_access_env = "JUPYTER_SERVER_ALLOW_UNAUTHENTICATED_ACCESS" + allow_unauthenticated_access = Bool( True, config=True, - help="""Allow requests unauthenticated access to endpoints without authentication rules. + help=f"""Allow unauthenticated access to endpoints without authentication rule. When set to `True` (default in jupyter-server 2.0, subject to change in the future), any request to an endpoint without an authentication rule @@ -1287,9 +1289,19 @@ def _deprecated_password_config(self, change: t.Any) -> None: When set to `False`, logging in will be required for access to each endpoint, excluding the endpoints marked with `@allow_unauthenticated` decorator. + + This option can be configured using `{_allow_unauthenticated_access_env}` + environment variable: any non-empty value other than "true" and "yes" will + prevent unauthenticated access to endpoints without `@allow_unauthenticated`. """, ) + @default("allow_unauthenticated_access") + def _allow_unauthenticated_access_default(self): + if os.getenv(self._allow_unauthenticated_access_env): + return os.environ[self._allow_unauthenticated_access_env].lower() in ["true", "yes"] + return True + allow_remote_access = Bool( config=True, help="""Allow requests where the Host header doesn't point to a local server diff --git a/tests/test_serverapp.py b/tests/test_serverapp.py index df703f550c..eade03a24c 100644 --- a/tests/test_serverapp.py +++ b/tests/test_serverapp.py @@ -163,6 +163,26 @@ def test_server_password(tmp_path, jp_configurable_serverapp): passwd_check(sv.identity_provider.hashed_password, password) +@pytest.mark.parametrize( + "env,expected", + [ + ["yes", True], + ["Yes", True], + ["True", True], + ["true", True], + ["TRUE", True], + ["no", False], + ["nooo", False], + ["FALSE", False], + ["false", False], + ], +) +def test_allow_unauthenticated_env_var(jp_configurable_serverapp, env, expected): + with patch.dict("os.environ", {"JUPYTER_SERVER_ALLOW_UNAUTHENTICATED_ACCESS": env}): + app = jp_configurable_serverapp() + assert app.allow_unauthenticated_access == expected + + def test_list_running_servers(jp_serverapp, jp_web_app): servers = list(list_running_servers(jp_serverapp.runtime_dir)) assert len(servers) >= 1