From 5bd410515d06418e0c36fb367e92ebb1c2883ab8 Mon Sep 17 00:00:00 2001 From: Konstantin Taletskiy Date: Thu, 8 Sep 2022 16:23:56 -0700 Subject: [PATCH 1/3] feat: make extension configurable feat: migrate from Jupyter Notebook to Jupyter Server Signed-off-by: Konstantin Taletskiy --- README.md | 13 ++++++++- jhoauthrefresh/__init__.py | 60 +++++++++++++++++++------------------- jhoauthrefresh/config.py | 39 +++++++++++++++++++++++++ setup.py | 8 ++--- 4 files changed, 84 insertions(+), 36 deletions(-) create mode 100644 jhoauthrefresh/config.py diff --git a/README.md b/README.md index f3f9599..68bd53c 100644 --- a/README.md +++ b/README.md @@ -3,11 +3,22 @@ Jupyter notebook extension that periodically asks a service for a token and stores it in an environment variable. - ## Install Clone this repository and then: + ``` pip install -e. jupyter serverextension enable --py jhoauthrefresh ``` + +## Configuration + +This extension is configured by customizing your jupyter_notebook_config.py file: + +``` +c.JHOauthRefreshConfig.jupyterhub_token_env_var = 'JUPYTERHUB_API_TOKEN' +c.JHOauthRefreshConfig.oauth_token_env_var = 'OAUTH_ACCESS_TOKEN' +c.JHOauthRefreshConfig.new_token_url = 'https://notebooks.openhumans.org/services/refresher/tokens' +c.JHOauthRefreshConfig.renew_period = 1 +``` diff --git a/jhoauthrefresh/__init__.py b/jhoauthrefresh/__init__.py index 49781ec..2dfd6a3 100644 --- a/jhoauthrefresh/__init__.py +++ b/jhoauthrefresh/__init__.py @@ -1,64 +1,64 @@ import os import json -import urllib +from jupyter_server.base.handlers import JupyterHandler +from jupyter_server.serverapp import ServerApp +import tornado from tornado import web from tornado.ioloop import IOLoop from tornado.ioloop import PeriodicCallback from tornado.httpclient import AsyncHTTPClient, HTTPRequest - from notebook.utils import url_path_join -from notebook.base.handlers import IPythonHandler + +from .config import JHOauthRefreshConfig -class TokenHandler(IPythonHandler): - @web.authenticated +class TokenHandler(JupyterHandler): + @tornado.web.authenticated async def get(self): - self.write(os.getenv('OH_ACCESS_TOKEN')) + config = self.settings["jhoauthrefresh"] + self.write(os.getenv(config.oauth_token_env_var)) -def setup_handlers(web_app): - web_app.add_handlers('.*', [ - (url_path_join(web_app.settings['base_url'], 'oh-token'), TokenHandler) - ]) +def setup_handlers(web_app, endpoint): + web_app.add_handlers( + ".*", [(url_path_join(web_app.settings["base_url"], endpoint), TokenHandler,)], + ) -async def fetch_new_token(token, - url='https://notebooks.openhumans.org/services/refresher/tokens'): +async def fetch_new_token(token, url): req = HTTPRequest(url, headers={"Authorization": "token %s" % token}) client = AsyncHTTPClient() resp = await client.fetch(req) - resp_json = json.loads(resp.body.decode('utf8', 'replace')) + resp_json = json.loads(resp.body.decode("utf8", "replace")) return resp_json -async def update(): - jhub_api_token = os.getenv("JUPYTERHUB_API_TOKEN") - tokens = await fetch_new_token(jhub_api_token) - os.environ['OH_ACCESS_TOKEN'] = tokens['access_token'] +async def update(config): + jhub_api_token = os.getenv(config.jupyterhub_token_env_var) + tokens = await fetch_new_token(jhub_api_token, config.new_token_url) + os.environ[config.oauth_token_env_var] = tokens["access_token"] -def _jupyter_server_extension_paths(): - return [{ - 'module': 'jhoauthrefresh', - }] +def _jupyter_server_extension_points(): + return [{"module": "jhoauthrefresh",}] -def load_jupyter_server_extension(nbapp): +def _load_jupyter_server_extension(serverapp: ServerApp): """ - Called when the extension is loaded. + This function is called when the extension is loaded. """ - setup_handlers(nbapp.web_app) + config = JHOauthRefreshConfig(config=serverapp.config) + serverapp.web_app.settings["jhoauthrefresh"] = config + setup_handlers(serverapp.web_app, config.extension_endpoint) - # update once at teh start to handle the case where the server is + # update once at the start to handle the case where the server is # being started so long after the login that the token itself has # expired so we need to refresh it straight away loop = IOLoop.current() - loop.run_sync(update) - # XXX set the period properly based on expiry time of the token - # the period has to be specified in milliseconds - # OpenHumans tokens expire after ten hours, we renew every 8.5h - pc = PeriodicCallback(update, 1e3 * 60 * 60 * 8.5) + loop.run_sync(lambda: update(config)) + print(config.renew_period) + pc = PeriodicCallback(lambda: update(config), config.renew_period) pc.start() diff --git a/jhoauthrefresh/config.py b/jhoauthrefresh/config.py new file mode 100644 index 0000000..fd7b443 --- /dev/null +++ b/jhoauthrefresh/config.py @@ -0,0 +1,39 @@ +from traitlets import Unicode, Integer +from traitlets.config import Configurable + + +class JHOauthRefreshConfig(Configurable): + """ + A Configurable that declares the configuration options + for the jhoauthrefresh. + """ + + jupyterhub_token_env_var = Unicode( + "JUPYTERHUB_API_TOKEN", + config=True, + help="Name of the environment variable storing JuyterHub API token.", + ) + oauth_token_env_var = Unicode( + "OAUTH_ACCESS_TOKEN", + config=True, + help="Name of the environment variable storing refreshing OAuth token.", + ) + new_token_url = Unicode( + "https://notebooks.openhumans.org/services/refresher/tokens", + config=True, + help="URL of the JupyterHub service providing refreshed token.", + ) + # renew_period sets the period properly based on expiry time of the token + # the period has to be specified in milliseconds + # for example, for tokens that expire after ten hours, you can set + # the variable to 1e3 * 60 * 60 * 8.5 (8.5 hours) + renew_period = Integer( + default_value=3600000, + config=True, + help="Time between token refreshes in milliseconds.", + ) + extension_endpoint = Unicode( + "oauth-token", + config=True, + help="Jupyter Server extension endpoint.", + ) diff --git a/setup.py b/setup.py index 5e10c65..7de9917 100644 --- a/setup.py +++ b/setup.py @@ -2,11 +2,9 @@ setuptools.setup( name="jhoauthrefresh", - version='0.2.0', - url="https://github.com/OpenHumans/jhoauth-refresh", + version="0.3.0", + url="https://github.com/ktaletsk/jhoauth-refresh", author="Tim Head", packages=setuptools.find_packages(), - install_requires=[ - 'notebook', - ], + install_requires=["notebook",], ) From 7139761cc2dceac7492259e55681ac674c6a6db7 Mon Sep 17 00:00:00 2001 From: Konstantin Taletskiy Date: Fri, 9 Sep 2022 09:38:27 -0700 Subject: [PATCH 2/3] Update README.md --- README.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 68bd53c..e8a6736 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,19 @@ # JupyterHub OAuth2 Token Refresher -Jupyter notebook extension that periodically asks a service for a token and +Jupyter notebook extension that periodically asks a [service](https://github.com/wildtreetech/ohjh/tree/master/images/refresher) for a token and stores it in an environment variable. ## Install Clone this repository and then: +``` +pip install jhoauthrefresh +jupyter serverextension enable --py jhoauthrefresh +``` + +### Development install + ``` pip install -e. jupyter serverextension enable --py jhoauthrefresh @@ -20,5 +27,10 @@ This extension is configured by customizing your jupyter_notebook_config.py file c.JHOauthRefreshConfig.jupyterhub_token_env_var = 'JUPYTERHUB_API_TOKEN' c.JHOauthRefreshConfig.oauth_token_env_var = 'OAUTH_ACCESS_TOKEN' c.JHOauthRefreshConfig.new_token_url = 'https://notebooks.openhumans.org/services/refresher/tokens' -c.JHOauthRefreshConfig.renew_period = 1 +c.JHOauthRefreshConfig.renew_period = 5000 +``` + +Alternatively, parameters can be passed as command line arguments to Jupyter, as such: +``` +jupyter lab --JHOauthRefreshConfig.oauth_token_env_var='JUPYTERHUB_API_TOKEN' --JHOauthRefreshConfig.renew_period=5000 ``` From 5868f45e34a278d4c0a829b3d1ab790e1c9af7fc Mon Sep 17 00:00:00 2001 From: Konstantin Taletskiy Date: Fri, 9 Sep 2022 09:42:43 -0700 Subject: [PATCH 3/3] Update setup.py --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 7de9917..56137cb 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ setuptools.setup( name="jhoauthrefresh", version="0.3.0", - url="https://github.com/ktaletsk/jhoauth-refresh", + url="https://github.com/OpenHumans/jhoauth-refresh", author="Tim Head", packages=setuptools.find_packages(), install_requires=["notebook",],