Skip to content

Commit c18361c

Browse files
authored
Merge pull request #462 from afshin/jupyter-token-file
Add support for JUPYTER_TOKEN_FILE
2 parents 5d207a8 + 5ee5e2b commit c18361c

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

jupyter_server/serverapp.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -786,6 +786,9 @@ def _write_cookie_secret_file(self, secret):
786786
token = Unicode('<generated>',
787787
help=_i18n("""Token used for authenticating first-time connections to the server.
788788
789+
The token can be read from the file referenced by JUPYTER_TOKEN_FILE or set directly
790+
with the JUPYTER_TOKEN environment variable.
791+
789792
When no password is enabled,
790793
the default is to generate a new, random token.
791794
@@ -800,6 +803,10 @@ def _token_default(self):
800803
if os.getenv('JUPYTER_TOKEN'):
801804
self._token_generated = False
802805
return os.getenv('JUPYTER_TOKEN')
806+
if os.getenv('JUPYTER_TOKEN_FILE'):
807+
self._token_generated = False
808+
with io.open(os.getenv('JUPYTER_TOKEN_FILE'), "r") as token_file:
809+
return token_file.read()
803810
if self.password:
804811
# no token if password is enabled
805812
self._token_generated = False

jupyter_server/tests/extension/test_launch.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Test launching Jupyter Server Applications
22
through as ExtensionApp launch_instance.
33
"""
4+
from pathlib import Path
45
import os
56
import sys
67
import time
@@ -45,7 +46,7 @@ def wait_up(url, interval=0.1, check=None):
4546

4647
@pytest.fixture
4748
def launch_instance(request, port, token):
48-
def _run_in_subprocess(argv=[]):
49+
def _run_in_subprocess(argv=[], add_token=True):
4950

5051
def _kill_extension_app():
5152
try:
@@ -55,13 +56,15 @@ def _kill_extension_app():
5556
pass
5657
process.wait(10)
5758

59+
if add_token:
60+
f'--ServerApp.token="{token}"',
61+
5862
process = subprocess.Popen([
5963
sys.executable, '-m',
6064
'mockextensions.app',
6165
f'--port={port}',
6266
'--ip=127.0.0.1',
6367
'--no-browser',
64-
f'--ServerApp.token="{token}"',
6568
*argv,
6669
], cwd=HERE)
6770

@@ -93,3 +96,15 @@ def test_base_url(launch_instance, fetch):
9396
assert r.status_code == 200
9497

9598

99+
def test_token_file(launch_instance, fetch, token):
100+
token_file = HERE / Path('token_file.txt')
101+
os.environ['JUPYTER_TOKEN_FILE'] = str(token_file)
102+
token_file.write_text(token, encoding='utf-8')
103+
104+
launch_instance(add_token=False)
105+
r = fetch("/mock")
106+
del os.environ['JUPYTER_TOKEN_FILE']
107+
token_file.unlink()
108+
assert r.status_code == 200
109+
110+

0 commit comments

Comments
 (0)