repo
stringclasses
358 values
pull_number
int64
6
67.9k
instance_id
stringlengths
12
49
issue_numbers
sequencelengths
1
7
base_commit
stringlengths
40
40
patch
stringlengths
87
101M
test_patch
stringlengths
72
22.3M
problem_statement
stringlengths
3
256k
hints_text
stringlengths
0
545k
created_at
stringlengths
20
20
PASS_TO_PASS
sequencelengths
0
0
FAIL_TO_PASS
sequencelengths
0
0
freedomofpress/securedrop
7,116
freedomofpress__securedrop-7116
[ "7092" ]
ae491cc65f73fee06f7cd41a1e78a0d500e30654
diff --git a/admin/bootstrap.py b/admin/bootstrap.py --- a/admin/bootstrap.py +++ b/admin/bootstrap.py @@ -66,7 +66,7 @@ def run_command(command: List[str]) -> Iterator[bytes]: def is_tails() -> bool: with open("/etc/os-release") as f: - return "TAILS_PRODUCT_NAME" in f.read() + return 'NAME="Tails"' in f.read() def clean_up_old_tails_venv(virtualenv_dir: str = VENV_DIR) -> None: @@ -80,15 +80,15 @@ def clean_up_old_tails_venv(virtualenv_dir: str = VENV_DIR) -> None: with open("/etc/os-release") as f: os_release = f.readlines() for line in os_release: - if line.startswith("TAILS_VERSION_ID="): + if line.startswith("VERSION="): version = line.split("=")[1].strip().strip('"') - if version.startswith("5."): - # Tails 5 is based on Python 3.9 - python_lib_path = os.path.join(virtualenv_dir, "lib/python3.7") + if version.startswith("6."): + # Tails 6 is based on Python 3.11 + python_lib_path = os.path.join(virtualenv_dir, "lib/python3.9") if os.path.exists(python_lib_path): - sdlog.info("Tails 4 virtualenv detected. Removing it.") + sdlog.info("Tails 5 virtualenv detected. Removing it.") shutil.rmtree(virtualenv_dir) - sdlog.info("Tails 4 virtualenv deleted.") + sdlog.info("Tails 5 virtualenv deleted.") break @@ -146,13 +146,7 @@ def install_apt_dependencies(args: argparse.Namespace) -> None: " which was set on Tails login screen" ) - apt_command = [ - "sudo", - "su", - "-c", - f"apt-get update && \ - apt-get -q -o=Dpkg::Use-Pty=0 install -y {APT_DEPENDENCIES_STR}", - ] + apt_command = f"sudo apt-get -q -o=Dpkg::Use-Pty=0 install -y {APT_DEPENDENCIES_STR}".split(" ") try: # Print command results in real-time, to keep Admin apprised diff --git a/admin/securedrop_admin/__init__.py b/admin/securedrop_admin/__init__.py --- a/admin/securedrop_admin/__init__.py +++ b/admin/securedrop_admin/__init__.py @@ -63,6 +63,29 @@ I18N_DEFAULT_LOCALES = {"en_US"} +# Check OpenSSH version - ansible requires an extra argument for scp on OpenSSH 9 +def openssh_version() -> int: + try: + result = subprocess.run(["ssh", "-V"], capture_output=True, text=True) + if result.stderr.startswith("OpenSSH_9"): + return 9 + elif result.stderr.startswith("OpenSSH_8"): + return 8 + else: + return 0 + except subprocess.CalledProcessError: + return 0 + pass + return 0 + + +def ansible_command() -> List[str]: + cmd = ["ansible-playbook"] + if openssh_version() == 9: + cmd = ["ansible-playbook", "--scp-extra-args='-O'"] + return cmd + + class FingerprintException(Exception): pass @@ -845,7 +868,8 @@ def install_securedrop(args: argparse.Namespace) -> int: sdlog.info("You will be prompted for the sudo password on the " "servers.") sdlog.info("The sudo password is only necessary during initial " "installation.") return subprocess.check_call( - [os.path.join(args.ansible_path, "securedrop-prod.yml"), "--ask-become-pass"], + ansible_command() + + [os.path.join(args.ansible_path, "securedrop-prod.yml"), "--ask-become-pass"], cwd=args.ansible_path, ) @@ -864,11 +888,8 @@ def backup_securedrop(args: argparse.Namespace) -> int: Creates a tarball of submissions and server config, and fetches back to the Admin Workstation. Future `restore` actions can be performed with the backup tarball.""" - sdlog.info("Backing up the SecureDrop Application Server") - ansible_cmd = [ - "ansible-playbook", - os.path.join(args.ansible_path, "securedrop-backup.yml"), - ] + sdlog.info("Backing up the Sec Application Server") + ansible_cmd = ansible_command() + [os.path.join(args.ansible_path, "securedrop-backup.yml")] return subprocess.check_call(ansible_cmd, cwd=args.ansible_path) @@ -887,8 +908,7 @@ def restore_securedrop(args: argparse.Namespace) -> int: # Would like readable output if there's a problem os.environ["ANSIBLE_STDOUT_CALLBACK"] = "debug" - ansible_cmd = [ - "ansible-playbook", + ansible_cmd = ansible_command() + [ os.path.join(args.ansible_path, "securedrop-restore.yml"), "-e", ] @@ -915,7 +935,7 @@ def run_tails_config(args: argparse.Namespace) -> int: "You'll be prompted for the temporary Tails admin password," " which was set on Tails login screen" ) - ansible_cmd = [ + ansible_cmd = ansible_command() + [ os.path.join(args.ansible_path, "securedrop-tails.yml"), "--ask-become-pass", # Passing an empty inventory file to override the automatic dynamic @@ -1077,10 +1097,10 @@ def update(args: argparse.Namespace) -> int: def get_logs(args: argparse.Namespace) -> int: """Get logs for forensics and debugging purposes""" sdlog.info("Gathering logs for forensics and debugging") - ansible_cmd = [ - "ansible-playbook", + ansible_cmd = ansible_command() + [ os.path.join(args.ansible_path, "securedrop-logs.yml"), ] + subprocess.check_call(ansible_cmd, cwd=args.ansible_path) sdlog.info( "Please send the encrypted logs to [email protected] or " @@ -1107,8 +1127,7 @@ def reset_admin_access(args: argparse.Namespace) -> int: """Resets SSH access to the SecureDrop servers, locking it to this Admin Workstation.""" sdlog.info("Resetting SSH access to the SecureDrop servers") - ansible_cmd = [ - "ansible-playbook", + ansible_cmd = ansible_command() + [ os.path.join(args.ansible_path, "securedrop-reset-ssh-key.yml"), ] return subprocess.check_call(ansible_cmd, cwd=args.ansible_path) diff --git a/install_files/ansible-base/callback_plugins/ansible_version_check.py b/install_files/ansible-base/callback_plugins/ansible_version_check.py --- a/install_files/ansible-base/callback_plugins/ansible_version_check.py +++ b/install_files/ansible-base/callback_plugins/ansible_version_check.py @@ -17,8 +17,8 @@ class CallbackModule(CallbackBase): def __init__(self): # The acceptable version range needs to be synchronized with # requirements files. - viable_start = [2, 11, 0] - viable_end = [2, 15, 0] + viable_start = [2, 13, 0] + viable_end = [2, 15, 10] ansible_version = [int(v) for v in ansible.__version__.split(".")] if not (viable_start <= ansible_version < viable_end): print_red_bold( diff --git a/install_files/ansible-base/roles/tails-config/files/securedrop_init.py b/install_files/ansible-base/roles/tails-config/files/securedrop_init.py --- a/install_files/ansible-base/roles/tails-config/files/securedrop_init.py +++ b/install_files/ansible-base/roles/tails-config/files/securedrop_init.py @@ -120,9 +120,9 @@ ) subprocess.call(["gio", "set", path_desktop + shortcut, "metadata::trusted", "true"], env=env) -# in Tails 4, reload gnome-shell desktop icons extension to update with changes above +# in Tails 4 or greater, reload gnome-shell desktop icons extension to update with changes above with open("/etc/os-release") as f: - is_tails = "TAILS_PRODUCT_NAME" in f.read() + is_tails = 'NAME="Tails"' in f.read() if is_tails: subprocess.call(["gnome-shell-extension-tool", "-r", "desktop-icons@csoriano"], env=env) @@ -165,7 +165,7 @@ for line in file: try: k, v = line.strip().split("=") - if k == "TAILS_VERSION_ID": + if k == "VERSION": tails_current_version = v.strip('"').split(".") except ValueError: continue
diff --git a/admin/tests/test_securedrop-admin-setup.py b/admin/tests/test_securedrop-admin-setup.py --- a/admin/tests/test_securedrop-admin-setup.py +++ b/admin/tests/test_securedrop-admin-setup.py @@ -75,39 +75,39 @@ def test_install_pip_dependencies_fail(self, caplog): bootstrap.install_pip_dependencies(args) assert "Failed to install" in caplog.text - def test_python3_buster_venv_deleted_in_bullseye(self, tmpdir, caplog): + def test_python3_bullseye_venv_deleted_in_bookworm(self, tmpdir, caplog): venv_path = str(tmpdir) - python_lib_path = os.path.join(str(tmpdir), "lib/python3.7") + python_lib_path = os.path.join(str(tmpdir), "lib/python3.9") os.makedirs(python_lib_path) with mock.patch("bootstrap.is_tails", return_value=True): - with mock.patch("builtins.open", mock.mock_open(read_data='TAILS_VERSION_ID="5.0"')): + with mock.patch("builtins.open", mock.mock_open(read_data='VERSION="6.0"')): bootstrap.clean_up_old_tails_venv(venv_path) - assert "Tails 4 virtualenv detected." in caplog.text - assert "Tails 4 virtualenv deleted." in caplog.text + assert "Tails 5 virtualenv detected." in caplog.text + assert "Tails 5 virtualenv deleted." in caplog.text assert not os.path.exists(venv_path) - def test_python3_bullseye_venv_not_deleted_in_bullseye(self, tmpdir, caplog): + def test_python3_bookworm_venv_not_deleted_in_bookworm(self, tmpdir, caplog): venv_path = str(tmpdir) - python_lib_path = os.path.join(venv_path, "lib/python3.9") + python_lib_path = os.path.join(venv_path, "lib/python3.11") os.makedirs(python_lib_path) with mock.patch("bootstrap.is_tails", return_value=True): - with mock.patch("subprocess.check_output", return_value="bullseye"): + with mock.patch("subprocess.check_output", return_value="bookworm"): bootstrap.clean_up_old_tails_venv(venv_path) - assert "Tails 4 virtualenv detected" not in caplog.text + assert "Tails 5 virtualenv detected" not in caplog.text assert os.path.exists(venv_path) def test_python3_buster_venv_not_deleted_in_buster(self, tmpdir, caplog): venv_path = str(tmpdir) - python_lib_path = os.path.join(venv_path, "lib/python3.7") + python_lib_path = os.path.join(venv_path, "lib/python3.9") os.makedirs(python_lib_path) with mock.patch("bootstrap.is_tails", return_value=True): - with mock.patch("subprocess.check_output", return_value="buster"): + with mock.patch("subprocess.check_output", return_value="bullseye"): bootstrap.clean_up_old_tails_venv(venv_path) assert os.path.exists(venv_path) def test_venv_cleanup_subprocess_exception(self, tmpdir, caplog): venv_path = str(tmpdir) - python_lib_path = os.path.join(venv_path, "lib/python3.7") + python_lib_path = os.path.join(venv_path, "lib/python3.9") os.makedirs(python_lib_path) with mock.patch("bootstrap.is_tails", return_value=True), mock.patch( "subprocess.check_output", side_effect=subprocess.CalledProcessError(1, ":o") diff --git a/admin/tests/test_securedrop-admin.py b/admin/tests/test_securedrop-admin.py --- a/admin/tests/test_securedrop-admin.py +++ b/admin/tests/test_securedrop-admin.py @@ -53,6 +53,15 @@ def test_not_verbose(self, capsys): assert "HIDDEN" not in out assert "VISIBLE" in out + def test_openssh_detection(self): + with mock.patch("securedrop_admin.openssh_version", side_effect=[9]): + assert securedrop_admin.ansible_command() == [ + "ansible-playbook", + "--scp-extra-args='-O'", + ] + with mock.patch("securedrop_admin.openssh_version", side_effect=[8]): + assert securedrop_admin.ansible_command() == ["ansible-playbook"] + def test_update_check_decorator_when_no_update_needed(self, caplog): """ When a function decorated with `@update_check_required` is run
Update admin and journalist workstations to use Tails 6 Tails 6 is in RC mode with a projected release date of Feb 27 2024. This version is based on Debian Bookworm and has a tonne of changes both under the hood and to the UX. Updates to Tails 6 in terms of code changes and dependencies seem to be compatible with Tails 5 as well, so users still on Tails 5 can update to a version with said changes and upgrade tails independently (tho they will need to run `setup` again to remove the Python 3.9 virtualenv and set up a 3.11 one). Update tasks roughly break out as follows: ## code - [x] Update admin scripts for Tails 6 - [x] update bootstrap script to account for changes in apt's behaviour and Python version - [x] update Python dependencies (stretch: upgrade to latest Ansible :heavy_check_mark: ) - [x] test and update Ansible playbooks as needed - [x] Update network hook script (changes may be required if TCA or Tor itself behave differently) - [x] ~Update GUI updater for Tails 6~ no changes necessary - [x] ~Update Gnome menu for Tails 6~ no changes necessary ## docs - [x] Update user documentation with any changes (for the sake of consistency any screenshots etc should be in existing light mode theme) ## comms and release - [ ] Plan comms - Tails users should be notified of requirement a decent time ahead of release. Users will probably have to do a CLI update after upgrading to Tails 6 as well. - [ ] consider a blog post describing changes, a bit more substantial than usual release notification. - [ ] schedule 2.8.0 release to coincide with or immediately follow Tails 6 release. At a minimum the Tails 6 changes should be in place in time
2024-02-19T19:17:24Z
[]
[]
freedomofpress/securedrop
7,120
freedomofpress__securedrop-7120
[ "6784" ]
bbf143425a1a5b8e9146330baaaf31c104ca7425
diff --git a/securedrop/sdconfig.py b/securedrop/sdconfig.py --- a/securedrop/sdconfig.py +++ b/securedrop/sdconfig.py @@ -71,6 +71,8 @@ class SecureDropConfig: RQ_WORKER_NAME: str + env: str = "prod" + @property def TEMP_DIR(self) -> Path: # We use a directory under the SECUREDROP_DATA_ROOT instead of `/tmp` because @@ -115,6 +117,8 @@ def _parse_config_from_file(config_module_name: str) -> SecureDropConfig: config_from_local_file, "SCRYPT_PARAMS", dict(N=2**14, r=8, p=1) ) + env = getattr(config_from_local_file, "env", "prod") + try: final_securedrop_root = Path(config_from_local_file.SECUREDROP_ROOT) except AttributeError: @@ -188,6 +192,7 @@ def _parse_config_from_file(config_module_name: str) -> SecureDropConfig: ) return SecureDropConfig( + env=env, JOURNALIST_APP_FLASK_CONFIG_CLS=parsed_journ_flask_config, SOURCE_APP_FLASK_CONFIG_CLS=parsed_source_flask_config, GPG_KEY_DIR=final_gpg_key_dir,
diff --git a/securedrop/tests/test_config.py b/securedrop/tests/test_config.py --- a/securedrop/tests/test_config.py +++ b/securedrop/tests/test_config.py @@ -19,8 +19,12 @@ def test_parse_current_config(): try: current_config_file.write_text(current_sample_config.read_text()) - # When trying to parse it, it succeeds - assert _parse_config_from_file(f"tests.{current_config_module}") + # When trying to parse it, it succeeds... + parsed_config = _parse_config_from_file(f"tests.{current_config_module}") + assert parsed_config + + # ...and has one of our `env` values rather than one of Flask's: + assert parsed_config.env in ["prod", "dev", "test"] finally: current_config_file.unlink(missing_ok=True)
development server no longer hot-reloads on file changes ## Description After #6563, `make dev` no longer hot-reloads on file changes, because the immutable `SDConfig` doesn't carry the `env` attribute from `config.py`. (This regression was last encountered in #5594.) ## Steps to Reproduce Same as #5594. ## Expected Behavior Same as #5594. ## Actual Behavior Same as #5594. ## Comments The fix in <https://github.com/freedomofpress/securedrop/issues/6669#issuecomment-1526129678> is trivial, but I want to take a moment to see if there's an easy way to test for this regression (fool me once, fool me twice, etc.).
Can I work on this? On Wed, May 10, 2023 at 08:55:40AM -0700, Siddhant Ota wrote: > Can I work on this? Sure; thanks your interest! You'll find the basic fix in <https://github.com/freedomofpress/securedrop/issues/6669#issuecomment-1526129678>. The goal here is to find out if we can add a test that checks that "env" is passed through as expected. Let us know if you have any questions. Thanks, I'm new to open source but I'll give me best. I'll let you know if I need anything. I have applied the patch you mentioned in #6669 and reload works in my machine. But I don't know how to write tests (I don't understand how it is implemented in this repo to be specific). Can you point me to some resources where I can learn? Thanks > On Wed, May 10, 2023 at 08:55:40AM -0700, Siddhant Ota wrote: Can I work on this? > Sure; thanks your interest! You'll find the basic fix in <[#6669 (comment)](https://github.com/freedomofpress/securedrop/issues/6669#issuecomment-1526129678)>. The goal here is to find out if we can add a test that checks that "env" is passed through as expected. Let us know if you have any questions. I have applied the patch you mentioned in https://github.com/freedomofpress/securedrop/issues/6669 and reload works in my machine. But I don't know how to write tests (I don't understand how it is implemented in this repo to be specific). Can you point me to some resources where I can learn? Thanks
2024-02-22T02:12:10Z
[]
[]
freedomofpress/securedrop
7,160
freedomofpress__securedrop-7160
[ "3907" ]
3a50273be99c78c78ea169854b2264f1edef3dab
diff --git a/securedrop/journalist_app/utils.py b/securedrop/journalist_app/utils.py --- a/securedrop/journalist_app/utils.py +++ b/securedrop/journalist_app/utils.py @@ -371,7 +371,6 @@ def col_delete_data(cols_selected: List[str]) -> werkzeug.Response: "error", ) else: - for filesystem_id in cols_selected: delete_source_files(filesystem_id) @@ -535,4 +534,5 @@ def serve_file_with_etag(db_obj: Union[Reply, Submission]) -> flask.Response: response.direct_passthrough = False response.headers["Etag"] = db_obj.checksum + response.headers["Accept-Ranges"] = "bytes" return response
diff --git a/securedrop/tests/test_journalist_api.py b/securedrop/tests/test_journalist_api.py --- a/securedrop/tests/test_journalist_api.py +++ b/securedrop/tests/test_journalist_api.py @@ -1,3 +1,5 @@ +import binascii +import hashlib import json import random from datetime import datetime @@ -232,7 +234,6 @@ def test_user_without_token_cannot_del_protected_endpoints(journalist_app, test_ def test_attacker_cannot_use_token_after_admin_deletes( journalist_app, test_source, journalist_api_token ): - with journalist_app.test_client() as app: uuid = test_source["source"].uuid @@ -893,7 +894,6 @@ def test_reply_with_valid_square_json_400( def test_malformed_json_400(journalist_app, journalist_api_token, test_journo, test_source): - with journalist_app.app_context(): uuid = test_source["source"].uuid protected_routes = [ @@ -904,7 +904,6 @@ def test_malformed_json_400(journalist_app, journalist_api_token, test_journo, t ] with journalist_app.test_client() as app: for protected_route in protected_routes: - response = app.post( protected_route, data="{this is invalid {json!", @@ -916,7 +915,6 @@ def test_malformed_json_400(journalist_app, journalist_api_token, test_journo, t def test_empty_json_400(journalist_app, journalist_api_token, test_journo, test_source): - with journalist_app.app_context(): uuid = test_source["source"].uuid protected_routes = [ @@ -925,7 +923,6 @@ def test_empty_json_400(journalist_app, journalist_api_token, test_journo, test_ ] with journalist_app.test_client() as app: for protected_route in protected_routes: - response = app.post( protected_route, data="", headers=get_api_headers(journalist_api_token) ) @@ -935,7 +932,6 @@ def test_empty_json_400(journalist_app, journalist_api_token, test_journo, test_ def test_empty_json_20X(journalist_app, journalist_api_token, test_journo, test_source): - with journalist_app.app_context(): uuid = test_source["source"].uuid protected_routes = [ @@ -944,7 +940,6 @@ def test_empty_json_20X(journalist_app, journalist_api_token, test_journo, test_ ] with journalist_app.test_client() as app: for protected_route in protected_routes: - response = app.post( protected_route, data="", headers=get_api_headers(journalist_api_token) ) @@ -1246,3 +1241,70 @@ def test_seen_bad_requests(journalist_app, journalist_api_token): response = app.post(seen_url, data=json.dumps(data), headers=headers) assert response.status_code == 404 assert response.json["message"] == "reply not found: not-a-reply" + + +def test_download_submission_range(journalist_app, test_files, journalist_api_token): + with journalist_app.test_client() as app: + submission_uuid = test_files["submissions"][0].uuid + uuid = test_files["source"].uuid + + # Download the full file + full_response = app.get( + url_for( + "api.download_submission", + source_uuid=uuid, + submission_uuid=submission_uuid, + ), + headers=get_api_headers(journalist_api_token), + ) + assert full_response.status_code == 200 + assert full_response.mimetype == "application/pgp-encrypted" + + # Verify the etag header is actually the sha256 hash + hasher = hashlib.sha256() + hasher.update(full_response.data) + digest = binascii.hexlify(hasher.digest()).decode("utf-8") + digest_str = "sha256:" + digest + assert full_response.headers.get("ETag") == digest_str + + # Verify the Content-Length header matches the length of the content + assert full_response.headers.get("Content-Length") == str(len(full_response.data)) + + # Verify that range requests are accepted + assert full_response.headers.get("Accept-Ranges") == "bytes" + + # Download the first 10 bytes of data + headers = get_api_headers(journalist_api_token) + headers["Range"] = "bytes=0-9" + partial_response = app.get( + url_for( + "api.download_submission", + source_uuid=uuid, + submission_uuid=submission_uuid, + ), + headers=headers, + ) + assert partial_response.status_code == 206 # HTTP/1.1 206 Partial Content + assert partial_response.mimetype == "application/pgp-encrypted" + assert partial_response.headers.get("Content-Length") == "10" + assert len(partial_response.data) == 10 + assert full_response.data[0:10] == partial_response.data + + # Download the second half of the data + range_start = int(len(full_response.data) / 2) + range_end = len(full_response.data) + headers = get_api_headers(journalist_api_token) + headers["Range"] = f"bytes={range_start}-{range_end}" + partial_response = app.get( + url_for( + "api.download_submission", + source_uuid=uuid, + submission_uuid=submission_uuid, + ), + headers=headers, + ) + assert partial_response.status_code == 206 # HTTP/1.1 206 Partial Content + assert partial_response.mimetype == "application/pgp-encrypted" + assert partial_response.headers.get("Content-Length") == str(range_end - range_start) + assert len(partial_response.data) == range_end - range_start + assert full_response.data[range_start:] == partial_response.data
Support range requests (RFC 7233) on journalist interface ## Description The journalist interface should support range requests so user agents can continue downloads that failed part way through. We have the most control over this on the journalist workstation, so we would see the most benefit there. ### Current behavior ```http HTTP/1.0 200 OK Cache-Control: public, max-age=43200 Content-Disposition: attachment; filename=1-barren_unfamiliarity-msg.gpg Content-Length: 604 Content-Type: application/pgp-encrypted Date: Fri, 26 Oct 2018 08:44:49 GMT Etag: "sha256:25aef0be2cb6900a88a2590b2ee3637117eb51a733a105ae692e212623450f7f" Expires: Fri, 26 Oct 2018 20:44:49 GMT Last-Modified: Fri, 26 Oct 2018 08:42:46 GMT Server: Werkzeug/0.14.1 Python/2.7.6 Set-Cookie: js=eyJleHBpcmVzIjp7IiBkIjoiRnJpLCAyNiBPY3QgMjAxOCAxMDo0NDo0OSBHTVQifX0.DrRlgQ.17vemUmgcvLR2QvisGT0TOiZfyU; HttpOnly; Path=/ Vary: Cookie ``` ### Proposed Behavior ```http HTTP/1.0 200 OK Cache-Control: public, max-age=43200 Content-Disposition: attachment; filename=1-barren_unfamiliarity-msg.gpg Content-Length: 604 Content-Type: application/pgp-encrypted Date: Fri, 26 Oct 2018 08:44:49 GMT Accept-Ranges: bytes Etag: "sha256:25aef0be2cb6900a88a2590b2ee3637117eb51a733a105ae692e212623450f7f" Last-Modified: Fri, 26 Oct 2018 08:42:46 GMT Server: Werkzeug/0.14.1 Python/2.7.6 Vary: Authorization ``` ## User Stories As a journalist downloading large documents on a flaky Tor connection, I want downloads to pickup where they left off.
note that we would also need to make some non-trivial changes to the [securedrop-proxy](https://github.com/freedomofpress/securedrop-proxy) to use this - right now for file downloads we wait for the entire encrypted file to download and then `qvm-move` it into the SVS
2024-05-09T23:27:11Z
[]
[]
jupyterhub/jupyterhub
48
jupyterhub__jupyterhub-48
[ "12" ]
cf64828d32507411da95ab666e43e191ead189fe
diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -133,9 +133,11 @@ class UserServerAPIHandler(BaseUserHandler): def post(self, name): user = self.find_user(name) if user.spawner: - raise web.HTTPError(400, "%s's server is already running" % name) - else: - yield self.spawn_single_user(user) + state = yield user.spawner.poll() + if state is None: + raise web.HTTPError(400, "%s's server is already running" % name) + + yield self.spawn_single_user(user) self.set_status(201) @gen.coroutine diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -25,11 +25,10 @@ from tornado import gen, web from IPython.utils.traitlets import ( - Unicode, Integer, Dict, TraitError, List, Bool, Bytes, Any, - DottedObjectName, Set, + Unicode, Integer, Dict, TraitError, List, Bool, Any, + Type, Set, Instance, ) from IPython.config import Application, catch_config_error -from IPython.utils.importstring import import_item here = os.path.dirname(__file__) @@ -37,7 +36,7 @@ from . import orm from ._data import DATA_FILES_PATH -from .utils import url_path_join +from .utils import url_path_join, random_hex, TimeoutError # classes for config from .auth import Authenticator, PAMAuthenticator @@ -57,10 +56,13 @@ } flags = { - 'debug': ({'Application' : {'log_level' : logging.DEBUG}}, + 'debug': ({'Application' : {'log_level': logging.DEBUG}}, "set log level to logging.DEBUG (maximize logging output)"), - 'generate-config': ({'JupyterHubApp': {'generate_config' : True}}, - "generate default config file") + 'generate-config': ({'JupyterHubApp': {'generate_config': True}}, + "generate default config file"), + 'no-db': ({'JupyterHubApp': {'db_url': 'sqlite:///:memory:'}}, + "disable persisting state database to disk" + ), } @@ -150,10 +152,13 @@ class JupyterHubApp(Application): """ ) proxy_auth_token = Unicode(config=True, - help="The Proxy Auth token" + help="""The Proxy Auth token. + + Loaded from the CONFIGPROXY_AUTH_TOKEN env variable by default. + """ ) def _proxy_auth_token_default(self): - return orm.new_token() + return os.environ.get('CONFIGPROXY_AUTH_TOKEN', orm.new_token()) proxy_api_ip = Unicode('localhost', config=True, help="The ip for the proxy API handlers" @@ -190,11 +195,16 @@ def _hub_prefix_changed(self, name, old, new): if newnew != new: self.hub_prefix = newnew - cookie_secret = Bytes(config=True) + cookie_secret = Unicode(config=True, + help="""The cookie secret to use to encrypt cookies. + + Loaded from the JPY_COOKIE_SECRET env variable by default. + """ + ) def _cookie_secret_default(self): - return b'secret!' + return os.environ.get('JPY_COOKIE_SECRET', random_hex(64)) - authenticator = DottedObjectName("jupyterhub.auth.PAMAuthenticator", config=True, + authenticator_class = Type("jupyterhub.auth.PAMAuthenticator", config=True, help="""Class for authenticating users. This should be a class with the following form: @@ -208,16 +218,38 @@ def _cookie_secret_default(self): and `data` is the POST form data from the login page. """ ) + authenticator = Instance(Authenticator) + def _authenticator_default(self): + return self.authenticator_class(config=self.config) + # class for spawning single-user servers - spawner_class = DottedObjectName("jupyterhub.spawner.LocalProcessSpawner", config=True, + spawner_class = Type("jupyterhub.spawner.LocalProcessSpawner", config=True, help="""The class to use for spawning single-user servers. Should be a subclass of Spawner. """ ) - db_url = Unicode('sqlite:///:memory:', config=True) - debug_db = Bool(False) + db_url = Unicode('sqlite:///jupyterhub.sqlite', config=True, + help="url for the database. e.g. `sqlite:///jupyterhub.sqlite`" + ) + def _db_url_changed(self, name, old, new): + if '://' not in new: + # assume sqlite, if given as a plain filename + self.db_url = 'sqlite:///%s' % new + + db_kwargs = Dict(config=True, + help="""Include any kwargs to pass to the database connection. + See sqlalchemy.create_engine for details. + """ + ) + + reset_db = Bool(False, config=True, + help="Purge and reset the database." + ) + debug_db = Bool(False, config=True, + help="log all database transactions. This has A LOT of output" + ) db = Any() admin_users = Set({getpass.getuser()}, config=True, @@ -288,7 +320,6 @@ def init_handlers(self): self.handlers = self.add_url_prefix(self.hub_prefix, h) - # some extra handlers, outside hub_prefix self.handlers.extend([ (r"%s" % self.hub_prefix.rstrip('/'), web.RedirectHandler, @@ -302,48 +333,139 @@ def init_handlers(self): ]) def init_db(self): - # TODO: load state from db for resume - # TODO: if not resuming, clear existing db contents - self.db = orm.new_session(self.db_url, echo=self.debug_db) - for name in self.admin_users: - user = orm.User(name=name, admin=True) - self.db.add(user) - self.db.commit() + """Create the database connection""" + self.db = orm.new_session(self.db_url, reset=self.reset_db, echo=self.debug_db, + **self.db_kwargs + ) def init_hub(self): """Load the Hub config into the database""" - self.hub = orm.Hub( - server=orm.Server( - ip=self.hub_ip, - port=self.hub_port, - base_url=self.hub_prefix, - cookie_secret=self.cookie_secret, - cookie_name='jupyter-hub-token', + self.hub = self.db.query(orm.Hub).first() + if self.hub is None: + self.hub = orm.Hub( + server=orm.Server( + ip=self.hub_ip, + port=self.hub_port, + base_url=self.hub_prefix, + cookie_secret=self.cookie_secret, + cookie_name='jupyter-hub-token', + ) ) - ) - self.db.add(self.hub) + self.db.add(self.hub) + else: + server = self.hub.server + server.ip = self.hub_ip + server.port = self.hub_port + server.base_url = self.hub_prefix + self.db.commit() + def init_users(self): + """Load users into and from the database""" + db = self.db + + for name in self.admin_users: + # ensure anyone specified as admin in config is admin in db + user = orm.User.find(db, name) + if user is None: + user = orm.User(name=name, admin=True) + db.add(user) + else: + user.admin = True + + # the admin_users config variable will never be used after this point. + # only the database values will be referenced. + + whitelist = self.authenticator.whitelist + + if not whitelist: + self.log.info("Not using whitelist. Any authenticated user will be allowed.") + + # add whitelisted users to the db + for name in whitelist: + user = orm.User.find(db, name) + if user is None: + user = orm.User(name=name) + db.add(user) + + if whitelist: + # fill the whitelist with any users loaded from the db, + # so we are consistent in both directions. + # This lets whitelist be used to set up initial list, + # but changes to the whitelist can occur in the database, + # and persist across sessions. + for user in db.query(orm.User): + whitelist.add(user.name) + + # The whitelist set and the users in the db are now the same. + # From this point on, any user changes should be done simultaneously + # to the whitelist set and user db, unless the whitelist is empty (all users allowed). + + db.commit() + + # load any still-active spawners from JSON + run_sync = IOLoop().run_sync + + user_summaries = [''] + def _user_summary(user): + parts = ['{0: >8}'.format(user.name)] + if user.admin: + parts.append('admin') + if user.server: + parts.append('running at %s' % user.server) + return ' '.join(parts) + + for user in db.query(orm.User): + if not user.state: + user_summaries.append(_user_summary(user)) + continue + self.log.debug("Loading state for %s from db", user.name) + spawner = self.spawner_class.fromJSON(user.state, user=user, hub=self.hub, config=self.config) + status = run_sync(spawner.poll) + if status is None: + self.log.info("User %s still running", user.name) + user.spawner = spawner + else: + self.log.warn("Failed to load state for %s, assuming server is not running.", user.name) + # not running, state is invalid + user.state = {} + user.server = None + + user_summaries.append(_user_summary(user)) + + self.log.debug("Loaded users: %s", '\n'.join(user_summaries)) + db.commit() + def init_proxy(self): """Load the Proxy config into the database""" - self.proxy = orm.Proxy( - public_server=orm.Server( - ip=self.ip, - port=self.port, - ), - api_server=orm.Server( - ip=self.proxy_api_ip, - port=self.proxy_api_port, - base_url='/api/routes/' - ), - auth_token = orm.new_token(), - ) - self.db.add(self.proxy) + self.proxy = self.db.query(orm.Proxy).first() + if self.proxy is None: + self.proxy = orm.Proxy( + public_server=orm.Server(), + api_server=orm.Server(), + auth_token = self.proxy_auth_token, + ) + self.db.add(self.proxy) + self.db.commit() + self.proxy.log = self.log + self.proxy.public_server.ip = self.ip + self.proxy.public_server.port = self.port + self.proxy.api_server.ip = self.proxy_api_ip + self.proxy.api_server.port = self.proxy_api_port + self.proxy.api_server.base_url = '/api/routes/' + if self.proxy.auth_token is None: + self.proxy.auth_token = self.proxy_auth_token self.db.commit() @gen.coroutine def start_proxy(self): """Actually start the configurable-http-proxy""" + if self.proxy.public_server.is_up() and \ + self.proxy.api_server.is_up(): + self.log.warn("Proxy already running at: %s", self.proxy.public_server.url) + self.proxy_process = None + return + env = os.environ.copy() env['CONFIGPROXY_AUTH_TOKEN'] = self.proxy.auth_token cmd = [self.proxy_cmd, @@ -385,7 +507,9 @@ def _check(): def check_proxy(self): if self.proxy_process.poll() is None: return - self.log.error("Proxy stopped with exit code %i", self.proxy_process.poll()) + self.log.error("Proxy stopped with exit code %r", + 'unknown' if self.proxy_process is None else self.proxy_process.poll() + ) yield self.start_proxy() self.log.info("Setting up routes on new proxy") yield self.proxy.add_all_users() @@ -407,10 +531,10 @@ def init_tornado_settings(self): proxy=self.proxy, hub=self.hub, admin_users=self.admin_users, - authenticator=import_item(self.authenticator)(config=self.config), - spawner_class=import_item(self.spawner_class), + authenticator=self.authenticator, + spawner_class=self.spawner_class, base_url=base_url, - cookie_secret=self.cookie_secret, + cookie_secret=self.hub.server.cookie_secret, login_url=url_path_join(self.hub.server.base_url, 'login'), static_path=os.path.join(self.data_files_path, 'static'), static_url_prefix=url_path_join(self.hub.server.base_url, 'static/'), @@ -438,12 +562,13 @@ def initialize(self, *args, **kwargs): if self.generate_config: return self.load_config_file(self.config_file) - self.write_pid_file() self.init_logging() + self.write_pid_file() self.init_ports() self.init_db() self.init_hub() self.init_proxy() + self.init_users() self.init_handlers() self.init_tornado_settings() self.init_tornado_application() @@ -456,15 +581,24 @@ def cleanup(self): futures = [] for user in self.db.query(orm.User): if user.spawner is not None: - futures.append(user.spawner.stop()) + futures.append(user.stop()) # clean up proxy while SUS are shutting down - self.log.info("Cleaning up proxy[%i]..." % self.proxy_process.pid) - self.proxy_process.terminate() + if self.proxy_process and self.proxy_process.poll() is None: + self.log.info("Cleaning up proxy[%i]...", self.proxy_process.pid) + try: + self.proxy_process.terminate() + except Exception as e: + self.log.error("Failed to terminate proxy process: %s", e) # wait for the requests to stop finish: for f in futures: - yield f + try: + yield f + except Exception as e: + self.log.error("Failed to stop user: %s", e) + + self.db.commit() if self.pid_file and os.path.exists(self.pid_file): self.log.info("Cleaning up PID file %s", self.pid_file) @@ -474,6 +608,7 @@ def cleanup(self): self.log.info("...done") def write_config_file(self): + """Write our default config to a .py config file""" if os.path.exists(self.config_file) and not self.answer_yes: answer = '' def ask(): @@ -509,9 +644,14 @@ def start(self): return loop = IOLoop.current() + loop.add_callback(self.proxy.add_all_users) - pc = PeriodicCallback(self.check_proxy, self.proxy_check_interval) - pc.start() + if self.proxy_process: + # only check / restart the proxy if we started it in the first place. + # this means a restarted Hub cannot restart a Proxy that its + # predecessor started. + pc = PeriodicCallback(self.check_proxy, self.proxy_check_interval) + pc.start() # start the webserver http_server = tornado.httpserver.HTTPServer(self.tornado_application) diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -73,7 +73,7 @@ def get_current_user_token(self): if not match: return None token = match.group(1) - orm_token = self.db.query(orm.APIToken).filter(orm.APIToken.token == token).first() + orm_token = orm.APIToken.find(self.db, token) if orm_token is None: return None else: @@ -83,8 +83,7 @@ def get_current_user_cookie(self): """get_current_user from a cookie token""" token = self.get_cookie(self.hub.server.cookie_name, None) if token: - cookie_token = self.db.query(orm.CookieToken).filter( - orm.CookieToken.token==token).first() + cookie_token = orm.CookieToken.find(self.db, token) if cookie_token: return cookie_token.user else: @@ -103,7 +102,7 @@ def find_user(self, name): return None if no such user """ - return self.db.query(orm.User).filter(orm.User.name==name).first() + return orm.User.find(self.db, name) def user_from_username(self, username): """Get ORM User for username""" diff --git a/jupyterhub/handlers/login.py b/jupyterhub/handlers/login.py --- a/jupyterhub/handlers/login.py +++ b/jupyterhub/handlers/login.py @@ -51,7 +51,12 @@ def post(self): authorized = yield self.authenticate(data) if authorized: user = self.user_from_username(username) - yield self.spawn_single_user(user) + already_running = False + if user.spawner: + status = yield user.spawner.poll() + already_running = (status == None) + if not already_running: + yield self.spawn_single_user(user) self.set_login_cookie(user) next_url = self.get_argument('next', default='') or self.hub.server.base_url self.redirect(next_url) diff --git a/jupyterhub/orm.py b/jupyterhub/orm.py --- a/jupyterhub/orm.py +++ b/jupyterhub/orm.py @@ -9,6 +9,7 @@ import uuid from tornado import gen +from tornado.log import app_log from tornado.httpclient import HTTPRequest, AsyncHTTPClient, HTTPError from sqlalchemy.types import TypeDecorator, VARCHAR @@ -71,7 +72,7 @@ class Server(Base): ip = Column(Unicode, default=u'localhost') port = Column(Integer, default=random_port) base_url = Column(Unicode, default=u'/') - cookie_secret = Column(Binary, default=b'secret') + cookie_secret = Column(Unicode, default=u'') cookie_name = Column(Unicode, default=u'cookie') def __repr__(self): @@ -103,12 +104,11 @@ def is_up(self): socket.create_connection((self.ip or 'localhost', self.port)) except socket.error as e: if e.errno == errno.ECONNREFUSED: - return True + return False else: raise else: return True - class Proxy(Base): @@ -124,6 +124,7 @@ class Proxy(Base): public_server = relationship(Server, primaryjoin=_public_server_id == Server.id) _api_server_id = Column(Integer, ForeignKey('servers.id')) api_server = relationship(Server, primaryjoin=_api_server_id == Server.id) + log = app_log def __repr__(self): if self.public_server: @@ -136,6 +137,9 @@ def __repr__(self): @gen.coroutine def add_user(self, user, client=None): """Add a user's server to the proxy table.""" + self.log.info("Adding user %s to proxy %s => %s", + user.name, user.server.base_url, user.server.host, + ) client = client or AsyncHTTPClient() req = HTTPRequest(url_path_join( @@ -155,6 +159,7 @@ def add_user(self, user, client=None): @gen.coroutine def delete_user(self, user, client=None): """Remove a user's server to the proxy table.""" + self.log.info("Removing user %s from proxy", user.name) client = client or AsyncHTTPClient() req = HTTPRequest(url_path_join( self.api_server.url, @@ -262,6 +267,14 @@ def new_cookie_token(self): """Return a new cookie token""" return self._new_token(CookieToken) + @classmethod + def find(cls, db, name): + """Find a user by name. + + Returns None if not found. + """ + return db.query(cls).filter(cls.name==name).first() + @gen.coroutine def spawn(self, spawner_class, base_url='/', hub=None, config=None): db = inspect(self).session @@ -321,6 +334,14 @@ def __repr__(self): u=self.user.name, ) + @classmethod + def find(cls, db, token): + """Find a token object by value. + + Returns None if not found. + """ + return db.query(cls).filter(cls.token==token).first() + class APIToken(Token, Base): """An API token""" @@ -332,13 +353,15 @@ class CookieToken(Token, Base): __tablename__ = 'cookie_tokens' -def new_session(url="sqlite:///:memory:", **kwargs): +def new_session(url="sqlite:///:memory:", reset=False, **kwargs): """Create a new session at url""" kwargs.setdefault('connect_args', {'check_same_thread': False}) kwargs.setdefault('poolclass', StaticPool) engine = create_engine(url, **kwargs) Session = sessionmaker(bind=engine) session = Session() + if reset: + Base.metadata.drop_all(engine) Base.metadata.create_all(engine) return session diff --git a/jupyterhub/spawner.py b/jupyterhub/spawner.py --- a/jupyterhub/spawner.py +++ b/jupyterhub/spawner.py @@ -60,7 +60,7 @@ def _env_default(self): env = os.environ.copy() for key in ['HOME', 'USER', 'USERNAME', 'LOGNAME', 'LNAME']: env.pop(key, None) - self._env_key(env, 'COOKIE_SECRET', self.user.server.cookie_secret.decode('ascii')) + self._env_key(env, 'COOKIE_SECRET', self.user.server.cookie_secret) self._env_key(env, 'API_TOKEN', self.api_token) return env @@ -103,7 +103,7 @@ def get_state(self): state: dict a JSONable dict of state """ - return {} + return dict(api_token=self.api_token) def get_args(self): """Return the arguments to be passed after self.cmd""" @@ -211,10 +211,13 @@ def _set_user_changed(self, name, old, new): raise ValueError("This should be impossible") def load_state(self, state): + super(LocalProcessSpawner, self).load_state(state) self.pid = state['pid'] def get_state(self): - return dict(pid=self.pid) + state = super(LocalProcessSpawner, self).get_state() + state['pid'] = self.pid + return state def sudo_cmd(self, user): return ['sudo', '-u', user.name] + self.sudo_args diff --git a/jupyterhub/utils.py b/jupyterhub/utils.py --- a/jupyterhub/utils.py +++ b/jupyterhub/utils.py @@ -3,7 +3,9 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. +import binascii import errno +import os import socket from tornado import web, gen, ioloop from tornado.log import app_log @@ -11,7 +13,8 @@ from IPython.html.utils import url_path_join try: - TimeoutError + # make TimeoutError importable on Python >= 3.3 + TimeoutError = TimeoutError except NameError: # python < 3.3 class TimeoutError(Exception): @@ -25,6 +28,12 @@ def random_port(): sock.close() return port +def random_hex(nbytes): + """Return nbytes random bytes as a unicode hex string + + It will have length nbytes * 2 + """ + return binascii.hexlify(os.urandom(nbytes)).decode('ascii') @gen.coroutine def wait_for_server(ip, port, timeout=10):
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -56,11 +56,14 @@ class MockHubApp(JupyterHubApp): def _ip_default(self): return 'localhost' - def _authenticator_default(self): - return '%s.%s' % (__name__, 'MockPAMAuthenticator') + def _db_url_default(self): + return 'sqlite:///:memory:' + + def _authenticator_class_default(self): + return MockPAMAuthenticator def _spawner_class_default(self): - return '%s.%s' % (__name__, 'MockSpawner') + return MockSpawner def _admin_users_default(self): return {'admin'} diff --git a/jupyterhub/tests/test_orm.py b/jupyterhub/tests/test_orm.py --- a/jupyterhub/tests/test_orm.py +++ b/jupyterhub/tests/test_orm.py @@ -21,7 +21,7 @@ def test_server(db): assert server.proto == 'http' assert isinstance(server.port, int) assert isinstance(server.cookie_name, unicode) - assert isinstance(server.cookie_secret, bytes) + assert isinstance(server.cookie_secret, unicode) assert server.url == 'http://localhost:%i/' % server.port @@ -71,6 +71,11 @@ def test_user(db): assert user.server.ip == u'localhost' assert user.state == {'pid': 4234} + found = orm.User.find(db, u'kaylee') + assert found.name == user.name + found = orm.User.find(db, u'badger') + assert found is None + def test_tokens(db): user = orm.User(name=u'inara') @@ -87,3 +92,7 @@ def test_tokens(db): assert len(user.api_tokens) == 1 assert len(user.cookie_tokens) == 3 + found = orm.CookieToken.find(db, token=token.token) + assert found.token == token.token + found = orm.APIToken.find(db, token.token) + assert found is None
support resuming Hub from db state The reason for the ORM is to enable resuming the Hub from state on disk, which is not yet implemented.
2014-09-22T00:36:28Z
[]
[]
jupyterhub/jupyterhub
86
jupyterhub__jupyterhub-86
[ "84" ]
db5cf9cf99f68f133b0024435409b74221bddd14
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -262,6 +262,7 @@ def _db_url_changed(self, name, old, new): help="log all database transactions. This has A LOT of output" ) db = Any() + session_factory = Any() admin_users = Set(config=True, help="""set of usernames of admin users @@ -364,9 +365,13 @@ def init_db(self): """Create the database connection""" self.log.debug("Connecting to db: %s", self.db_url) try: - self.db = orm.new_session(self.db_url, reset=self.reset_db, echo=self.debug_db, + self.session_factory = orm.new_session_factory( + self.db_url, + reset=self.reset_db, + echo=self.debug_db, **self.db_kwargs ) + self.db = self.session_factory() except OperationalError as e: self.log.error("Failed to connect to db: %s", self.db_url) self.log.debug("Database error was:", exc_info=True) diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -58,6 +58,11 @@ def proxy(self): def authenticator(self): return self.settings.get('authenticator', None) + def finish(self, *args, **kwargs): + """Roll back any uncommitted transactions from the handler.""" + self.db.rollback() + super(BaseHandler, self).finish(*args, **kwargs) + #--------------------------------------------------------------- # Login and cookie-related #--------------------------------------------------------------- diff --git a/jupyterhub/orm.py b/jupyterhub/orm.py --- a/jupyterhub/orm.py +++ b/jupyterhub/orm.py @@ -381,17 +381,20 @@ class CookieToken(Token, Base): __tablename__ = 'cookie_tokens' -def new_session(url="sqlite:///:memory:", reset=False, **kwargs): +def new_session_factory(url="sqlite:///:memory:", reset=False, **kwargs): """Create a new session at url""" if url.startswith('sqlite'): kwargs.setdefault('connect_args', {'check_same_thread': False}) - kwargs.setdefault('poolclass', StaticPool) + + if url.endswith(':memory:'): + # If we're using an in-memory database, ensure that only one connection + # is ever created. + kwargs.setdefault('poolclass', StaticPool) + engine = create_engine(url, **kwargs) - Session = sessionmaker(bind=engine) - session = Session() if reset: Base.metadata.drop_all(engine) Base.metadata.create_all(engine) - return session - + session_factory = sessionmaker(bind=engine) + return session_factory
diff --git a/jupyterhub/tests/conftest.py b/jupyterhub/tests/conftest.py --- a/jupyterhub/tests/conftest.py +++ b/jupyterhub/tests/conftest.py @@ -22,7 +22,7 @@ def db(): """Get a db session""" global _db if _db is None: - _db = orm.new_session('sqlite:///:memory:', echo=True) + _db = orm.new_session_factory('sqlite:///:memory:', echo=True)() user = orm.User( name=getuser_unicode(), server=orm.Server(), diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -1,6 +1,8 @@ """mock utilities for testing""" +import os import sys +from tempfile import NamedTemporaryFile import threading try: @@ -56,13 +58,12 @@ def authenticate(self, *args, **kwargs): class MockHubApp(JupyterHubApp): """HubApp with various mock bits""" - + + db_file = None + def _ip_default(self): return 'localhost' - def _db_url_default(self): - return 'sqlite:///:memory:' - def _authenticator_class_default(self): return MockPAMAuthenticator @@ -71,8 +72,10 @@ def _spawner_class_default(self): def _admin_users_default(self): return {'admin'} - + def start(self, argv=None): + self.db_file = NamedTemporaryFile() + self.db_url = 'sqlite:///' + self.db_file.name evt = threading.Event() def _start(): self.io_loop = IOLoop.current() @@ -91,6 +94,6 @@ def _start(): evt.wait(timeout=5) def stop(self): + self.db_file.close() self.io_loop.add_callback(self.io_loop.stop) self._thread.join() - diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -7,6 +7,30 @@ from ..utils import url_path_join as ujoin from .. import orm + +def check_db_locks(func): + """ + Decorator for test functions that verifies no locks are held on the + application's database upon exit by creating and dropping a dummy table. + + Relies on an instance of JupyterhubApp being the first argument to the + decorated function. + """ + + def new_func(*args, **kwargs): + retval = func(*args, **kwargs) + + app = args[0] + temp_session = app.session_factory() + temp_session.execute('CREATE TABLE dummy (foo INT)') + temp_session.execute('DROP TABLE dummy') + temp_session.close() + + return retval + + return new_func + + def find_user(db, name): return db.query(orm.User).filter(orm.User.name==name).first() @@ -28,6 +52,7 @@ def auth_header(db, name): token = user.api_tokens[0] return {'Authorization': 'token %s' % token.token} +@check_db_locks def api_request(app, *api_path, **kwargs): """Make an API request""" base_url = app.hub.server.url @@ -70,7 +95,6 @@ def test_auth_api(app): headers={'Authorization': 'token: %s' % cookie_token.token}, ) assert r.status_code == 403 - def test_get_users(app): db = app.db @@ -179,4 +203,3 @@ def test_spawn(app, io_loop): assert 'pid' not in user.state status = io_loop.run_sync(user.spawner.poll) assert status == 0 - \ No newline at end of file
An active Jupyterhub session locks Postgres tables from writes. Noticed while testing permissions issues on #83. It looks like maintaining a single open session for the entire lifetime of the App results in transactions never being closed, which causes Postgres to write-lock any tables being used by Jupyterhub. From reading the SQLAlchemy docs, it looks like the expected pattern for webapps is to create a `Session` class at global scope, but create and tear down instances of the session on each request.
Looks like the current setup also completely locks the sqlite database. When running with an active jupyterhub process, I get: ``` (jupyterhub)[~/jupyterhub]@(master:db5cf9cf99)$ sqlite jupyterhub.sqlite SQLite version 2.8.17 Enter ".help" for instructions sqlite> .tables Error: database is locked sqlite> ``` Working on a fix for this now. Thanks for noting these and updating rapidly. You said you're working a fix right as I was typing this. Relevant SO post from one of the SQLAlchemy maintainers: http://stackoverflow.com/questions/12223335/sqlalchemy-creating-vs-reusing-a-session Makes sense, looking forward to the patch. More documentation excerpts: http://docs.sqlalchemy.org/en/rel_0_9/dialects/sqlite.html#sqlite-concurrency Database Locking Behavior / Concurrency SQLite is not designed for a high level of write concurrency. The database itself, being a file, is locked completely during write operations within transactions, meaning exactly one “connection” (in reality a file handle) has exclusive access to the database during this period - all other “connections” will be blocked during this time. The Python DBAPI specification also calls for a connection model that is always in a transaction; there is no connection.begin() method, only connection.commit() and connection.rollback(), upon which a new transaction is to be begun immediately. This may seem to imply that the SQLite driver would in theory allow only a single filehandle on a particular database file at any time; however, there are several factors both within SQlite itself as well as within the pysqlite driver which loosen this restriction significantly. However, no matter what locking modes are used, SQLite will still always lock the database file once a transaction is started and DML (e.g. INSERT, UPDATE, DELETE) has at least been emitted, and this will block other transactions at least at the point that they also attempt to emit DML. By default, the length of time on this block is very short before it times out with an error. This behavior becomes more critical when used in conjunction with the SQLAlchemy ORM. SQLAlchemy’s Session object by default runs within a transaction, and with its autoflush model, may emit DML preceding any SELECT statement. This may lead to a SQLite database that locks more quickly than is expected. The locking mode of SQLite and the pysqlite driver can be manipulated to some degree, however it should be noted that achieving a high degree of write-concurrency with SQLite is a losing battle. For more information on SQLite’s lack of write concurrency by design, please see Situations Where Another RDBMS May Work Better - High Concurrency near the bottom of the page. The following subsections introduce areas that are impacted by SQLite’s file-based architecture and additionally will usually require workarounds to work when using the pysqlite driver. We should make sure to note that the maximum level of concurrency expected for JupyterHub is one, especially with SQLite. I know you are working on shared-state Hubs with Postgres, and that _may_ be feasible. I don't think we have any need to make concurrent JupyterHub sessions work with SQLite. Taking Min's comment in another direction, @ssanderson if you take us down the path of doing Postgres well (including a Docker container for the Postgres setup), I'd be _super_ pleased. @minrk working on tests for this change; is there a reason there's a 5 second wait on the mock app created in `tests/mocking.py`? It's super annoying to wait 5 seconds for each run... What 5 second wait? There's a wait on an event with a _timeout_ of 5 seconds, but that should only be hit if something's not working. It only takes me 7 seconds to run the whole test suite. Ah. The failure I was looking at is currently happening inside the app initialization, which causes the full duration of the wait to happen. It should probably raise if the timeout is hit, instead of just moving right along after making you wait. Sorry about that. WIP fix for this is at https://github.com/jupyter/jupyterhub/pull/85. I'm not super excited about the first cut. Given the amount of manual management of the Session that this requires of the Hub, I'm inclined to think we'd be better off just using `Engine` and `Connection` directly. The one thing I'm not sure of w/r/t that approach is how it interacts with Python-level objects that aren't persisted in the database but are stored on the models. This is most noticeably true of `User.spawner`. More investigation this morning: the offending locks that are causing this issue are being created in `CookieAPIHandler.get`. When we do ``` orm_token = self.db.query(orm.CookieToken).filter(orm.CookieToken.token == token).first() ``` that actually creates an exclusive lock on the orm_token (and by extension, the user row to which it's related) that's never released because we don't commit or rollback the db session. When running with SQLite, it locks the entire database from any externel connections. I **think** this is happening because, even though the entire query has been iterated by the call to `first()`, the object has join attributes that haven't been loaded, so SQLALchemy doesn't consider the transaction completed. A simple fix to this is to put a call to one of `self.db.close()`, `self.db.rollback()` or `self.db.commit()` in `BaseHandler.finish`. This is more dangerous than it sounds though, because the fact that the Hub's maintenance loop shares a Session with the tornado app's handlers means that the close/rollback could splice into the transaction of a running `gen.coroutine`. (This might happen for example at a yield point like https://github.com/jupyter/jupyterhub/blob/master/jupyterhub/orm.py#L321.)
2014-10-29T20:02:41Z
[]
[]
jupyterhub/jupyterhub
89
jupyterhub__jupyterhub-89
[ "88" ]
83569221b969c3441322d12db8b0f346eb183254
diff --git a/jupyterhub/__init__.py b/jupyterhub/__init__.py --- a/jupyterhub/__init__.py +++ b/jupyterhub/__init__.py @@ -1 +1,2 @@ from .version import * + diff --git a/jupyterhub/apihandlers/base.py b/jupyterhub/apihandlers/base.py --- a/jupyterhub/apihandlers/base.py +++ b/jupyterhub/apihandlers/base.py @@ -4,11 +4,7 @@ import json -try: - # py3 - from http.client import responses -except ImportError: - from httplib import responses +from http.client import responses from tornado import web @@ -19,7 +15,7 @@ def get_json_body(self): """Return the body of the request as JSON data.""" if not self.request.body: return None - body = self.request.body.strip().decode(u'utf-8') + body = self.request.body.strip().decode('utf-8') try: model = json.loads(body) except Exception: diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -11,11 +11,6 @@ from ..utils import admin_only, authenticated_403 from .base import APIHandler -try: - basestring -except NameError: - basestring = str # py3 - class BaseUserHandler(APIHandler): def user_model(self, user): @@ -26,7 +21,7 @@ def user_model(self, user): } _model_types = { - 'name': basestring, + 'name': str, 'admin': bool, } diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -5,20 +5,18 @@ # Distributed under the terms of the Modified BSD License. import binascii -import io import logging import os import socket +import sys from datetime import datetime +from distutils.version import LooseVersion as V +from getpass import getuser from subprocess import Popen -try: - raw_input -except NameError: - # py3 - raw_input = input +if sys.version_info[:2] < (3,3): + raise ValueError("Python < 3.3 not supported: %s" % sys.version) -from six import text_type from jinja2 import Environment, FileSystemLoader from sqlalchemy.exc import OperationalError @@ -30,6 +28,10 @@ from tornado.log import LogFormatter, app_log, access_log, gen_log from tornado import gen, web +import IPython +if V(IPython.__version__) < V('3.0'): + raise ImportError("JupyterHub Requires IPython >= 3.0, found %s" % IPython.__version__) + from IPython.utils.traitlets import ( Unicode, Integer, Dict, TraitError, List, Bool, Any, Type, Set, Instance, Bytes, @@ -43,8 +45,8 @@ from . import orm from ._data import DATA_FILES_PATH from .utils import ( - url_path_join, TimeoutError, - ISO8601_ms, ISO8601_s, getuser_unicode, + url_path_join, + ISO8601_ms, ISO8601_s, ) # classes for config from .auth import Authenticator, PAMAuthenticator @@ -299,18 +301,11 @@ def _log_level_default(self): def _log_datefmt_default(self): """Exclude date from default date format""" return "%H:%M:%S" - + def _log_format_default(self): """override default log format to include time""" - return u"%(color)s[%(levelname)1.1s %(asctime)s.%(msecs).03d %(name)s]%(end_color)s %(message)s" - - def _log_format_changed(self, name, old, new): - """Change the log formatter when log_format is set.""" - # FIXME: IPython < 3 compat - _log_handler = self.log.handlers[0] - _log_formatter = self._log_formatter_cls(fmt=new, datefmt=self.log_datefmt) - _log_handler.setFormatter(_log_formatter) - + return "%(color)s[%(levelname)1.1s %(asctime)s.%(msecs).03d %(name)s]%(end_color)s %(message)s" + def init_logging(self): # This prevents double log messages because tornado use a root logger that # self.log is a child of. The logging module dipatches log messages to a log @@ -325,8 +320,6 @@ def init_logging(self): logger.propagate = True logger.parent = self.log logger.setLevel(self.log.level) - # FIXME: IPython < 3 compat - self._log_format_changed('', '', self.log_format) def init_ports(self): if self.hub_port == self.port: @@ -370,7 +363,7 @@ def _check_db_path(self, path): """More informative log messages for failed filesystem access""" path = os.path.abspath(path) parent, fname = os.path.split(path) - user = getuser_unicode() + user = getuser() if not os.path.isdir(parent): self.log.error("Directory %s does not exist", parent) if os.path.exists(parent) and not os.access(parent, os.W_OK): @@ -399,7 +392,7 @@ def init_secrets(self): self.log.error("Bad permissions on %s", secret_file) else: self.log.info("Loading %s from %s", trait_name, secret_file) - with io.open(secret_file) as f: + with open(secret_file) as f: b64_secret = f.read() try: secret = binascii.a2b_base64(b64_secret) @@ -413,8 +406,8 @@ def init_secrets(self): if secret_file and secret_from == 'new': # if we generated a new secret, store it in the secret_file self.log.info("Writing %s to %s", trait_name, secret_file) - b64_secret = text_type(binascii.b2a_base64(secret)) - with io.open(secret_file, 'w', encoding='utf8') as f: + b64_secret = binascii.b2a_base64(secret).decode('ascii') + with open(secret_file, 'w') as f: f.write(b64_secret) try: os.chmod(secret_file, 0o600) @@ -450,7 +443,7 @@ def init_hub(self): ip=self.hub_ip, port=self.hub_port, base_url=self.hub_prefix, - cookie_name=u'jupyter-hub-token', + cookie_name='jupyter-hub-token', ) ) self.db.add(self.hub) @@ -470,7 +463,7 @@ def init_users(self): # add current user as admin if there aren't any others admins = db.query(orm.User).filter(orm.User.admin==True) if admins.first() is None: - self.admin_users.add(getuser_unicode()) + self.admin_users.add(getuser()) for name in self.admin_users: # ensure anyone specified as admin in config is admin in db @@ -576,7 +569,7 @@ def init_proxy(self): self.proxy.public_server.port = self.port self.proxy.api_server.ip = self.proxy_api_ip self.proxy.api_server.port = self.proxy_api_port - self.proxy.api_server.base_url = u'/api/routes/' + self.proxy.api_server.base_url = '/api/routes/' self.db.commit() @gen.coroutine @@ -694,8 +687,8 @@ def write_pid_file(self): pid = os.getpid() if self.pid_file: self.log.debug("Writing PID %i to %s", pid, self.pid_file) - with io.open(self.pid_file, 'w') as f: - f.write(u'%i' % pid) + with open(self.pid_file, 'w') as f: + f.write('%i' % pid) @catch_config_error def initialize(self, *args, **kwargs): @@ -756,7 +749,7 @@ def write_config_file(self): def ask(): prompt = "Overwrite %s with default config? [y/N]" % self.config_file try: - return raw_input(prompt).lower() or 'n' + return input(prompt).lower() or 'n' except KeyboardInterrupt: print('') # empty line return 'n' @@ -771,7 +764,7 @@ def ask(): if isinstance(config_text, bytes): config_text = config_text.decode('utf8') print("Writing default config to: %s" % self.config_file) - with io.open(self.config_file, encoding='utf8', mode='w') as f: + with open(self.config_file, mode='w') as f: f.write(config_text) @gen.coroutine diff --git a/jupyterhub/auth.py b/jupyterhub/auth.py --- a/jupyterhub/auth.py +++ b/jupyterhub/auth.py @@ -153,5 +153,5 @@ def authenticate(self, handler, data): busername = username.encode(self.encoding) bpassword = data['password'].encode(self.encoding) if simplepam.authenticate(busername, bpassword, service=self.service): - raise gen.Return(username) + return username \ No newline at end of file diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -5,11 +5,7 @@ import re from datetime import datetime -try: - # py3 - from http.client import responses -except ImportError: - from httplib import responses +from http.client import responses from jinja2 import TemplateNotFound @@ -156,7 +152,7 @@ def authenticate(self, data): auth = self.authenticator if auth is not None: result = yield auth.authenticate(self, data) - raise gen.Return(result) + return result else: self.log.error("No authentication function, login is impossible!") @@ -179,7 +175,7 @@ def spawn_single_user(self, user): ) yield self.proxy.add_user(user) user.spawner.add_poll_callback(self.user_stopped, user) - raise gen.Return(user) + return user @gen.coroutine def user_stopped(self, user): diff --git a/jupyterhub/orm.py b/jupyterhub/orm.py --- a/jupyterhub/orm.py +++ b/jupyterhub/orm.py @@ -63,11 +63,11 @@ class Server(Base): """ __tablename__ = 'servers' id = Column(Integer, primary_key=True) - proto = Column(Unicode, default=u'http') - ip = Column(Unicode, default=u'localhost') + proto = Column(Unicode, default='http') + ip = Column(Unicode, default='localhost') port = Column(Integer, default=random_port) - base_url = Column(Unicode, default=u'/') - cookie_name = Column(Unicode, default=u'cookie') + base_url = Column(Unicode, default='/') + cookie_name = Column(Unicode, default='cookie') def __repr__(self): return "<Server(%s:%s)>" % (self.ip, self.port) diff --git a/jupyterhub/singleuser.py b/jupyterhub/singleuser.py --- a/jupyterhub/singleuser.py +++ b/jupyterhub/singleuser.py @@ -9,7 +9,6 @@ import requests from tornado import ioloop -from tornado import web from IPython.utils.traitlets import Unicode @@ -21,8 +20,8 @@ from distutils.version import LooseVersion as V import IPython -if V(IPython.__version__) < V('2.2'): - raise ImportError("JupyterHub Requires IPython >= 2.2, found %s" % IPython.__version__) +if V(IPython.__version__) < V('3.0'): + raise ImportError("JupyterHub Requires IPython >= 3.0, found %s" % IPython.__version__) # Define two methods to attach to AuthenticatedHandler, # which authenticate via the central auth server. @@ -97,11 +96,6 @@ def _confirm_exit(self): # disable the exit confirmation for background notebook processes ioloop.IOLoop.instance().stop() - def init_kernel_argv(self): - """construct the kernel arguments""" - # FIXME: This is 2.x-compat, remove when 3.x is requred - self.kernel_argv = ["--profile-dir", self.profile_dir.location] - def init_webapp(self): # monkeypatch authentication to use the hub from IPython.html.base.handlers import AuthenticatedHandler @@ -120,10 +114,7 @@ def logout_get(self): # load the hub related settings into the tornado settings dict env = os.environ - # FIXME: IPython < 3 compat - s = getattr(self, 'tornado_settings', - getattr(self, 'webapp_settings') - ) + s = self.webapp_settings s['cookie_cache'] = {} s['user'] = self.user s['hub_api_key'] = env.pop('JPY_API_TOKEN') diff --git a/jupyterhub/spawner.py b/jupyterhub/spawner.py --- a/jupyterhub/spawner.py +++ b/jupyterhub/spawner.py @@ -114,7 +114,7 @@ def clear_state(self): Subclasses should call super, to ensure that state is properly cleared. """ - self.api_token = u'' + self.api_token = '' def get_args(self): """Return the arguments to be passed after self.cmd""" @@ -339,13 +339,13 @@ def get_sudo_pid(self): break pids = self._get_pg_pids(ppid) if pids: - raise gen.Return(pids[0]) + return pids[0] else: yield gen.Task(loop.add_timeout, loop.time() + 0.1) self.log.error("Failed to get single-user PID") # return sudo pid if we can't get the real PID # this shouldn't happen - raise gen.Return(ppid) + return ppid @gen.coroutine def start(self): @@ -378,7 +378,7 @@ def poll(self): if status is not None: # clear state if the process is done self.clear_state() - raise gen.Return(status) + return status # if we resumed from stored state, # we don't have the Popen handle anymore, so rely on self.pid @@ -386,16 +386,16 @@ def poll(self): if not self.pid: # no pid, not running self.clear_state() - raise gen.Return(0) + return 0 # send signal 0 to check if PID exists # this doesn't work on Windows, but that's okay because we don't support Windows. alive = yield self._signal(0) if not alive: self.clear_state() - raise gen.Return(0) + return 0 else: - raise gen.Return(None) + return None @gen.coroutine def _signal(self, sig): @@ -405,9 +405,9 @@ def _signal(self, sig): """ if self.set_user == 'sudo': rc = yield self._signal_sudo(sig) - raise gen.Return(rc) + return rc else: - raise gen.Return(self._signal_setuid(sig)) + return self._signal_setuid(sig) def _signal_setuid(self, sig): """simple implementation of signal, which we can use when we are using setuid (we are root)""" @@ -427,10 +427,10 @@ def _signal_sudo(self, sig): try: check_output(['ps', '-p', str(self.pid)], stderr=PIPE) except CalledProcessError: - raise gen.Return(False) # process is gone + return False # process is gone else: if sig == 0: - raise gen.Return(True) # process exists + return True # process exists # build sudo -u user kill -SIG PID cmd = self.sudo_cmd(self.user) @@ -441,7 +441,7 @@ def _signal_sudo(self, sig): check_output(cmd, preexec_fn=self.make_preexec_fn(self.user.name), ) - raise gen.Return(True) # process exists + return True # process exists @gen.coroutine def stop(self, now=False): diff --git a/jupyterhub/utils.py b/jupyterhub/utils.py --- a/jupyterhub/utils.py +++ b/jupyterhub/utils.py @@ -5,34 +5,17 @@ from binascii import b2a_hex import errno -import getpass import hashlib import os import socket import uuid -from six import text_type from tornado import web, gen, ioloop from tornado.httpclient import AsyncHTTPClient, HTTPError from tornado.log import app_log from IPython.html.utils import url_path_join -try: - # make TimeoutError importable on Python >= 3.3 - TimeoutError = TimeoutError -except NameError: - # python < 3.3 - class TimeoutError(Exception): - pass - - -def getuser_unicode(): - """ - Call getpass.getuser, ensuring that the output is returned as unicode. - """ - return text_type(getpass.getuser()) - def random_port(): """get a single random port""" @@ -147,7 +130,7 @@ def new_token(*args, **kwargs): For now, just UUIDs. """ - return text_type(uuid.uuid4().hex) + return uuid.uuid4().hex def hash_token(token, salt=8, rounds=16384, algorithm='sha512'): @@ -169,7 +152,7 @@ def hash_token(token, salt=8, rounds=16384, algorithm='sha512'): h.update(btoken) digest = h.hexdigest() - return u"{algorithm}:{rounds}:{salt}:{digest}".format(**locals()) + return "{algorithm}:{rounds}:{salt}:{digest}".format(**locals()) def compare_token(compare, token): diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -14,12 +14,11 @@ import sys v = sys.version_info -if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)): - error = "ERROR: IPython requires Python version 2.7 or 3.3 or above." +if v[:2] < (3,3): + error = "ERROR: Jupyter Hub requires Python version 3.3 or above." print(error, file=sys.stderr) sys.exit(1) -PY3 = (sys.version_info[0] >= 3) if os.name in ('nt', 'dos'): error = "ERROR: Windows is not supported" @@ -34,14 +33,6 @@ from distutils.core import setup from subprocess import check_call -try: - execfile -except NameError: - # py3 - def execfile(fname, globs, locs=None): - locs = locs or globs - exec(compile(open(fname).read(), fname, "exec"), globs, locs) - pjoin = os.path.join here = os.path.abspath(os.path.dirname(__file__)) @@ -67,7 +58,9 @@ def get_data_files(): ns = {} -execfile(pjoin(here, 'jupyterhub', 'version.py'), ns) +with open(pjoin(here, 'jupyterhub', 'version.py')) as f: + exec(f.read(), {}, ns) + packages = [] for d, _, _ in os.walk('jupyterhub'): @@ -92,13 +85,11 @@ def get_data_files(): keywords = ['Interactive', 'Interpreter', 'Shell', 'Web'], classifiers = [ 'Intended Audience :: Developers', + 'Intended Audience :: System Administrators', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', - 'Topic :: System :: Shells', ], ) @@ -194,11 +185,14 @@ def run(self): self.distribution.run_command('css') develop.run(self) setup_args['cmdclass']['develop'] = develop_js_css - + setup_args['install_requires'] = install_requires = [] with open('requirements.txt') as f: - install_requires = [ line.strip() for line in f.readlines() ] - setup_args['install_requires'] = install_requires + for line in f.readlines(): + req = line.strip() + if req.startswith('-e'): + req = line.split('#egg=', 1)[1] + install_requires.append(req) #--------------------------------------------------------------------------- # setup
diff --git a/jupyterhub/tests/conftest.py b/jupyterhub/tests/conftest.py --- a/jupyterhub/tests/conftest.py +++ b/jupyterhub/tests/conftest.py @@ -4,12 +4,12 @@ # Distributed under the terms of the Modified BSD License. import logging +from getpass import getuser from pytest import fixture from tornado import ioloop from .. import orm -from ..utils import getuser_unicode from .mocking import MockHubApp @@ -24,7 +24,7 @@ def db(): if _db is None: _db = orm.new_session_factory('sqlite:///:memory:', echo=True)() user = orm.User( - name=getuser_unicode(), + name=getuser(), server=orm.Server(), ) hub = orm.Hub( diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -1,29 +1,23 @@ """mock utilities for testing""" -import os import sys from tempfile import NamedTemporaryFile import threading -try: - from unittest import mock -except ImportError: - import mock +from unittest import mock from tornado.ioloop import IOLoop -from six import text_type - from ..spawner import LocalProcessSpawner from ..app import JupyterHubApp -from ..auth import PAMAuthenticator, Authenticator +from ..auth import PAMAuthenticator from .. import orm def mock_authenticate(username, password, service='login'): # mimic simplepam's failure to handle unicode - if isinstance(username, text_type): + if isinstance(username, str): return False - if isinstance(password, text_type): + if isinstance(password, str): return False # just use equality for testing diff --git a/jupyterhub/tests/test_app.py b/jupyterhub/tests/test_app.py --- a/jupyterhub/tests/test_app.py +++ b/jupyterhub/tests/test_app.py @@ -1,6 +1,5 @@ """Test the JupyterHubApp entry point""" -import io import os import sys from subprocess import check_output @@ -8,8 +7,8 @@ def test_help_all(): out = check_output([sys.executable, '-m', 'jupyterhub', '--help-all']).decode('utf8', 'replace') - assert u'--ip' in out - assert u'--JupyterHubApp.ip' in out + assert '--ip' in out + assert '--JupyterHubApp.ip' in out def test_generate_config(): with NamedTemporaryFile(prefix='jupyter_hub_config', suffix='.py') as tf: @@ -19,7 +18,7 @@ def test_generate_config(): '--generate-config', '-f', cfg_file] ).decode('utf8', 'replace') assert os.path.exists(cfg_file) - with io.open(cfg_file) as f: + with open(cfg_file) as f: cfg_text = f.read() os.remove(cfg_file) assert cfg_file in out diff --git a/jupyterhub/tests/test_auth.py b/jupyterhub/tests/test_auth.py --- a/jupyterhub/tests/test_auth.py +++ b/jupyterhub/tests/test_auth.py @@ -9,33 +9,33 @@ def test_pam_auth(io_loop): authenticator = MockPAMAuthenticator() authorized = io_loop.run_sync(lambda : authenticator.authenticate(None, { - u'username': u'match', - u'password': u'match', + 'username': 'match', + 'password': 'match', })) - assert authorized == u'match' + assert authorized == 'match' authorized = io_loop.run_sync(lambda : authenticator.authenticate(None, { - u'username': u'match', - u'password': u'nomatch', + 'username': 'match', + 'password': 'nomatch', })) assert authorized is None def test_pam_auth_whitelist(io_loop): authenticator = MockPAMAuthenticator(whitelist={'wash', 'kaylee'}) authorized = io_loop.run_sync(lambda : authenticator.authenticate(None, { - u'username': u'kaylee', - u'password': u'kaylee', + 'username': 'kaylee', + 'password': 'kaylee', })) - assert authorized == u'kaylee' + assert authorized == 'kaylee' authorized = io_loop.run_sync(lambda : authenticator.authenticate(None, { - u'username': u'wash', - u'password': u'nomatch', + 'username': 'wash', + 'password': 'nomatch', })) assert authorized is None authorized = io_loop.run_sync(lambda : authenticator.authenticate(None, { - u'username': u'mal', - u'password': u'mal', + 'username': 'mal', + 'password': 'mal', })) assert authorized is None diff --git a/jupyterhub/tests/test_orm.py b/jupyterhub/tests/test_orm.py --- a/jupyterhub/tests/test_orm.py +++ b/jupyterhub/tests/test_orm.py @@ -5,48 +5,42 @@ from .. import orm -try: - unicode -except NameError: - # py3 - unicode = str - def test_server(db): server = orm.Server() db.add(server) db.commit() - assert server.ip == u'localhost' + assert server.ip == 'localhost' assert server.base_url == '/' assert server.proto == 'http' assert isinstance(server.port, int) - assert isinstance(server.cookie_name, unicode) + assert isinstance(server.cookie_name, str) assert server.url == 'http://localhost:%i/' % server.port def test_proxy(db): proxy = orm.Proxy( - auth_token=u'abc-123', + auth_token='abc-123', public_server=orm.Server( - ip=u'192.168.1.1', + ip='192.168.1.1', port=8000, ), api_server=orm.Server( - ip=u'127.0.0.1', + ip='127.0.0.1', port=8001, ), ) db.add(proxy) db.commit() - assert proxy.public_server.ip == u'192.168.1.1' - assert proxy.api_server.ip == u'127.0.0.1' - assert proxy.auth_token == u'abc-123' + assert proxy.public_server.ip == '192.168.1.1' + assert proxy.api_server.ip == '127.0.0.1' + assert proxy.auth_token == 'abc-123' def test_hub(db): hub = orm.Hub( server=orm.Server( - ip = u'1.2.3.4', + ip = '1.2.3.4', port = 1234, base_url='/hubtest/', ), @@ -54,30 +48,30 @@ def test_hub(db): ) db.add(hub) db.commit() - assert hub.server.ip == u'1.2.3.4' + assert hub.server.ip == '1.2.3.4' hub.server.port == 1234 - assert hub.api_url == u'http://1.2.3.4:1234/hubtest/api' + assert hub.api_url == 'http://1.2.3.4:1234/hubtest/api' def test_user(db): - user = orm.User(name=u'kaylee', + user = orm.User(name='kaylee', server=orm.Server(), state={'pid': 4234}, ) db.add(user) db.commit() - assert user.name == u'kaylee' - assert user.server.ip == u'localhost' + assert user.name == 'kaylee' + assert user.server.ip == 'localhost' assert user.state == {'pid': 4234} - found = orm.User.find(db, u'kaylee') + found = orm.User.find(db, 'kaylee') assert found.name == user.name - found = orm.User.find(db, u'badger') + found = orm.User.find(db, 'badger') assert found is None def test_tokens(db): - user = orm.User(name=u'inara') + user = orm.User(name='inara') db.add(user) db.commit() token = user.new_api_token()
minimum Python, IPython versions By the time IPython 3 is released, that will be the minimum version of the notebook server. There won't be a release of JupyterHub that supports IPython 2. I'm considering doing that now, so that I don't need to keep adding workarounds for IPython 2. Related to that, I'm also considering bumping the minimum Python version for JupyterHub to Python 3.3 or 3.4. Since almost everything in JupyterHub is either passing text around or async code, several things would be simplified, and the whole project would be easier to develop and maintain. Part of the reason I feel comfortable doing both of these things is that it affects JupyterHub deployment, but does _not_ affect the end users of IPython, where the kernel does not need to use the same version of Python (or even IPython, technically) as the notebook server or the Hub. I'd like to hear from @dsblank, @ssanderson, and @rgbkrk before doing one or both of these. Would Python 3.4 be too aggressive (e.g. Ubuntu 14.04 is the first Ubuntu to ship with 3.4)? Is anyone planning to pin IPython to 2.x?
I can't think of a reason that we would need to run jupyterhub with IPython 2.x. And, I don't see a problem requiring Python 3.4. It is aggressive, but if more projects would push ahead just a bit, we could put Python 2 down for good. I am all for making the codebase simpler and smaller. Allows a small team to focus and move forward. I'm in favor of moving to all Python3 for JupyterHub. :+1: to go with 3.4 I'm all for IPython>=3.0. If Python 2 support were continued in Jupyterhub I would probably continue to use that. Most of the rest of our stack at Quantopian is gevent-based, which still hasn't been ported to python 3, so we're all still back in the stone ages. If you do end up going with Python 3 though, I'll figure out a way to make it work. 3.3 vs 3.4 doesn't make any difference to me.
2014-10-31T21:18:08Z
[]
[]
jupyterhub/jupyterhub
103
jupyterhub__jupyterhub-103
[ "102" ]
f8f9c9e121df6f7ff1556a7ccdbca9602ca09931
diff --git a/examples/sudo/jupyterhub_config.py b/examples/sudo/jupyterhub_config.py deleted file mode 100644 --- a/examples/sudo/jupyterhub_config.py +++ /dev/null @@ -1,7 +0,0 @@ -# Configuration file for jupyterhub - -c = get_config() - -c.JupyterHub.admin_users = {'rhea'} -c.LocalProcessSpawner.set_user = 'sudo' -c.Authenticator.whitelist = {'ganymede', 'io', 'rhea'} diff --git a/jupyterhub/spawner.py b/jupyterhub/spawner.py --- a/jupyterhub/spawner.py +++ b/jupyterhub/spawner.py @@ -5,6 +5,7 @@ import errno import os +import pipes import pwd import re import signal @@ -262,20 +263,6 @@ def preexec(): return preexec -def set_user_sudo(username): - """return a preexec_fn for setting the user (assuming sudo is used for setting the user)""" - user = pwd.getpwnam(username) - home = user.pw_dir - - def preexec(): - # don't forward signals - os.setpgrp() - - # start in the user's home dir - _try_setcwd(home) - return preexec - - class LocalProcessSpawner(Spawner): """A Spawner that just uses Popen to start local processes.""" @@ -291,29 +278,9 @@ class LocalProcessSpawner(Spawner): proc = Instance(Popen) pid = Integer(0) - sudo_args = List(['-n'], config=True, - help="""arguments to be passed to sudo (in addition to -u [username]) - - only used if set_user = sudo - """ - ) - - make_preexec_fn = Any(set_user_setuid) - - set_user = Enum(['sudo', 'setuid'], default_value='setuid', config=True, - help="""scheme for setting the user of the spawned process - - 'sudo' can be more prudently restricted, - but 'setuid' is simpler for a server run as root - """ - ) - def _set_user_changed(self, name, old, new): - if new == 'sudo': - self.make_preexec_fn = set_user_sudo - elif new == 'setuid': - self.make_preexec_fn = set_user_setuid - else: - raise ValueError("This should be impossible") + + def make_preexec_fn(self, name): + return set_user_setuid(name) def load_state(self, state): """load pid from state""" @@ -333,66 +300,30 @@ def clear_state(self): super(LocalProcessSpawner, self).clear_state() self.pid = 0 - def sudo_cmd(self, user): - return ['sudo', '-u', user.name] + self.sudo_args - def user_env(self, env): - if self.set_user == 'setuid': - env['USER'] = self.user.name - env['HOME'] = pwd.getpwnam(self.user.name).pw_dir + env['USER'] = self.user.name + env['HOME'] = pwd.getpwnam(self.user.name).pw_dir return env - def _get_pg_pids(self, ppid): - """get pids in group excluding the group id itself - - used for getting actual process started by `sudo` - """ - out = check_output(['pgrep', '-g', str(ppid)]).decode('utf8', 'replace') - self.log.debug("pgrep output: %r", out) - return [ int(ns) for ns in NUM_PAT.findall(out) if int(ns) != ppid ] - - @gen.coroutine - def get_sudo_pid(self): - """Get the actual process started with sudo - - use the output of `pgrep -g PPID` to get the child process ID - """ - ppid = self.proc.pid - loop = IOLoop.current() - for i in range(100): - if self.proc.poll() is not None: - break - pids = self._get_pg_pids(ppid) - if pids: - return pids[0] - else: - yield gen.Task(loop.add_timeout, loop.time() + 0.1) - self.log.error("Failed to get single-user PID") - # return sudo pid if we can't get the real PID - # this shouldn't happen - return ppid + def _env_default(self): + env = super()._env_default() + return self.user_env(env) @gen.coroutine def start(self): """Start the process""" self.user.server.port = random_port() cmd = [] - env = self.user_env(self.env) - if self.set_user == 'sudo': - cmd = self.sudo_cmd(self.user) + env = self.env.copy() cmd.extend(self.cmd) cmd.extend(self.get_args()) - self.log.info("Spawning %r", cmd) + self.log.info("Spawning %s", ' '.join(pipes.quote(s) for s in cmd)) self.proc = Popen(cmd, env=env, preexec_fn=self.make_preexec_fn(self.user.name), ) - if self.set_user == 'sudo': - self.pid = yield self.get_sudo_pid() - self.proc = None - else: - self.pid = self.proc.pid + self.pid = self.proc.pid @gen.coroutine def poll(self): @@ -424,17 +355,6 @@ def poll(self): @gen.coroutine def _signal(self, sig): - """send a signal, and ignore ERSCH because it just means it already died - - returns bool for whether the process existed to receive the signal. - """ - if self.set_user == 'sudo': - rc = yield self._signal_sudo(sig) - return rc - else: - return self._signal_setuid(sig) - - def _signal_setuid(self, sig): """simple implementation of signal, which we can use when we are using setuid (we are root)""" try: os.kill(self.pid, sig) @@ -444,29 +364,6 @@ def _signal_setuid(self, sig): else: raise return True # process exists - - @gen.coroutine - def _signal_sudo(self, sig): - """use `sudo kill` to send signals""" - # check for existence with `ps -p` instead of `kill -0` - try: - check_output(['ps', '-p', str(self.pid)], stderr=PIPE) - except CalledProcessError: - return False # process is gone - else: - if sig == 0: - return True # process exists - - # build sudo -u user kill -SIG PID - cmd = self.sudo_cmd(self.user) - cmd.extend([ - 'kill', '-%i' % sig, str(self.pid), - ]) - self.log.debug("Signaling: %s", cmd) - check_output(cmd, - preexec_fn=self.make_preexec_fn(self.user.name), - ) - return True # process exists @gen.coroutine def stop(self, now=False):
diff --git a/jupyterhub/tests/test_spawner.py b/jupyterhub/tests/test_spawner.py --- a/jupyterhub/tests/test_spawner.py +++ b/jupyterhub/tests/test_spawner.py @@ -54,15 +54,6 @@ def test_spawner(db, io_loop): assert status == -signal.SIGINT -def test_preexec_switch(db): - spawner = new_spawner(db) - assert spawner.make_preexec_fn is spawnermod.set_user_setuid - spawner.set_user = 'sudo' - assert spawner.make_preexec_fn is spawnermod.set_user_sudo - spawner.set_user = 'setuid' - assert spawner.make_preexec_fn is spawnermod.set_user_setuid - - def test_stop_spawner_sigint_fails(db, io_loop): spawner = new_spawner(db, cmd=[sys.executable, '-c', _uninterruptible]) io_loop.run_sync(spawner.start)
select method base on egid Not we want that since @minrk started a sudospawner.
-1, this makes the wrong decision in many cases, and `(not recommended)` is also not true. If sudo worked a lot better this would make sense, but only setuid works reliably at this point.
2014-11-26T03:43:04Z
[]
[]
jupyterhub/jupyterhub
147
jupyterhub__jupyterhub-147
[ "146" ]
d1c42f960c9548037640e198c18cf17b9a818821
diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -14,12 +14,18 @@ class BaseUserHandler(APIHandler): def user_model(self, user): - return { + model = { 'name': user.name, 'admin': user.admin, - 'server': user.server.base_url if user.server and not (user.spawn_pending or user.stop_pending) else None, + 'server': user.server.base_url if user.running else None, + 'pending': None, 'last_activity': user.last_activity.isoformat(), } + if user.spawn_pending: + model['pending'] = 'spawn' + elif user.stop_pending: + model['pending'] = 'stop' + return model _model_types = { 'name': str, @@ -150,7 +156,7 @@ def delete(self, name): if user.stop_pending: self.set_status(202) return - if user.spawner is None: + if not user.running: raise web.HTTPError(400, "%s's server is not running" % name) status = yield user.spawner.poll() if status is not None: @@ -175,8 +181,8 @@ def post(self, name): user = self.find_user(name) if user is None: raise web.HTTPError(404) - if user.server is None: - raise web.HTTPError(400, "%s has no server running" % name) + if not user.running: + raise web.HTTPError(400, "%s's server is not running" % name) self.set_server_cookie(user) diff --git a/jupyterhub/orm.py b/jupyterhub/orm.py --- a/jupyterhub/orm.py +++ b/jupyterhub/orm.py @@ -267,6 +267,15 @@ def __repr__(self): name=self.name, ) + @property + def running(self): + """property for whether a user has a running server""" + if self.spawner is None: + return False + if self.server is None: + return False + return True + def new_api_token(self): """Create a new API token""" assert self.id is not None @@ -285,7 +294,7 @@ def find(cls, db, name): Returns None if not found. """ return db.query(cls).filter(cls.name==name).first() - + @gen.coroutine def spawn(self, spawner_class, base_url='/', hub=None, config=None): """Start the user's spawner""" @@ -298,11 +307,10 @@ def spawn(self, spawner_class, base_url='/', hub=None, config=None): ) db.add(self.server) db.commit() - + api_token = self.new_api_token() db.commit() - spawner = self.spawner = spawner_class( config=config, user=self, @@ -314,21 +322,26 @@ def spawn(self, spawner_class, base_url='/', hub=None, config=None): spawner.api_token = api_token self.spawn_pending = True - f = spawner.start() # wait for spawner.start to return try: + f = spawner.start() yield gen.with_timeout(timedelta(seconds=spawner.start_timeout), f) - except gen.TimeoutError as e: - self.log.warn("{user}'s server failed to start in {s} seconds, giving up".format( - user=self.name, s=spawner.start_timeout, - )) + except Exception as e: + if isinstance(e, gen.TimeoutError): + self.log.warn("{user}'s server failed to start in {s} seconds, giving up".format( + user=self.name, s=spawner.start_timeout, + )) + else: + self.log.error("Unhandled error starting {user}'s server: {error}".format( + user=self.name, error=e, + )) try: yield self.stop() except Exception: self.log.error("Failed to cleanup {user}'s server that failed to start".format( user=self.name, ), exc_info=True) - # raise original TimeoutError + # raise original exception raise e spawner.start_polling() @@ -338,10 +351,15 @@ def spawn(self, spawner_class, base_url='/', hub=None, config=None): db.commit() try: yield self.server.wait_up(http=True) - except TimeoutError as e: - self.log.warn("{user}'s server never showed up at {url}, giving up".format( - user=self.name, url=self.server.url, - )) + except Exception as e: + if isinstance(e, TimeoutError): + self.log.warn("{user}'s server never showed up at {url}, giving up".format( + user=self.name, url=self.server.url, + )) + else: + self.log.error("Unhandled error waiting for {user}'s server to show up at {url}: {error}".format( + user=self.name, url=self.server.url, error=e, + )) try: yield self.stop() except Exception:
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -104,11 +104,13 @@ def test_get_users(app): 'name': 'admin', 'admin': True, 'server': None, + 'pending': None, }, { 'name': 'user', 'admin': False, 'server': None, + 'pending': None, } ] diff --git a/jupyterhub/tests/test_orm.py b/jupyterhub/tests/test_orm.py --- a/jupyterhub/tests/test_orm.py +++ b/jupyterhub/tests/test_orm.py @@ -3,7 +3,11 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. +import pytest +from tornado import gen + from .. import orm +from .mocking import MockSpawner def test_server(db): @@ -82,3 +86,20 @@ def test_tokens(db): assert found.match(token) found = orm.APIToken.find(db, 'something else') assert found is None + + +def test_spawn_fails(db, io_loop): + user = orm.User(name='aeofel') + db.add(user) + db.commit() + + class BadSpawner(MockSpawner): + @gen.coroutine + def start(self): + raise RuntimeError("Split the party") + + with pytest.raises(Exception) as exc: + io_loop.run_sync(lambda : user.spawn(BadSpawner)) + assert user.server is None + assert not user.running +
inconsistent db state when spawner fails to start it's possible for some parts of the Hub to think a server is running when it's not, preventing stop/restart from working. /cc @jhamrick
@minrk what does "some parts of the hub" mean here? There's definitely a window from https://github.com/jupyter/jupyterhub/blob/master/jupyterhub/orm.py#L300 to https://github.com/jupyter/jupyterhub/blob/master/jupyterhub/orm.py#L333 where there's a server entry for the user but the server hasn't actually come up yet. Is that the issue you're referring to, or is there something else you're seeing? Apparently some APIs are using different information to report whether there's already a server running, so the admin page shows a 'stop' button, but clicking it results in "server isn't running". This state can happen after a spawner fails to start, not just the spawn pending state, which isn't a problem.
2015-02-06T23:44:41Z
[]
[]
jupyterhub/jupyterhub
165
jupyterhub__jupyterhub-165
[ "164" ]
09b27ca44dcb423b2a1d5709ee4831f680b0c011
diff --git a/jupyterhub/orm.py b/jupyterhub/orm.py --- a/jupyterhub/orm.py +++ b/jupyterhub/orm.py @@ -77,7 +77,7 @@ def __repr__(self): def host(self): return "{proto}://{ip}:{port}".format( proto=self.proto, - ip=self.ip or '*', + ip=self.ip or 'localhost', port=self.port, ) @@ -92,7 +92,7 @@ def url(self): def wait_up(self, timeout=10, http=False): """Wait for this server to come up""" if http: - yield wait_for_http_server(self.url.replace('//*', '//localhost'), timeout=timeout) + yield wait_for_http_server(self.url, timeout=timeout) else: yield wait_for_server(self.ip or 'localhost', self.port, timeout=timeout)
diff --git a/jupyterhub/tests/test_orm.py b/jupyterhub/tests/test_orm.py --- a/jupyterhub/tests/test_orm.py +++ b/jupyterhub/tests/test_orm.py @@ -19,7 +19,11 @@ def test_server(db): assert server.proto == 'http' assert isinstance(server.port, int) assert isinstance(server.cookie_name, str) - assert server.url == 'http://*:%i/' % server.port + assert server.host == 'http://localhost:%i' % server.port + assert server.url == server.host + '/' + server.ip = '127.0.0.1' + assert server.host == 'http://127.0.0.1:%i' % server.port + assert server.url == server.host + '/' def test_proxy(db):
Proxy error while non root I've just installed jupyterhub and tested it successfully running it as root. However, following the non-root procedure end up on a proxy error after being logged in: ``` rhea@pcjlaforet-cr:/etc/jupyterhub$ jupyterhub --JupyterHub.spawner_class=sudospawner.SudoSpawner [I 2015-03-03 17:41:32.475 JupyterHub app:506] Loading cookie_secret from /etc/jupyterhub/jupyterhub_cookie_secret [W 2015-03-03 17:41:32.504 JupyterHub app:242] Generating CONFIGPROXY_AUTH_TOKEN. Restarting the Hub will require restarting the proxy. Set CONFIGPROXY_AUTH_TOKEN env or JupyterHub.proxy_auth_token config to avoid this message. [I 2015-03-03 17:41:32.511 JupyterHub app:599] Not using whitelist. Any authenticated user will be allowed. [I 2015-03-03 17:41:32.523 JupyterHub app:731] Starting proxy @ http://*:8000/ 17:41:32.633 - info: [ConfigProxy] Proxying http://*:8000 to http://localhost:8081 17:41:32.635 - info: [ConfigProxy] Proxy API at http://localhost:8001/api/routes [I 2015-03-03 17:41:42.694 JupyterHub web:1825] 302 GET / (127.0.0.1) 1.45ms [I 2015-03-03 17:41:42.700 JupyterHub web:1825] 302 GET /hub (127.0.0.1) 0.34ms [I 2015-03-03 17:41:42.710 JupyterHub web:1825] 302 GET /hub/ (127.0.0.1) 5.91ms [I 2015-03-03 17:41:42.747 JupyterHub web:1825] 200 GET /hub/home (127.0.0.1) 33.46ms [I 2015-03-03 17:41:42.906 JupyterHub web:1825] 200 GET /hub/static/js/home.js?v=(%2720150303174132%27,) (127.0.0.1) 5.62ms [I 2015-03-03 17:41:42.917 JupyterHub web:1825] 200 GET /hub/static/components/jquery/jquery.min.js?v=(%2720150303174132%27,) (127.0.0.1) 2.20ms [I 2015-03-03 17:41:42.919 JupyterHub web:1825] 200 GET /hub/static/js/jhapi.js?v=(%2720150303174132%27,) (127.0.0.1) 0.70ms [I 2015-03-03 17:41:42.961 JupyterHub web:1825] 200 GET /hub/static/js/utils.js?v=(%2720150303174132%27,) (127.0.0.1) 0.88ms [I 150303 17:41:45 mediator:62] Spawning /usr/bin/python3 -m jupyterhub.singleuser --user=jlaforet --port=46992 --cookie-name=jupyter-hub-token-jlaforet --base-url=/user/jlaforet --hub-prefix=/hub/ --hub-api-url=http://localhost:8081/hub/api --ip=localhost [I 2015-03-03 17:41:45.929 JupyterHub base:209] User jlaforet server took 0.893 seconds to start [I 2015-03-03 17:41:45.929 JupyterHub orm:154] Adding user jlaforet to proxy /user/jlaforet => http://*:46992 [I 2015-03-03 17:41:45.939 JupyterHub web:1825] 302 GET /hub/user/jlaforet/ (127.0.0.1) 908.02ms 17:41:46.086 - error: [ConfigProxy] Proxy error: code=ENOTFOUND, errno=ENOTFOUND, syscall=getaddrinfo ``` Feels like there's something misconfigured for the proxy, but i have no clue what.
Can you run it again with: ``` --debug --JupyterHub.debug_db=True ``` ? I'm experiencing the same issue after following the instructions for [Using sudo to run JupyterHub without root privileges](https://github.com/jupyter/jupyterhub/wiki/Using-sudo-to-run-JupyterHub-without-root-privileges). It works fine as a single-user running as root via sudo. After starting the server and navigating the front page it displays correctly. The login works, making it to the "My Server" green button. Clicking this however produces the proxy error: the resulting page has the message `Proxy target missing` ``` http://<ip-address>:8000/hub/home [...click green button...] http://<ip-address>:8000/user/mfitzp/ Proxy target missing ``` Alongside the displayed message is the similar output to @jere19 described above. ``` [I 2015-03-04 17:38:51.370 JupyterHub web:1825] 302 GET /hub/user/mfitzp/ (<ip-address>) 565.94ms 17:38:51.380 - error: [ConfigProxy] Proxy error: code=ENOTFOUND, errno=ENOTFOUND, syscall=getaddrinfo ``` Running the server with `--debug --JupyterHub.debug_db=True` produces the following output. I've trimmed it for the highlighted lines and information regarding proxy/users (removing the SQL debug from SQLAlchemy - happy to provide if it will be helpful). ``` Connecting to db: sqlite:///jupyterhub.sqlite [W 2015-03-04 17:41:26.368 JupyterHub app:242] Generating CONFIGPROXY_AUTH_TOKEN. Restarting the Hub will require restarting the proxy. Set CONFIGPROXY_AUTH_TOKEN env or JupyterHub.proxy_auth_token config to avoid this message. [I 2015-03-04 17:41:26.376 JupyterHub app:599] Not using whitelist. Any authenticated user will be allowed. [D 2015-03-04 17:41:26.379 JupyterHub app:671] Loaded users: jupyter admin mfitzp [I 2015-03-04 17:41:26.392 JupyterHub app:731] Starting proxy @ http://*:8000/ [D 2015-03-04 17:41:26.392 JupyterHub app:732] Proxy cmd: ['configurable-http-proxy', '--ip', '', '--port', '8000', '--api-ip', 'localhost', '--api-port', '8001', '--default-target', 'http://localhost:8081'] 17:41:26.500 - info: [ConfigProxy] Proxying http://*:8000 to http://localhost:8081 17:41:26.503 - info: [ConfigProxy] Proxy API at http://localhost:8001/api/routes [D 2015-03-04 17:41:26.609 JupyterHub app:752] Proxy started and appears to be up [D 2015-03-04 17:43:28.456 JupyterHub utils:73] Server at http://localhost:53906/user/mfitzp responded with 302 [I 2015-03-04 17:43:28.457 JupyterHub base:209] User mfitzp server took 1.689 seconds to start [I 2015-03-04 17:43:28.457 JupyterHub orm:154] Adding user mfitzp to proxy /user/mfitzp => http://*:53906 [D 2015-03-04 17:43:28.460 JupyterHub orm:141] Fetching POST http://localhost:8001/api/routes/user/mfitzp [I 2015-03-04 17:43:28.472 JupyterHub web:1825] 302 GET /hub/user/mfitzp/ (<ip-address>) 1715.60ms 17:43:28.767 - error: [ConfigProxy] Proxy error: code=ENOTFOUND, errno=ENOTFOUND, syscall=getaddrinfo ``` I'm running with today's master from Github. Thanks, I'll see if I can pin down what's wrong.
2015-03-04T19:57:40Z
[]
[]
jupyterhub/jupyterhub
250
jupyterhub__jupyterhub-250
[ "225" ]
36bc07b02e3e81ba00fd65ac57e98506c80e1723
diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -18,6 +18,49 @@ def get(self): users = self.db.query(orm.User) data = [ self.user_model(u) for u in users ] self.write(json.dumps(data)) + + @admin_only + @gen.coroutine + def post(self): + data = self.get_json_body() + if not data or not isinstance(data, dict) or not data.get('usernames'): + raise web.HTTPError(400, "Must specify at least one user to create") + + usernames = data.pop('usernames') + self._check_user_model(data) + # admin is set for all users + # to create admin and non-admin users requires at least two API requests + admin = data.get('admin', False) + + to_create = [] + for name in usernames: + user = self.find_user(name) + if user is not None: + self.log.warn("User %s already exists" % name) + else: + to_create.append(name) + + if not to_create: + raise web.HTTPError(400, "All %i users already exist" % len(usernames)) + + created = [] + for name in to_create: + user = self.user_from_username(name) + if admin: + user.admin = True + self.db.commit() + try: + yield gen.maybe_future(self.authenticator.add_user(user)) + except Exception: + self.log.error("Failed to create user: %s" % name, exc_info=True) + self.db.delete(user) + self.db.commit() + raise web.HTTPError(400, "Failed to create user: %s" % name) + else: + created.append(user) + + self.write(json.dumps([ self.user_model(u) for u in created ])) + self.set_status(201) def admin_or_self(method):
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -132,6 +132,82 @@ def test_add_user(app): assert user.name == name assert not user.admin + +def test_get_user(app): + name = 'user' + r = api_request(app, 'users', name) + assert r.status_code == 200 + user = r.json() + user.pop('last_activity') + assert user == { + 'name': name, + 'admin': False, + 'server': None, + 'pending': None, + } + + +def test_add_multi_user_bad(app): + r = api_request(app, 'users', method='post') + assert r.status_code == 400 + r = api_request(app, 'users', method='post', data='{}') + assert r.status_code == 400 + r = api_request(app, 'users', method='post', data='[]') + assert r.status_code == 400 + +def test_add_multi_user(app): + db = app.db + names = ['a', 'b'] + r = api_request(app, 'users', method='post', + data=json.dumps({'usernames': names}), + ) + assert r.status_code == 201 + reply = r.json() + r_names = [ user['name'] for user in reply ] + assert names == r_names + + for name in names: + user = find_user(db, name) + assert user is not None + assert user.name == name + assert not user.admin + + # try to create the same users again + r = api_request(app, 'users', method='post', + data=json.dumps({'usernames': names}), + ) + assert r.status_code == 400 + + names = ['a', 'b', 'ab'] + + # try to create the same users again + r = api_request(app, 'users', method='post', + data=json.dumps({'usernames': names}), + ) + assert r.status_code == 201 + reply = r.json() + r_names = [ user['name'] for user in reply ] + assert r_names == ['ab'] + + +def test_add_multi_user_admin(app): + db = app.db + names = ['c', 'd'] + r = api_request(app, 'users', method='post', + data=json.dumps({'usernames': names, 'admin': True}), + ) + assert r.status_code == 201 + reply = r.json() + r_names = [ user['name'] for user in reply ] + assert names == r_names + + for name in names: + user = find_user(db, name) + assert user is not None + assert user.name == name + assert user.admin + + def test_add_user_bad(app): db = app.db name = 'dne_newuser'
Admin panel - Add ability to import multiple users at once It would be nice to add a list of users as a bulk list of newline delimited users.
Like the userlist file used in a few examples? Yeah, pretty much. We added a whole workshop class to demohub. Hm. I'd like to push a little against adding web UI for everything. That would be an easy operation from a script, for instance. I agree that we shouldn't add a web UI for everything, but I think in this case it would be nice to have this, as there already is an "add user" option. It seems like it wouldn't be too hard to change it from just a single-line text box to a multiline text box where usernames are separated by newlines. That's true - and the admin checkbox can be used for admin, so the space-separated format of the userlist file is unnecessary. That should be easy enough. newlines, commas or spaces, any delimiter would work if it's just usernames for now. If we later want to allow username + first/last, then perhaps better to define the delimiter as newline, so further parsing can be done on the individual field. It's a common enough thing to want that I'm +1 on that bit of UI at least.
2015-05-06T21:04:30Z
[]
[]
jupyterhub/jupyterhub
263
jupyterhub__jupyterhub-263
[ "262" ]
cfd19c3e614abbb2c35bf2b029b034570939b5fc
diff --git a/jupyterhub/singleuser.py b/jupyterhub/singleuser.py --- a/jupyterhub/singleuser.py +++ b/jupyterhub/singleuser.py @@ -17,7 +17,7 @@ from tornado import ioloop from tornado.web import HTTPError -from traitlets import ( +from IPython.utils.traitlets import ( Integer, Unicode, CUnicode,
diff --git a/jupyterhub/tests/test_spawner.py b/jupyterhub/tests/test_spawner.py --- a/jupyterhub/tests/test_spawner.py +++ b/jupyterhub/tests/test_spawner.py @@ -56,6 +56,30 @@ def test_spawner(db, io_loop): status = io_loop.run_sync(spawner.poll) assert status == 1 +def test_single_user_spawner(db, io_loop): + spawner = new_spawner(db, cmd=[sys.executable, '-m', 'jupyterhub.singleuser']) + io_loop.run_sync(spawner.start) + assert spawner.user.server.ip == 'localhost' + # wait for http server to come up, + # checking for early termination every 1s + def wait(): + return spawner.user.server.wait_up(timeout=1, http=True) + for i in range(30): + status = io_loop.run_sync(spawner.poll) + assert status is None + try: + io_loop.run_sync(wait) + except TimeoutError: + continue + else: + break + io_loop.run_sync(wait) + status = io_loop.run_sync(spawner.poll) + assert status == None + io_loop.run_sync(spawner.stop) + status = io_loop.run_sync(spawner.poll) + assert status == 0 + def test_stop_spawner_sigint_fails(db, io_loop): spawner = new_spawner(db, cmd=[sys.executable, '-c', _uninterruptible])
Single user server launch is broken I think that #261 broke the launching of the single user server. I am seeing the following errors in the nbgrader tests: ``` Traceback (most recent call last): File "/Users/jhamrick/.virtualenvs/nbgrader/bin/jupyterhub-singleuser", line 6, in <module> exec(compile(open(__file__).read(), __file__, 'exec')) File "/Users/jhamrick/project/tools/jupyterhub/scripts/jupyterhub-singleuser", line 4, in <module> main() File "/Users/jhamrick/project/tools/jupyterhub/jupyterhub/singleuser.py", line 221, in main return SingleUserNotebookApp.launch_instance() File "/Users/jhamrick/.virtualenvs/nbgrader/lib/python3.4/site-packages/IPython/config/application.py", line 573, in launch_instance app.initialize(argv) File "<string>", line 2, in initialize File "/Users/jhamrick/.virtualenvs/nbgrader/lib/python3.4/site-packages/IPython/config/application.py", line 75, in catch_config_error return method(app, *args, **kwargs) File "/Users/jhamrick/.virtualenvs/nbgrader/lib/python3.4/site-packages/IPython/html/notebookapp.py", line 1015, in initialize self.init_webapp() File "/Users/jhamrick/project/tools/jupyterhub/jupyterhub/singleuser.py", line 191, in init_webapp s['user'] = self.user File "/Users/jhamrick/.virtualenvs/nbgrader/lib/python3.4/site-packages/traitlets/traitlets.py", line 438, in __get__ % (self.name, obj)) traitlets.traitlets.TraitError: No default value found for None trait of <jupyterhub.singleuser.SingleUserNotebookApp object at 0x102953b00> ``` If I revert to the version of jupyterhub prior to that PR, this error does not occur. @epifanio reported on gitter seeing the same thing as well, so I don't think it's isolated to nbgrader. Given the error message, I suspect this has to do with ipython/traitlets#39 and/or ipython/traitlets#40 though I haven't actually tested it. I tried giving the `user` trait a default value but it did not seem to fix the error. I will try to do a bit more debugging, but I fear I don't really understand the internals of traitlets well enough to know exactly what's going on here. Ping @takluyver and @minrk ?
Min's on his way to the UK, I'll try to look at this in the morning. It certainly looks like something my traitlets changes could have broken; sorry about that. On 23 Jun 2015 10:15 pm, "Jessica B. Hamrick" [email protected] wrote: > I think that #261 https://github.com/jupyter/jupyterhub/pull/261 broke > the launching of the single user server. I am seeing the following errors > in the nbgrader tests: > > Traceback (most recent call last): > File "/Users/jhamrick/.virtualenvs/nbgrader/bin/jupyterhub-singleuser", line 6, in <module> > exec(compile(open(**file**).read(), **file**, 'exec')) > File "/Users/jhamrick/project/tools/jupyterhub/scripts/jupyterhub-singleuser", line 4, in <module> > main() > File "/Users/jhamrick/project/tools/jupyterhub/jupyterhub/singleuser.py", line 221, in main > return SingleUserNotebookApp.launch_instance() > File "/Users/jhamrick/.virtualenvs/nbgrader/lib/python3.4/site-packages/IPython/config/application.py", line 573, in launch_instance > app.initialize(argv) > File "<string>", line 2, in initialize > File "/Users/jhamrick/.virtualenvs/nbgrader/lib/python3.4/site-packages/IPython/config/application.py", line 75, in catch_config_error > return method(app, _args, *_kwargs) > File "/Users/jhamrick/.virtualenvs/nbgrader/lib/python3.4/site-packages/IPython/html/notebookapp.py", line 1015, in initialize > self.init_webapp() > File "/Users/jhamrick/project/tools/jupyterhub/jupyterhub/singleuser.py", line 191, in init_webapp > s['user'] = self.user > File "/Users/jhamrick/.virtualenvs/nbgrader/lib/python3.4/site-packages/traitlets/traitlets.py", line 438, in **get** > % (self.name, obj)) > traitlets.traitlets.TraitError: No default value found for None trait of <jupyterhub.singleuser.SingleUserNotebookApp object at 0x102953b00> > > If I revert to the version of jupyterhub prior to that PR, this error does > not occur. @epifanio https://github.com/epifanio reported on gitter > seeing the same thing as well, so I don't think it's isolated to nbgrader. > > Given the error message, I suspect this has to do with > ipython/traitlets#39 https://github.com/ipython/traitlets/pull/39 > and/or ipython/traitlets#40 https://github.com/ipython/traitlets/pull/40 > though I haven't actually tested it. I tried giving the user trait a > default value but it did not seem to fix the error. I will try to do a bit > more debugging, but I fear I don't really understand the internals of > traitlets well enough to know exactly what's going on here. > > Ping @takluyver https://github.com/takluyver and @minrk > https://github.com/minrk ? > > — > Reply to this email directly or view it on GitHub > https://github.com/jupyter/jupyterhub/issues/262. Ok, thanks. Not a huge rush for me -- it's not a crucial part of nbgrader and I've marked my failing tests as xfail for now -- but it does seem like it's causing trouble for other people using jupyterhub. I'm getting the same error trying to login to a local server I am getting the following error message on a fresh installation: ``` [I 2015-06-24 11:39:48.334 JupyterHub app:1020] JupyterHub is now running at http://192.168.178.54:8000/ [I 2015-06-24 11:40:11.808 JupyterHub spawner:359] Spawning jupyterhub-singleuser --user=jhub --port=60429 --cookie-name=jupyter-hub-token-jhub --base-url=/user/jhub --hub-prefix=/hub/ --hub-api-url=http://localhost:8081/hub/api --ip=localhost '--notebook-dir=~/notebook/' Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 432, in __get__ value = obj._trait_values[self.name] KeyError: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/bin/jupyterhub-singleuser", line 4, in <module> main() File "/usr/local/lib/python3.4/dist-packages/jupyterhub/singleuser.py", line 221, in main return SingleUserNotebookApp.launch_instance() File "/usr/local/lib/python3.4/dist-packages/IPython/config/application.py", line 573, in launch_instance app.initialize(argv) File "<string>", line 2, in initialize File "/usr/local/lib/python3.4/dist-packages/IPython/config/application.py", line 75, in catch_config_error return method(app, *args, **kwargs) File "/usr/local/lib/python3.4/dist-packages/IPython/html/notebookapp.py", line 1015, in initialize self.init_webapp() File "/usr/local/lib/python3.4/dist-packages/jupyterhub/singleuser.py", line 191, in init_webapp s['user'] = self.user File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 438, in __get__ % (self.name, obj)) traitlets.traitlets.TraitError: No default value found for None trait of <jupyterhub.singleuser.SingleUserNotebookApp object at 0xb72c302c> If you suspect this is an IPython bug, please report it at: https://github.com/ipython/ipython/issues or send an email to the mailing list at [email protected] You can print a more detailed traceback right now with "%tb", or use "%debug" to interactively debug it. Extra-detailed tracebacks for bug-reporting purposes can be enabled via: c.Application.verbose_crash=True 11:40:14.820 - error: [ConfigProxy] Proxy error: code=ECONNRESET [I 2015-06-24 11:40:14.830 JupyterHub log:100] 302 GET / (@192.168.178.39) 4.76ms [I 2015-06-24 11:40:14.836 JupyterHub log:100] 302 GET /hub (@192.168.178.39) 0.92ms [I 2015-06-24 11:40:14.849 JupyterHub log:100] 302 GET /hub/ ([email protected]) 3.92ms [I 2015-06-24 11:40:14.856 JupyterHub log:100] 302 GET /user/jhub (@192.168.178.39) 1.07ms [I 2015-06-24 11:40:14.888 JupyterHub log:100] 200 GET /hub/user/jhub ([email protected]) 23.65ms [W 2015-06-24 11:40:21.821 JupyterHub base:264] User jhub server is slow to start [I 2015-06-24 11:40:21.831 JupyterHub log:100] 302 GET /hub/user/jhub ([email protected]) 10040.55ms ^C Interrupted [I 2015-06-24 11:40:23.357 JupyterHub app:889] Cleaning up single-user servers... [I 2015-06-24 11:40:23.361 JupyterHub app:900] Cleaning up proxy[13700]... [I 2015-06-24 11:40:23.361 JupyterHub app:926] ...done ``` Is this connected to this issue? It appears the issue comes from the `BaseDescriptor` class defaulting `name` to `None` and the `KeyError` exception not acoccunting for a `None`. I'll see if I can generate a pull request on the traitlets project covering it Yeah, it seemed to me like it had to do with `name` not ever being set -- but I should think that it would be set in this case, because based on my understanding of traitlets, `name` should always be set if the trait is an attribute of an object that inherits from `HasTraits`. But I don't know why it's not being set, then, because `SingleUserNotebookApp` does inherit from `HasTraits` -- and when I looked at the traitlets source, I couldn't actually find any instances of `name` being set anywhere. I think there is probably some fancy metaclass magic going on somewhere that sets it, but at least at 2am last night I was unable to track it down :-) I thought it might be that the `KeyError` handler has no check for the `allow_none` property which should disallow `None` by default. I could be totally wrong, this traitlets rabbit hole appears to be deeper than first glance. no luck so far, need sleep. Might continue to chase this down tomorrow if there is no progress.
2015-06-24T15:48:14Z
[]
[]
jupyterhub/jupyterhub
296
jupyterhub__jupyterhub-296
[ "295" ]
a1a10be747046bc45acb720db04389959ee70fac
diff --git a/jupyterhub/auth.py b/jupyterhub/auth.py --- a/jupyterhub/auth.py +++ b/jupyterhub/auth.py @@ -8,7 +8,7 @@ from subprocess import check_call, check_output, CalledProcessError from tornado import gen -import simplepam +import pamela from traitlets.config import LoggingConfigurable from traitlets import Bool, Set, Unicode, Any @@ -208,10 +208,11 @@ def authenticate(self, handler, data): username = data['username'] if not self.check_whitelist(username): return - # simplepam wants bytes, not unicode - # see simplepam#3 - busername = username.encode(self.encoding) - bpassword = data['password'].encode(self.encoding) - if simplepam.authenticate(busername, bpassword, service=self.service): + try: + pamela.authenticate(username, data['password'], service=self.service) + pamela.open_session(username, service=self.service) + except pamela.PAMError as e: + self.log.warn("PAM Authentication failed: %s", e) + else: return username
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -18,16 +18,18 @@ from ..auth import PAMAuthenticator from .. import orm +from pamela import PAMError + def mock_authenticate(username, password, service='login'): - # mimic simplepam's failure to handle unicode - if isinstance(username, str): - return False - if isinstance(password, str): - return False - # just use equality for testing if password == username: return True + else: + raise PAMError("Fake") + + +def mock_open_session(username, service): + pass class MockSpawner(LocalProcessSpawner): @@ -80,7 +82,9 @@ def system_user_exists(self, user): return not user.name.startswith('dne') def authenticate(self, *args, **kwargs): - with mock.patch('simplepam.authenticate', mock_authenticate): + with mock.patch.multiple('pamela', + authenticate=mock_authenticate, + open_session=mock_open_session): return super(MockPAMAuthenticator, self).authenticate(*args, **kwargs) class MockHub(JupyterHub):
PAM/AD auth doesn't create homedir on first login So from what i can see in auth.py, the 'login' pam service is used to authenticate the user. For some reason I don't think the 'session' part of this service is honoured. I've tested this by using pamtester with the login service (see below) and the home directory is created. pamtester login <username> open_session close_session Any idea why this may be? I think it has something to do with the simplepam python module functionality but i'm not certain. any help is appreciated. Cheers
I'm not sure what would be different, but I will try to investigate. Hey, chers for quick reply. Done a bit of digging and it seems like the simple pam module doesn't implement any PAM arguemnts (open/close session as stated above). I have however found a modified module here - https://github.com/gnosek/python-pam. If you take a look at pam.py, you'll notice the implementation of a handle for passing raw PAM arguments, such as open session/close session. If these were implemented, then home directory creation of the 'login' service would be honoured. However, I don't think this is an issue with jupyterhub as such. It seems to me like the simplepam module in python doesn't allow this functionality... Just to give you a bit of background on my use of jupyter. I've got a container based jupyter instance that i've implemented in CentOS. Jupyter relies on the home directory for storage of some critical files so if the home directory isn't there then the server wont start after login. I've considered mounting the home directory of the host into the container, however this doesn't really solve the problem. If the use has never logged in to this machine before then they have no home directory and we have the same problem. Any help/advice is much appreciated. I think since containers are becoming more popular now, maybe there is a need for the session information to be used? maybe I'm wrong though.
2015-09-08T12:45:33Z
[]
[]
jupyterhub/jupyterhub
349
jupyterhub__jupyterhub-349
[ "348" ]
8d90a92ef3323c74f6f631650aba9dfe622245e0
diff --git a/jupyterhub/auth.py b/jupyterhub/auth.py --- a/jupyterhub/auth.py +++ b/jupyterhub/auth.py @@ -4,8 +4,11 @@ # Distributed under the terms of the Modified BSD License. from grp import getgrnam +import pipes import pwd -from subprocess import check_call, check_output, CalledProcessError +from shutil import which +import sys +from subprocess import check_call from tornado import gen import pamela @@ -15,6 +18,7 @@ from .handlers.login import LoginHandler from .utils import url_path_join +from .traitlets import Command class Authenticator(LoggingConfigurable): """A class for authentication. @@ -123,17 +127,36 @@ class LocalAuthenticator(Authenticator): should I try to create the system user? """ ) - system_user_home = Unicode('', config=True, - help="""Specify root home directory for users if different from system default. + add_user_cmd = Command(config=True, + help="""The command to use for creating users as a list of strings. - Passed to `useradd -b`. - If specified, when system users are created their home directories will be created in + For each element in the list, the string USERNAME will be replaced with + the user's username. The username will also be appended as the final argument. - system_user_home/username + For Linux, the default value is: - Only has an effect when users are created with `create_system_users=True`. + ['adduser', '-q', '--gecos', '""', '--disabled-password'] + + To specify a custom home directory, set this to: + + ['adduser', '-q', '--gecos', '""', '--home', '/customhome/USERNAME', '--disabled-password'] + + This will run the command: + + adduser -q --gecos "" --home /customhome/river --disabled-password river + + when the user 'river' is created. """ ) + def _add_user_cmd_default(self): + if sys.platform == 'darwin': + raise ValueError("I don't know how to create users on OS X") + elif which('pw'): + # Probably BSD + return ['pw', 'useradd', '-m'] + else: + # This appears to be the Linux non-interactive adduser command: + return ['adduser', '-q', '--gecos', '""', '--disabled-password'] group_whitelist = Set( config=True, @@ -196,23 +219,9 @@ def system_user_exists(user): def add_system_user(self, user): """Create a new *ix user on the system. Works on FreeBSD and Linux, at least.""" name = user.name - for useradd in ( - ['pw', 'useradd', '-m'], - ['useradd', '-m'], - ): - try: - check_output(['which', useradd[0]]) - except CalledProcessError: - continue - else: - break - else: - raise RuntimeError("I don't know how to add users on this system.") - - cmd = useradd - if self.system_user_home: - cmd = cmd + ['-b', self.system_user_home] - check_call(cmd + [name]) + cmd = [ arg.replace('USERNAME', name) for arg in self.add_user_cmd ] + [name] + self.log.info("Creating user: %s", ' '.join(map(pipes.quote, cmd))) + check_call(cmd) class PAMAuthenticator(LocalAuthenticator):
diff --git a/jupyterhub/tests/test_auth.py b/jupyterhub/tests/test_auth.py --- a/jupyterhub/tests/test_auth.py +++ b/jupyterhub/tests/test_auth.py @@ -93,13 +93,14 @@ def test_wont_add_system_user(io_loop): def test_cant_add_system_user(io_loop): user = orm.User(name='lioness4321') authenticator = auth.PAMAuthenticator(whitelist={'mal'}) + authenticator.add_user_cmd = ['jupyterhub-fake-command'] authenticator.create_system_users = True - def check_output(cmd, *a, **kw): + def check_call(cmd, *a, **kw): raise CalledProcessError(1, cmd) - with mock.patch.object(auth, 'check_output', check_output): - with pytest.raises(RuntimeError): + with mock.patch.object(auth, 'check_call', check_call): + with pytest.raises(CalledProcessError): io_loop.run_sync(lambda : authenticator.add_user(user)) @@ -107,19 +108,15 @@ def test_add_system_user(io_loop): user = orm.User(name='lioness4321') authenticator = auth.PAMAuthenticator(whitelist={'mal'}) authenticator.create_system_users = True - - def check_output(*a, **kw): - return + authenticator.add_user_cmd = ['echo', '/home/USERNAME'] record = {} def check_call(cmd, *a, **kw): record['cmd'] = cmd - with mock.patch.object(auth, 'check_output', check_output), \ - mock.patch.object(auth, 'check_call', check_call): + with mock.patch.object(auth, 'check_call', check_call): io_loop.run_sync(lambda : authenticator.add_user(user)) - - assert user.name in record['cmd'] + assert record['cmd'] == ['echo', '/home/lioness4321', 'lioness4321'] def test_delete_user(io_loop):
Default shell to bash Right now, if users are created by jupyterhub with useradd on a stock Ubuntu, there is no default shell. This leads to `/bin/sh` being used rather than bash. When the web terminal is opened all readline related actions (tab, up, down) don't work. I know I can configure this in `/etc/default/useradd`, but we jut added an option to set the home directory base path. Should we default the shell to bash in the useradd CLI call? Maybe add an config option that defaults to `/bin/bash`. This behavior means that a pretty standard config on Ubuntu will have a (slightly) broken terminal. I could have sworn that we did something on this previously, when I was debugging things with my Active Directory setup where `SHELL` wasn't being set. But I don't remember what we ended up doing (I may have just set it myself). Thoughts?
I think the previous bug had to do with how the user's shell was looked up, not how it is set initially, so that would have been slightly different, but I'm not 100% sure. I think the problem may be that we are using `useradd` instead of `adduser`, which has different defaults. When I create a user with `adduser`, the default shell is bash. For reference, the non-interactive `adduser` call is: ``` adduser -q --gecos "" --disabled-password new2 ``` (and totally different on BSD, of course) We could also add a `useradd_args`, so that all args are exposed. I would prefer not to add a configurable for every option, so a passthrough to useradd (or adduser) would be the easiest way to make sure you can set whatever you need. Min, thanks for the thoughtful response. I think the problem may be that we are using useradd instead of adduser, > which has different defaults. When I create a user with adduser, the > default shell is bash. > > For reference, the non-interactive adduser call is: > > adduser -q --gecos "" --disabled-password new2 > > I had a look at the config for adduser and it does look a bit more sane > that useradd. It is also equally easy to configure using the config file. > > (and totally different on BSD, of course) > > We could also add a useradd_args, so that all args are exposed. I would > prefer not to add a configurable for every option, so a passthrough to > useradd (or adduser) would be the easiest way to make sure you can set > whatever you need. > > What about using adduser so the defaults are a bit more sane and then > adding a adduser_args that is string valued to provide extra flags? Or, another option that would address the BSD difference would be to have a single command for user creation that is templated by the username, with a default like: 'adduser -q --gecos "" --disabled-password {username}' That would be the most flexible and have pretty sane default behavior. I almost like that best as it makes it easy to get working for other setups as well. > — > Reply to this email directly or view it on GitHub > https://github.com/jupyter/jupyterhub/issues/348#issuecomment-163048387. ## Brian E. Granger Associate Professor of Physics and Data Science Cal Poly State University, San Luis Obispo @ellisonbg on Twitter and GitHub [email protected] and [email protected] > What about using adduser so the defaults are a bit more sane and then adding a adduser_args that is string valued to provide extra flags? I think that's the most sensible. Possibly with an escape hatch for producing the complete command.
2015-12-10T22:23:46Z
[]
[]
jupyterhub/jupyterhub
353
jupyterhub__jupyterhub-353
[ "271" ]
aa529f3aba24b85ecb388ddbce1581c7392ba348
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -50,7 +50,7 @@ from .log import CoroutineLogFormatter, log_request from .traitlets import URLPrefix, Command from .utils import ( - url_path_join, + url_path_join, localhost, ISO8601_ms, ISO8601_s, ) # classes for config @@ -260,7 +260,7 @@ def _proxy_auth_token_default(self): token = orm.new_token() return token - proxy_api_ip = Unicode('localhost', config=True, + proxy_api_ip = Unicode(localhost(), config=True, help="The ip for the proxy API handlers" ) proxy_api_port = Integer(config=True, @@ -272,7 +272,7 @@ def _proxy_api_port_default(self): hub_port = Integer(8081, config=True, help="The port for this process" ) - hub_ip = Unicode('localhost', config=True, + hub_ip = Unicode(localhost(), config=True, help="The ip for this process" ) diff --git a/jupyterhub/orm.py b/jupyterhub/orm.py --- a/jupyterhub/orm.py +++ b/jupyterhub/orm.py @@ -26,7 +26,7 @@ from .utils import ( random_port, url_path_join, wait_for_server, wait_for_http_server, - new_token, hash_token, compare_token, + new_token, hash_token, compare_token, localhost, ) @@ -78,7 +78,7 @@ def host(self): ip = self.ip if ip in {'', '0.0.0.0'}: # when listening on all interfaces, connect to localhost - ip = 'localhost' + ip = localhost() return "{proto}://{ip}:{port}".format( proto=self.proto, ip=ip, @@ -109,12 +109,12 @@ def wait_up(self, timeout=10, http=False): if http: yield wait_for_http_server(self.url, timeout=timeout) else: - yield wait_for_server(self.ip or 'localhost', self.port, timeout=timeout) + yield wait_for_server(self.ip or localhost(), self.port, timeout=timeout) def is_up(self): """Is the server accepting connections?""" try: - socket.create_connection((self.ip or 'localhost', self.port)) + socket.create_connection((self.ip or localhost(), self.port)) except socket.error as e: if e.errno == errno.ECONNREFUSED: return False diff --git a/jupyterhub/spawner.py b/jupyterhub/spawner.py --- a/jupyterhub/spawner.py +++ b/jupyterhub/spawner.py @@ -22,7 +22,7 @@ ) from .traitlets import Command -from .utils import random_port +from .utils import random_port, localhost class Spawner(LoggingConfigurable): """Base class for spawning single-user notebook servers. @@ -41,7 +41,7 @@ class Spawner(LoggingConfigurable): hub = Any() authenticator = Any() api_token = Unicode() - ip = Unicode('localhost', config=True, + ip = Unicode(localhost(), config=True, help="The IP address (or hostname) the single-user server should listen on" ) start_timeout = Integer(60, config=True, diff --git a/jupyterhub/utils.py b/jupyterhub/utils.py --- a/jupyterhub/utils.py +++ b/jupyterhub/utils.py @@ -6,10 +6,12 @@ from binascii import b2a_hex import errno import hashlib +from hmac import compare_digest import os import socket +from threading import Thread import uuid -from hmac import compare_digest +import warnings from tornado import web, gen, ioloop from tornado.httpclient import AsyncHTTPClient, HTTPError @@ -192,3 +194,36 @@ def url_path_join(*pieces): result = '/' return result + +def localhost(): + """Return localhost or 127.0.0.1""" + if hasattr(localhost, '_localhost'): + return localhost._localhost + binder = connector = None + try: + binder = socket.socket() + binder.bind(('localhost', 0)) + binder.listen(1) + port = binder.getsockname()[1] + def accept(): + try: + conn, addr = binder.accept() + except ConnectionAbortedError: + pass + else: + conn.close() + t = Thread(target=accept) + t.start() + connector = socket.create_connection(('localhost', port), timeout=10) + t.join(timeout=10) + except (socket.error, socket.gaierror) as e: + warnings.warn("localhost doesn't appear to work, using 127.0.0.1\n%s" % e, RuntimeWarning) + localhost._localhost = '127.0.0.1' + else: + localhost._localhost = 'localhost' + finally: + if binder: + binder.close() + if connector: + connector.close() + return localhost._localhost
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -17,6 +17,7 @@ from ..app import JupyterHub from ..auth import PAMAuthenticator from .. import orm +from ..utils import localhost from pamela import PAMError @@ -93,7 +94,7 @@ class MockHub(JupyterHub): db_file = None def _ip_default(self): - return 'localhost' + return localhost() def _authenticator_class_default(self): return MockPAMAuthenticator
server works well as local host but fails to 'start proxy' Can you help me diagnose, this was working initially, but broke once i had some issues trying to get docker spawner working. now it is not working with its default configuration. ``` [I 2015-07-10 21:53:18.643 JupyterHub app:619] Not using whitelist. Any authenticated user will be allowed. [I 2015-07-10 21:53:18.664 JupyterHub app:997] Hub API listening on http://localhost:8081/hub/ [I 2015-07-10 21:53:18.670 JupyterHub app:754] Starting proxy @ http://*:8000/ 21:53:18.834 - info: [ConfigProxy] Proxying http://*:8000 to http://localhost:8081 21:53:18.838 - info: [ConfigProxy] Proxy API at http://localhost:8001/api/routes events.js:72 throw er; // Unhandled 'error' event ^ Error: getaddrinfo ENOTFOUND at errnoException (dns.js:37:11) at Object.onanswer [as oncomplete] (dns.js:124:16) [C 2015-07-10 21:53:19.686 JupyterHub app:1003] Failed to start proxy Traceback (most recent call last): File "/home/gpillemer/jupyterhub/dockerspawner/src/jupyterhub/jupyterhub/app.py", line 1001, in start yield self.start_proxy() File "/home/gpillemer/jupyterhub/dockerspawner/src/jupyterhub/jupyterhub/app.py", line 775, in start_proxy _check() File "/home/gpillemer/jupyterhub/dockerspawner/src/jupyterhub/jupyterhub/app.py", line 771, in _check raise e RuntimeError: Proxy failed to start with exit code 8 [gpillemer@cloud-server-16 jupyterhub]$ ```
Can you share your jupyter config? It loots like it's trying to bind to an invalid address. thanks - i was actually trying to start the server with --ip='*', which i use with the ipython noteboiok starting it and specifying the ip, i.e ip=xx.xx.xxx.xx works perfectly. thanks I am getting a similar error - works well on locally, but with proxy. Any pointers on what might be going on? [I 2015-10-02 08:08:45.461 JupyterHub app:1031] Hub API listening on http://localhost:8081/hub/ [C 2015-10-02 08:10:52.627 JupyterHub app:1037] Failed to start proxy Traceback (most recent call last): File "/home/ubuntu/pkgs/jupyterhub/jupyterhub/app.py", line 1035, in start yield self.start_proxy() File "/home/ubuntu/pkgs/jupyterhub/jupyterhub/app.py", line 755, in start_proxy if self.proxy.public_server.is_up() or self.proxy.api_server.is_up(): File "/home/ubuntu/pkgs/jupyterhub/jupyterhub/orm.py", line 118, in is_up socket.create_connection((self.ip or 'localhost', self.port)) File "/usr/lib/python3.4/socket.py", line 512, in create_connection raise err File "/usr/lib/python3.4/socket.py", line 503, in create_connection sock.connect(sa) TimeoutError: [Errno 110] Connection timed out I have the same / similar issue. Did you ever figure it out? [I 2015-12-11 22:53:37.322 JupyterHub app:1031] Hub API listening on http://abc.com:8081/hub/ [C 2015-12-11 22:53:37.324 JupyterHub app:1037] Failed to start proxy Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/jupyterhub/app.py", line 1035, in start yield self.start_proxy() File "/usr/lib/python3.5/site-packages/jupyterhub/app.py", line 755, in start_proxy if self.proxy.public_server.is_up() or self.proxy.api_server.is_up(): File "/usr/lib/python3.5/site-packages/jupyterhub/orm.py", line 118, in is_up socket.create_connection((self.ip or 'localhost', self.port)) File "/usr/lib64/python3.5/socket.py", line 707, in create_connection raise err File "/usr/lib64/python3.5/socket.py", line 698, in create_connection sock.connect(sa) OSError: [Errno 101] Network is unreachable Are you using a DNS name for the proxy or an IP address? DNS name. On Mon, Dec 14, 2015, 5:57 AM Min RK [email protected] wrote: > Are you using a DNS name for the proxy or an IP address? > > — > Reply to this email directly or view it on GitHub > https://github.com/jupyter/jupyterhub/issues/271#issuecomment-164408871. It looks like the DNS name isn't getting handled properly. Can you `curl` anything from that URL from where the Hub is running? It is all running on one server. I did run a python http server on it with no problem. But anyhow I will also try it with ip and report back in 2 hours. On Mon, Dec 14, 2015, 7:40 AM Min RK [email protected] wrote: > It looks like the DNS name isn't getting handled properly. Can you curl > anything from that URL from where the Hub is running? > > — > Reply to this email directly or view it on GitHub > https://github.com/jupyter/jupyterhub/issues/271#issuecomment-164427177. I have switched to IP, but unfortunately the issue is the exact same. I do code a lot in Python and I have a feeling that this is the usual Python proxy issue - namely that when you have proxy settings in the user profile in unix to access the internet then Python's socket library automatically picks that up and tries to send all traffic to that proxy, even the local ones. I will test and make changes to the code to verify, but if it turns out to be this, then that will likely require some code change to correct. [I 2015-12-14 14:34:39.763 JupyterHub app:1031] Hub API listening on http://10.xx.xx.xx:8081/hub/ [C 2015-12-14 14:34:39.766 JupyterHub app:1037] Failed to start proxy Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/jupyterhub/app.py", line 1035, in start yield self.start_proxy() File "/usr/lib/python3.5/site-packages/jupyterhub/app.py", line 755, in start_proxy if self.proxy.public_server.is_up() or self.proxy.api_server.is_up(): File "/usr/lib/python3.5/site-packages/jupyterhub/orm.py", line 118, in is_up socket.create_connection((self.ip or 'localhost', self.port)) File "/usr/lib64/python3.5/socket.py", line 707, in create_connection raise err File "/usr/lib64/python3.5/socket.py", line 698, in create_connection sock.connect(sa) OSError: [Errno 101] Network is unreachable I have managed to resolve this. I had created the jupyterhub_config.py file (instead of supplying server ip / server name as command line parameter) and set the proxy_api_ip, ip, and hub_ip to the same ip address, the ip of the server and now it starts fine. [I 2015-12-14 16:18:35.002 JupyterHub app:1031] Hub API listening on http://10.xx.xx.xx:8081/hub/ [I 2015-12-14 16:18:35.006 JupyterHub app:788] Starting proxy @ http://10.xx.xx.xx:8000/ 16:18:35.116 - info: [ConfigProxy] Proxying http://10.xx.xx.xx:8000 to http://10.xx.xx.xx:8081 16:18:35.118 - info: [ConfigProxy] Proxy API at http://10.xx.xx.xx:8001/api/routes [I 2015-12-14 16:18:35.211 JupyterHub app:1054] JupyterHub is now running at http://10.xx.xx.xx:8000/ Now it has another problem - when connecting tot he spawned instance. I guess because it is spawing with "--ip=localhost" instead of "--ip=[IP]". Any idea where to change this in the config. I have already set he proxy_api_ip, ip and hub_ip in the config to the actual server ip. [I 2015-12-14 16:24:06.545 JupyterHub log:100] 200 GET /hub/login (@10.xx.xx.45) 21.80ms [I 2015-12-14 16:24:13.138 JupyterHub spawner:363] Spawning jupyterhub-singleuser --user=zoltan.fedor --port=38020 --cookie-name=jupyter-hub-token-zoltan.fedor --base-url=/user/zoltan.fedor --hub-prefix=/hub/ --hub-api-url=http://10.xx.xx.xx.9:80/hub/api --ip=localhost [W 2015-12-14 16:24:13.188 JupyterHub utils:76] Failed to connect to http://localhost:38020/user/zoltan.fedor ([Errno 101] Network is unreachable) Found it, c.Spawner.ip @zoltan-fedor so it looks like `localhost` is broken on your machine. Any idea as to what might be the cause of that? We've seen it reported intermittently, but I haven't been able to work out the cause. It seems like a pretty significant problem in the local system configuration.
2015-12-15T13:37:39Z
[]
[]
jupyterhub/jupyterhub
364
jupyterhub__jupyterhub-364
[ "362" ]
0fbd69be9bfc584e6c7d7613f517886ae7993b51
diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -71,7 +71,7 @@ def get(self): self.finish(html) else: # not running, no form. Trigger spawn. - url = url_path_join(self.base_url, 'users', user.name) + url = url_path_join(self.base_url, 'user', user.name) self.redirect(url) @web.authenticated
diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -1,5 +1,7 @@ """Tests for HTML pages""" +from urllib.parse import urlparse + import requests from ..utils import url_path_join as ujoin @@ -7,6 +9,7 @@ import mock from .mocking import FormSpawner +from .test_api import api_request def get_page(path, app, **kw): @@ -59,10 +62,34 @@ def test_admin(app): r.raise_for_status() assert r.url.endswith('/admin') -def test_spawn_redirect(app): - cookies = app.login_user('wash') +def test_spawn_redirect(app, io_loop): + name = 'wash' + cookies = app.login_user(name) + u = app.users[orm.User.find(app.db, name)] + + # ensure wash's server isn't running: + r = api_request(app, 'users', name, 'server', method='delete', cookies=cookies) + r.raise_for_status() + status = io_loop.run_sync(u.spawner.poll) + assert status is not None + + # test spawn page when no server is running r = get_page('spawn', app, cookies=cookies) - assert r.url.endswith('/wash') + r.raise_for_status() + print(urlparse(r.url)) + path = urlparse(r.url).path + assert path == '/user/%s' % name + + # should have started server + status = io_loop.run_sync(u.spawner.poll) + assert status is None + + # test spawn page when server is already running (just redirect) + r = get_page('spawn', app, cookies=cookies) + r.raise_for_status() + print(urlparse(r.url)) + path = urlparse(r.url).path + assert path == '/user/%s' % name def test_spawn_page(app): with mock.patch.dict(app.users.settings, {'spawner_class': FormSpawner}):
404 on single user notebook server anytime I restart jupyterhub I just deployed jupyterhub from scratch using my ansible scripts this morning. The script are unchanged from 2-3 weeks ago when I did it previously and it was all working. I am running from latest master of jupyterhub. Anytime I restart jupyterhub (hub+proxy) I see the following behavior: - I can log in (using GitHub OAuth) - Trying to start my server gives me a 404 on `/hub/users/ellisonbg`. I can tell from the server log that the single user server isn't being started. - I can go to the Admin page and start my server from there. - But then, I get a redirect loop when I try to go to my single user server. - If I clear all my cookies while my single user server (started through the Admin page) is still running, it starts to work as expected. I can start and stop the single user server on the control panel page just fine. - If a restart jupyterhub, the problems start all over again. I am using a fixed proxy_auth_token and cookie secret.
OK tracking this down a bit: In this line of code there is a redirect to a URL that has `users` in it: https://github.com/jupyter/jupyterhub/blob/master/jupyterhub/handlers/pages.py#L74 But I don't see any handlers targeting URLs with `users`. I do, however, see one that targets `users` (singular) here: https://github.com/jupyter/jupyterhub/blob/master/jupyterhub/handlers/base.py#L482 Looks like this is a bug that crept in in the recent spawner form work. I will pin my work to a hash that is before that work for now. More than willing to test fixes for this though. I just installed this SHA: https://github.com/jupyter/jupyterhub/commit/2f1a2036999cd5ab02a720af62ea698645d2a8b5 and everything works fine. This doesn't explain exactly what the problem is, but it does bisect it to the recent spawner work. HTH! Thanks! I know what's going wrong, just need to figure out why...
2015-12-31T11:06:46Z
[]
[]
jupyterhub/jupyterhub
373
jupyterhub__jupyterhub-373
[ "369" ]
8a5a85a489b204a1168418bd0d6cbc11f7c1615c
diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -33,13 +33,25 @@ def post(self): admin = data.get('admin', False) to_create = [] + invalid_names = [] for name in usernames: + name = self.authenticator.normalize_username(name) + if not self.authenticator.validate_username(name): + invalid_names.append(name) + continue user = self.find_user(name) if user is not None: self.log.warn("User %s already exists" % name) else: to_create.append(name) + if invalid_names: + if len(invalid_names) == 1: + msg = "Invalid username: %s" % invalid_names[0] + else: + msg = "Invalid usernames: %s" % ', '.join(invalid_names) + raise web.HTTPError(400, msg) + if not to_create: raise web.HTTPError(400, "All %i users already exist" % len(usernames)) @@ -51,10 +63,10 @@ def post(self): self.db.commit() try: yield gen.maybe_future(self.authenticator.add_user(user)) - except Exception: + except Exception as e: self.log.error("Failed to create user: %s" % name, exc_info=True) del self.users[user] - raise web.HTTPError(400, "Failed to create user: %s" % name) + raise web.HTTPError(400, "Failed to create user %s: %s" % (name, str(e))) else: created.append(user) diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -630,7 +630,13 @@ def init_users(self): "\nUse Authenticator.admin_users instead." ) self.authenticator.admin_users = self.admin_users - admin_users = self.authenticator.admin_users + admin_users = [ + self.authenticator.normalize_username(name) + for name in self.authenticator.admin_users + ] + for username in admin_users: + if not self.authenticator.validate_username(username): + raise ValueError("username %r is not valid" % username) if not admin_users: self.log.warning("No admin users, admin interface will be unavailable.") @@ -651,7 +657,13 @@ def init_users(self): # the admin_users config variable will never be used after this point. # only the database values will be referenced. - whitelist = self.authenticator.whitelist + whitelist = [ + self.authenticator.normalize_username(name) + for name in self.authenticator.whitelist + ] + for username in whitelist: + if not self.authenticator.validate_username(username): + raise ValueError("username %r is not valid" % username) if not whitelist: self.log.info("Not using whitelist. Any authenticated user will be allowed.") @@ -671,7 +683,7 @@ def init_users(self): # but changes to the whitelist can occur in the database, # and persist across sessions. for user in db.query(orm.User): - whitelist.add(user.name) + self.authenticator.whitelist.add(user.name) # The whitelist set and the users in the db are now the same. # From this point on, any user changes should be done simultaneously diff --git a/jupyterhub/auth.py b/jupyterhub/auth.py --- a/jupyterhub/auth.py +++ b/jupyterhub/auth.py @@ -6,15 +6,16 @@ from grp import getgrnam import pipes import pwd +import re from shutil import which import sys -from subprocess import check_call +from subprocess import Popen, PIPE, STDOUT from tornado import gen import pamela from traitlets.config import LoggingConfigurable -from traitlets import Bool, Set, Unicode, Any +from traitlets import Bool, Set, Unicode, Dict, Any from .handlers.login import LoginHandler from .utils import url_path_join @@ -53,6 +54,88 @@ class Authenticator(LoggingConfigurable): """ ) + username_pattern = Unicode(config=True, + help="""Regular expression pattern for validating usernames. + + If not defined: allow any username. + """ + ) + def _username_pattern_changed(self, name, old, new): + if not new: + self.username_regex = None + self.username_regex = re.compile(new) + + username_regex = Any() + + def validate_username(self, username): + """Validate a (normalized) username. + + Return True if username is valid, False otherwise. + """ + if not self.username_regex: + return True + return bool(self.username_regex.match(username)) + + username_map = Dict(config=True, + help="""Dictionary mapping authenticator usernames to JupyterHub users. + + Can be used to map OAuth service names to local users, for instance. + + Used in normalize_username. + """ + ) + + def normalize_username(self, username): + """Normalize a username. + + Override in subclasses if usernames should have some normalization. + Default: cast to lowercase, lookup in username_map. + """ + username = username.lower() + username = self.username_map.get(username, username) + return username + + def check_whitelist(self, username): + """Check a username against our whitelist. + + Return True if username is allowed, False otherwise. + No whitelist means any username should be allowed. + + Names are normalized *before* being checked against the whitelist. + """ + if not self.whitelist: + # No whitelist means any name is allowed + return True + return username in self.whitelist + + @gen.coroutine + def get_authenticated_user(self, handler, data): + """This is the outer API for authenticating a user. + + This calls `authenticate`, which should be overridden in subclasses, + normalizes the username if any normalization should be done, + and then validates the name in the whitelist. + + Subclasses should not need to override this method. + The various stages can be overridden separately: + + - authenticate turns formdata into a username + - normalize_username normalizes the username + - check_whitelist checks against the user whitelist + """ + username = yield self.authenticate(handler, data) + if username is None: + return + username = self.normalize_username(username) + if not self.validate_username(username): + self.log.warning("Disallowing invalid username %r.", username) + return + if self.check_whitelist(username): + return username + else: + self.log.warning("User %r not in whitelist.", username) + return + @gen.coroutine def authenticate(self, handler, data): """Authenticate a user with login form data. @@ -60,6 +143,8 @@ def authenticate(self, handler, data): This must be a tornado gen.coroutine. It must return the username on successful authentication, and return None on failed authentication. + + Checking the whitelist is handled separately by the caller. """ def pre_spawn_start(self, user, spawner): @@ -74,13 +159,6 @@ def post_spawn_stop(self, user, spawner): Can be used to do auth-related cleanup, e.g. closing PAM sessions. """ - def check_whitelist(self, user): - """ - Return True if the whitelist is empty or user is in the whitelist. - """ - # Parens aren't necessary here, but they make this easier to parse. - return (not self.whitelist) or (user in self.whitelist) - def add_user(self, user): """Add a new user @@ -89,6 +167,8 @@ def add_user(self, user): Subclasses may do more extensive things, such as adding actual unix users. """ + if not self.validate_username(user.name): + raise ValueError("Invalid username: %s" % user.name) if self.whitelist: self.whitelist.add(user.name) @@ -192,10 +272,7 @@ def check_group_whitelist(self, username): def add_user(self, user): """Add a new user - By default, this just adds the user to the whitelist. - - Subclasses may do more extensive things, - such as adding actual unix users. + If self.create_system_users, the user will attempt to be created. """ user_exists = yield gen.maybe_future(self.system_user_exists(user)) if not user_exists: @@ -221,7 +298,11 @@ def add_system_user(self, user): name = user.name cmd = [ arg.replace('USERNAME', name) for arg in self.add_user_cmd ] + [name] self.log.info("Creating user: %s", ' '.join(map(pipes.quote, cmd))) - check_call(cmd) + p = Popen(cmd, stdout=PIPE, stderr=STDOUT) + p.wait() + if p.returncode: + err = p.stdout.read().decode('utf8', 'replace') + raise RuntimeError("Failed to create system user %s: %s" % (name, err)) class PAMAuthenticator(LocalAuthenticator): @@ -240,8 +321,6 @@ def authenticate(self, handler, data): Return None otherwise. """ username = data['username'] - if not self.check_whitelist(username): - return try: pamela.authenticate(username, data['password'], service=self.service) except pamela.PAMError as e: diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -247,7 +247,7 @@ def set_login_cookie(self, user): def authenticate(self, data): auth = self.authenticator if auth is not None: - result = yield auth.authenticate(self, data) + result = yield auth.get_authenticated_user(self, data) return result else: self.log.error("No authentication function, login is impossible!")
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -209,6 +209,17 @@ def test_add_multi_user_bad(app): r = api_request(app, 'users', method='post', data='[]') assert r.status_code == 400 + +def test_add_multi_user_invalid(app): + app.authenticator.username_pattern = r'w.*' + r = api_request(app, 'users', method='post', + data=json.dumps({'usernames': ['Willow', 'Andrew', 'Tara']}) + ) + app.authenticator.username_pattern = '' + assert r.status_code == 400 + assert r.json()['message'] == 'Invalid usernames: andrew, tara' + + def test_add_multi_user(app): db = app.db names = ['a', 'b'] diff --git a/jupyterhub/tests/test_auth.py b/jupyterhub/tests/test_auth.py --- a/jupyterhub/tests/test_auth.py +++ b/jupyterhub/tests/test_auth.py @@ -3,7 +3,6 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. -from subprocess import CalledProcessError from unittest import mock import pytest @@ -13,13 +12,13 @@ def test_pam_auth(io_loop): authenticator = MockPAMAuthenticator() - authorized = io_loop.run_sync(lambda : authenticator.authenticate(None, { + authorized = io_loop.run_sync(lambda : authenticator.get_authenticated_user(None, { 'username': 'match', 'password': 'match', })) assert authorized == 'match' - authorized = io_loop.run_sync(lambda : authenticator.authenticate(None, { + authorized = io_loop.run_sync(lambda : authenticator.get_authenticated_user(None, { 'username': 'match', 'password': 'nomatch', })) @@ -27,19 +26,19 @@ def test_pam_auth(io_loop): def test_pam_auth_whitelist(io_loop): authenticator = MockPAMAuthenticator(whitelist={'wash', 'kaylee'}) - authorized = io_loop.run_sync(lambda : authenticator.authenticate(None, { + authorized = io_loop.run_sync(lambda : authenticator.get_authenticated_user(None, { 'username': 'kaylee', 'password': 'kaylee', })) assert authorized == 'kaylee' - authorized = io_loop.run_sync(lambda : authenticator.authenticate(None, { + authorized = io_loop.run_sync(lambda : authenticator.get_authenticated_user(None, { 'username': 'wash', 'password': 'nomatch', })) assert authorized is None - authorized = io_loop.run_sync(lambda : authenticator.authenticate(None, { + authorized = io_loop.run_sync(lambda : authenticator.get_authenticated_user(None, { 'username': 'mal', 'password': 'mal', })) @@ -59,14 +58,14 @@ def getgrnam(name): authenticator = MockPAMAuthenticator(group_whitelist={'group'}) with mock.patch.object(auth, 'getgrnam', getgrnam): - authorized = io_loop.run_sync(lambda : authenticator.authenticate(None, { + authorized = io_loop.run_sync(lambda : authenticator.get_authenticated_user(None, { 'username': 'kaylee', 'password': 'kaylee', })) assert authorized == 'kaylee' with mock.patch.object(auth, 'getgrnam', getgrnam): - authorized = io_loop.run_sync(lambda : authenticator.authenticate(None, { + authorized = io_loop.run_sync(lambda : authenticator.get_authenticated_user(None, { 'username': 'mal', 'password': 'mal', })) @@ -75,7 +74,7 @@ def getgrnam(name): def test_pam_auth_no_such_group(io_loop): authenticator = MockPAMAuthenticator(group_whitelist={'nosuchcrazygroup'}) - authorized = io_loop.run_sync(lambda : authenticator.authenticate(None, { + authorized = io_loop.run_sync(lambda : authenticator.get_authenticated_user(None, { 'username': 'kaylee', 'password': 'kaylee', })) @@ -96,12 +95,24 @@ def test_cant_add_system_user(io_loop): authenticator.add_user_cmd = ['jupyterhub-fake-command'] authenticator.create_system_users = True - def check_call(cmd, *a, **kw): - raise CalledProcessError(1, cmd) + class DummyFile: + def read(self): + return b'dummy error' - with mock.patch.object(auth, 'check_call', check_call): - with pytest.raises(CalledProcessError): + class DummyPopen: + def __init__(self, *args, **kwargs): + self.args = args + self.kwargs = kwargs + self.returncode = 1 + self.stdout = DummyFile() + + def wait(self): + return + + with mock.patch.object(auth, 'Popen', DummyPopen): + with pytest.raises(RuntimeError) as exc: io_loop.run_sync(lambda : authenticator.add_user(user)) + assert str(exc.value) == 'Failed to create system user lioness4321: dummy error' def test_add_system_user(io_loop): @@ -111,10 +122,15 @@ def test_add_system_user(io_loop): authenticator.add_user_cmd = ['echo', '/home/USERNAME'] record = {} - def check_call(cmd, *a, **kw): - record['cmd'] = cmd + class DummyPopen: + def __init__(self, cmd, *args, **kwargs): + record['cmd'] = cmd + self.returncode = 0 + + def wait(self): + return - with mock.patch.object(auth, 'check_call', check_call): + with mock.patch.object(auth, 'Popen', DummyPopen): io_loop.run_sync(lambda : authenticator.add_user(user)) assert record['cmd'] == ['echo', '/home/lioness4321', 'lioness4321'] @@ -144,3 +160,37 @@ def test_handlers(app): assert handlers[0][0] == '/login' +def test_normalize_names(io_loop): + a = MockPAMAuthenticator() + authorized = io_loop.run_sync(lambda : a.get_authenticated_user(None, { + 'username': 'ZOE', + 'password': 'ZOE', + })) + assert authorized == 'zoe' + + +def test_username_map(io_loop): + a = MockPAMAuthenticator(username_map={'wash': 'alpha'}) + authorized = io_loop.run_sync(lambda : a.get_authenticated_user(None, { + 'username': 'WASH', + 'password': 'WASH', + })) + + assert authorized == 'alpha' + + authorized = io_loop.run_sync(lambda : a.get_authenticated_user(None, { + 'username': 'Inara', + 'password': 'Inara', + })) + assert authorized == 'inara' + + +def test_validate_names(io_loop): + a = auth.PAMAuthenticator() + assert a.validate_username('willow') + assert a.validate_username('giles') + a = auth.PAMAuthenticator(username_pattern='w.*') + assert not a.validate_username('xander') + assert a.validate_username('willow') + +
Bugs related to usernames Today I ran into a couple of bugs related to usernames on a JupyterHub deployment (GitHub OAuth, automatic user account creation (adduser). - Some students had usernames with CamelCase and other chars `-`. - When I used the Admin pages to add such a user, adduser failed (could see in the logs) because the format didn't match the allowable regexp (Ubuntu 15.04 default). - But, after that failed attempt, adding users with valid usernames also failed, until I restarted the server. Possible steps to take: - Normalize usernames (lowercase, strip other chars). - Add the `--force-badname` option to all `adduser` calls to get the system to accept the usernames. - Better error handling so this error doesn't mess up the servers state like that. - Better error reporting so admins can see what is going on better.
I'm most curious about how one bad name could get it stuck in a bad state that would prevent creating new users. I'm looking into that one now. The other issues probably belong in the LocalGitHubAuthenticator. Fixed the reused user issue in #371. What would you like as an error message in the UI? Should it contain the full traceback, just the error string, or "See server logs for more details"? As for what to do in the LocalGitHubAuth about usernames, I think it was only the camelCase users that caused the problem. When I tested, the hyphens were not considered an issue. Did you see something different? What would you prefer do do about that? I see a few options: 1. normalize to lowercase for _all usernames always_ 2. normalize to lowercase in the base LocalAuthenticator (seems like too much to me) 3. normalize to lowercase always with GitHub OAuth (GitHub usernames are not case sensitive, though they can have a reference case for display) 4. normalize only on LocalGitHubOAuth Any other options? I didn't test to see if names with `-` failed as well. Mainly the camel case. I think the options you describe are pretty comprehensive. I think the main factor I am thinking about is that any Authenticator which can create users: - Should have a clear specification of what types of usernames are allowed. - When the Admin pane is used to add a user that doesn't match that format, we tell the admin "Sorry, that username has invalid characters." Furthermore, any Authenticator that can create users which accepts usernames from another service (such as GitHub): - Should either 1) accept all valid usernames that service supports (--force-badname in adduser) or 2) normalize the names to be acceptable to adduser. I think that --force-badname is probably a --bad-idea in general though. - Should also warn appropriately on the Admin page. Seems like there are two related change then: - Allow _some_ Authenticators to have a regular expression that is used to match usernames - Have a normalization API that Authenticators can override for doing normalizations that are appropriate. On Wed, Jan 6, 2016 at 6:34 AM, Min RK [email protected] wrote: > Fixed the reused user issue in #371 > https://github.com/jupyter/jupyterhub/pull/371. What would you like as > an error message in the UI? Should it contain the full traceback, just the > error string, or "See server logs for more details"? > > As for what to do in the LocalGitHubAuth about usernames, I think it was > only the camelCase users that caused the problem. When I tested, the > hyphens were not considered an issue. Did you see something different? What > would you prefer do do about that? I see a few options: > 1. normalize to lowercase for _all usernames always_ > 2. normalize to lowercase in the base LocalAuthenticator (seems like > too much to me) > 3. normalize to lowercase always with GitHub OAuth (GitHub usernames > are not case sensitive, though they can have a reference case for display) > 4. normalize only on LocalGitHubOAuth > > Any other options? > > — > Reply to this email directly or view it on GitHub > https://github.com/jupyter/jupyterhub/issues/369#issuecomment-169338196. ## Brian E. Granger Associate Professor of Physics and Data Science Cal Poly State University, San Luis Obispo @ellisonbg on Twitter and GitHub [email protected] and [email protected] I think both proposals are a good idea. I wouldn't use the username regex on local usernames, though, since the underlying user creation already does this, and there's always a chance for the two to get out of sync. There is already an informative error on a bad username, we just don't propagate it to the UI.
2016-01-08T15:05:51Z
[]
[]
jupyterhub/jupyterhub
423
jupyterhub__jupyterhub-423
[ "418" ]
c81cefd7682de8e51f1801bf6d58427bab64d2f7
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -42,7 +42,7 @@ import jupyterhub from . import handlers, apihandlers -from .handlers.static import CacheControlStaticFilesHandler +from .handlers.static import CacheControlStaticFilesHandler, LogoHandler from . import orm from .user import User, UserDict @@ -238,6 +238,11 @@ def _template_paths_default(self): base_url = URLPrefix('/', config=True, help="The base URL of the entire application" ) + logo_file = Unicode('', config=True, + help="Specify path to a logo image to override the Jupyter logo in the banner." + ) + def _logo_file_default(self): + return os.path.join(self.data_files_path, 'static', 'images', 'jupyter.png') jinja_environment_options = Dict(config=True, help="Supply extra arguments that will be passed to Jinja environment." @@ -483,6 +488,8 @@ def init_handlers(self): # set default handlers h.extend(handlers.default_handlers) h.extend(apihandlers.default_handlers) + + h.append((r'/logo', LogoHandler, {'path': self.logo_file})) self.handlers = self.add_url_prefix(self.hub_prefix, h) # some extra handlers, outside hub_prefix self.handlers.extend([ diff --git a/jupyterhub/handlers/static.py b/jupyterhub/handlers/static.py --- a/jupyterhub/handlers/static.py +++ b/jupyterhub/handlers/static.py @@ -1,6 +1,7 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. +import os from tornado.web import StaticFileHandler class CacheControlStaticFilesHandler(StaticFileHandler): @@ -14,4 +15,14 @@ def compute_etag(self): def set_extra_headers(self, path): if "v" not in self.request.arguments: self.add_header("Cache-Control", "no-cache") - \ No newline at end of file + +class LogoHandler(StaticFileHandler): + """A singular handler for serving the logo.""" + def get(self): + return super().get('') + + @classmethod + def get_absolute_path(cls, root, path): + """We only serve one file, ignore relative path""" + return os.path.abspath(root) +
diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -147,3 +147,18 @@ def test_spawn_form_with_file(app, io_loop): 'content_type': 'application/unknown'}, } + +def test_static_files(app): + base_url = ujoin(app.proxy.public_server.url, app.hub.server.base_url) + print(base_url) + r = requests.get(ujoin(base_url, 'logo')) + r.raise_for_status() + assert r.headers['content-type'] == 'image/png' + r = requests.get(ujoin(base_url, 'static', 'images', 'jupyter.png')) + r.raise_for_status() + assert r.headers['content-type'] == 'image/png' + r = requests.get(ujoin(base_url, 'static', 'css', 'style.min.css')) + r.raise_for_status() + assert r.headers['content-type'] == 'text/css' + + \ No newline at end of file
Make the logo image easily customizable Right now you have to modify page.html template (or replace the static/images/jupyter.png. This is a common customization, so we should make this be available as a configurable parameter.
Makes sense. The only hairy bit is the separation of Hub and single-user servers, which means that the only reasonable choice is for it to be a URL if we want it to affect both. Should be easy enough, though.
2016-02-09T14:20:58Z
[]
[]
jupyterhub/jupyterhub
448
jupyterhub__jupyterhub-448
[ "424" ]
b2ece4823917415390f6dd8a825d5ad67ebdfb45
diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -454,22 +454,26 @@ def get(self): class UserSpawnHandler(BaseHandler): - """Requests to /user/name handled by the Hub - should result in spawning the single-user server and - being redirected to the original. + """Redirect requests to /user/name/* handled by the Hub. + + If logged in, spawn a single-user server and redirect request. + If a user, alice, requests /user/bob/notebooks/mynotebook.ipynb, + redirect her to /user/alice/notebooks/mynotebook.ipynb, which should + in turn call this function. """ + @gen.coroutine - def get(self, name): + def get(self, name, user_path): current_user = self.get_current_user() if current_user and current_user.name == name: - # logged in, spawn the server + # logged in as correct user, spawn the server if current_user.spawner: if current_user.spawn_pending: # spawn has started, but not finished html = self.render_template("spawn_pending.html", user=current_user) self.finish(html) return - + # spawn has supposedly finished, check on the status status = yield current_user.spawner.poll() if status is not None: @@ -485,14 +489,19 @@ def get(self, name): if self.use_subdomains: target = current_user.host + target self.redirect(target) + elif current_user: + # logged in as a different user, redirect + target = url_path_join(self.base_url, 'user', current_user.name, + user_path or '') + self.redirect(target) else: - # not logged in to the right user, - # clear any cookies and reload (will redirect to login) + # not logged in, clear any cookies and reload self.clear_login_cookie() self.redirect(url_concat( self.settings['login_url'], - {'next': self.request.uri, - })) + {'next': self.request.uri}, + )) + class CSPReportHandler(BaseHandler): '''Accepts a content security policy violation report''' @@ -503,6 +512,6 @@ def post(self): self.request.body.decode('utf8', 'replace')) default_handlers = [ - (r'/user/([^/]+)/?.*', UserSpawnHandler), + (r'/user/([^/]+)(/.*)?', UserSpawnHandler), (r'/security/csp-report', CSPReportHandler), ]
diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -1,6 +1,6 @@ """Tests for HTML pages""" -from urllib.parse import urlparse +from urllib.parse import urlencode, urlparse import requests @@ -149,6 +149,31 @@ def test_spawn_form_with_file(app, io_loop): } +def test_user_redirect(app): + name = 'wash' + cookies = app.login_user(name) + + r = get_page('/user/baduser', app, cookies=cookies) + r.raise_for_status() + print(urlparse(r.url)) + path = urlparse(r.url).path + assert path == '/user/%s' % name + + r = get_page('/user/baduser/test.ipynb', app, cookies=cookies) + r.raise_for_status() + print(urlparse(r.url)) + path = urlparse(r.url).path + assert path == '/user/%s/test.ipynb' % name + + r = get_page('/user/baduser/test.ipynb', app) + r.raise_for_status() + print(urlparse(r.url)) + path = urlparse(r.url).path + assert path == '/hub/login' + query = urlparse(r.url).query + assert query == urlencode({'next': '/hub/user/baduser/test.ipynb'}) + + def test_static_files(app): base_url = ujoin(public_url(app), app.hub.server.base_url) print(base_url)
Can't share links to notebooks I use the Docker spawner and have the following volume configuration: ``` c.DockerSpawner.volumes = {'/notebooks/Users/{username}': '/notebooks/Home'} c.DockerSpawner.read_only_volumes = {'/notebooks/Users': '/notebooks/Users'} ``` I can create a notebook at `http://myserver/user/akaihola/notebooks/Users/akaihola/example.ipynb` and view it as another user at `http://myserver/user/friend/notebooks/Users/akaihola/example.ipynb` But, if I send the link `http://myserver/user/akaihola/notebooks/Users/akaihola/example.ipynb` to a friend, he can't just log in to the server and click on the link since `/user/akaihola/` doesn't match his username. It would be convenient if JupyterHub would redirect from `/user/akaihola/*` to `/user/friend/*` automatically when the username in the URL doesn't match the logged in user.
For sharing notebooks between users, I am trying out an `/examples` server extension, [nbexamples](https://github.com/danielballan/nbexamples). Maybe it will be of use to you.
2016-03-02T23:20:59Z
[]
[]
jupyterhub/jupyterhub
467
jupyterhub__jupyterhub-467
[ "466" ]
a0501c6ee4071f2776bc372a96ba50542174c563
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -677,6 +677,7 @@ def init_users(self): self.authenticator.normalize_username(name) for name in self.authenticator.admin_users ] + self.authenticator.admin_users = set(admin_users) # force normalization for username in admin_users: if not self.authenticator.validate_username(username): raise ValueError("username %r is not valid" % username) @@ -704,6 +705,7 @@ def init_users(self): self.authenticator.normalize_username(name) for name in self.authenticator.whitelist ] + self.authenticator.whitelist = set(whitelist) # force normalization for username in whitelist: if not self.authenticator.validate_username(username): raise ValueError("username %r is not valid" % username) @@ -719,24 +721,21 @@ def init_users(self): new_users.append(user) db.add(user) - if whitelist: - # fill the whitelist with any users loaded from the db, - # so we are consistent in both directions. - # This lets whitelist be used to set up initial list, - # but changes to the whitelist can occur in the database, - # and persist across sessions. - for user in db.query(orm.User): - self.authenticator.whitelist.add(user.name) + db.commit() + + # Notify authenticator of all users. + # This ensures Auth whitelist is up-to-date with the database. + # This lets whitelist be used to set up initial list, + # but changes to the whitelist can occur in the database, + # and persist across sessions. + for user in db.query(orm.User): + yield gen.maybe_future(self.authenticator.add_user(user)) + db.commit() # can add_user touch the db? # The whitelist set and the users in the db are now the same. # From this point on, any user changes should be done simultaneously # to the whitelist set and user db, unless the whitelist is empty (all users allowed). - db.commit() - - for user in new_users: - yield gen.maybe_future(self.authenticator.add_user(user)) - db.commit() @gen.coroutine def init_spawners(self): diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -200,6 +200,7 @@ def user_from_username(self, username): self.db.add(u) self.db.commit() user = self._user_from_orm(u) + self.authenticator.add_user(user) return user def clear_login_cookie(self, name=None):
diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -222,6 +222,16 @@ def test_logout(app): assert r.cookies == {} +def test_login_no_whitelist_adds_user(app): + auth = app.authenticator + mock_add_user = mock.Mock() + with mock.patch.object(auth, 'add_user', mock_add_user): + cookies = app.login_user('jubal') + + user = app.users['jubal'] + assert mock_add_user.mock_calls == [mock.call(user)] + + def test_static_files(app): base_url = ujoin(public_url(app), app.hub.server.base_url) print(base_url)
Setup allowing any Github user access Hi there, Trying to use Jupyterhub for a talk I'm giving on Thursday. I've basically setup a server and want anyone who is in the room to be able to login to the server using their github credentials. Is this possible? It seems possible to automatically add system users but not github users. Having no whitelist allows any Github user to login but once they hit "_Start my Server_" they will get a 500 and I'll see the error `KeyError: 'getpwnam(): name not found: GITHUB_USERNAME'` Here is my current config: ``` # Github Settings c.GitHubOAuthenticator.client_id = os.environ['GITHUB_CLIENT_ID'] c.GitHubOAuthenticator.client_secret = os.environ['GITHUB_CLIENT_SECRET'] c.GitHubOAuthenticator.oauth_callback_url = os.environ['OAUTH_CALLBACK_URL'] # Authentication Setup c.JupyterHub.authenticator_class = 'oauthenticator.LocalGitHubOAuthenticator' c.LocalGitHubOAuthenticator.create_system_users = True # Create empty whitelist and setup admin users c.Authenticator.whitelist = whitelist = set() c.Authenticator.admin_users = admin = set() c.JupyterHub.admin_access = True # Use userlist to determine administrators with open(join(here, 'userlist')) as f: for line in f: if not line: continue parts = line.split() name = parts[0] if len(parts) > 1 and parts[1] == 'admin': admin.add(name) ``` I'd appreciate any feedback of how to approach achieving what I want.
2016-03-08T09:49:21Z
[]
[]
jupyterhub/jupyterhub
768
jupyterhub__jupyterhub-768
[ "765" ]
150b67c1c9b5fed3cbb43482d8b771d0b7ddcf82
diff --git a/jupyterhub/services/service.py b/jupyterhub/services/service.py --- a/jupyterhub/services/service.py +++ b/jupyterhub/services/service.py @@ -225,8 +225,9 @@ def start(self): env['JUPYTERHUB_API_TOKEN'] = self.api_token env['JUPYTERHUB_API_URL'] = self.hub_api_url env['JUPYTERHUB_BASE_URL'] = self.base_url - env['JUPYTERHUB_SERVICE_PREFIX'] = self.server.base_url - env['JUPYTERHUB_SERVICE_URL'] = self.url + if self.url: + env['JUPYTERHUB_SERVICE_URL'] = self.url + env['JUPYTERHUB_SERVICE_PREFIX'] = self.server.base_url self.spawner = _ServiceSpawner( cmd=self.command, @@ -248,7 +249,7 @@ def _proc_stopped(self): """Called when the service process unexpectedly exits""" self.log.error("Service %s exited with status %i", self.name, self.proc.returncode) self.start() - + def stop(self): """Stop a managed service""" if not self.managed:
diff --git a/jupyterhub/tests/conftest.py b/jupyterhub/tests/conftest.py --- a/jupyterhub/tests/conftest.py +++ b/jupyterhub/tests/conftest.py @@ -66,9 +66,16 @@ class MockServiceSpawner(jupyterhub.services.service._ServiceSpawner): poll_interval = 1 -@yield_fixture -def mockservice(request, app): +def _mockservice(request, app, url=False): name = 'mock-service' + spec = { + 'name': name, + 'command': mockservice_cmd, + 'admin': True, + } + if url: + spec['url'] = 'http://127.0.0.1:%i' % random_port(), + with mock.patch.object(jupyterhub.services.service, '_ServiceSpawner', MockServiceSpawner): app.services = [{ 'name': name, @@ -88,4 +95,12 @@ def mockservice(request, app): # ensure process finishes starting with raises(TimeoutExpired): service.proc.wait(1) - yield service + return service + +@yield_fixture +def mockservice(request, app): + yield _mockservice(request, app, url=False) + +@yield_fixture +def mockservice_url(request, app): + yield _mockservice(request, app, url=True) diff --git a/jupyterhub/tests/test_services.py b/jupyterhub/tests/test_services.py --- a/jupyterhub/tests/test_services.py +++ b/jupyterhub/tests/test_services.py @@ -59,10 +59,11 @@ def test_managed_service(app, mockservice): assert service.proc.poll() is None -def test_proxy_service(app, mockservice, io_loop): - name = mockservice.name +def test_proxy_service(app, mockservice_url, io_loop): + service = mockservice_url + name = service.name routes = io_loop.run_sync(app.proxy.get_routes) - url = public_url(app, mockservice) + '/foo' + url = public_url(app, service) + '/foo' r = requests.get(url, allow_redirects=False) path = '/services/{}/foo'.format(name) r.raise_for_status() @@ -99,3 +100,5 @@ def add_services(): assert len(resp) >= 1 assert isinstance(resp[0], dict) assert 'name' in resp[0] + +
Cull_Idle Instructions I'm having trouble using the [cull_idle example](https://github.com/jupyterhub/jupyterhub/tree/master/examples/cull-idle#configure-cull-idle-to-run-as-a-hub-managed-service) as a managed service. I added the [example config section](https://github.com/jupyterhub/jupyterhub/blob/master/examples/cull-idle/jupyterhub_config.py) to the bottom of my existing `jupyterhub_config.py` file: ``` python c = get_config() docker_ip = '172.17.0.1' hub_name='127.0.0.1' c.JupyterHub.ip = hub_name c.JupyterHub.hub_ip = docker_ip c.JupyterHub.debug_proxy = True c.JupyterHub.port = 8000 c.JupyterHub.cleanup_servers = False c.JupyterHub.cleanup_proxy = True c.JupyterHub.ssl_key = '/etc/jupyterhub/ssl/jhub.key' c.JupyterHub.ssl_cert = '/etc/jupyterhub/ssl/jhub.crt' c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner' c.DockerSpawner.hub_ip_connect = docker_ip c.DockerSpawner.container_ip = docker_ip c.JupyterHub.cookie_secret_file = '/srv/jupyterhub/jupyterhub_cookie_secret' c.JupyterHub.log_level = 'DEBUG' #CULL_IDLE SECTION c.JupyterHub.services = [{ 'name': 'cull-idle', 'admin': True, 'command': 'python cull_idle_servers.py --timeout=3600'.split()}] ``` I see the resulting error: ``` [C 2016-09-20 02:28:37.026 JupyterHub app:1444] Failed to start service cull-idle Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 1442, in start yield service.start() File "/usr/local/lib/python3.5/dist-packages/jupyterhub/services/service.py", line 228, in start env['JUPYTERHUB_SERVICE_PREFIX'] = self.server.base_url AttributeError: 'NoneType' object has no attribute 'base_url' ``` Any ideas of what could be causing this? Thank you!
@whitead It looks as if the `base_url` is not set in `jupyterhub_config.py`. Try adding the following to your `jupyterhub_config.py`: ``` c.JupyterHub.base_url= '/' ``` This section and the following in the JupyterHub docs on services provide a bit more information on the url and the information passed between the Hub and the service: https://jupyterhub.readthedocs.io/en/latest/services.html#properties-of-a-service This is the environment variables passed from the Hub to the service: ``` JUPYTERHUB_SERVICE_NAME: 'cull-idle' JUPYTERHUB_API_TOKEN: API token assigned to the service JUPYTERHUB_API_URL: http://127.0.0.1:8080/hub/api JUPYTERHUB_BASE_URL: https://mydomain[:port] JUPYTERHUB_SERVICE_PREFIX: /services/cull-idle/ ``` Hi, thank you for the reply. From what I understand, that is default value. I tried setting it to different options (including `'/'`) though and there was no change. I should mention that the `NoneType` problem is the `self.server` which is an `orm.py` `Server` class. @whitead Since services are still under development for the upcoming release, it's possible that you have uncovered a bug. Thanks for the additional detail. We'll take a look at the underlying code. If possible, please run with `--debug` and share with us. Thanks. One additional question: which version of Dockerspawner are you using? A recent change in Dockerspawner (not yet in the released stable version) may be related (https://github.com/jupyterhub/dockerspawner/pull/115/commits/6bdbb64f742d8e819551cea1537050551af0f663) cc @minrk Well the services look like they'll be great when ready! I am on latest git repositories for everything, including Dockerspawner (where I just did a PR by the way) and configurable-http-proxy. Here's more of the surrounding logfile. I've omitted my whitelist of users: ``` [I 2016-09-20 11:34:37.691 JupyterHub app:705] Loading cookie_secret from /srv/jupyterhub/jupyterhub_cookie_secret [D 2016-09-20 11:34:37.691 JupyterHub app:777] Connecting to db: sqlite:///jupyterhub.sqlite [I 2016-09-20 11:34:39.035 JupyterHub app:1431] Hub API listening on http://172.17.0.1:8081/hub/ [I 2016-09-20 11:34:39.040 JupyterHub app:1166] Starting proxy @ http://127.0.0.1:8000/ [D 2016-09-20 11:34:39.040 JupyterHub app:1167] Proxy cmd: ['configurable-http-proxy', '--ip', '127.0.0.1', '--port', '8000', '--api-ip', '127.0.0.1', '--api-port', '8001', '--default-target', 'http://172.17.0.1:8081', '--error-target', 'http://172.17.0.1:8081/hub/error', '--log-level', 'debug', '--ssl-key', '/etc/jupyterhub/ssl/jhub.key', '--ssl-cert', '/etc/jupyterhub/ssl/jhub.crt'] 11:34:39.273 - info: [ConfigProxy] Proxying https://127.0.0.1:8000 to http://172.17.0.1:8081 11:34:39.277 - info: [ConfigProxy] Proxy API at http://127.0.0.1:8001/api/routes [D 2016-09-20 11:34:39.346 JupyterHub app:1195] Proxy started and appears to be up [I 2016-09-20 11:34:39.347 JupyterHub service:220] Starting service 'cull-idle': ['python', 'cull_idle_severs.py', '--timeout=25'] [C 2016-09-20 11:34:39.350 JupyterHub app:1444] Failed to start service cull-idle Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 1442, in start yield service.start() File "/usr/local/lib/python3.5/dist-packages/jupyterhub/services/service.py", line 228, in start env['JUPYTERHUB_SERVICE_PREFIX'] = self.server.base_url AttributeError: 'NoneType' object has no attribute 'base_url' [D 2016-09-20 11:34:39.351 JupyterHub application:642] Exiting application: jupyterhub ``` So I won't pretend to understand if this is right or wrong, but here's a patch that fixes my problem. I'm pretty sure the missing `@gen.coroutine` is a bug, but I'm not sure if just removing the api prefix is correct. The issue is that managed services don't get access to an `orm.server` (see `jupyterhub/app.py:1020`) so they can't ever have an api prefix set. ``` diff diff --git a/jupyterhub/services/service.py b/jupyterhub/services/service.py index bfa1736..b0e9d40 100644 --- a/jupyterhub/services/service.py +++ b/jupyterhub/services/service.py @@ -82,6 +82,7 @@ class _ServiceSpawner(LocalProcessSpawner): return return super().make_preexec_fn(name) + @gen.coroutine def start(self): """Start the process""" env = self.get_env() @@ -213,6 +214,7 @@ class Service(LoggingConfigurable): managed=' managed' if self.managed else '', ) + @gen.coroutine def start(self): """Start a managed service""" if not self.managed: @@ -225,7 +227,6 @@ class Service(LoggingConfigurable): env['JUPYTERHUB_API_TOKEN'] = self.api_token env['JUPYTERHUB_API_URL'] = self.hub_api_url env['JUPYTERHUB_BASE_URL'] = self.base_url - env['JUPYTERHUB_SERVICE_PREFIX'] = self.server.base_url env['JUPYTERHUB_SERVICE_URL'] = self.url self.spawner = _ServiceSpawner( ``` I'll just leave this open if you don't mind and so we can see if @minrk finds this useful. @whitead Thanks! Definitely useful since you've identified a root cause. Yes, please leave it open for @minrk. I'm going to look at the managed services tests as well. I also tried it and found the same error and same solution but I think instead of removing that env it has to be set to `self.proxy_path`. ``` python env['JUPYTERHUB_SERVICE_PREFIX'] = self.proxy_path ``` I also think the spawned processes for services are not being terminated but that might just be me testing.
2016-09-21T10:39:23Z
[]
[]
jupyterhub/jupyterhub
838
jupyterhub__jupyterhub-838
[ "836" ]
53bdcd7d74578d560e9a9dcebbb9c1b95581f0f8
diff --git a/jupyterhub/spawner.py b/jupyterhub/spawner.py --- a/jupyterhub/spawner.py +++ b/jupyterhub/spawner.py @@ -298,15 +298,15 @@ def format_string(self, s): def get_args(self): """Return the arguments to be passed after self.cmd""" args = [ - '--user=%s' % self.user.name, - '--cookie-name=%s' % self.user.server.cookie_name, - '--base-url=%s' % self.user.server.base_url, - '--hub-host=%s' % self.hub.host, - '--hub-prefix=%s' % self.hub.server.base_url, - '--hub-api-url=%s' % self.hub.api_url, + '--user="%s"' % self.user.name, + '--cookie-name="%s"' % self.user.server.cookie_name, + '--base-url="%s"' % self.user.server.base_url, + '--hub-host="%s"' % self.hub.host, + '--hub-prefix="%s"' % self.hub.server.base_url, + '--hub-api-url="%s"' % self.hub.api_url, ] if self.ip: - args.append('--ip=%s' % self.ip) + args.append('--ip="%s"' % self.ip) if self.port: args.append('--port=%i' % self.port) @@ -316,10 +316,10 @@ def get_args(self): if self.notebook_dir: notebook_dir = self.format_string(self.notebook_dir) - args.append('--notebook-dir=%s' % notebook_dir) + args.append('--notebook-dir="%s"' % notebook_dir) if self.default_url: default_url = self.format_string(self.default_url) - args.append('--NotebookApp.default_url=%s' % default_url) + args.append('--NotebookApp.default_url="%s"' % default_url) if self.debug: args.append('--debug')
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -390,10 +390,10 @@ def test_spawn(app, io_loop): r = requests.get(ujoin(url, 'args')) assert r.status_code == 200 argv = r.json() - for expected in ['--user=%s' % name, '--base-url=%s' % user.server.base_url]: + for expected in ['--user="%s"' % name, '--base-url="%s"' % user.server.base_url]: assert expected in argv if app.subdomain_host: - assert '--hub-host=%s' % app.subdomain_host in argv + assert '--hub-host="%s"' % app.subdomain_host in argv r = api_request(app, 'users', name, 'server', method='delete') assert r.status_code == 204
Redirect loop after starting server My JupyterHub installation uses GitHub authentication. It works well for a dozen users, however, for one user, myself, I enter a redirect loop when starting the server. It’s completely bizarre. The only difference between my user and the other users is that my username starts with a digit. Any ideas?
If it matters, I’m able to access the admin page without issue. I can also successfully start the server from the admin panel. However, when I try to access /hub/ I enter the redirect loop. Do you see anything in the logs? What Spawner are you using? @minrk I don't see anything unusual in the logs: ``` [I 2016-10-27 13:11:15.654 JupyterHub log:100] 302 GET / (@172.17.0.1) 4.66ms [I 2016-10-27 13:11:15.894 JupyterHub log:100] 302 GET /hub (@172.17.0.1) 0.62ms [D 2016-10-27 13:11:16.143 JupyterHub pages:35] User is not running: /hub/home [I 2016-10-27 13:11:16.150 JupyterHub log:100] 302 GET /hub/ ([email protected]) 4.13ms [I 2016-10-27 13:11:16.722 JupyterHub log:100] 200 GET /hub/home ([email protected]) 8.27ms [I 2016-10-27 13:11:18.022 JupyterHub log:100] 302 GET /apple-touch-icon-precomposed.png (@172.17.0.1) 1.24ms [W 2016-10-27 13:11:18.449 JupyterHub log:100] 404 GET /hub/apple-touch-icon-precomposed.png ([email protected]) 15.77ms [I 2016-10-27 13:11:18.668 JupyterHub log:100] 302 GET /apple-touch-icon.png (@172.17.0.1) 1.21ms [W 2016-10-27 13:11:18.838 JupyterHub log:100] 404 GET /hub/apple-touch-icon.png ([email protected]) 4.59ms [I 2016-10-27 13:11:43.550 JupyterHub log:100] 302 GET /hub/spawn ([email protected]) 5.20ms [I 2016-10-27 13:11:43.799 JupyterHub log:100] 302 GET /user/0x00b1 (@172.17.0.1) 1.25ms [I 2016-10-27 13:11:44.169 JupyterHub spawner:467] Spawning jupyterhub-singleuser --user=0x00b1 --port=55108 --cookie-name=jupyter-hub-token-0x00b1 --base-url=/user/0x00b1 --hub-host= --hub-prefix=/hub/ --hub-api-url=http://127.0.0.1:8081/hub/api --ip=127.0.0.1 [D 2016-10-27 13:11:44.191 JupyterHub spawner:316] Polling subprocess every 30s [I 2016-10-27 13:11:44.968 177 notebookapp:1128] Serving notebooks from local directory: /home/0x00b1 [I 2016-10-27 13:11:44.968 177 notebookapp:1128] 0 active kernels [I 2016-10-27 13:11:44.968 177 notebookapp:1128] The Jupyter Notebook is running at: http://127.0.0.1:55108/user/0x00b1/ [I 2016-10-27 13:11:44.968 177 notebookapp:1129] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [I 2016-10-27 13:11:45.027 177 log:47] 302 GET /user/0x00b1 (127.0.0.1) 0.62ms [D 2016-10-27 13:11:45.028 JupyterHub utils:84] Server at http://127.0.0.1:55108/user/0x00b1 responded with 302 [I 2016-10-27 13:11:45.028 JupyterHub base:306] User 0x00b1 server took 0.914 seconds to start [I 2016-10-27 13:11:45.028 JupyterHub orm:159] Adding user 0x00b1 to proxy /user/0x00b1 => http://127.0.0.1:55108 [D 2016-10-27 13:11:45.031 JupyterHub orm:146] Fetching POST http://127.0.0.1:8001/api/routes/user/0x00b1 [D 2016-10-27 13:11:45.035 JupyterHub base:231] Setting cookie for 0x00b1: jupyter-hub-token-0x00b1, {'secure': True} [I 2016-10-27 13:11:45.047 JupyterHub log:100] 302 GET /hub/user/0x00b1 ([email protected]) 930.66ms [I 2016-10-27 13:11:45.419 177 log:47] 302 GET /user/0x00b1 (172.17.0.1) 0.63ms [I 2016-10-27 13:11:45.773 177 log:47] 302 GET /user/0x00b1/tree (172.17.0.1) 24.60ms [I 2016-10-27 13:11:45.784 JupyterHub log:100] 200 GET /hub/api/authorizations/cookie/jupyter-hub-token-0x00b1/[secret] ([email protected]) 16.95ms [D 2016-10-27 13:11:46.076 JupyterHub pages:31] User is running: /user/0x00b1 [D 2016-10-27 13:11:46.077 JupyterHub base:231] Setting cookie for 0x00b1: jupyter-hub-token-0x00b1, {'secure': True} [I 2016-10-27 13:11:46.086 JupyterHub log:100] 302 GET /hub/?next=%2Fuser%2F0x00b1%2Ftree ([email protected]) 9.82ms [I 2016-10-27 13:11:46.320 177 log:47] 302 GET /user/0x00b1 (172.17.0.1) 0.63ms [I 2016-10-27 13:11:46.909 177 log:47] 302 GET /user/0x00b1/tree (172.17.0.1) 21.23ms [I 2016-10-27 13:11:46.921 JupyterHub log:100] 200 GET /hub/api/authorizations/cookie/jupyter-hub-token-0x00b1/[secret] ([email protected]) 16.49ms [D 2016-10-27 13:11:47.145 JupyterHub pages:31] User is running: /user/0x00b1 [D 2016-10-27 13:11:47.145 JupyterHub base:231] Setting cookie for 0x00b1: jupyter-hub-token-0x00b1, {'secure': True} [I 2016-10-27 13:11:47.153 JupyterHub log:100] 302 GET /hub/?next=%2Fuser%2F0x00b1%2Ftree ([email protected]) 9.81ms [I 2016-10-27 13:11:47.461 177 log:47] 302 GET /user/0x00b1 (172.17.0.1) 0.58ms [I 2016-10-27 13:11:47.813 177 log:47] 302 GET /user/0x00b1/tree (172.17.0.1) 22.03ms [I 2016-10-27 13:11:47.824 JupyterHub log:100] 200 GET /hub/api/authorizations/cookie/jupyter-hub-token-0x00b1/[secret] ([email protected]) 17.28ms [D 2016-10-27 13:11:48.042 JupyterHub pages:31] User is running: /user/0x00b1 [D 2016-10-27 13:11:48.043 JupyterHub base:231] Setting cookie for 0x00b1: jupyter-hub-token-0x00b1, {'secure': True} [I 2016-10-27 13:11:48.051 JupyterHub log:100] 302 GET /hub/?next=%2Fuser%2F0x00b1%2Ftree ([email protected]) 9.96ms [I 2016-10-27 13:11:48.611 177 log:47] 302 GET /user/0x00b1 (172.17.0.1) 0.69ms [I 2016-10-27 13:11:48.879 177 log:47] 302 GET /user/0x00b1/tree (172.17.0.1) 21.40ms [I 2016-10-27 13:11:48.891 JupyterHub log:100] 200 GET /hub/api/authorizations/cookie/jupyter-hub-token-0x00b1/[secret] ([email protected]) 16.81ms [D 2016-10-27 13:11:49.190 JupyterHub pages:31] User is running: /user/0x00b1 [D 2016-10-27 13:11:49.190 JupyterHub base:231] Setting cookie for 0x00b1: jupyter-hub-token-0x00b1, {'secure': True} [I 2016-10-27 13:11:49.198 JupyterHub log:100] 302 GET /hub/?next=%2Fuser%2F0x00b1%2Ftree ([email protected]) 9.96ms [I 2016-10-27 13:11:49.510 177 log:47] 302 GET /user/0x00b1 (172.17.0.1) 0.65ms [I 2016-10-27 13:11:49.857 177 log:47] 302 GET /user/0x00b1/tree (172.17.0.1) 21.26ms [I 2016-10-27 13:11:49.869 JupyterHub log:100] 200 GET /hub/api/authorizations/cookie/jupyter-hub-token-0x00b1/[secret] ([email protected]) 16.58ms [D 2016-10-27 13:12:31.434 JupyterHub orm:146] Fetching GET http://127.0.0.1:8001/api/routes [I 2016-10-27 13:13:27.334 JupyterHub log:100] 302 GET / (@172.17.0.1) 3.88ms [I 2016-10-27 13:13:27.656 JupyterHub log:100] 302 GET /hub (@172.17.0.1) 0.65ms [D 2016-10-27 13:13:28.077 JupyterHub pages:31] User is running: /user/0x00b1 [D 2016-10-27 13:13:28.077 JupyterHub base:231] Setting cookie for 0x00b1: jupyter-hub-token-0x00b1, {'secure': True} [I 2016-10-27 13:13:28.086 JupyterHub log:100] 302 GET /hub/ ([email protected]) 7.40ms [I 2016-10-27 13:13:28.156 JupyterHub log:100] 302 GET / (@172.17.0.1) 1.23ms [I 2016-10-27 13:13:28.318 177 log:47] 302 GET /user/0x00b1 (172.17.0.1) 0.75ms [I 2016-10-27 13:13:28.483 JupyterHub log:100] 302 GET /hub (@172.17.0.1) 0.59ms [I 2016-10-27 13:13:28.666 177 log:47] 302 GET /user/0x00b1/tree (172.17.0.1) 23.06ms [I 2016-10-27 13:13:28.677 JupyterHub log:100] 200 GET /hub/api/authorizations/cookie/jupyter-hub-token-0x00b1/[secret] ([email protected]) 18.08ms [I 2016-10-27 13:13:28.819 JupyterHub log:100] 302 GET /hub/ (@172.17.0.1) 3.91ms [D 2016-10-27 13:13:28.983 JupyterHub pages:31] User is running: /user/0x00b1 [D 2016-10-27 13:13:28.983 JupyterHub base:231] Setting cookie for 0x00b1: jupyter-hub-token-0x00b1, {'secure': True} [I 2016-10-27 13:13:28.992 JupyterHub log:100] 302 GET /hub/?next=%2Fuser%2F0x00b1%2Ftree ([email protected]) 8.33ms [I 2016-10-27 13:13:29.145 JupyterHub log:100] 200 GET /hub/login (@172.17.0.1) 2.48ms [I 2016-10-27 13:13:29.308 177 log:47] 302 GET /user/0x00b1 (172.17.0.1) 0.66ms [D 2016-10-27 13:13:29.472 JupyterHub log:100] 200 GET /hub/static/css/style.min.css?v=91c753d3c28f12b7480e5d0d9e7c55b2 (@172.17.0.1) 1.75ms [I 2016-10-27 13:13:30.131 177 log:47] 302 GET /user/0x00b1/tree (172.17.0.1) 0.92ms [D 2016-10-27 13:13:30.545 JupyterHub pages:31] User is running: /user/0x00b1 [D 2016-10-27 13:13:30.545 JupyterHub base:231] Setting cookie for 0x00b1: jupyter-hub-token-0x00b1, {'secure': True} [I 2016-10-27 13:13:30.554 JupyterHub log:100] 302 GET /hub/?next=%2Fuser%2F0x00b1%2Ftree ([email protected]) 7.38ms [D 2016-10-27 13:13:30.710 JupyterHub log:100] 200 GET /hub/static/components/requirejs/require.js?v=6da8be361b9ee26c5e721e76c6d4afce (@172.17.0.1) 1.53ms [I 2016-10-27 13:13:30.873 177 log:47] 302 GET /user/0x00b1 (172.17.0.1) 0.65ms [I 2016-10-27 13:13:31.226 177 log:47] 302 GET /user/0x00b1/tree (172.17.0.1) 23.10ms [I 2016-10-27 13:13:31.237 JupyterHub log:100] 200 GET /hub/api/authorizations/cookie/jupyter-hub-token-0x00b1/[secret] ([email protected]) 16.75ms [D 2016-10-27 13:13:31.278 JupyterHub log:100] 200 GET /hub/logo (@172.17.0.1) 1.06ms [D 2016-10-27 13:13:31.699 JupyterHub pages:31] User is running: /user/0x00b1 [D 2016-10-27 13:13:31.700 JupyterHub base:231] Setting cookie for 0x00b1: jupyter-hub-token-0x00b1, {'secure': True} [I 2016-10-27 13:13:31.708 JupyterHub log:100] 302 GET /hub/?next=%2Fuser%2F0x00b1%2Ftree ([email protected]) 10.00ms [I 2016-10-27 13:13:31.938 177 log:47] 302 GET /user/0x00b1 (172.17.0.1) 0.60ms [D 2016-10-27 13:13:31.939 JupyterHub log:100] 200 GET /favicon.ico (@172.17.0.1) 1.30ms [I 2016-10-27 13:13:32.205 177 log:47] 302 GET /user/0x00b1/tree (172.17.0.1) 22.06ms [I 2016-10-27 13:13:32.216 JupyterHub log:100] 200 GET /hub/api/authorizations/cookie/jupyter-hub-token-0x00b1/[secret] ([email protected]) 17.39ms [D 2016-10-27 13:13:32.346 JupyterHub log:100] 200 GET /favicon.ico (@172.17.0.1) 1.21ms [D 2016-10-27 13:13:32.521 JupyterHub pages:31] User is running: /user/0x00b1 [D 2016-10-27 13:13:32.521 JupyterHub base:231] Setting cookie for 0x00b1: jupyter-hub-token-0x00b1, {'secure': True} [I 2016-10-27 13:13:32.530 JupyterHub log:100] 302 GET /hub/?next=%2Fuser%2F0x00b1%2Ftree ([email protected]) 10.02ms [I 2016-10-27 13:13:32.767 177 log:47] 302 GET /user/0x00b1 (172.17.0.1) 0.66ms [I 2016-10-27 13:13:33.029 177 log:47] 302 GET /user/0x00b1/tree (172.17.0.1) 23.13ms [I 2016-10-27 13:13:33.041 JupyterHub log:100] 200 GET /hub/api/authorizations/cookie/jupyter-hub-token-0x00b1/[secret] ([email protected]) 18.45ms [I 2016-10-27 13:13:34.979 JupyterHub oauth2:37] oauth redirect: 'https://graphics.imagi.ng:9100/hub/oauth_callback' [I 2016-10-27 13:13:34.984 JupyterHub log:100] 302 GET /hub/oauth_login (@172.17.0.1) 4.25ms [D 2016-10-27 13:13:35.723 JupyterHub base:231] Setting cookie for mcquin: jupyter-hub-token, {'secure': True} [I 2016-10-27 13:13:35.727 JupyterHub log:100] 302 GET /hub/oauth_callback?code=d3c82ac7fb1850396137 (@172.17.0.1) 247.79ms [I 2016-10-27 13:13:36.145 JupyterHub log:100] 200 GET /hub/home ([email protected]) 8.24ms [D 2016-10-27 13:13:36.463 JupyterHub log:100] 200 GET /hub/static/components/font-awesome/fonts/fontawesome-webfont.woff?v=4.1.0 (@172.17.0.1) 1.55ms [D 2016-10-27 13:13:36.465 JupyterHub log:100] 200 GET /hub/static/js/home.js?v=(& (@172.17.0.1) 1.35ms [D 2016-10-27 13:13:37.195 JupyterHub log:100] 200 GET /hub/static/components/jquery/jquery.min.js?v=(& (@172.17.0.1) 1.49ms [D 2016-10-27 13:13:38.022 JupyterHub log:100] 200 GET /hub/static/js/jhapi.js?v=(& (@172.17.0.1) 1.30ms [D 2016-10-27 13:13:38.350 JupyterHub log:100] 200 GET /hub/static/js/utils.js?v=(& (@172.17.0.1) 1.30ms [D 2016-10-27 13:13:38.840 JupyterHub log:100] 304 GET /favicon.ico (@172.17.0.1) 1.05ms [I 2016-10-27 13:13:39.834 JupyterHub log:100] 302 GET /hub/spawn ([email protected]) 5.75ms [I 2016-10-27 13:13:40.157 JupyterHub log:100] 302 GET /user/mcquin (@172.17.0.1) 1.26ms [I 2016-10-27 13:13:40.700 JupyterHub spawner:467] Spawning jupyterhub-singleuser --user=mcquin --port=44400 --cookie-name=jupyter-hub-token-mcquin --base-url=/user/mcquin --hub-host= --hub-prefix=/hub/ --hub-api-url=http://127.0.0.1:8081/hub/api --ip=127.0.0.1 [D 2016-10-27 13:13:40.721 JupyterHub spawner:316] Polling subprocess every 30s [I 2016-10-27 13:13:41.507 mcquin notebookapp:1128] Serving notebooks from local directory: /home/mcquin [I 2016-10-27 13:13:41.507 mcquin notebookapp:1128] 0 active kernels [I 2016-10-27 13:13:41.507 mcquin notebookapp:1128] The Jupyter Notebook is running at: http://127.0.0.1:44400/user/mcquin/ [I 2016-10-27 13:13:41.507 mcquin notebookapp:1129] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [I 2016-10-27 13:13:41.558 mcquin log:47] 302 GET /user/mcquin (127.0.0.1) 1.02ms [D 2016-10-27 13:13:41.559 JupyterHub utils:84] Server at http://127.0.0.1:44400/user/mcquin responded with 302 [I 2016-10-27 13:13:41.559 JupyterHub base:306] User mcquin server took 0.911 seconds to start [I 2016-10-27 13:13:41.560 JupyterHub orm:159] Adding user mcquin to proxy /user/mcquin => http://127.0.0.1:44400 [D 2016-10-27 13:13:41.563 JupyterHub orm:146] Fetching POST http://127.0.0.1:8001/api/routes/user/mcquin [D 2016-10-27 13:13:41.566 JupyterHub base:231] Setting cookie for mcquin: jupyter-hub-token-mcquin, {'secure': True} [I 2016-10-27 13:13:41.578 JupyterHub log:100] 302 GET /hub/user/mcquin ([email protected]) 927.69ms [I 2016-10-27 13:13:41.792 mcquin log:47] 302 GET /user/mcquin (172.17.0.1) 0.73ms [I 2016-10-27 13:13:42.237 JupyterHub log:100] 200 GET /hub/api/authorizations/cookie/jupyter-hub-token-mcquin/[secret] ([email protected]) 16.96ms [I 2016-10-27 13:13:52.554 mcquin handlers:170] Creating new notebook in [I 2016-10-27 13:13:52.562 mcquin sign:195] Writing notebook-signing key to /home/mcquin/.local/share/jupyter/notebook_secret [I 2016-10-27 13:13:58.162 mcquin kernelmanager:89] Kernel started: b978fe3c-fcd8-4146-b6a7-eaee6f346ba1 [W 2016-10-27 13:13:58.187 mcquin log:47] 404 GET /user/mcquin/nbextensions/widgets/notebook/js/extension.js?v=20161027131341 (172.17.0.1) 15.09ms referer=https://graphics.imagi.ng:9100/user/mcquin/notebooks/Untitled.ipynb?kernel_name=python2 ``` We are using the default spawner. @minrk Mentioning this unicode issue here since it may relate: https://github.com/jupyterhub/jupyterhub/issues/444#issuecomment-256639192
2016-10-28T13:50:28Z
[]
[]
jupyterhub/jupyterhub
938
jupyterhub__jupyterhub-938
[ "553" ]
6b33358c56aa324ef4119d2256da80fec5e39127
diff --git a/jupyterhub/apihandlers/auth.py b/jupyterhub/apihandlers/auth.py --- a/jupyterhub/apihandlers/auth.py +++ b/jupyterhub/apihandlers/auth.py @@ -6,10 +6,12 @@ import json from urllib.parse import quote +from oauth2.web.tornado import OAuth2Handler from tornado import web, gen + from .. import orm from ..utils import token_authenticated -from .base import APIHandler +from .base import BaseHandler, APIHandler class TokenAPIHandler(APIHandler): @@ -58,8 +60,24 @@ def get(self, cookie_name, cookie_value=None): self.write(json.dumps(self.user_model(user))) +class OAuthHandler(BaseHandler, OAuth2Handler): + """Implement OAuth provider handlers + + OAuth2Handler sets `self.provider` in initialize, + but we are already passing the Provider object via settings. + """ + @property + def provider(self): + return self.settings['oauth_provider'] + + def initialize(self): + pass + + default_handlers = [ (r"/api/authorizations/cookie/([^/]+)(?:/([^/]+))?", CookieAPIHandler), (r"/api/authorizations/token/([^/]+)", TokenAPIHandler), (r"/api/authorizations/token", TokenAPIHandler), + (r"/api/oauth2/authorize", OAuthHandler), + (r"/api/oauth2/token", OAuthHandler), ] diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -12,6 +12,17 @@ from .base import APIHandler +class SelfAPIHandler(APIHandler): + """Return the authenticated user's model + + Based on the authentication info. Acts as a 'whoami' for auth tokens. + """ + @web.authenticated + def get(self): + user = self.get_current_user() + self.write(json.dumps(self.user_model(user))) + + class UserListAPIHandler(APIHandler): @admin_only def get(self): @@ -252,6 +263,8 @@ class UserAdminAccessAPIHandler(APIHandler): """ @admin_only def post(self, name): + self.log.warning("Deprecated in JupyterHub 0.8." + " Admin access API is not needed now that we use OAuth.") current = self.get_current_user() self.log.warning("Admin user %s has requested access to %s's server", current.name, name, @@ -263,15 +276,10 @@ def post(self, name): raise web.HTTPError(404) if not user.running: raise web.HTTPError(400, "%s's server is not running" % name) - self.set_server_cookie(user) - # a service can also ask for a user cookie - # this code prevents to raise an error - # cause service doesn't have 'other_user_cookies' - if getattr(current, 'other_user_cookies', None) is not None: - current.other_user_cookies.add(name) default_handlers = [ + (r"/api/user", SelfAPIHandler), (r"/api/users", UserListAPIHandler), (r"/api/users/([^/]+)", UserAPIHandler), (r"/api/users/([^/]+)/server", UserServerAPIHandler), diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -51,6 +51,7 @@ from . import dbutil, orm from .user import User, UserDict +from .oauth.store import make_provider from ._data import DATA_FILES_PATH from .log import CoroutineLogFormatter, log_request from .traitlets import URLPrefix, Command @@ -1040,6 +1041,7 @@ def init_services(self): host = '%s://services.%s' % (parsed.scheme, parsed.netloc) else: domain = host = '' + client_store = self.oauth_provider.client_authenticator.client_store for spec in self.services: if 'name' not in spec: raise ValueError('service spec must have a name: %r' % spec) @@ -1057,6 +1059,7 @@ def init_services(self): db=self.db, orm=orm_service, domain=domain, host=host, hub_api_url=self.hub.api_url, + hub=self.hub, ) traits = service.traits(input=True) @@ -1065,6 +1068,16 @@ def init_services(self): raise AttributeError("No such service field: %s" % key) setattr(service, key, value) + if service.managed: + if not service.api_token: + # generate new token + service.api_token = service.orm.new_api_token() + else: + # ensure provided token is registered + self.service_tokens[service.api_token] = service.name + else: + self.service_tokens[service.api_token] = service.name + if service.url: parsed = urlparse(service.url) if parsed.port is not None: @@ -1081,19 +1094,16 @@ def init_services(self): base_url=service.prefix, ) self.db.add(server) + + client_store.add_client( + client_id=service.oauth_client_id, + client_secret=service.api_token, + redirect_uri=host + url_path_join(service.prefix, 'oauth_callback'), + ) else: service.orm.server = None self._service_map[name] = service - if service.managed: - if not service.api_token: - # generate new token - service.api_token = service.orm.new_api_token() - else: - # ensure provided token is registered - self.service_tokens[service.api_token] = service.name - else: - self.service_tokens[service.api_token] = service.name # delete services from db not in service config: for service in self.db.query(orm.Service): @@ -1162,6 +1172,13 @@ def user_stopped(user): self.log.debug("Loaded users: %s", '\n'.join(user_summaries)) db.commit() + def init_oauth(self): + self.oauth_provider = make_provider( + self.session_factory, + url_prefix=url_path_join(self.hub.server.base_url, 'api/oauth2'), + login_url=self.authenticator.login_url(self.hub.server.base_url), + ) + def init_proxy(self): """Load the Proxy config into the database""" self.proxy = self.db.query(orm.Proxy).first() @@ -1327,6 +1344,7 @@ def init_tornado_settings(self): domain=self.domain, statsd=self.statsd, allow_multiple_servers=self.allow_multiple_servers, + oauth_provider=self.oauth_provider, ) # allow configured settings to have priority settings.update(self.tornado_settings) @@ -1369,6 +1387,7 @@ def initialize(self, *args, **kwargs): self.init_db() self.init_hub() self.init_proxy() + self.init_oauth() yield self.init_users() yield self.init_groups() self.init_services() diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -22,7 +22,7 @@ from ..utils import url_path_join # pattern for the authentication token header -auth_header_pat = re.compile(r'^token\s+([^\s]+)$') +auth_header_pat = re.compile(r'^(?:token|bearer)\s+([^\s]+)$', flags=re.IGNORECASE) # mapping of reason: reason_message reasons = { @@ -87,6 +87,10 @@ def statsd(self): def authenticator(self): return self.settings.get('authenticator', None) + @property + def oauth_provider(self): + return self.settings['oauth_provider'] + def finish(self, *args, **kwargs): """Roll back any uncommitted transactions from the handler.""" self.db.rollback() @@ -148,7 +152,7 @@ def get_current_user_token(self): if orm_token is None: return None else: - return orm_token.user or orm_token.service + return orm_token.service or self._user_from_orm(orm_token.user) def _user_for_cookie(self, cookie_name, cookie_value=None): """Get the User for a given cookie, if there is one""" @@ -248,10 +252,6 @@ def set_service_cookie(self, user): base_url=url_path_join(self.base_url, 'services') )) - def set_server_cookie(self, user): - """set the login cookie for the single-user server""" - self._set_user_cookie(user, user.server) - def set_hub_cookie(self, user): """set the login cookie for the Hub""" self._set_user_cookie(user, self.hub.server) @@ -262,9 +262,6 @@ def set_login_cookie(self, user): self.log.warning( "Possibly setting cookie on wrong domain: %s != %s", self.request.host, self.domain) - # create and set a new cookie token for the single-user server - if user.server: - self.set_server_cookie(user) # set single cookie for services if self.db.query(orm.Service).filter(orm.Service.server != None).first(): diff --git a/jupyterhub/oauth/__init__.py b/jupyterhub/oauth/__init__.py new file mode 100644 diff --git a/jupyterhub/oauth/store.py b/jupyterhub/oauth/store.py new file mode 100644 --- /dev/null +++ b/jupyterhub/oauth/store.py @@ -0,0 +1,250 @@ +"""Utilities for hooking up oauth2 to JupyterHub's database + +implements https://python-oauth2.readthedocs.io/en/latest/store.html +""" + +import threading + +from oauth2.datatype import Client, AccessToken, AuthorizationCode +from oauth2.error import AccessTokenNotFound, AuthCodeNotFound, ClientNotFoundError, UserNotAuthenticated +from oauth2.grant import AuthorizationCodeGrant +from oauth2.web import AuthorizationCodeGrantSiteAdapter +import oauth2.store +from oauth2 import Provider +from oauth2.tokengenerator import Uuid4 as UUID4 + +from sqlalchemy.orm import scoped_session +from tornado.escape import url_escape + +from .. import orm +from jupyterhub.orm import APIToken +from ..utils import url_path_join, hash_token, compare_token + + +class JupyterHubSiteAdapter(AuthorizationCodeGrantSiteAdapter): + """ + This adapter renders a confirmation page so the user can confirm the auth + request. + """ + def __init__(self, login_url): + self.login_url = login_url + + def render_auth_page(self, request, response, environ, scopes, client): + """Auth page is a redirect to login page""" + response.status_code = 302 + response.headers['Location'] = self.login_url + '?next={}'.format( + url_escape(request.handler.request.path + '?' + request.handler.request.query) + ) + return response + + def authenticate(self, request, environ, scopes, client): + handler = request.handler + user = handler.get_current_user() + if user: + return {}, user.id + else: + raise UserNotAuthenticated() + + def user_has_denied_access(self, request): + # user can't deny access + return False + + +class HubDBMixin(object): + """Mixin for connecting to the hub database""" + def __init__(self, session_factory): + self.session_factory = session_factory + self._local = threading.local() + + @property + def db(self): + if not hasattr(self._local, 'db'): + self._local.db = scoped_session(self.session_factory)() + return self._local.db + + +class AccessTokenStore(HubDBMixin, oauth2.store.AccessTokenStore): + """OAuth2 AccessTokenStore, storing data in the Hub database""" + + def _access_token_from_orm(self, orm_token): + """Transform an ORM AccessToken record into an oauth2 AccessToken instance""" + return AccessToken( + client_id=orm_token.client_id, + grant_type=orm_token.grant_type, + expires_at=orm_token.expires_at, + refresh_token=orm_token.refresh_token, + refresh_expires_at=orm_token.refresh_expires_at, + user_id=orm_token.user_id, + ) + + def save_token(self, access_token): + """ + Stores an access token in the database. + + :param access_token: An instance of :class:`oauth2.datatype.AccessToken`. + + """ + + user = self.db.query(orm.User).filter(orm.User.id == access_token.user_id).first() + token = user.new_api_token(access_token.token) + orm_api_token = APIToken.find(self.db, token, kind='user') + + orm_access_token = orm.OAuthAccessToken( + client_id=access_token.client_id, + grant_type=access_token.grant_type, + expires_at=access_token.expires_at, + refresh_token=access_token.refresh_token, + refresh_expires_at=access_token.refresh_expires_at, + user=user, + api_token=orm_api_token, + ) + self.db.add(orm_access_token) + self.db.commit() + + +class AuthCodeStore(HubDBMixin, oauth2.store.AuthCodeStore): + """ + OAuth2 AuthCodeStore, storing data in the Hub database + """ + def fetch_by_code(self, code): + """ + Returns an AuthorizationCode fetched from a storage. + + :param code: The authorization code. + :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. + :raises: :class:`oauth2.error.AuthCodeNotFound` if no data could be retrieved for + given code. + + """ + orm_code = self.db\ + .query(orm.OAuthCode)\ + .filter(orm.OAuthCode.code == code)\ + .first() + if orm_code is None: + raise AuthCodeNotFound() + else: + return AuthorizationCode( + client_id=orm_code.client_id, + code=code, + expires_at=orm_code.expires_at, + redirect_uri=orm_code.redirect_uri, + scopes=[], + user_id=orm_code.user_id, + ) + + + def save_code(self, authorization_code): + """ + Stores the data belonging to an authorization code token. + + :param authorization_code: An instance of + :class:`oauth2.datatype.AuthorizationCode`. + """ + orm_code = orm.OAuthCode( + client_id=authorization_code.client_id, + code=authorization_code.code, + expires_at=authorization_code.expires_at, + user_id=authorization_code.user_id, + redirect_uri=authorization_code.redirect_uri, + ) + self.db.add(orm_code) + self.db.commit() + + + def delete_code(self, code): + """ + Deletes an authorization code after its use per section 4.1.2. + + http://tools.ietf.org/html/rfc6749#section-4.1.2 + + :param code: The authorization code. + """ + orm_code = self.db.query(orm.OAuthCode).filter(orm.OAuthCode.code == code).first() + if orm_code is not None: + self.db.delete(orm_code) + self.db.commit() + + +class HashComparable: + """An object for storing hashed tokens + + Overrides `==` so that it compares as equal to its unhashed original + + Needed for storing hashed client_secrets + because python-oauth2 uses:: + + secret == client.client_secret + + and we don't want to store unhashed secrets in the database. + """ + def __init__(self, hashed_token): + self.hashed_token = hashed_token + + def __repr__(self): + return "<{} '{}'>".format(self.__class__.__name__, self.hashed_token) + + def __eq__(self, other): + return compare_token(self.hashed_token, other) + + +class ClientStore(HubDBMixin, oauth2.store.ClientStore): + """OAuth2 ClientStore, storing data in the Hub database""" + + def fetch_by_client_id(self, client_id): + """Retrieve a client by its identifier. + + :param client_id: Identifier of a client app. + :return: An instance of :class:`oauth2.datatype.Client`. + :raises: :class:`oauth2.error.ClientNotFoundError` if no data could be retrieved for + given client_id. + """ + orm_client = self.db\ + .query(orm.OAuthClient)\ + .filter(orm.OAuthClient.identifier == client_id)\ + .first() + if orm_client is None: + raise ClientNotFoundError() + return Client(identifier=client_id, + redirect_uris=[orm_client.redirect_uri], + secret=HashComparable(orm_client.secret), + ) + + def add_client(self, client_id, client_secret, redirect_uri): + """Add a client + + hash its client_secret before putting it in the database. + """ + # clear existing clients with same ID + for client in self.db\ + .query(orm.OAuthClient)\ + .filter(orm.OAuthClient.identifier == client_id): + self.db.delete(client) + self.db.commit() + + orm_client = orm.OAuthClient( + identifier=client_id, + secret=hash_token(client_secret), + redirect_uri=redirect_uri, + ) + self.db.add(orm_client) + self.db.commit() + + +def make_provider(session_factory, url_prefix, login_url): + """Make an OAuth provider""" + token_store = AccessTokenStore(session_factory) + code_store = AuthCodeStore(session_factory) + client_store = ClientStore(session_factory) + + provider = Provider( + access_token_store=token_store, + auth_code_store=code_store, + client_store=client_store, + token_generator=UUID4(), + ) + provider.token_path = url_path_join(url_prefix, 'token') + provider.authorize_path = url_path_join(url_prefix, 'authorize') + site_adapter = JupyterHubSiteAdapter(login_url=login_url) + provider.add_grant(AuthorizationCodeGrant(site_adapter=site_adapter)) + return provider + diff --git a/jupyterhub/orm.py b/jupyterhub/orm.py --- a/jupyterhub/orm.py +++ b/jupyterhub/orm.py @@ -4,6 +4,7 @@ # Distributed under the terms of the Modified BSD License. from datetime import datetime +import enum import json from tornado import gen @@ -14,7 +15,7 @@ from sqlalchemy import ( inspect, Column, Integer, ForeignKey, Unicode, Boolean, - DateTime, + DateTime, Enum ) from sqlalchemy.ext.declarative import declarative_base, declared_attr from sqlalchemy.orm import sessionmaker, relationship, backref @@ -512,7 +513,6 @@ class APIToken(Base): """An API token""" __tablename__ = 'api_tokens' - # _constraint = ForeignKeyConstraint(['user_id', 'server_id'], ['users.id', 'services.id']) @declared_attr def user_id(cls): return Column(Integer, ForeignKey('users.id', ondelete="CASCADE"), nullable=True) @@ -610,6 +610,53 @@ def new(cls, token=None, user=None, service=None): return token +#------------------------------------ +# OAuth tables +#------------------------------------ + + +class GrantType(enum.Enum): + # we only use authorization_code for now + authorization_code = 'authorization_code' + implicit = 'implicit' + password = 'password' + client_credentials = 'client_credentials' + refresh_token = 'refresh_token' + + +class OAuthAccessToken(Base): + __tablename__ = 'oauth_access_tokens' + id = Column(Integer, primary_key=True, autoincrement=True) + + client_id = Column(Unicode(1023)) + grant_type = Column(Enum(GrantType), nullable=False) + expires_at = Column(Integer) + refresh_token = Column(Unicode(36)) + refresh_expires_at = Column(Integer) + user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE')) + user = relationship(User) + api_token_id = Column(Integer, ForeignKey('api_tokens.id', ondelete='CASCADE')) + api_token = relationship(APIToken, backref='oauth_token') + + +class OAuthCode(Base): + __tablename__ = 'oauth_codes' + id = Column(Integer, primary_key=True, autoincrement=True) + client_id = Column(Unicode(1023)) + code = Column(Unicode(36)) + expires_at = Column(Integer) + redirect_uri = Column(Unicode(1023)) + user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE')) + + +class OAuthClient(Base): + __tablename__ = 'oauth_clients' + id = Column(Integer, primary_key=True, autoincrement=True) + identifier = Column(Unicode(1023), unique=True) + secret = Column(Unicode(1023)) + redirect_uri = Column(Unicode(1023)) + + def new_session_factory(url="sqlite:///:memory:", reset=False, **kwargs): """Create a new session at url""" if url.startswith('sqlite'): diff --git a/jupyterhub/services/auth.py b/jupyterhub/services/auth.py --- a/jupyterhub/services/auth.py +++ b/jupyterhub/services/auth.py @@ -7,20 +7,23 @@ HubAuthenticated is a mixin class for tornado handlers that should authenticate with the Hub. """ +import json import os import re import socket import time -from urllib.parse import quote +from urllib.parse import quote, urlencode import warnings import requests +from tornado.gen import coroutine from tornado.log import app_log -from tornado.web import HTTPError +from tornado.httputil import url_concat +from tornado.web import HTTPError, RequestHandler from traitlets.config import Configurable -from traitlets import Unicode, Integer, Instance, default, observe +from traitlets import Unicode, Integer, Instance, default, observe, validate from ..utils import url_path_join @@ -102,31 +105,80 @@ class HubAuth(Configurable): """ + hub_host = Unicode('', + help="""The public host of JupyterHub + + Only used if JupyterHub is spreading servers across subdomains. + """ + ).tag(config=True) + @default('hub_host') + def _default_hub_host(self): + return os.getenv('JUPYTERHUB_HOST', '') + + base_url = Unicode(os.getenv('JUPYTERHUB_SERVICE_PREFIX') or '/', + help="""The base URL prefix of this application + + e.g. /services/service-name/ or /user/name/ + + Default: get from JUPYTERHUB_SERVICE_PREFIX + """ + ).tag(config=True) + @validate('base_url') + def _add_slash(self, proposal): + """Ensure base_url starts and ends with /""" + value = proposal['value'] + if not value.startswith('/'): + value = '/' + value + if not value.endswith('/'): + value = value + '/' + return value + # where is the hub - api_url = Unicode(os.environ.get('JUPYTERHUB_API_URL') or 'http://127.0.0.1:8081/hub/api', + api_url = Unicode(os.getenv('JUPYTERHUB_API_URL') or 'http://127.0.0.1:8081/hub/api', help="""The base API URL of the Hub. Typically http://hub-ip:hub-port/hub/api """ ).tag(config=True) + @default('api_url') + def _api_url(self): + env_url = os.getenv('JUPYTERHUB_API_URL') + if env_url: + return env_url + else: + return 'http://127.0.0.1:8081' + url_path_join(self.hub_prefix, 'api') + + api_token = Unicode(os.getenv('JUPYTERHUB_API_TOKEN', ''), + help="""API key for accessing Hub API. - login_url = Unicode('/hub/login', - help="""The login URL of the Hub - - Typically /hub/login + Generate with `jupyterhub token [username]` or add to JupyterHub.services config. """ ).tag(config=True) - api_token = Unicode(os.environ.get('JUPYTERHUB_API_TOKEN', ''), - help="""API key for accessing Hub API. + hub_prefix = Unicode('/hub/', + help="""The URL prefix for the Hub itself. + + Typically /hub/ + """ + ).tag(config=True) + @default('hub_prefix') + def _default_hub_prefix(self): + return url_path_join(os.getenv('JUPYTERHUB_BASE_URL') or '/', 'hub') + '/' - Generate with `jupyterhub token [username]` or add to JupyterHub.services config. + login_url = Unicode('/hub/login', + help="""The login URL to use + + Typically /hub/login """ ).tag(config=True) + @default('login_url') + def _default_login_url(self): + return self.hub_host + url_path_join(self.hub_prefix, 'login') cookie_name = Unicode('jupyterhub-services', help="""The name of the cookie I should be looking for""" ).tag(config=True) + cookie_cache_max_age = Integer(help="DEPRECATED. Use cache_max_age") @observe('cookie_cache_max_age') def _deprecated_cookie_cache(self, change): @@ -169,12 +221,23 @@ def _check_hub_authorization(self, url, cache_key=None, use_cache=True): if cached is not None: return cached + data = self._api_request('GET', url, allow_404=True) + if data is None: + app_log.warning("No Hub user identified for request") + else: + app_log.debug("Received request from Hub user %s", data) + if use_cache: + # cache result + self.cache[cache_key] = data + return data + + def _api_request(self, method, url, **kwargs): + """Make an API request""" + allow_404 = kwargs.pop('allow_404', False) + headers = kwargs.setdefault('headers', {}) + headers.setdefault('Authorization', 'token %s' % self.api_token) try: - r = requests.get(url, - headers = { - 'Authorization' : 'token %s' % self.api_token, - }, - ) + r = requests.request(method, url, **kwargs) except requests.ConnectionError: msg = "Failed to connect to Hub API at %r." % self.api_url msg += " Is the Hub accessible at this URL (from host: %s)?" % socket.gethostname() @@ -184,27 +247,25 @@ def _check_hub_authorization(self, url, cache_key=None, use_cache=True): raise HTTPError(500, msg) data = None - if r.status_code == 404: - app_log.warning("No Hub user identified for request") + if r.status_code == 404 and allow_404: + pass elif r.status_code == 403: app_log.error("I don't have permission to check authorization with JupyterHub, my auth token may have expired: [%i] %s", r.status_code, r.reason) + app_log.error(r.text) raise HTTPError(500, "Permission failure checking authorization, I may need a new token") elif r.status_code >= 500: app_log.error("Upstream failure verifying auth token: [%i] %s", r.status_code, r.reason) + app_log.error(r.text) raise HTTPError(502, "Failed to check authorization (upstream problem)") elif r.status_code >= 400: app_log.warning("Failed to check authorization: [%i] %s", r.status_code, r.reason) + app_log.warning(r.text) raise HTTPError(500, "Failed to check authorization") else: data = r.json() - app_log.debug("Received request from Hub user %s", data) - if use_cache: - # cache result - self.cache[cache_key] = data return data - def user_for_cookie(self, encrypted_cookie, use_cache=True): """Ask the Hub to identify the user for a given cookie. @@ -264,6 +325,12 @@ def get_token(self, handler): user_token = m.group(1) return user_token + def _get_user_cookie(self, handler): + """Get the user model from a cookie""" + encrypted_cookie = handler.get_cookie(self.cookie_name) + if encrypted_cookie: + return self.user_for_cookie(encrypted_cookie) + def get_user(self, handler): """Get the Hub user for a given tornado handler. @@ -295,9 +362,7 @@ def get_user(self, handler): # no token, check cookie if user_model is None: - encrypted_cookie = handler.get_cookie(self.cookie_name) - if encrypted_cookie: - user_model = self.user_for_cookie(encrypted_cookie) + user_model = self._get_user_cookie(handler) # cache result handler._cached_hub_user = user_model @@ -306,6 +371,130 @@ def get_user(self, handler): return user_model +class HubOAuth(HubAuth): + """HubAuth using OAuth for login instead of cookies set by the Hub. + + .. versionadded: 0.8 + """ + + # Overrides of HubAuth API + + @default('login_url') + def _login_url(self): + return url_concat(self.oauth_authorization_url, { + 'client_id': self.oauth_client_id, + 'redirect_uri': self.oauth_redirect_uri, + 'response_type': 'code', + }) + + @property + def cookie_name(self): + """Use OAuth client_id for cookie name + + because we don't want to use the same cookie name + across OAuth clients. + """ + return self.oauth_client_id + + def _get_user_cookie(self, handler): + token = handler.get_secure_cookie(self.cookie_name) + if token: + user_model = self.user_for_token(token) + if user_model is None: + app_log.warning("Token stored in cookie may have expired") + handler.clear_cookie(self.cookie_name) + return user_model + + # HubOAuth API + + oauth_client_id = Unicode( + help="""The OAuth client ID for this application. + + Use JUPYTERHUB_CLIENT_ID by default. + """ + ).tag(config=True) + @default('oauth_client_id') + def _client_id(self): + return os.getenv('JUPYTERHUB_CLIENT_ID', '') + + @validate('oauth_client_id', 'api_token') + def _ensure_not_empty(self, proposal): + if not proposal.value: + raise ValueError("%s cannot be empty." % proposal.trait.name) + return proposal.value + + oauth_redirect_uri = Unicode( + help="""OAuth redirect URI + + Should generally be /base_url/oauth_callback + """ + ).tag(config=True) + @default('oauth_redirect_uri') + def _default_redirect(self): + return os.getenv('JUPYTERHUB_OAUTH_CALLBACK_URL') or url_path_join(self.base_url, 'oauth_callback') + + oauth_authorization_url = Unicode('/hub/api/oauth2/authorize', + help="The URL to redirect to when starting the OAuth process", + ).tag(config=True) + @default('oauth_authorization_url') + def _auth_url(self): + return self.hub_host + url_path_join(self.hub_prefix, 'api/oauth2/authorize') + + oauth_token_url = Unicode( + help="""The URL for requesting an OAuth token from JupyterHub""" + ).tag(config=True) + @default('oauth_token_url') + def _token_url(self): + return url_path_join(self.api_url, 'oauth2/token') + + def token_for_code(self, code): + """Get token for OAuth temporary code + + This is the last step of OAuth login. + Should be called in OAuth Callback handler. + + Args: + code (str): oauth code for finishing OAuth login + Returns: + token (str): JupyterHub API Token + """ + # GitHub specifies a POST request yet requires URL parameters + params = dict( + client_id=self.oauth_client_id, + client_secret=self.api_token, + grant_type='authorization_code', + code=code, + redirect_uri=self.oauth_redirect_uri, + ) + + token_reply = self._api_request('POST', self.oauth_token_url, + data=urlencode(params).encode('utf8'), + headers={ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + return token_reply['access_token'] + + def set_cookie(self, handler, access_token): + """Set a cookie recording OAuth result""" + kwargs = { + 'path': self.base_url, + } + if handler.request.protocol == 'https': + kwargs['secure'] = True + app_log.debug("Setting oauth cookie for %s: %s, %s", + handler.request.remote_ip, self.cookie_name, kwargs) + handler.set_secure_cookie( + self.cookie_name, + access_token, + **kwargs + ) + def clear_cookie(self, handler): + """Clear the OAuth cookie""" + handler.clear_cookie(self.cookie_name, path=self.base_url) + + + class HubAuthenticated(object): """Mixin for tornado handlers that are authenticated with JupyterHub @@ -333,6 +522,7 @@ def get(self): hub_services = None # set of allowed services hub_users = None # set of allowed users hub_groups = None # set of allowed groups + allow_admin = False # allow any admin user access @property def allow_all(self): @@ -348,10 +538,11 @@ def allow_all(self): # which will be configured with defaults # based on JupyterHub environment variables for services. _hub_auth = None + hub_auth_class = HubAuth @property def hub_auth(self): if self._hub_auth is None: - self._hub_auth = HubAuth() + self._hub_auth = self.hub_auth_class() return self._hub_auth @hub_auth.setter @@ -360,6 +551,7 @@ def hub_auth(self, auth): def get_login_url(self): """Return the Hub's login URL""" + app_log.debug("Redirecting to login url: %s" % self.hub_auth.login_url) return self.hub_auth.login_url def check_hub_user(self, model): @@ -374,13 +566,17 @@ def check_hub_user(self, model): Returns: user_model (dict): The user model if the user should be allowed, None otherwise. """ - + name = model['name'] kind = model.get('kind', 'user') if self.allow_all: app_log.debug("Allowing Hub %s %s (all Hub users and services allowed)", kind, name) return model + if self.allow_admin and model.get('admin', False): + app_log.debug("Allowing Hub admin %s", name) + return model + if kind == 'service': # it's a service, check hub_services if self.hub_services and name in self.hub_services: @@ -418,3 +614,33 @@ def get_current_user(self): self._hub_auth_user_cache = self.check_hub_user(user_model) return self._hub_auth_user_cache + +class HubOAuthenticated(HubAuthenticated): + """Simple subclass of HubAuthenticated using OAuth instead of old shared cookies""" + hub_auth_class = HubOAuth + + +class HubOAuthCallbackHandler(HubOAuthenticated, RequestHandler): + """OAuth Callback handler + + Finishes the OAuth flow, setting a cookie to record the user's info. + + Should be registered at SERVICE_PREFIX/oauth_callback + + .. versionadded: 0.8 + """ + + @coroutine + def get(self): + code = self.get_argument("code", False) + if not code: + raise HTTPError(400, "oauth callback made without a token") + # TODO: make async (in a Thread?) + token = self.hub_auth.token_for_code(code) + user_model = self.hub_auth.user_for_token(token) + app_log.info("Logged-in user %s", user_model) + self.hub_auth.set_cookie(self, token) + next_url = self.get_argument('next', '') or self.hub_auth.base_url + self.redirect(next_url) + + diff --git a/jupyterhub/services/service.py b/jupyterhub/services/service.py --- a/jupyterhub/services/service.py +++ b/jupyterhub/services/service.py @@ -43,14 +43,11 @@ import pipes import shutil from subprocess import Popen -from urllib.parse import urlparse - -from tornado import gen from traitlets import ( HasTraits, Any, Bool, Dict, Unicode, Instance, - default, observe, + default, ) from traitlets.config import LoggingConfigurable @@ -64,6 +61,16 @@ class _MockUser(HasTraits): server = Instance(orm.Server, allow_none=True) state = Dict() service = Instance(__module__ + '.Service') + host = Unicode() + + @property + def url(self): + if not self.server: + return '' + if self.host: + return self.host + self.server.base_url + else: + return self.server.base_url # We probably shouldn't use a Spawner here, # but there are too many concepts to share. @@ -190,6 +197,7 @@ def kind(self): domain = Unicode() host = Unicode() + hub = Any() proc = Any() # handles on globals: @@ -198,6 +206,19 @@ def kind(self): db = Any() orm = Any() + oauth_provider = Any() + + oauth_client_id = Unicode( + help="""OAuth client ID for this service. + + You shouldn't generally need to change this. + Default: `service-<name>` + """ + ).tag(input=True) + @default('oauth_client_id') + def _default_client_id(self): + return 'service-%s' % self.name + @property def server(self): return self.orm.server @@ -242,11 +263,14 @@ def start(self): cmd=self.command, environment=env, api_token=self.api_token, + oauth_client_id=self.oauth_client_id, cwd=self.cwd, + hub=self.hub, user=_MockUser( name=self.user, service=self, server=self.orm.server, + host=self.host, ), ) self.spawner.start() diff --git a/jupyterhub/singleuser.py b/jupyterhub/singleuser.py --- a/jupyterhub/singleuser.py +++ b/jupyterhub/singleuser.py @@ -34,17 +34,23 @@ ) from notebook.auth.login import LoginHandler from notebook.auth.logout import LogoutHandler +from notebook.base.handlers import IPythonHandler from jupyterhub import __version__ -from .services.auth import HubAuth, HubAuthenticated +from .services.auth import HubOAuth, HubOAuthenticated, HubOAuthCallbackHandler from .utils import url_path_join # Authenticate requests with the Hub -class HubAuthenticatedHandler(HubAuthenticated): +class HubAuthenticatedHandler(HubOAuthenticated): """Class we are going to patch-in for authentication with the Hub""" + + @property + def allow_admin(self): + return self.settings.get('admin_access', os.getenv('JUPYTERHUB_ADMIN_ACCESS') or False) + @property def hub_auth(self): return self.settings['hub_auth'] @@ -78,9 +84,12 @@ def is_token_authenticated(handler): def get_user(handler): """alternative get_current_user to query the Hub""" # patch in HubAuthenticated class for querying the Hub for cookie authentication - name = 'NowHubAuthenticated' - if handler.__class__.__name__ != name: - handler.__class__ = type(name, (HubAuthenticatedHandler, handler.__class__), {}) + if HubAuthenticatedHandler not in handler.__class__.__bases__: + handler.__class__ = type( + handler.__class__.__name__, + (HubAuthenticatedHandler, handler.__class__), + {}, + ) return handler.get_current_user() @classmethod @@ -91,11 +100,31 @@ def validate_security(cls, app, ssl_options=None): class JupyterHubLogoutHandler(LogoutHandler): def get(self): + self.settings['hub_auth'].clear_cookie(self) self.redirect( self.settings['hub_host'] + url_path_join(self.settings['hub_prefix'], 'logout')) +class OAuthCallbackHandler(HubOAuthCallbackHandler, IPythonHandler): + """Mixin IPythonHandler to get the right error pages, etc.""" + @property + def hub_auth(self): + return self.settings['hub_auth'] + + def get(self): + code = self.get_argument("code", False) + if not code: + raise HTTPError(400, "oauth callback made without a token") + # TODO: make async (in a Thread?) + token = self.hub_auth.token_for_code(code) + user_model = self.hub_auth.user_for_token(token) + self.log.info("Logged-in user %s", user_model) + self.hub_auth.set_cookie(self, token) + next_url = self.get_argument('next', '') or self.base_url + self.redirect(next_url) + + # register new hub related command-line aliases aliases = dict(notebook_aliases) aliases.update({ @@ -156,7 +185,7 @@ class SingleUserNotebookApp(NotebookApp): examples = "" subcommands = {} version = __version__ - classes = NotebookApp.classes + [HubAuth] + classes = NotebookApp.classes + [HubOAuth] user = CUnicode().tag(config=True) group = CUnicode().tag(config=True) @@ -307,14 +336,16 @@ def init_hub_auth(self): if not api_token: self.exit("JUPYTERHUB_API_TOKEN env is required to run jupyterhub-singleuser. Did you launch it manually?") - self.hub_auth = HubAuth( + self.hub_auth = HubOAuth( parent=self, api_token=api_token, api_url=self.hub_api_url, + hub_prefix=self.hub_prefix, + base_url=self.base_url, ) def init_webapp(self): - # load the hub related settings into the tornado settings dict + # load the hub-related settings into the tornado settings dict self.init_hub_auth() s = self.tornado_settings s['user'] = self.user @@ -322,11 +353,17 @@ def init_webapp(self): s['hub_prefix'] = self.hub_prefix s['hub_host'] = self.hub_host s['hub_auth'] = self.hub_auth - self.hub_auth.login_url = self.hub_host + self.hub_prefix s['csp_report_uri'] = self.hub_host + url_path_join(self.hub_prefix, 'security/csp-report') super(SingleUserNotebookApp, self).init_webapp() - self.patch_templates() + # add OAuth callback + self.web_app.add_handlers(r".*$", [( + urlparse(self.hub_auth.oauth_redirect_uri).path, + OAuthCallbackHandler + )]) + + self.patch_templates() + def patch_templates(self): """Patch page templates to add Hub-related buttons""" diff --git a/jupyterhub/spawner.py b/jupyterhub/spawner.py --- a/jupyterhub/spawner.py +++ b/jupyterhub/spawner.py @@ -27,7 +27,7 @@ ) from .traitlets import Command, ByteSpecification -from .utils import random_port +from .utils import random_port, url_path_join class Spawner(LoggingConfigurable): @@ -50,7 +50,9 @@ class Spawner(LoggingConfigurable): user = Any() hub = Any() authenticator = Any() + admin_access = Bool(False) api_token = Unicode() + oauth_client_id = Unicode() will_resume = Bool(False, help="""Whether the Spawner will resume on next start @@ -425,6 +427,13 @@ def get_env(self): env['JUPYTERHUB_API_TOKEN'] = self.api_token # deprecated (as of 0.7.2), for old versions of singleuser env['JPY_API_TOKEN'] = self.api_token + if self.admin_access: + env['JUPYTERHUB_ADMIN_ACCESS'] = '1' + # OAuth settings + env['JUPYTERHUB_CLIENT_ID'] = self.oauth_client_id + env['JUPYTERHUB_HOST'] = self.hub.host + env['JUPYTERHUB_OAUTH_CALLBACK_URL'] = \ + url_path_join(self.user.url, 'oauth_callback') # Put in limit and guarantee info if they exist. # Note that this is for use by the humans / notebook extensions in the @@ -486,7 +495,6 @@ def get_args(self): """ args = [ '--user="%s"' % self.user.name, - '--cookie-name="%s"' % self.user.server.cookie_name, '--base-url="%s"' % self.user.server.base_url, '--hub-host="%s"' % self.hub.host, '--hub-prefix="%s"' % self.hub.server.base_url, diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -4,12 +4,12 @@ from datetime import datetime, timedelta from urllib.parse import quote, urlparse +from oauth2.error import ClientNotFoundError +from sqlalchemy import inspect from tornado import gen from tornado.log import app_log -from sqlalchemy import inspect - -from .utils import url_path_join, default_server_name +from .utils import url_path_join, default_server_name, new_token from . import orm from traitlets import HasTraits, Any, Dict, observe, default @@ -213,7 +213,6 @@ def spawn(self, options=None): url of the server will be /user/:name/:server_name """ db = self.db - if self.allow_named_servers: if options is not None and 'server_name' in options: server_name = options['server_name'] @@ -242,7 +241,28 @@ def spawn(self, options=None): spawner.user_options = options or {} # we are starting a new server, make sure it doesn't restore state spawner.clear_state() + + # create API and OAuth tokens spawner.api_token = api_token + spawner.admin_access = self.settings.get('admin_access', False) + client_id = 'user-%s' % self.escaped_name + if server_name: + client_id = '%s-%s' % (client_id, server_name) + spawner.oauth_client_id = client_id + oauth_provider = self.settings.get('oauth_provider') + if oauth_provider: + client_store = oauth_provider.client_authenticator.client_store + try: + oauth_client = client_store.fetch_by_client_id(client_id) + except ClientNotFoundError: + oauth_client = None + # create a new OAuth client + secret on every launch, + # except for resuming containers. + if oauth_client is None or not spawner.will_resume: + client_store.add_client(client_id, api_token, + url_path_join(self.url, 'oauth_callback'), + ) + db.commit() # trigger pre-spawn hook on authenticator authenticator = self.authenticator
diff --git a/jupyterhub/tests/conftest.py b/jupyterhub/tests/conftest.py --- a/jupyterhub/tests/conftest.py +++ b/jupyterhub/tests/conftest.py @@ -68,30 +68,32 @@ def fin(): class MockServiceSpawner(jupyterhub.services.service._ServiceSpawner): poll_interval = 1 +_mock_service_counter = 0 def _mockservice(request, app, url=False): - name = 'mock-service' + global _mock_service_counter + _mock_service_counter += 1 + name = 'mock-service-%i' % _mock_service_counter spec = { 'name': name, 'command': mockservice_cmd, 'admin': True, } if url: - spec['url'] = 'http://127.0.0.1:%i' % random_port(), + spec['url'] = 'http://127.0.0.1:%i' % random_port() with mock.patch.object(jupyterhub.services.service, '_ServiceSpawner', MockServiceSpawner): - app.services = [{ - 'name': name, - 'command': mockservice_cmd, - 'url': 'http://127.0.0.1:%i' % random_port(), - 'admin': True, - }] + app.services = [spec] app.init_services() app.io_loop.add_callback(app.proxy.add_all_services, app._service_map) assert name in app._service_map service = app._service_map[name] app.io_loop.add_callback(service.start) - request.addfinalizer(service.stop) + def cleanup(): + service.stop() + app.services[:] = [] + app._service_map.clear() + request.addfinalizer(cleanup) for i in range(20): if not getattr(service, 'proc', False): time.sleep(0.2) diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -254,6 +254,8 @@ def _run(): with mock.patch.dict(os.environ, env): app = self._app = MockSingleUserServer() app.initialize(args) + assert app.hub_auth.oauth_client_id + assert app.hub_auth.api_token app.start() self._thread = threading.Thread(target=_run) diff --git a/jupyterhub/tests/mockservice.py b/jupyterhub/tests/mockservice.py --- a/jupyterhub/tests/mockservice.py +++ b/jupyterhub/tests/mockservice.py @@ -11,13 +11,15 @@ """ import json +import pprint import os +import sys from urllib.parse import urlparse import requests from tornado import web, httpserver, ioloop -from jupyterhub.services.auth import HubAuthenticated +from jupyterhub.services.auth import HubAuthenticated, HubOAuthenticated, HubOAuthCallbackHandler class EchoHandler(web.RequestHandler): @@ -47,21 +49,37 @@ def get(self, path): class WhoAmIHandler(HubAuthenticated, web.RequestHandler): - """Reply with the name of the user who made the request.""" + """Reply with the name of the user who made the request. + + Uses deprecated cookie login + """ + @web.authenticated + def get(self): + self.write(self.get_current_user()) + +class OWhoAmIHandler(HubOAuthenticated, web.RequestHandler): + """Reply with the name of the user who made the request. + + Uses OAuth login flow + """ @web.authenticated def get(self): self.write(self.get_current_user()) def main(): - if os.environ['JUPYTERHUB_SERVICE_URL']: + pprint.pprint(dict(os.environ), stream=sys.stderr) + + if os.getenv('JUPYTERHUB_SERVICE_URL'): url = urlparse(os.environ['JUPYTERHUB_SERVICE_URL']) app = web.Application([ (r'.*/env', EnvHandler), (r'.*/api/(.*)', APIHandler), (r'.*/whoami/?', WhoAmIHandler), + (r'.*/owhoami/?', OWhoAmIHandler), + (r'.*/oauth_callback', HubOAuthCallbackHandler), (r'.*', EchoHandler), - ]) + ], cookie_secret=os.urandom(32)) server = httpserver.HTTPServer(app) server.listen(url.port, url.hostname) @@ -70,6 +88,7 @@ def main(): except KeyboardInterrupt: print('\nInterrupted') + if __name__ == '__main__': from tornado.options import parse_command_line parse_command_line() diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -533,15 +533,16 @@ def test_cookie(app): app_user = get_app_user(app, name) cookies = app.login_user(name) + cookie_name = app.hub.server.cookie_name # cookie jar gives '"cookie-value"', we want 'cookie-value' - cookie = cookies[user.server.cookie_name][1:-1] + cookie = cookies[cookie_name][1:-1] r = api_request(app, 'authorizations/cookie', - user.server.cookie_name, "nothintoseehere", + cookie_name, "nothintoseehere", ) assert r.status_code == 404 r = api_request(app, 'authorizations/cookie', - user.server.cookie_name, quote(cookie, safe=''), + cookie_name, quote(cookie, safe=''), ) r.raise_for_status() reply = r.json() @@ -549,7 +550,7 @@ def test_cookie(app): # deprecated cookie in body: r = api_request(app, 'authorizations/cookie', - user.server.cookie_name, data=cookie, + cookie_name, data=cookie, ) r.raise_for_status() reply = r.json() @@ -722,7 +723,8 @@ def test_group_delete_users(app): @mark.services -def test_get_services(app, mockservice): +def test_get_services(app, mockservice_url): + mockservice = mockservice_url db = app.db r = api_request(app, 'services') r.raise_for_status() @@ -730,8 +732,8 @@ def test_get_services(app, mockservice): services = r.json() assert services == { - 'mock-service': { - 'name': 'mock-service', + mockservice.name: { + 'name': mockservice.name, 'admin': True, 'command': mockservice.command, 'pid': mockservice.proc.pid, @@ -747,7 +749,8 @@ def test_get_services(app, mockservice): @mark.services -def test_get_service(app, mockservice): +def test_get_service(app, mockservice_url): + mockservice = mockservice_url db = app.db r = api_request(app, 'services/%s' % mockservice.name) r.raise_for_status() @@ -755,7 +758,7 @@ def test_get_service(app, mockservice): service = r.json() assert service == { - 'name': 'mock-service', + 'name': mockservice.name, 'admin': True, 'command': mockservice.command, 'pid': mockservice.proc.pid, diff --git a/jupyterhub/tests/test_orm.py b/jupyterhub/tests/test_orm.py --- a/jupyterhub/tests/test_orm.py +++ b/jupyterhub/tests/test_orm.py @@ -183,7 +183,7 @@ def start(self): 'config': None, }) - with pytest.raises(Exception) as exc: + with pytest.raises(RuntimeError) as exc: io_loop.run_sync(user.spawn) assert user.server is None assert not user.running diff --git a/jupyterhub/tests/test_services_auth.py b/jupyterhub/tests/test_services_auth.py --- a/jupyterhub/tests/test_services_auth.py +++ b/jupyterhub/tests/test_services_auth.py @@ -18,7 +18,7 @@ from ..services.auth import _ExpiringDict, HubAuth, HubAuthenticated from ..utils import url_path_join -from .mocking import public_url +from .mocking import public_url, public_host from .test_api import add_user # mock for sending monotonic counter way into the future @@ -244,7 +244,6 @@ def test_hubauth_token(app, mockservice_url): headers={ 'Authorization': 'token %s' % token, }) - r.raise_for_status() reply = r.json() sub_reply = { key: reply.get(key, 'missing') for key in ['name', 'admin']} assert sub_reply == { @@ -312,3 +311,23 @@ def test_hubauth_service_token(app, mockservice_url, io_loop): path = urlparse(location).path assert path.endswith('/hub/login') + +def test_oauth_service(app, mockservice_url): + url = url_path_join(public_url(app, mockservice_url) + 'owhoami/') + # first request is only going to set login cookie + # FIXME: redirect to originating URL (OAuth loses this info) + s = requests.Session() + s.cookies = app.login_user('link') + r = s.get(url) + r.raise_for_status() + # second request should be authenticated + r = s.get(url, allow_redirects=False) + r.raise_for_status() + assert r.status_code == 200 + reply = r.json() + sub_reply = { key:reply.get(key, 'missing') for key in ('kind', 'name') } + assert sub_reply == { + 'name': 'link', + 'kind': 'user', + } + diff --git a/jupyterhub/tests/test_spawner.py b/jupyterhub/tests/test_spawner.py --- a/jupyterhub/tests/test_spawner.py +++ b/jupyterhub/tests/test_spawner.py @@ -16,6 +16,7 @@ import requests from tornado import gen +from ..user import User from .. import spawner as spawnermod from ..spawner import LocalProcessSpawner from .. import orm @@ -42,7 +43,7 @@ def setup(): def new_spawner(db, **kwargs): kwargs.setdefault('cmd', [sys.executable, '-c', _echo_sleep]) - kwargs.setdefault('user', db.query(orm.User).first()) + kwargs.setdefault('user', User(db.query(orm.User).first(), {})) kwargs.setdefault('hub', db.query(orm.Hub).first()) kwargs.setdefault('notebook_dir', os.getcwd()) kwargs.setdefault('default_url', '/user/{username}/lab')
Make JupyterHub an OAuth provider When discussing deploying services and things, we need to provide a mechanism for services to authenticate with the Hub. nbgrader [has an implementation of this](https://github.com/jupyter/nbgrader/blob/v0.2.2/nbgrader/auth/hubauth.py) with the current JupyterHub scheme. We're planning to make an importable implementation in JupyterHub for use in tornado-based apps, which should cover many cases. However, if we just made JupyterHub an OAuth provider then services written in many different ways could more easily "authenticate with JupyterHub" using standard libraries for whatever toolkit they use. I'm not planning to do this any time soon, but writing it down here, just in case.
2017-01-16T13:51:35Z
[]
[]
jupyterhub/jupyterhub
961
jupyterhub__jupyterhub-961
[ "891" ]
43c02740abfaf87451063e5f69ff33a9fa9943be
diff --git a/examples/service-whoami-flask/whoami.py b/examples/service-whoami-flask/whoami.py --- a/examples/service-whoami-flask/whoami.py +++ b/examples/service-whoami-flask/whoami.py @@ -29,7 +29,7 @@ def main(): app = Application([ (os.environ['JUPYTERHUB_SERVICE_PREFIX'] + '/?', WhoAmIHandler), (r'.*', WhoAmIHandler), - ], login_url='/hub/login') + ]) http_server = HTTPServer(app) url = urlparse(os.environ['JUPYTERHUB_SERVICE_URL']) diff --git a/jupyterhub/services/auth.py b/jupyterhub/services/auth.py --- a/jupyterhub/services/auth.py +++ b/jupyterhub/services/auth.py @@ -8,6 +8,7 @@ """ import os +import re import socket import time from urllib.parse import quote @@ -18,10 +19,11 @@ from tornado.web import HTTPError from traitlets.config import Configurable -from traitlets import Unicode, Integer, Instance, default +from traitlets import Unicode, Integer, Instance, default, observe from ..utils import url_path_join + class _ExpiringDict(dict): """Dict-like cache for Hub API requests @@ -124,8 +126,14 @@ class HubAuth(Configurable): cookie_name = Unicode('jupyterhub-services', help="""The name of the cookie I should be looking for""" ).tag(config=True) - cookie_cache_max_age = Integer(300, - help="""The maximum time (in seconds) to cache the Hub's response for cookie authentication. + cookie_cache_max_age = Integer(help="DEPRECATED. Use cache_max_age") + @observe('cookie_cache_max_age') + def _deprecated_cookie_cache(self, change): + warnings.warn("cookie_cache_max_age is deprecated in JupyterHub 0.8. Use cache_max_age instead.") + self.cache_max_age = change.new + + cache_max_age = Integer(300, + help="""The maximum time (in seconds) to cache the Hub's responses for authentication. A larger value reduces load on the Hub and occasional response lag. A smaller value reduces propagation time of changes on the Hub (rare). @@ -133,19 +141,51 @@ class HubAuth(Configurable): Default: 300 (five minutes) """ ).tag(config=True) - cookie_cache = Instance(_ExpiringDict, allow_none=False) - @default('cookie_cache') - def _cookie_cache(self): - return _ExpiringDict(self.cookie_cache_max_age) + cache = Instance(_ExpiringDict, allow_none=False) + @default('cache') + def _default_cache(self): + return _ExpiringDict(self.cache_max_age) + + def _check_hub_authorization(self, url, cache_key=None, use_cache=True): + """Identify a user with the Hub + + Args: + url (str): The API URL to check the Hub for authorization + (e.g. http://127.0.0.1:8081/hub/api/authorizations/token/abc-def) + cache_key (str): The key for checking the cache + use_cache (bool): Specify use_cache=False to skip cached cookie values (default: True) - def _check_response_for_authorization(self, r): - """Verify the response for authorizing a user + Returns: + user_model (dict): The user model, if a user is identified, None if authentication fails. - Raises an error if the response failed, otherwise returns the json + Raises an HTTPError if the request failed for a reason other than no such user. """ + if use_cache: + if cache_key is None: + raise ValueError("cache_key is required when using cache") + # check for a cached reply, so we don't check with the Hub if we don't have to + cached = self.cache.get(cache_key) + if cached is not None: + return cached + + try: + r = requests.get(url, + headers = { + 'Authorization' : 'token %s' % self.api_token, + }, + ) + except requests.ConnectionError: + msg = "Failed to connect to Hub API at %r." % self.api_url + msg += " Is the Hub accessible at this URL (from host: %s)?" % socket.gethostname() + if '127.0.0.1' in self.api_url: + msg += " Make sure to set c.JupyterHub.hub_ip to an IP accessible to" + \ + " single-user servers if the servers are not on the same host as the Hub." + raise HTTPError(500, msg) + + data = None + print(r.status_code) if r.status_code == 404: app_log.warning("No Hub user identified for request") - data = None elif r.status_code == 403: app_log.error("I don't have permission to check authorization with JupyterHub, my auth token may have expired: [%i] %s", r.status_code, r.reason) raise HTTPError(500, "Permission failure checking authorization, I may need a new token") @@ -158,7 +198,12 @@ def _check_response_for_authorization(self, r): else: data = r.json() app_log.debug("Received request from Hub user %s", data) - return data + + if use_cache: + # cache result + self.cache[cache_key] = data + return data + def user_for_cookie(self, encrypted_cookie, use_cache=True): """Ask the Hub to identify the user for a given cookie. @@ -172,32 +217,14 @@ def user_for_cookie(self, encrypted_cookie, use_cache=True): The 'name' field contains the user's name. """ - if use_cache: - cached = self.cookie_cache.get(encrypted_cookie) - if cached is not None: - return cached - try: - r = requests.get( - url_path_join(self.api_url, - "authorizations/cookie", - self.cookie_name, - quote(encrypted_cookie, safe=''), - ), - headers = { - 'Authorization' : 'token %s' % self.api_token, - }, - ) - except requests.ConnectionError: - msg = "Failed to connect to Hub API at %r." % self.api_url - msg += " Is the Hub accessible at this URL (from host: %s)?" % socket.gethostname() - if '127.0.0.1' in self.api_url: - msg += " Make sure to set c.JupyterHub.hub_ip to an IP accessible to" + \ - " single-user servers if the servers are not on the same host as the Hub." - raise HTTPError(500, msg) - - data = self._check_response_for_authorization(r) - self.cookie_cache[encrypted_cookie] = data - return data + return self._check_hub_authorization( + url=url_path_join(self.api_url, + "authorizations/cookie", + self.cookie_name, + quote(encrypted_cookie, safe='')), + cache_key='cookie:%s' % encrypted_cookie, + use_cache=use_cache, + ) def user_for_token(self, token, use_cache=True): """Ask the Hub to identify the user for a given token. @@ -211,31 +238,31 @@ def user_for_token(self, token, use_cache=True): The 'name' field contains the user's name. """ - if use_cache: - cached = self.cookie_cache.get(token) - if cached is not None: - return cached - try: - r = requests.get( - url_path_join(self.api_url, - "authorizations/token", - quote(token, safe=''), - ), - headers = { - 'Authorization' : 'token %s' % self.api_token, - }, - ) - except requests.ConnectionError: - msg = "Failed to connect to Hub API at %r." % self.api_url - msg += " Is the Hub accessible at this URL (from host: %s)?" % socket.gethostname() - if '127.0.0.1' in self.api_url: - msg += " Make sure to set c.JupyterHub.hub_ip to an IP accessible to" + \ - " single-user servers if the servers are not on the same host as the Hub." - raise HTTPError(500, msg) + return self._check_hub_authorization( + url=url_path_join(self.api_url, + "authorizations/token", + quote(token, safe='')), + cache_key='token:%s' % token, + use_cache=use_cache, + ) + + auth_header_name = 'Authorization' + auth_header_pat = re.compile('token\s+(.+)', re.IGNORECASE) - data = self._check_response_for_authorization(r) - self.cookie_cache[token] = data - return data + def get_token(self, handler): + """Get the user token from a request + + - in URL parameters: ?token=<token> + - in header: Authorization: token <token> + """ + + user_token = handler.get_argument('token', '') + if not user_token: + # get it from Authorization header + m = self.auth_header_pat.match(handler.request.headers.get(self.auth_header_name, '')) + if m: + user_token = m.group(1) + return user_token def get_user(self, handler): """Get the Hub user for a given tornado handler. @@ -257,15 +284,26 @@ def get_user(self, handler): if hasattr(handler, '_cached_hub_user'): return handler._cached_hub_user - handler._cached_hub_user = None - encrypted_cookie = handler.get_cookie(self.cookie_name) - if encrypted_cookie: - user_model = self.user_for_cookie(encrypted_cookie) - handler._cached_hub_user = user_model - return user_model - else: - app_log.debug("No token cookie") - return None + handler._cached_hub_user = user_model = None + + # check token first + token = self.get_token(handler) + if token: + user_model = self.user_for_token(token) + if user_model: + handler._token_authenticated = True + + # no token, check cookie + if user_model is None: + encrypted_cookie = handler.get_cookie(self.cookie_name) + if encrypted_cookie: + user_model = self.user_for_cookie(encrypted_cookie) + + # cache result + handler._cached_hub_user = user_model + if not user_model: + app_log.debug("No user identified") + return user_model class HubAuthenticated(object): @@ -310,6 +348,10 @@ def hub_auth(self): def hub_auth(self, auth): self._hub_auth = auth + def get_login_url(self): + """Return the Hub's login URL""" + return self.hub_auth.login_url + def check_hub_user(self, user_model): """Check whether Hub-authenticated user should be allowed. diff --git a/jupyterhub/singleuser.py b/jupyterhub/singleuser.py --- a/jupyterhub/singleuser.py +++ b/jupyterhub/singleuser.py @@ -62,6 +62,14 @@ class JupyterHubLoginHandler(LoginHandler): def login_available(settings): return True + @staticmethod + def is_token_authenticated(handler): + """Is the request token-authenticated?""" + if getattr(handler, '_cached_hub_user', None) is None: + # ensure get_user has been called, so we know if we're token-authenticated + handler.get_current_user() + return getattr(handler, '_token_authenticated', False) + @staticmethod def get_user(handler): """alternative get_current_user to query the Hub""" @@ -290,7 +298,7 @@ def init_webapp(self): s['hub_prefix'] = self.hub_prefix s['hub_host'] = self.hub_host s['hub_auth'] = self.hub_auth - s['login_url'] = self.hub_host + self.hub_prefix + self.hub_auth.login_url = self.hub_host + self.hub_prefix s['csp_report_uri'] = self.hub_host + url_path_join(self.hub_prefix, 'security/csp-report') super(SingleUserNotebookApp, self).init_webapp() self.patch_templates()
diff --git a/jupyterhub/tests/test_services_auth.py b/jupyterhub/tests/test_services_auth.py --- a/jupyterhub/tests/test_services_auth.py +++ b/jupyterhub/tests/test_services_auth.py @@ -4,6 +4,7 @@ from threading import Thread import time from unittest import mock +from urllib.parse import urlparse from pytest import raises import requests @@ -16,6 +17,7 @@ from ..services.auth import _ExpiringDict, HubAuth, HubAuthenticated from ..utils import url_path_join from .mocking import public_url +from .test_api import add_user # mock for sending monotonic counter way into the future monotonic_future = mock.patch('time.monotonic', lambda : sys.maxsize) @@ -227,3 +229,41 @@ def test_service_cookie_auth(app, mockservice_url): 'admin': False, } + +def test_service_token_auth(app, mockservice_url): + u = add_user(app.db, name='river') + token = u.new_api_token() + app.db.commit() + + # token in Authorization header + r = requests.get(public_url(app, mockservice_url) + '/whoami/', + headers={ + 'Authorization': 'token %s' % token, + }) + r.raise_for_status() + reply = r.json() + sub_reply = { key: reply.get(key, 'missing') for key in ['name', 'admin']} + assert sub_reply == { + 'name': 'river', + 'admin': False, + } + + # token in ?token parameter + r = requests.get(public_url(app, mockservice_url) + '/whoami/?token=%s' % token) + r.raise_for_status() + reply = r.json() + sub_reply = { key: reply.get(key, 'missing') for key in ['name', 'admin']} + assert sub_reply == { + 'name': 'river', + 'admin': False, + } + + r = requests.get(public_url(app, mockservice_url) + '/whoami/?token=no-such-token', + allow_redirects=False, + ) + assert r.status_code == 302 + assert 'Location' in r.headers + location = r.headers['Location'] + path = urlparse(location).path + assert path.endswith('/hub/login') +
Support token auth in single-user servers The default LoginHandler will support token auth in 4.3: https://github.com/jupyter/notebook/pull/1831 . Since JupyterHub replaces the LoginHandler, token auth won't work with JupyterHub without modifications. We should add support for the Authorization header in the single-user server so that JupyterHub tokens can be used to access single-user servers via the Authorization header. This will also likely drive demand for creation of new API tokens via UI, but that can be a separate step. cf https://github.com/jupyterhub/jupyterhub-deploy-docker/issues/30
@minrk ... is there anything I might be able to help with here, in order to be able to get the notebook API working against user servers running under Jupyterhub? If you'd like to make a PR, that would be great! The first thing to do is get the token auth from [here](https://github.com/jupyter/notebook/blob/4.x/notebook/auth/login.py#L100) and include the token checking (Authorization header and possibly `?token` parameter) in the single-user auth [here](https://github.com/jupyterhub/jupyterhub/blob/0.7.0/jupyterhub/services/auth.py#L192). It will need to check the *token* auth endpoint, rather than cookie. @minrk .... not unwilling to help ... but I'm not sure my python skills are up to that! If you'd like, I can help you through it if you want to start a PR and ask questions (feel free to open a PR early and ask for help!). If you think it's too much, don't worry; we can take care of it, too. @minrk ... I'm being a bit lame, I realise ... but I expect you are able to implement this more expeditiously than I could manage! Not at all! Feel free to tackle a problem you are more comfortable with. We got this covered. And don't hesitate to ask for help. Question: Jupyter notebooks offered through JupyterHub are already "secured" using the hub for the login and the cookie. What is the point to add this support ? is not easier to set `c.NotebookApp.token = ''` `c.NotebookApp.password = ''` ? [This comment above](https://github.com/jupyterhub/jupyterhub/issues/891#issuecomment-265150188) is the main thing to implement. Everything's in place in that JupyterHub has tokens, and an API for asking the Hub who a token corresponds to (`GET /authorizations/token/:token`). What's needed is for the HubAuthenticated wrapper to look for tokens in the Authorization header and url parameters, in addition to the cookie it supports now. Everything else ought to be set. Right now, we have: - `HubAuth.get_user` which calls `HubAuth.user_for_cookie` to identify the user We need to add checking for tokens to `HubAuth.get_user`, with: ```python class HubAuth(): def _get_token(self, handler): """Return the token from the Authorization header or ?token url query parameter returns None if no token found """ def user_for_token(self, token): """Ask the Hub for the user identified by a token returns user model (dict) if a user is identified, None otherwise """ # same as user_for_cookie, but use the token API instead of the cookie API ```
2017-01-25T12:56:48Z
[]
[]
jupyterhub/jupyterhub
966
jupyterhub__jupyterhub-966
[ "954" ]
3bb82ea330a33bfaf5d117590d1a3bf212dca575
diff --git a/jupyterhub/apihandlers/auth.py b/jupyterhub/apihandlers/auth.py --- a/jupyterhub/apihandlers/auth.py +++ b/jupyterhub/apihandlers/auth.py @@ -18,7 +18,11 @@ def get(self, token): orm_token = orm.APIToken.find(self.db, token) if orm_token is None: raise web.HTTPError(404) - self.write(json.dumps(self.user_model(self.users[orm_token.user]))) + if orm_token.user: + model = self.user_model(self.users[orm_token.user]) + elif orm_token.service: + model = self.service_model(orm_token.service) + self.write(json.dumps(model)) @gen.coroutine def post(self): diff --git a/jupyterhub/apihandlers/base.py b/jupyterhub/apihandlers/base.py --- a/jupyterhub/apihandlers/base.py +++ b/jupyterhub/apihandlers/base.py @@ -89,6 +89,7 @@ def write_error(self, status_code, **kwargs): def user_model(self, user): """Get the JSON model for a User object""" model = { + 'kind': 'user', 'name': user.name, 'admin': user.admin, 'groups': [ g.name for g in user.groups ], @@ -105,8 +106,17 @@ def user_model(self, user): def group_model(self, group): """Get the JSON model for a Group object""" return { + 'kind': 'group', 'name': group.name, - 'users': [ u.name for u in group.users ] + 'users': [ u.name for u in group.users ], + } + + def service_model(self, service): + """Get the JSON model for a Service object""" + return { + 'kind': 'service', + 'name': service.name, + 'admin': service.admin, } _user_model_types = { @@ -152,6 +162,7 @@ def _check_group_model(self, model): if not isinstance(groupname, str): raise web.HTTPError(400, ("group names must be str, not %r", type(groupname))) + def options(self, *args, **kwargs): self.set_header('Access-Control-Allow-Headers', 'accept, content-type') self.finish() diff --git a/jupyterhub/services/auth.py b/jupyterhub/services/auth.py --- a/jupyterhub/services/auth.py +++ b/jupyterhub/services/auth.py @@ -12,6 +12,7 @@ import socket import time from urllib.parse import quote +import warnings import requests @@ -183,7 +184,6 @@ def _check_hub_authorization(self, url, cache_key=None, use_cache=True): raise HTTPError(500, msg) data = None - print(r.status_code) if r.status_code == 404: app_log.warning("No Hub user identified for request") elif r.status_code == 403: @@ -330,9 +330,19 @@ def get(self): ... """ + hub_services = None # set of allowed services hub_users = None # set of allowed users hub_groups = None # set of allowed groups + @property + def allow_all(self): + """Property indicating that all successfully identified user + or service should be allowed. + """ + return (self.hub_services is None + and self.hub_users is None + and self.hub_groups is None) + # self.hub_auth must be a HubAuth instance. # If nothing specified, use default config, # which will be configured with defaults @@ -352,34 +362,45 @@ def get_login_url(self): """Return the Hub's login URL""" return self.hub_auth.login_url - def check_hub_user(self, user_model): - """Check whether Hub-authenticated user should be allowed. + def check_hub_user(self, model): + """Check whether Hub-authenticated user or service should be allowed. Returns the input if the user should be allowed, None otherwise. Override if you want to check anything other than the username's presence in hub_users list. Args: - user_model (dict): the user model returned from :class:`HubAuth` + model (dict): the user or service model returned from :class:`HubAuth` Returns: user_model (dict): The user model if the user should be allowed, None otherwise. """ - name = user_model['name'] - if self.hub_users is None and self.hub_groups is None: - # no whitelist specified, allow any authenticated Hub user - app_log.debug("Allowing Hub user %s (all Hub users allowed)", name) - return user_model + + name = model['name'] + kind = model.get('kind', 'user') + if self.allow_all: + app_log.debug("Allowing Hub %s %s (all Hub users and services allowed)", kind, name) + return model + + if kind == 'service': + # it's a service, check hub_services + if self.hub_services and name in self.hub_services: + app_log.debug("Allowing whitelisted Hub service %s", name) + return model + else: + app_log.warning("Not allowing Hub service %s", name) + return None + if self.hub_users and name in self.hub_users: # user in whitelist app_log.debug("Allowing whitelisted Hub user %s", name) - return user_model - elif self.hub_groups and set(user_model['groups']).intersection(self.hub_groups): - allowed_groups = set(user_model['groups']).intersection(self.hub_groups) + return model + elif self.hub_groups and set(model['groups']).intersection(self.hub_groups): + allowed_groups = set(model['groups']).intersection(self.hub_groups) app_log.debug("Allowing Hub user %s in group(s) %s", name, ','.join(sorted(allowed_groups))) # group in whitelist - return user_model + return model else: - app_log.warning("Not allowing Hub user %s" % name) + app_log.warning("Not allowing Hub user %s", name) return None def get_current_user(self):
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -127,6 +127,8 @@ class MockHub(JupyterHub): base_url = '/@/space%20word/' + log_datefmt = '%M:%S' + @default('subdomain_host') def _subdomain_host_default(self): return os.environ.get('JUPYTERHUB_TEST_SUBDOMAIN_HOST', '') diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -168,6 +168,7 @@ def test_get_users(app): u.pop('last_activity') assert users == [ { + 'kind': 'user', 'name': 'admin', 'groups': [], 'admin': True, @@ -175,6 +176,7 @@ def test_get_users(app): 'pending': None, }, { + 'kind': 'user', 'name': 'user', 'groups': [], 'admin': False, @@ -209,6 +211,7 @@ def test_get_user(app): user = r.json() user.pop('last_activity') assert user == { + 'kind': 'user', 'name': name, 'groups': [], 'admin': False, @@ -570,6 +573,7 @@ def test_groups_list(app): r.raise_for_status() reply = r.json() assert reply == [{ + 'kind': 'group', 'name': 'alphaflight', 'users': [] }] @@ -589,6 +593,7 @@ def test_group_get(app): r.raise_for_status() reply = r.json() assert reply == { + 'kind': 'group', 'name': 'alphaflight', 'users': ['sasquatch'] } diff --git a/jupyterhub/tests/test_services_auth.py b/jupyterhub/tests/test_services_auth.py --- a/jupyterhub/tests/test_services_auth.py +++ b/jupyterhub/tests/test_services_auth.py @@ -1,4 +1,6 @@ +from binascii import hexlify import json +import os from queue import Queue import sys from threading import Thread @@ -217,7 +219,8 @@ def finish_thread(): assert auth.login_url in r.headers['Location'] -def test_service_cookie_auth(app, mockservice_url): +def test_hubauth_cookie(app, mockservice_url): + """Test HubAuthenticated service with user cookies""" cookies = app.login_user('badger') r = requests.get(public_url(app, mockservice_url) + '/whoami/', cookies=cookies) r.raise_for_status() @@ -230,7 +233,8 @@ def test_service_cookie_auth(app, mockservice_url): } -def test_service_token_auth(app, mockservice_url): +def test_hubauth_token(app, mockservice_url): + """Test HubAuthenticated service with user API tokens""" u = add_user(app.db, name='river') token = u.new_api_token() app.db.commit() @@ -267,3 +271,44 @@ def test_service_token_auth(app, mockservice_url): path = urlparse(location).path assert path.endswith('/hub/login') + +def test_hubauth_service_token(app, mockservice_url, io_loop): + """Test HubAuthenticated service with service API tokens""" + + token = hexlify(os.urandom(5)).decode('utf8') + name = 'test-api-service' + app.service_tokens[token] = name + io_loop.run_sync(app.init_api_tokens) + + # token in Authorization header + r = requests.get(public_url(app, mockservice_url) + '/whoami/', + headers={ + 'Authorization': 'token %s' % token, + }) + r.raise_for_status() + reply = r.json() + assert reply == { + 'kind': 'service', + 'name': name, + 'admin': False, + } + + # token in ?token parameter + r = requests.get(public_url(app, mockservice_url) + '/whoami/?token=%s' % token) + r.raise_for_status() + reply = r.json() + assert reply == { + 'kind': 'service', + 'name': name, + 'admin': False, + } + + r = requests.get(public_url(app, mockservice_url) + '/whoami/?token=no-such-token', + allow_redirects=False, + ) + assert r.status_code == 302 + assert 'Location' in r.headers + location = r.headers['Location'] + path = urlparse(location).path + assert path.endswith('/hub/login') +
HubAuth does not work with service tokens It is currently not possible to authenticate a service using the HubAuth class. When attempting to use a service token to authenticate a service via `/api/authorizations/token/{token}`, it returns a 404. **How to reproduce the issue** Take a service token and make a request to `/api/authorizations/token/{token}` using the token and the proper authorization header. **What you expected to happen** A User model is returned about the service, with a `name` and `admin` field. **What actually happens** The request returns with a 404 **Share what version of JupyterHub you are using** 0.7.2
2017-01-27T15:33:23Z
[]
[]
jupyterhub/jupyterhub
1,066
jupyterhub__jupyterhub-1066
[ "1065" ]
5f498ffaf341ecfe4a86ee35e1a0d8d45ca37ba0
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -1173,10 +1173,12 @@ def user_stopped(user): db.commit() def init_oauth(self): + base_url = self.hub.server.base_url self.oauth_provider = make_provider( self.session_factory, - url_prefix=url_path_join(self.hub.server.base_url, 'api/oauth2'), - login_url=self.authenticator.login_url(self.hub.server.base_url), + url_prefix=url_path_join(base_url, 'api/oauth2'), + login_url=url_path_join(base_url, 'login') +, ) def init_proxy(self): @@ -1307,7 +1309,7 @@ def init_tornado_settings(self): **jinja_options ) - login_url = self.authenticator.login_url(base_url) + login_url = url_path_join(base_url, 'login') logout_url = self.authenticator.logout_url(base_url) # if running from git, disable caching of require.js diff --git a/jupyterhub/auth.py b/jupyterhub/auth.py --- a/jupyterhub/auth.py +++ b/jupyterhub/auth.py @@ -31,7 +31,7 @@ class Authenticator(LoggingConfigurable): help=""" Set of users that will have admin rights on this JupyterHub. - Admin users have extra privilages: + Admin users have extra privileges: - Use the admin panel to see list of users logged in - Add / remove users in some authenticators - Restart / halt the hub @@ -250,10 +250,23 @@ def delete_user(self, user): """ self.whitelist.discard(user.name) + auto_login = Bool(False, config=True, + help="""Automatically begin the login process + + rather than starting with a "Login with..." link at `/hub/login` + + To work, `.login_url()` must give a URL other than the default `/hub/login`, + such as an oauth handler or another automatic login handler, + registered with `.get_handlers()`. + + .. versionadded:: 0.8 + """ + ) + def login_url(self, base_url): """Override this when registering a custom login handler - Generally used by authenticators that do not use simple form based authentication. + Generally used by authenticators that do not use simple form-based authentication. The subclass overriding this is responsible for making sure there is a handler available to handle the URL returned from this method, using the `get_handlers` diff --git a/jupyterhub/handlers/login.py b/jupyterhub/handlers/login.py --- a/jupyterhub/handlers/login.py +++ b/jupyterhub/handlers/login.py @@ -7,8 +7,8 @@ from tornado.escape import url_escape from tornado import gen +from tornado.httputil import url_concat -from ..utils import url_path_join from .base import BaseHandler @@ -23,8 +23,10 @@ def get(self): self.clear_login_cookie(name) user.other_user_cookies = set([]) self.statsd.incr('logout') - - self.redirect(url_path_join(self.hub.server.base_url, 'login'), permanent=False) + if self.authenticator.auto_login: + self.render('logout.html') + else: + self.redirect(self.settings['login_url'], permanent=False) class LoginHandler(BaseHandler): @@ -37,6 +39,7 @@ def _render(self, login_error=None, username=None): login_error=login_error, custom_html=self.authenticator.custom_html, login_url=self.settings['login_url'], + authenticator_login_url=self.authenticator.login_url(self.hub.server.base_url), ) def get(self): @@ -60,6 +63,16 @@ def get(self): self.set_login_cookie(self.get_current_user()) self.redirect(next_url, permanent=False) else: + if self.authenticator.auto_login: + auto_login_url = self.authenticator.login_url(self.hub.server.base_url) + if auto_login_url == self.settings['login_url']: + self.authenticator.auto_login = False + self.log.warning("Authenticator.auto_login cannot be used without a custom login_url") + else: + if next_url: + auto_login_url = url_concat(auto_login_url, {'next': next_url}) + self.redirect(auto_login_url) + return username = self.get_argument('username', default='') self.finish(self._render(username=username)) diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -53,7 +53,7 @@ def get(self): url = url_path_join(self.hub.server.base_url, 'home') self.log.debug("User is not running: %s", url) else: - url = url_path_join(self.hub.server.base_url, 'login') + url = self.settings['login_url'] self.redirect(url)
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -20,7 +20,7 @@ from .. import orm from ..spawner import LocalProcessSpawner from ..singleuser import SingleUserNotebookApp -from ..utils import random_port +from ..utils import random_port, url_path_join from pamela import PAMError @@ -210,16 +210,21 @@ def public_host(app): return app.proxy.public_server.host -def public_url(app, user_or_service=None): +def public_url(app, user_or_service=None, path=''): """Return the full, public base URL (including prefix) of the given JupyterHub instance.""" if user_or_service: if app.subdomain_host: host = user_or_service.host else: host = public_host(app) - return host + user_or_service.server.base_url + prefix = user_or_service.server.base_url else: - return public_host(app) + app.proxy.public_server.base_url + host = public_host(app) + prefix = app.proxy.public_server.base_url + if path: + return host + url_path_join(prefix, path) + else: + return host + prefix # single-user-server mocking: diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -4,8 +4,10 @@ import requests +from ..handlers import BaseHandler from ..utils import url_path_join as ujoin from .. import orm +from ..auth import Authenticator import mock from .mocking import FormSpawner, public_url, public_host @@ -253,6 +255,28 @@ def test_login_redirect(app, io_loop): assert r.headers['Location'].endswith('/hub/admin') +def test_auto_login(app, io_loop, request): + class DummyLoginHandler(BaseHandler): + def get(self): + self.write('ok!') + base_url = public_url(app) + '/' + app.tornado_application.add_handlers(".*$", [ + (ujoin(app.hub.server.base_url, 'dummy'), DummyLoginHandler), + ]) + # no auto_login: end up at /hub/login + r = requests.get(base_url) + assert r.url == public_url(app, path='hub/login') + # enable auto_login: redirect from /hub/login to /hub/dummy + authenticator = Authenticator(auto_login=True) + authenticator.login_url = lambda base_url: ujoin(base_url, 'dummy') + + with mock.patch.dict(app.tornado_application.settings, { + 'authenticator': authenticator, + }): + r = requests.get(base_url) + assert r.url == public_url(app, path='hub/dummy') + + def test_logout(app): name = 'wash' cookies = app.login_user(name)
Better support explicit auto_login Authenticators Some Authenticators want to auto-login users. For example: - [tmpauth](https://github.com/yuvipanda/jupyterhub-tmpauthenticator) (generates temporary users) - [REMOTE_USER](https://github.com/cwaldbieser/jhub_remote_user_authenticator/blob/master/remote_user/remote_user_auth.py) (user already logged in with Apache, get user info from headers) However, automatically starting the login process is **not** the right thing to do for many authenticators, such as those using external OAuth. JupyterHub keeps going back and forth about which is better supported: - Right now (0.7.2), auto-login is served best, in such a way that makes logout impossible with OAuthenticators (#967) - Master fixes #967 in a way that makes the above auto-login authenticators more difficult. In particular, tmpauth will see `Sign in with...`, while REMOTE_USER still works because it overrides `/hub/login`. Part of the back and forth in bugs stems from the various login URLs and redirects we have: - The tornado `login_url` setting, which is where users get redirected if they make a request to the Hub and are not authenticated yet. This is currently `Authenticator.login_url()`. - A few places hardcode redirects to `/hub/login`, rather than `login_url()`, to ensure that the `Login with...` button is displayed. - The `Authenticator.login_url()` *method*, which lets Authenticators register a custom login handler. The `Login with...` button on `/hub/login` redirects to here. - The `/hub/login` *page* (served by `LoginHandler` by default), which hosts a login form, or the `Login with...` button, which redirects to `Authenticator.login_url()` - Logout redirects to the login page (should be `/hub/login`), which should be guaranteed not to redirect the user back into the login process. Sources of bugs in the past: - redirecting to `Authenticator.login_url()` instead of `/hub/login` (#967) - no public mechanism for auto-login (Setting Authenticator.login_url() *seems* like it should be it, but isn't, and works sometimes depending on bugs in JupyterHub) Right now, REMOTE_USER works by overriding the `/login` handler, which enables auto_login. It also means that logging out redirects to /login, which logs the user right back in again. tmpauthenticator only overrides login_url, which seems to be reliant on bugs in JupyterHub to get implicit auto-login. One option: Define auto-login API as officially overriding the `/login` handler. This is what REMOTE_USER does. tmpauthenticator could do the same. Logout would cause users to be immediately logged back in. ## Proposal One solution: add `Authenticator.auto_login` boolean flag. If set: - logout is disabled explicitly - `/hub/login` redirects to `Authenticator.login_url()` instead of rendering a login page This should clarify a few things: - the `login_url` of the application (from tornado's perspective) remains consistently `/hub/login` and not configurable. - The behavior of `/hub/login` is also clear:always render a page *unless* auto_login is True, in which case it redirects to `Authenticator.login_url()`. - Redirects to `Authenticator.login_url()` should only ever come by way of `/hub/login`, never directly from anywhere else.
2017-04-07T12:52:59Z
[]
[]
jupyterhub/jupyterhub
1,111
jupyterhub__jupyterhub-1111
[ "1105" ]
006488fc749923851df97d47d8850bdf5fd157cf
diff --git a/jupyterhub/handlers/login.py b/jupyterhub/handlers/login.py --- a/jupyterhub/handlers/login.py +++ b/jupyterhub/handlers/login.py @@ -78,7 +78,7 @@ def post(self): # parse the arguments dict data = {} for arg in self.request.arguments: - data[arg] = self.get_argument(arg) + data[arg] = self.get_argument(arg, strip=False) auth_timer = self.statsd.timer('login.authenticate').start() username = yield self.authenticate(data)
diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -3,6 +3,7 @@ from urllib.parse import urlencode, urlparse import requests +from tornado import gen from ..handlers import BaseHandler from ..utils import url_path_join as ujoin @@ -231,6 +232,27 @@ def test_login_fail(app): assert not r.cookies +def test_login_strip(app): + """Test that login form doesn't strip whitespace from passwords""" + form_data = { + 'username': 'spiff', + 'password': ' space man ', + } + base_url = public_url(app) + called_with = [] + @gen.coroutine + def mock_authenticate(handler, data): + called_with.append(data) + + with mock.patch.object(app.authenticator, 'authenticate', mock_authenticate): + r = requests.post(base_url + 'hub/login', + data=form_data, + allow_redirects=False, + ) + + assert called_with == [form_data] + + def test_login_redirect(app, io_loop): cookies = app.login_user('river') user = app.users['river']
Passwords beginning or ending with a whitespace are not supported Due to POST argument stripping, passwords with a beginning or ending whitespace are not allowed. **How to reproduce the issue** Set up a user password with an ending or beginning whitespace. **What you expected to happen** The user should be allowed to login with the password, given that the password should be any complicated sequence of characters the user can reproduce. **What actually happens** The user is denied access, because the LoginHandler will strip all posted values before considering the password for authentication (line 81, get_argument has a default "strip=True") **Share what version of JupyterHub you are using** HEAD (006488fc749923851df97d47d8850bdf5fd157cf)
2017-04-28T14:40:49Z
[]
[]
jupyterhub/jupyterhub
1,165
jupyterhub__jupyterhub-1165
[ "1163" ]
6810aba5e9105b97a2d04eea705a4aef9f944ebb
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -392,11 +392,26 @@ def _deprecated_proxy_api(self, change): ) hub_port = Integer(8081, - help="The port for this process" + help="The port for the Hub process" ).tag(config=True) hub_ip = Unicode('127.0.0.1', - help="The ip for this process" + help="""The ip address for the Hub process to *bind* to. + + See `hub_connect_ip` for cases where the bind and connect address should differ. + """ ).tag(config=True) + hub_connect_ip = Unicode('', + help="""The ip or hostname for proxies and spawners to use + for connecting to the Hub. + + Use when the bind address (`hub_ip`) is 0.0.0.0 or otherwise different + from the connect address. + + Default: when `hub_ip` is 0.0.0.0, use `socket.gethostname()`, otherwise use `hub_ip`. + + .. versionadded:: 0.8 + """ + ) hub_prefix = URLPrefix('/hub/', help="The prefix for the hub server. Always /base_url/hub/" ) @@ -836,7 +851,8 @@ def init_hub(self): cookie_name='jupyter-hub-token', public_host=self.subdomain_host, ) - print(self.hub) + if self.hub_connect_ip: + self.hub.connect_ip = self.hub_connect_ip @gen.coroutine def init_users(self): diff --git a/jupyterhub/objects.py b/jupyterhub/objects.py --- a/jupyterhub/objects.py +++ b/jupyterhub/objects.py @@ -3,6 +3,7 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. +import socket from urllib.parse import urlparse from tornado import gen @@ -26,11 +27,29 @@ class Server(HasTraits): orm_server = Instance(orm.Server, allow_none=True) ip = Unicode() + connect_ip = Unicode() proto = Unicode('http') port = Integer() base_url = Unicode('/') cookie_name = Unicode('') + @property + def _connect_ip(self): + """The address to use when connecting to this server + + When `ip` is set to a real ip address, the same value is used. + When `ip` refers to 'all interfaces' (e.g. '0.0.0.0'), + clients connect via hostname by default. + Setting `connect_ip` explicitly overrides any default behavior. + """ + if self.connect_ip: + return self.connect_ip + elif self.ip in {'', '0.0.0.0'}: + # if listening on all interfaces, default to hostname for connect + return socket.gethostname() + else: + return self.ip + @classmethod def from_url(cls, url): """Create a Server from a given URL""" @@ -67,13 +86,9 @@ def _change(self, change): @property def host(self): - ip = self.ip - if ip in {'', '0.0.0.0'}: - # when listening on all interfaces, connect to localhost - ip = '127.0.0.1' return "{proto}://{ip}:{port}".format( proto=self.proto, - ip=ip, + ip=self._connect_ip, port=self.port, ) @@ -92,7 +107,7 @@ def bind_url(self): since it can be non-connectable value, such as '', meaning all interfaces. """ if self.ip in {'', '0.0.0.0'}: - return self.url.replace('127.0.0.1', self.ip or '*', 1) + return self.url.replace(self._connect_ip, self.ip or '*', 1) return self.url @gen.coroutine @@ -101,7 +116,7 @@ def wait_up(self, timeout=10, http=False): if http: yield wait_for_http_server(self.url, timeout=timeout) else: - yield wait_for_server(self.ip or '127.0.0.1', self.port, timeout=timeout) + yield wait_for_server(self._connect_ip, self.port, timeout=timeout) def is_up(self): """Is the server accepting connections?"""
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -246,8 +246,8 @@ class StubSingleUserSpawner(MockSpawner): _thread = None @gen.coroutine def start(self): - ip = self.user.server.ip - port = self.user.server.port = random_port() + ip = self.ip = '127.0.0.1' + port = self.port = random_port() env = self.get_env() args = self.get_args() evt = threading.Event() diff --git a/jupyterhub/tests/test_orm.py b/jupyterhub/tests/test_orm.py --- a/jupyterhub/tests/test_orm.py +++ b/jupyterhub/tests/test_orm.py @@ -3,6 +3,8 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. +import socket + import pytest from tornado import gen @@ -24,13 +26,17 @@ def test_server(db): # test wrapper server = objects.Server(orm_server=server) - assert server.host == 'http://127.0.0.1:%i' % server.port + assert server.host == 'http://%s:%i' % (socket.gethostname(), server.port) assert server.url == server.host + '/' assert server.bind_url == 'http://*:%i/' % server.port server.ip = '127.0.0.1' assert server.host == 'http://127.0.0.1:%i' % server.port assert server.url == server.host + '/' + server.connect_ip = 'hub' + assert server.host == 'http://hub:%i' % server.port + assert server.url == server.host + '/' + def test_user(db): user = User(orm.User(name='kaylee',
Any way to give a different hub IP to singleuser servers? My current setup uses Jupyterhub 0.7.2 in a docker container, using a modified version of the batchspawner to start singleuser servers on a cluster. `JupyterHub.hub_ip` is set to `0.0.0.0`, but it binds to `127.0.0.1`. This address is given to the singleuser server under the `--hub-api-url` argument. This isn't OK since the singleuser servers are running on different machines than the hub. I can't set the `hub_ip` to the public address because it is running in a docker container and can't bind to that address. Is there any way from the config to tell the singleuser servers that it should connect to a different IP than the `hub_ip`? I'm currently doing a janky hack in the spawner to inject the correct address that obviously isn't the correct way to do it.
Setting `hub_ip` does set the bind ip. If you set this to 0.0.0.0, 127.0.0.1 is used for connecting unless overridden somewhere. Some Spawners (e.g. DockerSpawner) set a separate `hub_connect_ip`, but this should be handled at the Hub level so that different spawners don't need to reimplement this. I'll work on it.
2017-06-06T10:52:53Z
[]
[]
jupyterhub/jupyterhub
1,177
jupyterhub__jupyterhub-1177
[ "1175" ]
9f532d6b2d1fdb709e6400f5e1e629ad43d25607
diff --git a/jupyterhub/apihandlers/proxy.py b/jupyterhub/apihandlers/proxy.py --- a/jupyterhub/apihandlers/proxy.py +++ b/jupyterhub/apihandlers/proxy.py @@ -12,25 +12,29 @@ from ..utils import admin_only from .base import APIHandler + class ProxyAPIHandler(APIHandler): @admin_only @gen.coroutine def get(self): """GET /api/proxy fetches the routing table - + This is the same as fetching the routing table directly from the proxy, but without clients needing to maintain separate """ routes = yield self.proxy.get_all_routes() self.write(json.dumps(routes)) - + @admin_only @gen.coroutine def post(self): - """POST checks the proxy to ensure""" + """POST checks the proxy to ensure that it's up to date. + + Can be used to jumpstart a newly launched proxy + without waiting for the check_routes interval. + """ yield self.proxy.check_routes(self.users, self.services) - @admin_only @gen.coroutine diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -1182,6 +1182,7 @@ def init_proxy(self): app=self, log=self.log, hub=self.hub, + host_routing=bool(self.subdomain_host), ssl_cert=self.ssl_cert, ssl_key=self.ssl_key, ) diff --git a/jupyterhub/objects.py b/jupyterhub/objects.py --- a/jupyterhub/objects.py +++ b/jupyterhub/objects.py @@ -12,6 +12,7 @@ HasTraits, Instance, Integer, Unicode, default, observe, ) +from .traitlets import URLPrefix from . import orm from .utils import ( url_path_join, can_connect, wait_for_server, @@ -30,7 +31,7 @@ class Server(HasTraits): connect_ip = Unicode() proto = Unicode('http') port = Integer() - base_url = Unicode('/') + base_url = URLPrefix('/') cookie_name = Unicode('') @property diff --git a/jupyterhub/proxy.py b/jupyterhub/proxy.py --- a/jupyterhub/proxy.py +++ b/jupyterhub/proxy.py @@ -1,12 +1,29 @@ -"""API for JupyterHub's proxy.""" +"""API for JupyterHub's proxy. + +Custom proxy implementations can subclass :class:`Proxy` +and register in JupyterHub config: + +.. sourcecode:: python + + from mymodule import MyProxy + c.JupyterHub.proxy_class = MyProxy + +Route Specification: + +- A routespec is a URL prefix ([host]/path/), e.g. + 'host.tld/path/' for host-based routing or '/path/' for default routing. +- Route paths should be normalized to always start and end with '/' +""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. +from collections import namedtuple import json import os from subprocess import Popen import time +from urllib.parse import quote, urlparse from tornado import gen from tornado.httpclient import AsyncHTTPClient, HTTPRequest @@ -27,7 +44,28 @@ class Proxy(LoggingConfigurable): - """Base class for configurable proxies that JupyterHub can use.""" + """Base class for configurable proxies that JupyterHub can use. + + A proxy implementation should subclass this and must define the following methods: + + - :meth:`.get_all_routes` return a dictionary of all JupyterHub-related routes + - :meth:`.add_route` adds a route + - :meth:`.delete_route` deletes a route + + In addition to these, the following method(s) may need to be implemented: + + - :meth:`.start` start the proxy, if it should be launched by the Hub + instead of externally managed. + If the proxy is externally managed, it should set :attr:`should_start` to False. + - :meth:`.stop` stop the proxy. Only used if :meth:`.start` is also used. + + And the following method(s) are optional, but can be provided: + + - :meth:`.get_route` gets a single route. + There is a default implementation that extracts data from :meth:`.get_all_routes`, + but implementations may choose to provide a more efficient implementation + of fetching a single route. + """ db = Any() app = Any() @@ -35,9 +73,10 @@ class Proxy(LoggingConfigurable): public_url = Unicode() ssl_key = Unicode() ssl_cert = Unicode() + host_routing = Bool() should_start = Bool(True, config=True, - help="""Should the Hub start the proxy. + help="""Should the Hub start the proxy If True, the Hub will start the proxy and stop it. Set to False if the proxy is managed externally, @@ -48,22 +87,48 @@ def start(self): """Start the proxy. Will be called during startup if should_start is True. + + **Subclasses must define this method** + if the proxy is to be started by the Hub """ def stop(self): """Stop the proxy. Will be called during teardown if should_start is True. + + **Subclasses must define this method** + if the proxy is to be started by the Hub + """ + + def validate_routespec(self, routespec): + """Validate a routespec + + - Checks host value vs host-based routing. + - Ensures trailing slash on path. """ + # check host routing + host_route = not routespec.startswith('/') + if host_route and not self.host_routing: + raise ValueError("Cannot add host-based route %r, not using host-routing" % routespec) + if self.host_routing and not host_route: + raise ValueError("Cannot add route without host %r, using host-routing" % routespec) + # add trailing slash + if not routespec.endswith('/'): + return routespec + '/' + else: + return routespec @gen.coroutine def add_route(self, routespec, target, data): """Add a route to the proxy. + **Subclasses must define this method** + Args: - routespec (str): A specification for which this route will be matched. - Could be either a url_prefix or a fqdn. - target (str): A URL that will be the target of this route. + routespec (str): A URL prefix ([host]/path/) for which this route will be matched, + e.g. host.name/path/ + target (str): A full URL that will be the target of this route. data (dict): A JSONable dict that will be associated with this route, and will be returned when retrieving information about this route. @@ -77,7 +142,28 @@ def add_route(self, routespec, target, data): @gen.coroutine def delete_route(self, routespec): - """Delete a route with a given routespec if it exists.""" + """Delete a route with a given routespec if it exists. + + **Subclasses must define this method** + """ + pass + + @gen.coroutine + def get_all_routes(self): + """Fetch and return all the routes associated by JupyterHub from the + proxy. + + **Subclasses must define this method** + + Should return a dictionary of routes, where the keys are + routespecs and each value is a dict of the form:: + + { + 'routespec': the route specification ([host]/path/) + 'target': the target host URL (proto://host) for this route + 'data': the attached data dict for this route (as specified in add_route) + } + """ pass @gen.coroutine @@ -85,28 +171,26 @@ def get_route(self, routespec): """Return the route info for a given routespec. Args: - routespec (str): The route specification that was used to add this routespec + routespec (str): + A URI that was used to add this route, + e.g. `host.tld/path/` Returns: - result (dict): with the following keys: - `routespec`: The normalized route specification passed in to add_route - `target`: The target for this route - `data`: The arbitrary data that was passed in by JupyterHub when adding this + result (dict): + dict with the following keys:: + + 'routespec': The normalized route specification passed in to add_route + ([host]/path/) + 'target': The target host for this route (proto://host) + 'data': The arbitrary data dict that was passed in by JupyterHub when adding this route. - None: if there are no routes matching the given routespec - """ - pass - @gen.coroutine - def get_all_routes(self): - """Fetch and return all the routes associated by JupyterHub from the - proxy. - - Should return a dictionary of routes, where the keys are - routespecs and each value is the dict that would be returned by - `get_route(routespec)`. + None: if there are no routes matching the given routespec """ - pass + # default implementation relies on get_all_routes + routespec = self.validate_routespec(routespec) + routes = yield self.get_all_routes() + return routes.get(routespec) # Most basic implementers must only implement above methods @@ -118,11 +202,11 @@ def add_service(self, service, client=None): "Service %s does not have an http endpoint to add to the proxy.", service.name) self.log.info("Adding service %s to proxy %s => %s", - service.name, service.proxy_path, service.server.host, + service.name, service.proxy_spec, service.server.host, ) yield self.add_route( - service.proxy_path, + service.proxy_spec, service.server.host, {'service': service.name} ) @@ -131,13 +215,13 @@ def add_service(self, service, client=None): def delete_service(self, service, client=None): """Remove a service's server from the proxy table.""" self.log.info("Removing service %s from proxy", service.name) - yield self.delete_route(service.proxy_path) + yield self.delete_route(service.proxy_spec) @gen.coroutine def add_user(self, user, client=None): """Add a user's server to the proxy table.""" self.log.info("Adding user %s to proxy %s => %s", - user.name, user.proxy_path, user.server.host, + user.name, user.proxy_spec, user.server.host, ) if user.spawn_pending: @@ -145,7 +229,7 @@ def add_user(self, user, client=None): "User %s's spawn is pending, shouldn't be added to the proxy yet!", user.name) yield self.add_route( - user.proxy_path, + user.proxy_spec, user.server.host, {'user': user.name} ) @@ -154,7 +238,7 @@ def add_user(self, user, client=None): def delete_user(self, user): """Remove a user's server from the proxy table.""" self.log.info("Removing user %s from proxy", user.name) - yield self.delete_route(user.proxy_path) + yield self.delete_route(user.proxy_spec) @gen.coroutine def add_all_services(self, service_dict): @@ -236,18 +320,28 @@ def restore_routes(self): self.log.info("Setting up routes on new proxy") yield self.add_all_users(self.app.users) yield self.add_all_services(self.app.services) - self.log.info("New proxy back up, and good to go") + self.log.info("New proxy back up and good to go") class ConfigurableHTTPProxy(Proxy): - """Proxy implementation for the default configurable-http-proxy.""" + """Proxy implementation for the default configurable-http-proxy. + + This is the default proxy implementation + for running the nodejs proxy `configurable-http-proxy`. + + If the proxy should not be run as a subprocess of the Hub, + (e.g. in a separate container), + set:: + + c.ConfigurableHTTPProxy.should_start = False + """ proxy_process = Any() client = Instance(AsyncHTTPClient, ()) - debug = Bool(False, help="Add debug-level logging to the Proxy", config=True) + debug = Bool(False, help="Add debug-level logging to the Proxy.", config=True) auth_token = Unicode( - help="""The Proxy Auth token. + help="""The Proxy auth token Loaded from the CONFIGPROXY_AUTH_TOKEN env variable by default. """, @@ -362,6 +456,37 @@ def check_running(self): yield self.start() yield self.restore_routes() + def _routespec_to_chp_path(self, routespec): + """Turn a routespec into a CHP API path + + For host-based routing, CHP uses the host as the first path segment. + """ + path = self.validate_routespec(routespec) + # CHP always wants to start with / + if not path.startswith('/'): + path = path + '/' + # BUG: CHP doesn't seem to like trailing slashes on some endpoints (DELETE) + if path != '/' and path.endswith('/'): + path = path.rstrip('/') + return path + + def _routespec_from_chp_path(self, chp_path): + """Turn a CHP route into a route spec + + In the JSON API, CHP route keys are unescaped, + so re-escape them to raw URLs and ensure slashes are in the right places. + """ + # chp stores routes in unescaped form. + # restore escaped-form we created it with. + routespec = quote(chp_path, safe='@/') + if self.host_routing: + # host routes don't start with / + routespec = routespec.lstrip('/') + # all routes should end with / + if not routespec.endswith('/'): + routespec = routespec + '/' + return routespec + def api_request(self, path, method='GET', body=None, client=None): """Make an authenticated API request of the proxy.""" client = client or AsyncHTTPClient() @@ -382,13 +507,15 @@ def api_request(self, path, method='GET', body=None, client=None): def add_route(self, routespec, target, data=None): body = data or {} body['target'] = target - return self.api_request(routespec, + path = self._routespec_to_chp_path(routespec) + return self.api_request(path, method='POST', body=body, ) def delete_route(self, routespec): - return self.api_request(routespec, method='DELETE') + path = self._routespec_to_chp_path(routespec) + return self.api_request(path, method='DELETE') def _reformat_routespec(self, routespec, chp_data): """Reformat CHP data format to JupyterHub's proxy API.""" @@ -398,19 +525,15 @@ def _reformat_routespec(self, routespec, chp_data): 'target': target, 'data': chp_data, } - - @gen.coroutine - def get_route(self, routespec): - chp_data = yield self.api_request(routespec, method='DELETE') - return self._reformat_routespec(routespec, chp_data) - + @gen.coroutine def get_all_routes(self, client=None): """Fetch the proxy's routes.""" resp = yield self.api_request('', client=client) chp_routes = json.loads(resp.body.decode('utf8', 'replace')) all_routes = {} - for routespec, chp_data in chp_routes.items(): + for chp_path, chp_data in chp_routes.items(): + routespec = self._routespec_from_chp_path(chp_path) all_routes[routespec] = self._reformat_routespec( routespec, chp_data) return all_routes diff --git a/jupyterhub/services/service.py b/jupyterhub/services/service.py --- a/jupyterhub/services/service.py +++ b/jupyterhub/services/service.py @@ -174,6 +174,7 @@ class Service(LoggingConfigurable): """ ).tag(input=True) # Managed service API: + spawner = Any() @property def managed(self): @@ -243,11 +244,11 @@ def prefix(self): return url_path_join(self.base_url, 'services', self.name + '/') @property - def proxy_path(self): + def proxy_spec(self): if not self.server: return '' if self.domain: - return url_path_join('/' + self.domain, self.server.base_url) + return self.domain + self.server.base_url else: return self.server.base_url @@ -298,6 +299,7 @@ def _proc_stopped(self): def stop(self): """Stop a managed service""" if not self.managed: - raise RuntimeError("Cannot start unmanaged service %s" % self) - self.spawner.stop_polling() - return self.spawner.stop() + raise RuntimeError("Cannot stop unmanaged service %s" % self) + if self.spawner: + self.spawner.stop_polling() + return self.spawner.stop() diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -16,7 +16,6 @@ from traitlets import HasTraits, Any, Dict, observe, default from .spawner import LocalProcessSpawner - class UserDict(dict): """Like defaultdict, but for users @@ -120,7 +119,7 @@ def __init__(self, orm_user, settings=None, **kwargs): self.allow_named_servers = self.settings.get('allow_named_servers', False) self.base_url = url_path_join( - self.settings.get('base_url', '/'), 'user', self.escaped_name) + self.settings.get('base_url', '/'), 'user', self.escaped_name) + '/' self.spawner = self.spawner_class( user=self, @@ -169,9 +168,9 @@ def escaped_name(self): return quote(self.name, safe='@') @property - def proxy_path(self): + def proxy_spec(self): if self.settings.get('subdomain_host'): - return url_path_join('/' + self.domain, self.base_url) + return self.domain + self.base_url else: return self.base_url @@ -223,7 +222,7 @@ def spawn(self, options=None): server_name = options['server_name'] else: server_name = default_server_name(self) - base_url = url_path_join(self.base_url, server_name) + base_url = url_path_join(self.base_url, server_name) + '/' else: server_name = '' base_url = self.base_url
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -413,9 +413,8 @@ def test_spawn(app, io_loop): status = io_loop.run_sync(app_user.spawner.poll) assert status is None - assert user.server.base_url == ujoin(app.base_url, 'user/%s' % name) + assert user.server.base_url == ujoin(app.base_url, 'user/%s' % name) + '/' url = public_url(app, user) - print(url) r = requests.get(url) assert r.status_code == 200 assert r.text == user.server.base_url diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -97,7 +97,7 @@ def test_spawn_redirect(app, io_loop): r.raise_for_status() print(urlparse(r.url)) path = urlparse(r.url).path - assert path == ujoin(app.base_url, 'user/%s' % name) + assert path == ujoin(app.base_url, 'user/%s/' % name) # should have started server status = io_loop.run_sync(u.spawner.poll) @@ -108,7 +108,7 @@ def test_spawn_redirect(app, io_loop): r.raise_for_status() print(urlparse(r.url)) path = urlparse(r.url).path - assert path == ujoin(app.base_url, '/user/%s' % name) + assert path == ujoin(app.base_url, '/user/%s/' % name) def test_spawn_page(app): with mock.patch.dict(app.users.settings, {'spawner_class': FormSpawner}): diff --git a/jupyterhub/tests/test_proxy.py b/jupyterhub/tests/test_proxy.py --- a/jupyterhub/tests/test_proxy.py +++ b/jupyterhub/tests/test_proxy.py @@ -4,7 +4,7 @@ import os from queue import Queue from subprocess import Popen -from urllib.parse import urlparse, unquote +from urllib.parse import urlparse, quote from traitlets.config import Config @@ -75,11 +75,13 @@ def wait_for_proxy(): routes = io_loop.run_sync(app.proxy.get_all_routes) # sets the desired path result - user_path = unquote(ujoin(app.base_url, 'user/river')) + user_path = ujoin(app.base_url, 'user/river') + '/' + print(app.base_url, user_path) + host = '' if app.subdomain_host: - domain = urlparse(app.subdomain_host).hostname - user_path = '/%s.%s' % (name, domain) + user_path - assert sorted(routes.keys()) == ['/', user_path] + host = '%s.%s' % (name, urlparse(app.subdomain_host).hostname) + user_spec = host + user_path + assert sorted(routes.keys()) == ['/', user_spec] # teardown the proxy and start a new one in the same place proxy.terminate() @@ -96,7 +98,7 @@ def wait_for_proxy(): # check that the routes are correct routes = io_loop.run_sync(app.proxy.get_all_routes) - assert sorted(routes.keys()) == ['/', user_path] + assert sorted(routes.keys()) == ['/', user_spec] # teardown the proxy, and start a new one with different auth and port proxy.terminate() @@ -135,7 +137,7 @@ def get_app_proxy_token(): # check that the routes are correct routes = io_loop.run_sync(app.proxy.get_all_routes) - assert sorted(routes.keys()) == ['/', user_path] + assert sorted(routes.keys()) == ['/', user_spec] @pytest.mark.parametrize("username, endpoints", [ @@ -156,22 +158,69 @@ def test_check_routes(app, io_loop, username, endpoints): # check a valid route exists for user test_user = app.users[username] before = sorted(io_loop.run_sync(app.proxy.get_all_routes)) - assert unquote(test_user.proxy_path) in before + assert test_user.proxy_spec in before # check if a route is removed when user deleted io_loop.run_sync(lambda: app.proxy.check_routes(app.users, app._service_map)) io_loop.run_sync(lambda: proxy.delete_user(test_user)) during = sorted(io_loop.run_sync(app.proxy.get_all_routes)) - assert unquote(test_user.proxy_path) not in during + assert test_user.proxy_spec not in during # check if a route exists for user io_loop.run_sync(lambda: app.proxy.check_routes(app.users, app._service_map)) after = sorted(io_loop.run_sync(app.proxy.get_all_routes)) - assert unquote(test_user.proxy_path) in after + assert test_user.proxy_spec in after # check that before and after state are the same assert before == after +from contextlib import contextmanager + [email protected]_test [email protected]("routespec", [ + '/has%20space/foo/', + '/missing-trailing/slash', + '/has/@/', + '/has/' + quote('üñîçø∂é'), + 'host.name/path/', + 'other.host/path/no/slash', +]) +def test_add_get_delete(app, routespec): + arg = routespec + if not routespec.endswith('/'): + routespec = routespec + '/' + + # host-routes when not host-routing raises an error + # and vice versa + expect_value_error = bool(app.subdomain_host) ^ (not routespec.startswith('/')) + @contextmanager + def context(): + if expect_value_error: + with pytest.raises(ValueError): + yield + else: + yield + + proxy = app.proxy + target = 'https://localhost:1234' + with context(): + yield proxy.add_route(arg, target=target) + routes = yield proxy.get_all_routes() + if not expect_value_error: + assert routespec in routes.keys() + with context(): + route = yield proxy.get_route(arg) + assert route == { + 'target': target, + 'routespec': routespec, + 'data': route.get('data'), + } + with context(): + yield proxy.delete_route(arg) + with context(): + route = yield proxy.get_route(arg) + assert route is None + @pytest.mark.parametrize("test_data", [None, 'notjson', json.dumps([])]) def test_proxy_patch_bad_request_data(app, test_data):
Make sure pluggable proxy config supports user per-domain We currently support this, and should continue to in a way that works across implementations!
We know it works with CHP, at least, because some of the tests are run in this mode. We can look at it again to see if we should clarify the API, though. Yeah, we should. Right now I see: ``` routespec (str): A specification for which this route will be matched. Could be either a url_prefix or a fqdn. ``` in `add_route`. I think we should explicitly make it a routespec named tuple that has domain and path_prefix parts.
2017-06-21T11:14:11Z
[]
[]
jupyterhub/jupyterhub
1,189
jupyterhub__jupyterhub-1189
[ "1186" ]
1015f3bf533c21756d327847959e64bd75ac327d
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -1176,7 +1176,7 @@ def init_proxy(self): base_url=self.base_url, ) self.proxy = self.proxy_class( - db=self.db, + db_factory=lambda: self.db, public_url=public_url, parent=self, app=self, @@ -1433,6 +1433,7 @@ def start(self): self.exit(1) else: self.log.info("Not starting proxy") + yield self.proxy.add_hub_route(self.hub) # start the service(s) for service_name, service in self._service_map.items(): diff --git a/jupyterhub/proxy.py b/jupyterhub/proxy.py --- a/jupyterhub/proxy.py +++ b/jupyterhub/proxy.py @@ -67,7 +67,11 @@ class Proxy(LoggingConfigurable): of fetching a single route. """ - db = Any() + db_factory = Any() + @property + def db(self): + return self.db_factory() + app = Any() hub = Any() public_url = Unicode() @@ -107,6 +111,10 @@ def validate_routespec(self, routespec): - Checks host value vs host-based routing. - Ensures trailing slash on path. """ + if routespec == '/': + # / is the default route. + # don't check host-based routing + return routespec # check host routing host_route = not routespec.startswith('/') if host_route and not self.host_routing: @@ -281,6 +289,11 @@ def check_routes(self, user_dict, service_dict, routes=None): user_routes = {r['data']['user'] for r in routes.values() if 'user' in r['data']} futures = [] db = self.db + + if '/' not in routes: + self.log.warning("Adding missing default route") + self.add_hub_route(self.app.hub) + for orm_user in db.query(User): user = user_dict[orm_user] if user.running: @@ -315,9 +328,15 @@ def check_routes(self, user_dict, service_dict, routes=None): for f in futures: yield f + def add_hub_route(self, hub): + """Add the default route for the Hub""" + self.log.info("Adding default route for Hub: / => %s", hub.host) + return self.add_route('/', self.hub.host) + @gen.coroutine def restore_routes(self): self.log.info("Setting up routes on new proxy") + yield self.add_hub_route(self.app.hub) yield self.add_all_users(self.app.users) yield self.add_all_services(self.app.services) self.log.info("New proxy back up and good to go") @@ -379,7 +398,6 @@ def start(self): '--port', str(public_server.port), '--api-ip', api_server.ip, '--api-port', str(api_server.port), - '--default-target', self.hub.host, '--error-target', url_path_join(self.hub.url, 'error'), ] if self.app.subdomain_host: @@ -431,7 +449,6 @@ def _check_process(): else: break yield server.wait_up(1) - time.sleep(1) _check_process() self.log.debug("Proxy started and appears to be up") pc = PeriodicCallback(self.check_running, 1e3 * self.check_running_interval) @@ -464,7 +481,7 @@ def _routespec_to_chp_path(self, routespec): path = self.validate_routespec(routespec) # CHP always wants to start with / if not path.startswith('/'): - path = path + '/' + path = '/' + path # BUG: CHP doesn't seem to like trailing slashes on some endpoints (DELETE) if path != '/' and path.endswith('/'): path = path.rstrip('/') @@ -507,6 +524,7 @@ def api_request(self, path, method='GET', body=None, client=None): def add_route(self, routespec, target, data=None): body = data or {} body['target'] = target + body['jupyterhub'] = True path = self._routespec_to_chp_path(routespec) return self.api_request(path, method='POST', @@ -520,6 +538,7 @@ def delete_route(self, routespec): def _reformat_routespec(self, routespec, chp_data): """Reformat CHP data format to JupyterHub's proxy API.""" target = chp_data.pop('target') + chp_data.pop('jupyterhub') return { 'routespec': routespec, 'target': target, @@ -534,6 +553,10 @@ def get_all_routes(self, client=None): all_routes = {} for chp_path, chp_data in chp_routes.items(): routespec = self._routespec_from_chp_path(chp_path) + if 'jupyterhub' not in chp_data: + # exclude routes not associated with JupyterHub + self.log.debug("Omitting non-jupyterhub route %r", routespec) + continue all_routes[routespec] = self._reformat_routespec( routespec, chp_data) return all_routes
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -5,6 +5,7 @@ from tempfile import NamedTemporaryFile import threading from unittest import mock +from urllib.parse import urlparse import requests @@ -136,7 +137,15 @@ def _subdomain_host_default(self): @default('ip') def _ip_default(self): return '127.0.0.1' - + + @default('port') + def _port_default(self): + if self.subdomain_host: + port = urlparse(self.subdomain_host).port + if port: + return port + return random_port() + @default('authenticator_class') def _authenticator_class_default(self): return MockPAMAuthenticator diff --git a/jupyterhub/tests/test_proxy.py b/jupyterhub/tests/test_proxy.py --- a/jupyterhub/tests/test_proxy.py +++ b/jupyterhub/tests/test_proxy.py @@ -43,7 +43,7 @@ def fin(): '--port', str(app.port), '--api-ip', proxy_ip, '--api-port', str(proxy_port), - '--default-target', 'http://%s:%i' % (app.hub_ip, app.hub_port), + '--log-level=debug', ] if app.subdomain_host: cmd.append('--host-routing') @@ -90,7 +90,7 @@ def wait_for_proxy(): routes = io_loop.run_sync(app.proxy.get_all_routes) - assert list(routes.keys()) == ['/'] + assert list(routes.keys()) == [] # poke the server to update the proxy r = api_request(app, 'proxy', method='post')
Have the hub explicitly add a default route to the proxy that points back to the hub The hub should add a default route to the proxy that points `/` back to itself. This makes the lives of proxy implementations much easier.
2017-06-27T14:33:00Z
[]
[]
jupyterhub/jupyterhub
1,239
jupyterhub__jupyterhub-1239
[ "1229" ]
738976a9568d8e90fcf8fa94c3f97a9e0f872b9e
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -15,8 +15,8 @@ import sys v = sys.version_info -if v[:2] < (3,3): - error = "ERROR: JupyterHub requires Python version 3.3 or above." +if v[:2] < (3,4): + error = "ERROR: JupyterHub requires Python version 3.4 or above." print(error, file=sys.stderr) sys.exit(1) @@ -49,10 +49,10 @@ def get_data_files(): """Get data files in share/jupyter""" - + data_files = [] ntrim = len(here + os.path.sep) - + for (d, dirs, filenames) in os.walk(share_jupyter): data_files.append(( d[ntrim:], @@ -134,27 +134,27 @@ def mtime(path): class BaseCommand(Command): """Dumb empty command because Command needs subclasses to override too much""" user_options = [] - + def initialize_options(self): pass - + def finalize_options(self): pass - + def get_inputs(self): return [] - + def get_outputs(self): return [] class Bower(BaseCommand): description = "fetch static client-side components with bower" - + user_options = [] bower_dir = pjoin(static, 'components') node_modules = pjoin(here, 'node_modules') - + def should_run(self): if not os.path.exists(self.bower_dir): return True @@ -167,17 +167,17 @@ def should_run_npm(self): if not os.path.exists(self.node_modules): return True return mtime(self.node_modules) < mtime(pjoin(here, 'package.json')) - + def run(self): if not self.should_run(): print("bower dependencies up to date") return - + if self.should_run_npm(): print("installing build dependencies with npm") check_call(['npm', 'install', '--progress=false'], cwd=here, shell=shell) os.utime(self.node_modules) - + env = os.environ.copy() env['PATH'] = npm_path args = ['bower', 'install', '--allow-root', '--config.interactive=false'] @@ -194,11 +194,11 @@ def run(self): class CSS(BaseCommand): description = "compile CSS from LESS" - + def should_run(self): """Does less need to run?""" # from IPython.html.tasks.py - + css_targets = [pjoin(static, 'css', 'style.min.css')] css_maps = [t + '.map' for t in css_targets] targets = css_targets + css_maps @@ -206,7 +206,7 @@ def should_run(self): # some generated files don't exist return True earliest_target = sorted(mtime(t) for t in targets)[0] - + # check if any .less files are newer than the generated targets for (dirpath, dirnames, filenames) in os.walk(static): for f in filenames: @@ -215,20 +215,20 @@ def should_run(self): timestamp = mtime(path) if timestamp > earliest_target: return True - + return False - + def run(self): if not self.should_run(): print("CSS up-to-date") return - + self.run_command('js') - + style_less = pjoin(static, 'less', 'style.less') style_css = pjoin(static, 'css', 'style.min.css') sourcemap = style_css + '.map' - + env = os.environ.copy() env['PATH'] = npm_path args = [
diff --git a/jupyterhub/tests/test_app.py b/jupyterhub/tests/test_app.py --- a/jupyterhub/tests/test_app.py +++ b/jupyterhub/tests/test_app.py @@ -72,7 +72,7 @@ def test_init_tokens(io_loop): assert api_token is not None user = api_token.user assert user.name == username - + # simulate second startup, reloading same tokens: app = MockHub(db_url=db_file, api_tokens=tokens) io_loop.run_sync(lambda : app.initialize([])) @@ -82,7 +82,7 @@ def test_init_tokens(io_loop): assert api_token is not None user = api_token.user assert user.name == username - + # don't allow failed token insertion to create users: tokens['short'] = 'gman' app = MockHub(db_url=db_file, api_tokens=tokens) @@ -157,3 +157,7 @@ def test_load_groups(io_loop): gold = orm.Group.find(db, name='gold') assert gold is not None assert sorted([ u.name for u in gold.users ]) == sorted(to_load['gold']) + +def test_version(): + if sys.version_info[:2] < (3, 3): + assertRaises(ValueError)
When to drop Python 3.3 support Initially released in 2012, Python 3.3 reaches EOL on 09-29-2017. [python-dev mailing list reference](https://mail.python.org/pipermail/python-dev/2017-July/148584.html) I would recommend officially dropping Python 3.3 support for installation in JupyterHub 0.8.
+1! Dropping for 0.8 sounds great
2017-07-19T22:01:11Z
[]
[]
jupyterhub/jupyterhub
1,294
jupyterhub__jupyterhub-1294
[ "1162" ]
c78e31b136246d5b57c0b2f1cb6d45ebfd34a8b8
diff --git a/jupyterhub/alembic/versions/3ec6993fe20c_encrypted_auth_state.py b/jupyterhub/alembic/versions/3ec6993fe20c_encrypted_auth_state.py --- a/jupyterhub/alembic/versions/3ec6993fe20c_encrypted_auth_state.py +++ b/jupyterhub/alembic/versions/3ec6993fe20c_encrypted_auth_state.py @@ -1,4 +1,11 @@ -"""encrypted_auth_state +"""0.8 changes + +- encrypted auth_state +- remove proxy/hub data from db + +OAuth data was also added in this revision, +but no migration to do because they are entirely new tables, +which will be created on launch. Revision ID: 3ec6993fe20c Revises: af4cbdb2d13c @@ -12,7 +19,9 @@ branch_labels = None depends_on = None -import warnings +import logging + +logger = logging.getLogger('alembic') from alembic import op import sqlalchemy as sa @@ -20,15 +29,36 @@ def upgrade(): + # proxy/table info is no longer in the database + op.drop_table('proxies') + op.drop_table('hubs') + + # drop some columns no longer in use try: op.drop_column('users', 'auth_state') - except sa.exc.OperationalError as e: - # sqlite3 can't drop columns - warnings.warn("Failed to drop column: %s" % e) + op.drop_column('users', '_server_id') + except sa.exc.OperationalError: + # this won't be a problem moving forward, but downgrade will fail + if op.get_context().dialect.name == 'sqlite': + logger.warning("sqlite cannot drop columns. Leaving unused old columns in place.") + else: + raise + op.add_column('users', sa.Column('encrypted_auth_state', sa.types.LargeBinary)) def downgrade(): + # drop all the new tables + engine = op.get_bind().engine + for table in ('oauth_clients', + 'oauth_codes', + 'oauth_access_tokens', + 'spawners'): + if engine.has_table(table): + op.drop_table(table) + op.drop_column('users', 'encrypted_auth_state') + op.add_column('users', sa.Column('auth_state', JSONDict)) - + op.add_column('users', sa.Column('_server_id', sa.Integer, sa.ForeignKey('servers.id'))) + diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -185,6 +185,7 @@ def _backup_db_file(self, db_file): def start(self): hub = JupyterHub(parent=self) hub.load_config_file(hub.config_file) + self.log = hub.log if (hub.db_url.startswith('sqlite:///')): db_file = hub.db_url.split(':///', 1)[1] self._backup_db_file(db_file) @@ -862,6 +863,8 @@ def init_db(self): "to upgrade your JupyterHub database schema", ])) self.exit(1) + except orm.DatabaseSchemaMismatch as e: + self.exit(e) def init_hub(self): """Load the Hub config into the database""" diff --git a/jupyterhub/orm.py b/jupyterhub/orm.py --- a/jupyterhub/orm.py +++ b/jupyterhub/orm.py @@ -7,6 +7,9 @@ import enum import json +import alembic.config +import alembic.command +from alembic.script import ScriptDirectory from tornado.log import app_log from sqlalchemy.types import TypeDecorator, TEXT, LargeBinary @@ -21,6 +24,7 @@ from sqlalchemy.sql.expression import bindparam from sqlalchemy import create_engine, Table +from .dbutil import _temp_alembic_ini from .utils import ( random_port, new_token, hash_token, compare_token, @@ -431,6 +435,73 @@ class OAuthClient(Base): redirect_uri = Column(Unicode(1023)) +class DatabaseSchemaMismatch(Exception): + """Exception raised when the database schema version does not match + + the current version of JupyterHub. + """ + +def check_db_revision(engine): + """Check the JupyterHub database revision + + After calling this function, an alembic tag is guaranteed to be stored in the db. + + - Checks the alembic tag and raises a ValueError if it's not the current revision + - If no tag is stored (Bug in Hub prior to 0.8), + guess revision based on db contents and tag the revision. + - Empty databases are tagged with the current revision + """ + # Check database schema version + current_table_names = set(engine.table_names()) + my_table_names = set(Base.metadata.tables.keys()) + + with _temp_alembic_ini(engine.url) as ini: + cfg = alembic.config.Config(ini) + scripts = ScriptDirectory.from_config(cfg) + head = scripts.get_heads()[0] + base = scripts.get_base() + + if not my_table_names.intersection(current_table_names): + # no tables have been created, stamp with current revision + app_log.debug("Stamping empty database with alembic revision %s", head) + alembic.command.stamp(cfg, head) + return + + if 'alembic_version' not in current_table_names: + # Has not been tagged or upgraded before. + # we didn't start tagging revisions correctly except during `upgrade-db` + # until 0.8 + # This should only occur for databases created prior to JupyterHub 0.8 + msg_t = "Database schema version not found, guessing that JupyterHub %s created this database." + if 'spawners' in current_table_names: + # 0.8 + app_log.warning(msg_t, '0.8.dev') + rev = head + elif 'services' in current_table_names: + # services is present, tag for 0.7 + app_log.warning(msg_t, '0.7.x') + rev = 'af4cbdb2d13c' + else: + # it's old, mark as first revision + app_log.warning(msg_t, '0.6 or earlier') + rev = base + app_log.debug("Stamping database schema version %s", rev) + alembic.command.stamp(cfg, rev) + + # check database schema version + # it should always be defined at this point + alembic_revision = engine.execute('SELECT version_num FROM alembic_version').first()[0] + if alembic_revision == head: + app_log.debug("database schema version found: %s", alembic_revision) + pass + else: + raise DatabaseSchemaMismatch("Found database schema version {found} != {head}. " + "Backup your database and run `jupyterhub upgrade-db`" + " to upgrade to the latest schema.".format( + found=alembic_revision, + head=head, + )) + def new_session_factory(url="sqlite:///:memory:", reset=False, **kwargs): """Create a new session at url""" if url.startswith('sqlite'): @@ -446,6 +517,9 @@ def new_session_factory(url="sqlite:///:memory:", reset=False, **kwargs): engine = create_engine(url, **kwargs) if reset: Base.metadata.drop_all(engine) + + # check the db revision (will raise, pointing to `upgrade-db` if version doesn't match) + check_db_revision(engine) Base.metadata.create_all(engine) session_factory = sessionmaker(bind=engine)
diff --git a/jupyterhub/tests/test_db.py b/jupyterhub/tests/test_db.py --- a/jupyterhub/tests/test_db.py +++ b/jupyterhub/tests/test_db.py @@ -2,8 +2,6 @@ import os import shutil -from sqlalchemy.exc import OperationalError - import pytest from pytest import raises @@ -32,7 +30,7 @@ def test_upgrade_entrypoint(tmpdir): tmpdir.chdir() tokenapp = NewToken() tokenapp.initialize(['kaylee']) - with raises(OperationalError): + with raises(SystemExit): tokenapp.start() sqlite_files = glob(os.path.join(str(tmpdir), 'jupyterhub.sqlite*'))
Issues using upgrade-db on a fresh database Database migration works only if you start on an old version of the database. But, consider the case where I create a JupyterHub database today, and then a future release updates the database. Running `jupyterhub upgrade-db` then would fail, because the database existing today doesn't have the `alembic_version` table specifying what the current version is. So, alembic will assume the version is the old version, and try to insert columns that already exist: ``` $ jupyterhub ... $ jupyterhub upgrade-db INFO [alembic.runtime.migration] Context impl SQLiteImpl. INFO [alembic.runtime.migration] Will assume non-transactional DDL. INFO [alembic.runtime.migration] Running upgrade -> 19c0846f6344, base revision for 0.5 INFO [alembic.runtime.migration] Running upgrade 19c0846f6344 -> eeb276e51423, auth_state Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context context) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/default.py", line 470, in do_execute cursor.execute(statement, parameters) sqlite3.OperationalError: duplicate column name: auth_state The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/bin/alembic", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python3.5/dist-packages/alembic/config.py", line 479, in main CommandLine(prog=prog).main(argv=argv) File "/usr/local/lib/python3.5/dist-packages/alembic/config.py", line 473, in main self.run_cmd(cfg, options) File "/usr/local/lib/python3.5/dist-packages/alembic/config.py", line 456, in run_cmd **dict((k, getattr(options, k, None)) for k in kwarg) File "/usr/local/lib/python3.5/dist-packages/alembic/command.py", line 254, in upgrade script.run_env() File "/usr/local/lib/python3.5/dist-packages/alembic/script/base.py", line 416, in run_env util.load_python_file(self.dir, 'env.py') File "/usr/local/lib/python3.5/dist-packages/alembic/util/pyfiles.py", line 93, in load_python_file module = load_module_py(module_id, path) File "/usr/local/lib/python3.5/dist-packages/alembic/util/compat.py", line 64, in load_module_py module_id, path).load_module(module_id) File "<frozen importlib._bootstrap_external>", line 388, in _check_name_wrapper File "<frozen importlib._bootstrap_external>", line 809, in load_module File "<frozen importlib._bootstrap_external>", line 668, in load_module File "<frozen importlib._bootstrap>", line 268, in _load_module_shim File "<frozen importlib._bootstrap>", line 693, in _load File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/usr/local/lib/python3.5/dist-packages/jupyterhub/alembic/env.py", line 70, in <module> run_migrations_online() File "/usr/local/lib/python3.5/dist-packages/jupyterhub/alembic/env.py", line 65, in run_migrations_online context.run_migrations() File "<string>", line 8, in run_migrations File "/usr/local/lib/python3.5/dist-packages/alembic/runtime/environment.py", line 817, in run_migrations self.get_context().run_migrations(**kw) File "/usr/local/lib/python3.5/dist-packages/alembic/runtime/migration.py", line 323, in run_migrations step.migration_fn(**kw) File "/usr/local/lib/python3.5/dist-packages/jupyterhub/alembic/versions/eeb276e51423_auth_state.py", line 21, in upgrade op.add_column('users', sa.Column('auth_state', JSONDict)) File "<string>", line 8, in add_column File "<string>", line 3, in add_column File "/usr/local/lib/python3.5/dist-packages/alembic/operations/ops.py", line 1551, in add_column return operations.invoke(op) File "/usr/local/lib/python3.5/dist-packages/alembic/operations/base.py", line 318, in invoke return fn(self, operation) File "/usr/local/lib/python3.5/dist-packages/alembic/operations/toimpl.py", line 123, in add_column schema=schema File "/usr/local/lib/python3.5/dist-packages/alembic/ddl/impl.py", line 172, in add_column self._exec(base.AddColumn(table_name, column, schema=schema)) File "/usr/local/lib/python3.5/dist-packages/alembic/ddl/impl.py", line 118, in _exec return conn.execute(construct, *multiparams, **params) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 945, in execute return meth(self, multiparams, params) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/sql/ddl.py", line 68, in _execute_on_connection return connection._execute_ddl(self, multiparams, params) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1002, in _execute_ddl compiled File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context context) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception exc_info File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/compat.py", line 186, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context context) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/default.py", line 470, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) duplicate column name: auth_state [SQL: 'ALTER TABLE users ADD COLUMN auth_state TEXT'] [E 2017-06-02 19:55:16.017 JupyterHub app:1527] Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 1525, in launch_instance_async yield self.start() File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 1436, in start self.subapp.start() File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 185, in start dbutil.upgrade(hub.db_url) File "/usr/local/lib/python3.5/dist-packages/jupyterhub/dbutil.py", line 80, in upgrade ['alembic', '-c', alembic_ini, 'upgrade', revision] File "/usr/lib/python3.5/subprocess.py", line 581, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['alembic', '-c', '/tmp/tmpkqvnuq0a/alembic.ini', 'upgrade', 'head']' returned non-zero exit status 1 ``` I got around this in nbgrader by creating the `alembic_version` table the first time the database is initialized: https://github.com/jupyter/nbgrader/blob/master/nbgrader/api.py#L1045
Good catch @jhamrick. I'll try to get this one this week. I think we need to: 1. call ansible.tag on startup creating a new db, to prevent this in the future. But be careful to only do this if no tag is not already set 2. handle this bug: detect existing db without ansible tag data and trigger tag for 0.7 version
2017-07-31T14:24:01Z
[]
[]
jupyterhub/jupyterhub
1,301
jupyterhub__jupyterhub-1301
[ "1282" ]
875e5d59febff7ff1c2118dce8c733c6f063aac6
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -552,10 +552,39 @@ def _authenticator_default(self): help=""" Maximum number of concurrent users that can be spawning at a time. + Spawning lots of servers at the same time can cause performance + problems for the Hub or the underlying spawning system. + Set this limit to prevent bursts of logins from attempting + to spawn too many servers at the same time. + + This does not limit the number of total running servers. + See active_server_limit for that. + If more than this many users attempt to spawn at a time, their - request is rejected with a 429 error asking them to try again. + requests will be rejected with a 429 error asking them to try again. + Users will have to wait for some of the spawning services + to finish starting before they can start their own. + + If set to 0, no limit is enforced. + """ + ).tag(config=True) + + active_server_limit = Integer( + 0, + help=""" + Maximum number of concurrent servers that can be active at a time. + + Setting this can limit the total resources your users can consume. + + An active server is any server that's not fully stopped. + It is considered active from the time it has been requested + until the time that it has completely stopped. + + If this many user servers are active, users will not be able to + launch new servers until a server is shutdown. + Spawn requests will be rejected with a 429 error asking them to try again. - If set to 0, no concurrent_spawn_limit is enforced. + If set to 0, no limit is enforced. """ ).tag(config=True) @@ -1270,6 +1299,7 @@ def init_tornado_settings(self): allow_named_servers=self.allow_named_servers, oauth_provider=self.oauth_provider, concurrent_spawn_limit=self.concurrent_spawn_limit, + active_server_limit=self.active_server_limit, ) # allow configured settings to have priority settings.update(self.tornado_settings) diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -368,27 +368,41 @@ def concurrent_spawn_limit(self): return self.settings.get('concurrent_spawn_limit', 0) @property - def spawn_pending_count(self): - return self.settings.setdefault('_spawn_pending_count', 0) - - @spawn_pending_count.setter - def spawn_pending_count(self, value): - self.settings['_spawn_pending_count'] = value + def active_server_limit(self): + return self.settings.get('active_server_limit', 0) @gen.coroutine def spawn_single_user(self, user, server_name='', options=None): - if server_name in user.spawners and user.spawners[server_name]._spawn_pending: + if server_name in user.spawners and user.spawners[server_name].pending == 'spawn': raise RuntimeError("Spawn already pending for: %s" % user.name) + # count active servers and pending spawns + # we could do careful bookkeeping to avoid + # but for 10k users this takes ~5ms + # and saves us from bookkeeping errors + active_counts = self.users.count_active_users() + spawn_pending_count = active_counts['spawn_pending'] + active_counts['proxy_pending'] + active_count = active_counts['active'] + concurrent_spawn_limit = self.concurrent_spawn_limit - if concurrent_spawn_limit and self.spawn_pending_count >= concurrent_spawn_limit: + active_server_limit = self.active_server_limit + + if concurrent_spawn_limit and spawn_pending_count >= concurrent_spawn_limit: self.log.info( '%s pending spawns, throttling', - concurrent_spawn_limit, + spawn_pending_count, + ) + raise web.HTTPError( + 429, + "User startup rate limit exceeded. Try again in a few minutes.") + if active_server_limit and active_count >= active_server_limit: + self.log.info( + '%s servers active, no space available', + active_count, ) raise web.HTTPError( 429, - "User startup rate limit exceeded. Try to start again in a few minutes.") + "Active user limit exceeded. Try again in a few minutes.") tic = IOLoop.current().time() user_server_name = user.name @@ -401,15 +415,14 @@ def spawn_single_user(self, user, server_name='', options=None): f = user.spawn(server_name, options) - # increment spawn_pending only after spawn starts self.log.debug("%i%s concurrent spawns", - self.spawn_pending_count, + spawn_pending_count, '/%i' % concurrent_spawn_limit if concurrent_spawn_limit else '') - # FIXME: Move this out of settings, since this isn't really a setting - self.spawn_pending_count += 1 + self.log.debug("%i%s active servers", + active_count, + '/%i' % active_server_limit if active_server_limit else '') spawner = user.spawners[server_name] - spawner._proxy_pending = True @gen.coroutine def finish_user_spawn(f=None): @@ -420,12 +433,12 @@ def finish_user_spawn(f=None): """ if f and f.exception() is not None: # failed, don't add to the proxy - self.spawn_pending_count -= 1 return toc = IOLoop.current().time() self.log.info("User %s took %.3f seconds to start", user_server_name, toc-tic) self.statsd.timing('spawner.success', (toc - tic) * 1000) try: + spawner._proxy_pending = True yield self.proxy.add_user(user, server_name) except Exception: self.log.exception("Failed to add %s to proxy!", user_server_name) @@ -435,7 +448,6 @@ def finish_user_spawn(f=None): spawner.add_poll_callback(self.user_stopped, user) finally: spawner._proxy_pending = False - self.spawn_pending_count -= 1 try: yield gen.with_timeout(timedelta(seconds=self.slow_spawn_timeout), f) @@ -462,14 +474,9 @@ def finish_user_spawn(f=None): # schedule finish for when the user finishes spawning IOLoop.current().add_future(f, finish_user_spawn) else: - self.spawn_pending_count -= 1 toc = IOLoop.current().time() self.statsd.timing('spawner.failure', (toc - tic) * 1000) raise web.HTTPError(500, "Spawner failed to start [status=%s]" % status) - except Exception: - # error in start - self.spawn_pending_count -= 1 - raise else: yield finish_user_spawn() diff --git a/jupyterhub/objects.py b/jupyterhub/objects.py --- a/jupyterhub/objects.py +++ b/jupyterhub/objects.py @@ -62,6 +62,11 @@ def _connect_port(self): return self.connect_port return self.port + @classmethod + def from_orm(cls, orm_server): + """Create a server from an orm.Server""" + return cls(orm_server=orm_server) + @classmethod def from_url(cls, url): """Create a Server from a given URL""" diff --git a/jupyterhub/services/service.py b/jupyterhub/services/service.py --- a/jupyterhub/services/service.py +++ b/jupyterhub/services/service.py @@ -235,7 +235,7 @@ def _default_client_id(self): @property def server(self): if self.orm.server: - return Server(orm_server=self.orm.server) + return Server.from_orm(self.orm.server) else: return None diff --git a/jupyterhub/spawner.py b/jupyterhub/spawner.py --- a/jupyterhub/spawner.py +++ b/jupyterhub/spawner.py @@ -15,13 +15,15 @@ from subprocess import Popen from tempfile import mkdtemp +from sqlalchemy import inspect + from tornado import gen from tornado.ioloop import PeriodicCallback, IOLoop from traitlets.config import LoggingConfigurable from traitlets import ( Any, Bool, Dict, Instance, Integer, Float, List, Unicode, - validate, + observe, validate, ) from .objects import Server @@ -51,9 +53,50 @@ class Spawner(LoggingConfigurable): _proxy_pending = False _waiting_for_response = False + @property + def pending(self): + """Return the current pending event, if any + + Return False if nothing is pending. + """ + if self._spawn_pending or self._proxy_pending: + return 'spawn' + elif self._stop_pending: + return 'stop' + return False + + @property + def ready(self): + """Is this server ready to use? + + A server is not ready if an event is pending. + """ + if self.pending: + return False + if self.server is None: + return False + return True + + @property + def active(self): + """Return True if the server is active. + + This includes fully running and ready or any pending start/stop event. + """ + return bool(self.pending or self.ready) + + authenticator = Any() hub = Any() orm_spawner = Any() + + @observe('orm_spawner') + def _orm_spawner_changed(self, change): + if change.new and change.new.server: + self._server = Server(orm_server=change.new.server) + else: + self._server = None + user = Any() def __init_subclass__(cls, **kwargs): @@ -70,8 +113,24 @@ def __init_subclass__(cls, **kwargs): @property def server(self): + if hasattr(self, '_server'): + return self._server if self.orm_spawner and self.orm_spawner.server: return Server(orm_server=self.orm_spawner.server) + + @server.setter + def server(self, server): + self._server = server + if self.orm_spawner: + if self.orm_spawner.server is not None: + # delete the old value + db = inspect(self.orm_spawner.server).session + db.delete(self.orm_spawner.server) + if server is None: + self.orm_spawner.server = None + else: + self.orm_spawner.server = server.orm_server + @property def name(self): if self.orm_spawner: diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -1,6 +1,7 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. +from collections import defaultdict from datetime import datetime, timedelta from urllib.parse import quote, urlparse @@ -8,12 +9,13 @@ from sqlalchemy import inspect from tornado import gen from tornado.log import app_log +from traitlets import HasTraits, Any, Dict, default from .utils import url_path_join, default_server_name from . import orm from ._version import _check_version, __version__ -from traitlets import HasTraits, Any, Dict, observe, default +from .objects import Server from .spawner import LocalProcessSpawner from .crypto import encrypt, decrypt, CryptKeeper, EncryptionUnavailable, InvalidToken @@ -73,6 +75,25 @@ def __delitem__(self, key): db.commit() dict.__delitem__(self, user_id) + def count_active_users(self): + """Count the number of user servers that are active/pending/ready + + Returns dict with counts of active/pending/ready servers + """ + counts = defaultdict(lambda : 0) + for user in self.values(): + for spawner in user.spawners.values(): + pending = spawner.pending + if pending: + counts['pending'] += 1 + counts[pending + '_pending'] += 1 + if spawner.active: + counts['active'] += 1 + if spawner.ready: + counts['ready'] += 1 + + return counts + class _SpawnerDict(dict): def __init__(self, spawner_factory): @@ -294,8 +315,8 @@ def spawn(self, server_name='', options=None): spawner = self.spawners[server_name] - spawner.orm_spawner.server = orm_server - server = spawner.server + spawner.server = server = Server(orm_server=orm_server) + assert spawner.orm_spawner.server is orm_server # Passing user_options to the spawner spawner.user_options = options or {} @@ -432,9 +453,7 @@ def stop(self, server_name=''): spawner.orm_spawner.state = spawner.get_state() self.last_activity = datetime.utcnow() # remove server entry from db - if spawner.server is not None: - self.db.delete(spawner.orm_spawner.server) - spawner.orm_spawner.server = None + spawner.server = None if not spawner.will_resume: # find and remove the API token if the spawner isn't # going to re-use it next time
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -392,7 +392,6 @@ def test_make_admin(app): @mark.gen_test def test_spawn(app): - settings = app.tornado_application.settings db = app.db name = 'wash' user = add_user(db, app=app, name=name) @@ -444,12 +443,11 @@ def test_spawn(app): assert before_servers == after_servers tokens = list(db.query(orm.APIToken).filter(orm.APIToken.user_id == user.id)) assert tokens == [] - assert settings['_spawn_pending_count'] == 0 + assert app.users.count_active_users()['pending'] == 0 @mark.gen_test def test_slow_spawn(app, no_patience, slow_spawn): - settings = app.tornado_application.settings db = app.db name = 'zoe' app_user = add_user(db, app=app, name=name) @@ -459,7 +457,7 @@ def test_slow_spawn(app, no_patience, slow_spawn): assert app_user.spawner is not None assert app_user.spawner._spawn_pending assert not app_user.spawner._stop_pending - assert settings['_spawn_pending_count'] == 1 + assert app.users.count_active_users()['pending'] == 1 @gen.coroutine def wait_spawn(): @@ -493,31 +491,29 @@ def wait_stop(): assert app_user.spawner is not None r = yield api_request(app, 'users', name, 'server', method='delete') assert r.status_code == 400 - assert settings['_spawn_pending_count'] == 0 + assert app.users.count_active_users()['pending'] == 0 + assert app.users.count_active_users()['active'] == 0 @mark.gen_test def test_never_spawn(app, no_patience, never_spawn): - settings = app.tornado_application.settings db = app.db name = 'badger' app_user = add_user(db, app=app, name=name) r = yield api_request(app, 'users', name, 'server', method='post') assert app_user.spawner is not None assert app_user.spawner._spawn_pending - assert settings['_spawn_pending_count'] == 1 + assert app.users.count_active_users()['pending'] == 1 - @gen.coroutine - def wait_pending(): - while app_user.spawner._spawn_pending: - yield gen.sleep(0.1) + while app_user.spawner.pending: + yield gen.sleep(0.1) + print(app_user.spawner.pending) - yield wait_pending() assert not app_user.spawner._spawn_pending status = yield app_user.spawner.poll() assert status is not None # failed spawn should decrements pending count - assert settings['_spawn_pending_count'] == 0 + assert app.users.count_active_users()['pending'] == 0 @mark.gen_test @@ -528,7 +524,7 @@ def test_bad_spawn(app, no_patience, bad_spawn): user = add_user(db, app=app, name=name) r = yield api_request(app, 'users', name, 'server', method='post') assert r.status_code == 500 - assert settings['_spawn_pending_count'] == 0 + assert app.users.count_active_users()['pending'] == 0 @mark.gen_test @@ -539,11 +535,11 @@ def test_slow_bad_spawn(app, no_patience, slow_bad_spawn): user = add_user(db, app=app, name=name) r = yield api_request(app, 'users', name, 'server', method='post') r.raise_for_status() - while user.spawner._spawn_pending: + while user.spawner.pending: yield gen.sleep(0.1) # spawn failed assert not user.running('') - assert settings['_spawn_pending_count'] == 0 + assert app.users.count_active_users()['pending'] == 0 @mark.gen_test @@ -561,7 +557,7 @@ def _restore_limit(): for name in names: yield api_request(app, 'users', name, 'server', method='post') yield gen.sleep(0.5) - assert settings['_spawn_pending_count'] == 2 + assert app.users.count_active_users()['pending'] == 2 # ykka and hjarka's spawns are pending. Essun should fail with 429 name = 'essun' @@ -575,23 +571,82 @@ def _restore_limit(): # race? hjarka could finish in this time # come back to this if we see intermittent failures here - assert settings['_spawn_pending_count'] == 1 + assert app.users.count_active_users()['pending'] == 1 r = yield api_request(app, 'users', name, 'server', method='post') r.raise_for_status() - assert settings['_spawn_pending_count'] == 2 + assert app.users.count_active_users()['pending'] == 2 users.append(user) while not all(u.running('') for u in users): yield gen.sleep(0.1) # everybody's running, pending count should be back to 0 - assert settings['_spawn_pending_count'] == 0 + assert app.users.count_active_users()['pending'] == 0 for u in users: r = yield api_request(app, 'users', u.name, 'server', method='delete') yield r.raise_for_status() - while any(u.running('') for u in users): + while any(u.spawner.active for u in users): yield gen.sleep(0.1) [email protected]_test +def test_active_server_limit(app, request): + db = app.db + settings = app.tornado_application.settings + settings['active_server_limit'] = 2 + def _restore_limit(): + settings['active_server_limit'] = 0 + request.addfinalizer(_restore_limit) + + # start two pending spawns + names = ['ykka', 'hjarka'] + users = [ add_user(db, app=app, name=name) for name in names ] + for name in names: + r = yield api_request(app, 'users', name, 'server', method='post') + r.raise_for_status() + counts = app.users.count_active_users() + assert counts['active'] == 2 + assert counts['ready'] == 2 + assert counts['pending'] == 0 + + # ykka and hjarka's servers are running. Essun should fail with 429 + name = 'essun' + user = add_user(db, app=app, name=name) + r = yield api_request(app, 'users', name, 'server', method='post') + assert r.status_code == 429 + counts = app.users.count_active_users() + assert counts['active'] == 2 + assert counts['ready'] == 2 + assert counts['pending'] == 0 + + # stop one server + yield api_request(app, 'users', names[0], 'server', method='delete') + counts = app.users.count_active_users() + assert counts['active'] == 1 + assert counts['ready'] == 1 + assert counts['pending'] == 0 + + r = yield api_request(app, 'users', name, 'server', method='post') + r.raise_for_status() + counts = app.users.count_active_users() + assert counts['active'] == 2 + assert counts['ready'] == 2 + assert counts['pending'] == 0 + users.append(user) + + # everybody's running, pending count should be back to 0 + assert app.users.count_active_users()['pending'] == 0 + for u in users: + if not u.spawner.active: + continue + r = yield api_request(app, 'users', u.name, 'server', method='delete') + r.raise_for_status() + + counts = app.users.count_active_users() + assert counts['active'] == 0 + assert counts['ready'] == 0 + assert counts['pending'] == 0 + + @mark.gen_test def test_get_proxy(app): r = yield api_request(app, 'proxy') diff --git a/jupyterhub/tests/test_spawner.py b/jupyterhub/tests/test_spawner.py --- a/jupyterhub/tests/test_spawner.py +++ b/jupyterhub/tests/test_spawner.py @@ -16,7 +16,7 @@ from tornado import gen from ..user import User -from ..objects import Hub +from ..objects import Hub, Server from .. import spawner as spawnermod from ..spawner import LocalProcessSpawner, Spawner from .. import orm @@ -234,7 +234,10 @@ def test_shell_cmd(db, tmpdir, request): cmd=[sys.executable, '-m', 'jupyterhub.tests.mocksu'], shell_cmd=['bash', '--rcfile', str(f), '-i', '-c'], ) - s.orm_spawner.server = orm.Server() + server = orm.Server() + db.add(server) + db.commit() + s.server = Server.from_orm(server) db.commit() (ip, port) = yield s.start() request.addfinalizer(s.stop)
Allow limiting total hub resources or the number of notebook servers Right now jupyterhub *almost* allows to replace `tmpnb` by using `tmpauthenticator`. Since jupyterhub is much more developed and configurable than `tmpnb` (or at least it seems so), it would be a great way of replacing `tmpnb`. However, while it is relatively easy to limit resources of a single server, it is currently hard/impossible to configure the total amount of servers that run in parallel, opening a possibility of a very simple DOS attack. Therefore it would be useful it it was possible to restrict the total number of single user servers running in parallel, since it would allow anyone to simply run their own configurable tmpnb's.
2017-08-02T12:36:04Z
[]
[]
jupyterhub/jupyterhub
1,346
jupyterhub__jupyterhub-1346
[ "1345" ]
ef7d6dc0914a403c25bf65e19b5c6ab734f066d0
diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -146,14 +146,19 @@ def get(self): available = {'name', 'admin', 'running', 'last_activity'} default_sort = ['admin', 'name'] mapping = { - 'running': '_server_id' + 'running': orm.Spawner.server_id, } + for name in available: + if name not in mapping: + mapping[name] = getattr(orm.User, name) + default_order = { 'name': 'asc', 'last_activity': 'desc', 'admin': 'desc', 'running': 'desc', } + sorts = self.get_arguments('sort') or default_sort orders = self.get_arguments('order') @@ -176,11 +181,11 @@ def get(self): # this could be one incomprehensible nested list comprehension # get User columns - cols = [ getattr(orm.User, mapping.get(c, c)) for c in sorts ] + cols = [ mapping[c] for c in sorts ] # get User.col.desc() order objects ordered = [ getattr(c, o)() for c, o in zip(cols, orders) ] - users = self.db.query(orm.User).order_by(*ordered) + users = self.db.query(orm.User).join(orm.Spawner).order_by(*ordered) users = [ self._user_from_orm(u) for u in users ] running = [ u for u in users if u.running ]
diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -85,11 +85,25 @@ def test_admin_not_admin(app): @pytest.mark.gen_test def test_admin(app): cookies = yield app.login_user('admin') - r = yield get_page('admin', app, cookies=cookies) + r = yield get_page('admin', app, cookies=cookies, allow_redirects=False) r.raise_for_status() assert r.url.endswith('/admin') [email protected]('sort', [ + 'running', + 'last_activity', + 'admin', + 'name', +]) [email protected]_test +def test_admin_sort(app, sort): + cookies = yield app.login_user('admin') + r = yield get_page('admin?sort=%s' % sort, app, cookies=cookies) + r.raise_for_status() + assert r.status_code == 200 + + @pytest.mark.gen_test def test_spawn_redirect(app): name = 'wash'
Exception in /admin on sorting by running servers **How to reproduce the issue** On current master, visit /admin and click any sort arrow next to "Running". **What you expected to happen** Servers are sorted. **What actually happens** An error is produced, `500 : Internal Server Error`. The hub logs show ``` Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/tornado/web.py", line 1509, in _execute result = method(*self.path_args, **self.path_kwargs) File "/usr/local/lib/python3.5/dist-packages/jupyterhub/utils.py", line 193, in decorated return method(self, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/jupyterhub/handlers/pages.py", line 179, in get cols = [ getattr(orm.User, mapping.get(c, c)) for c in sorts ] File "/usr/local/lib/python3.5/dist-packages/jupyterhub/handlers/pages.py", line 179, in <listcomp> cols = [ getattr(orm.User, mapping.get(c, c)) for c in sorts ] AttributeError: type object 'User' has no attribute '_server_id' ``` **Share what version of JupyterHub you are using** Current master. Looks like this is related to https://github.com/jupyterhub/jupyterhub/issues/766#issuecomment-267297617.
2017-08-17T09:47:24Z
[]
[]
jupyterhub/jupyterhub
1,347
jupyterhub__jupyterhub-1347
[ "1343" ]
48f1da1b8d5bbe01b4a5fc7aa77d4ed73134d394
diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -385,12 +385,31 @@ def spawn(self, server_name='', options=None): # prior to 0.7, spawners had to store this info in user.server themselves. # Handle < 0.7 behavior with a warning, assuming info was stored in db by the Spawner. self.log.warning("DEPRECATION: Spawner.start should return (ip, port) in JupyterHub >= 0.7") - if spawner.api_token != api_token: + if spawner.api_token and spawner.api_token != api_token: # Spawner re-used an API token, discard the unused api_token orm_token = orm.APIToken.find(self.db, api_token) if orm_token is not None: self.db.delete(orm_token) self.db.commit() + # check if the re-used API token is valid + found = orm.APIToken.find(self.db, spawner.api_token) + if found: + if found.user is not self.orm_user: + self.log.error("%s's server is using %s's token! Revoking this token.", + self.name, (found.user or found.service).name) + self.db.delete(found) + self.db.commit() + raise ValueError("Invalid token for %s!" % self.name) + else: + # Spawner.api_token has changed, but isn't in the db. + # What happened? Maybe something unclean in a resumed container. + self.log.warning("%s's server specified its own API token that's not in the database", + self.name + ) + # use generated=False because we don't trust this token + # to have been generated properly + self.new_api_token(spawner.api_token, generated=False) + except Exception as e: if isinstance(e, gen.TimeoutError): self.log.warning("{user}'s server failed to start in {s} seconds, giving up".format(
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -7,8 +7,6 @@ from unittest import mock from urllib.parse import urlparse -import requests - from tornado import gen from tornado.concurrent import Future from tornado.ioloop import IOLoop @@ -58,6 +56,13 @@ def user_env(self, env): def _cmd_default(self): return [sys.executable, '-m', 'jupyterhub.tests.mocksu'] + use_this_api_token = None + def start(self): + if self.use_this_api_token: + self.api_token = self.use_this_api_token + elif self.will_resume: + self.use_this_api_token = self.api_token + return super().start() class SlowSpawner(MockSpawner): """A spawner that takes a few seconds to start""" diff --git a/jupyterhub/tests/test_spawner.py b/jupyterhub/tests/test_spawner.py --- a/jupyterhub/tests/test_spawner.py +++ b/jupyterhub/tests/test_spawner.py @@ -15,11 +15,13 @@ import pytest from tornado import gen -from ..user import User from ..objects import Hub, Server +from .. import orm from .. import spawner as spawnermod from ..spawner import LocalProcessSpawner, Spawner -from .. import orm +from ..user import User +from ..utils import new_token +from .test_api import add_user from .utils import async_requests _echo_sleep = """ @@ -270,3 +272,77 @@ def stop(): def poll(): pass + + [email protected]_test +def test_spawner_reuse_api_token(db, app): + # setup: user with no tokens, whose spawner has set the .will_resume flag + user = add_user(app.db, app, name='snoopy') + spawner = user.spawner + assert user.api_tokens == [] + # will_resume triggers reuse of tokens + spawner.will_resume = True + # first start: gets a new API token + yield user.spawn() + api_token = spawner.api_token + found = orm.APIToken.find(app.db, api_token) + assert found + assert found.user.name == user.name + assert user.api_tokens == [found] + yield user.stop() + # second start: should reuse the token + yield user.spawn() + # verify re-use of API token + assert spawner.api_token == api_token + # verify that a new token was not created + assert user.api_tokens == [found] + + [email protected]_test +def test_spawner_insert_api_token(db, app): + """Token provided by spawner is not in the db + + Insert token into db as a user-provided token. + """ + # setup: new user, double check that they don't have any tokens registered + user = add_user(app.db, app, name='tonkee') + spawner = user.spawner + assert user.api_tokens == [] + + # setup: spawner's going to use a token that's not in the db + api_token = new_token() + assert not orm.APIToken.find(app.db, api_token) + user.spawner.use_this_api_token = api_token + # The spawner's provided API token would already be in the db + # unless there is a bug somewhere else (in the Spawner), + # but handle it anyway. + yield user.spawn() + assert spawner.api_token == api_token + found = orm.APIToken.find(app.db, api_token) + assert found + assert found.user.name == user.name + assert user.api_tokens == [found] + yield user.stop() + + [email protected]_test +def test_spawner_bad_api_token(db, app): + """Tokens are revoked when a Spawner gets another user's token""" + # we need two users for this one + user = add_user(app.db, app, name='antimone') + spawner = user.spawner + other_user = add_user(app.db, app, name='alabaster') + assert user.api_tokens == [] + assert other_user.api_tokens == [] + + # create a token owned by alabaster that antimone's going to try to use + other_token = other_user.new_api_token() + spawner.use_this_api_token = other_token + assert len(other_user.api_tokens) == 1 + + # starting a user's server with another user's token + # should revoke it + with pytest.raises(ValueError): + yield user.spawn() + assert orm.APIToken.find(app.db, other_token) is None + assert other_user.api_tokens == []
hub doesn't check if the reused token is valid This is a follow-up of a discussion with @minrk in gitter. Observed when starting a container using `DockerSpawner` that failed on changing permissions due to mounting a read-only volume in `/home/jovyan` using hub 0.7.2 and dockerspawner 0.7.0. The initial spawn failed to start, that triggered token removal since the spawn failed, but on the other hand the container was still reused by the spawner and still used the old token. If I understand @minrk's explanation correctly, the hub should check that the reused hub token is still valid.
2017-08-17T11:15:00Z
[]
[]
jupyterhub/jupyterhub
1,413
jupyterhub__jupyterhub-1413
[ "1089" ]
3b07bd286b301b96ebb7b177bdae4ac6d1add42a
diff --git a/jupyterhub/traitlets.py b/jupyterhub/traitlets.py --- a/jupyterhub/traitlets.py +++ b/jupyterhub/traitlets.py @@ -48,7 +48,7 @@ class ByteSpecification(Integer): 'K': 1024, 'M': 1024 * 1024, 'G': 1024 * 1024 * 1024, - 'T': 1024 * 1024 * 1024 * 1024 + 'T': 1024 * 1024 * 1024 * 1024, } # Default to allowing None as a value @@ -62,11 +62,15 @@ def validate(self, obj, value): If it has one of the suffixes, it is converted into the appropriate pure byte value. """ - if isinstance(value, int): - return value - num = value[:-1] + if isinstance(value, (int, float)): + return int(value) + + try: + num = float(value[:-1]) + except ValueError: + raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value)) suffix = value[-1] - if not num.isdigit() and suffix not in ByteSpecification.UNIT_SUFFIXES: + if suffix not in self.UNIT_SUFFIXES: raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value)) else: - return int(num) * ByteSpecification.UNIT_SUFFIXES[suffix] + return int(float(num) * self.UNIT_SUFFIXES[suffix])
diff --git a/jupyterhub/tests/test_traitlets.py b/jupyterhub/tests/test_traitlets.py --- a/jupyterhub/tests/test_traitlets.py +++ b/jupyterhub/tests/test_traitlets.py @@ -34,18 +34,27 @@ class C(HasTraits): c = C() c.mem = 1024 + assert isinstance(c.mem, int) assert c.mem == 1024 c.mem = '1024K' + assert isinstance(c.mem, int) assert c.mem == 1024 * 1024 c.mem = '1024M' + assert isinstance(c.mem, int) assert c.mem == 1024 * 1024 * 1024 + c.mem = '1.5M' + assert isinstance(c.mem, int) + assert c.mem == 1.5 * 1024 * 1024 + c.mem = '1024G' + assert isinstance(c.mem, int) assert c.mem == 1024 * 1024 * 1024 * 1024 c.mem = '1024T' + assert isinstance(c.mem, int) assert c.mem == 1024 * 1024 * 1024 * 1024 * 1024 with pytest.raises(TraitError):
Fractional memory / CPU limits / guarantees fail **How to reproduce the issue** Set memory limit (or guarantee, or cpu limit / guarantee) to a non-integral spec: ```python c.Spawner.mem_limit = "1.5G" ``` **What you expected to happen** (In supported spawners) memory limit is set to 1.5 gigabytes of RAM **What actually happens** JupyterHub refuses to start, with: ``` [E 2017-04-18 05:39:02.270 JupyterHub app:1527] Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/jupyterhub/app.py", line 1524, in launch_instance_async yield self.initialize(argv) File "/usr/local/lib/python3.4/dist-packages/jupyterhub/app.py", line 1315, in initialize yield self.init_spawners() File "/usr/local/lib/python3.4/dist-packages/jupyterhub/app.py", line 1084, in init_spawners self.users[orm_user.id] = user = User(orm_user, self.tornado_settings) File "/usr/local/lib/python3.4/dist-packages/jupyterhub/user.py", line 128, in __init__ config=self.settings.get('config'), File "/usr/local/lib/python3.4/dist-packages/kubespawner/spawner.py", line 29, in __init__ super().__init__(*args, **kwargs) File "/usr/local/lib/python3.4/dist-packages/jupyterhub/spawner.py", line 345, in __init__ super(Spawner, self).__init__(**kwargs) File "/usr/local/lib/python3.4/dist-packages/traitlets/config/configurable.py", line 84, in __init__ self.config = config File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 585, in __set__ self.set(obj, value) File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 574, in set obj._notify_trait(self.name, old_value, new_value) File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 1139, in _notify_trait type='change', File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 1176, in notify_change c(change) File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 819, in compatible_observer return func(self, change) File "/usr/local/lib/python3.4/dist-packages/traitlets/config/configurable.py", line 186, in _config_changed self._load_config(change.new, traits=traits, section_names=section_names) File "/usr/local/lib/python3.4/dist-packages/traitlets/config/configurable.py", line 153, in _load_config setattr(self, name, deepcopy(config_value)) File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 585, in __set__ self.set(obj, value) File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 559, in set new_value = self._validate(obj, value) File "/usr/local/lib/python3.4/dist-packages/traitlets/traitlets.py", line 591, in _validate value = self.validate(obj, value) File "/usr/local/lib/python3.4/dist-packages/jupyterhub/traitlets.py", line 71, in validate return int(num) * ByteSpecification.UNIT_SUFFIXES[suffix] ValueError: invalid literal for int() with base 10: '1.5' ``` **Share what version of JupyterHub you are using** 0.72.
@yuvipanda @minrk Has recent work closed this? I think this bug still exists. Should be an easy enough fix to use `float` instead of `int` here, and then cast to int after multiplying. I'm going to try to fix this for 0.8.
2017-09-12T23:20:07Z
[]
[]
jupyterhub/jupyterhub
1,417
jupyterhub__jupyterhub-1417
[ "1414" ]
3b07bd286b301b96ebb7b177bdae4ac6d1add42a
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -1219,7 +1219,7 @@ def user_stopped(user, server_name): status = yield spawner.poll() except Exception: self.log.exception("Failed to poll spawner for %s, assuming the spawner is not running.", - user.name if name else '%s|%s' % (user.name, name)) + spawner._log_name) status = -1 if status is None: @@ -1230,11 +1230,13 @@ def user_stopped(user, server_name): # user not running. This is expected if server is None, # but indicates the user's server died while the Hub wasn't running # if spawner.server is defined. - log = self.log.warning if spawner.server else self.log.debug - log("%s not running.", user.name) - # remove all server or servers entry from db related to the user if spawner.server: + self.log.warning("%s appears to have stopped while the Hub was down", spawner._log_name) + # remove server entry from db db.delete(spawner.orm_spawner.server) + spawner.server = None + else: + self.log.debug("%s not running", spawner._log_name) db.commit() user_summaries.append(_user_summary(user)) diff --git a/jupyterhub/orm.py b/jupyterhub/orm.py --- a/jupyterhub/orm.py +++ b/jupyterhub/orm.py @@ -177,7 +177,7 @@ class Spawner(Base): id = Column(Integer, primary_key=True, autoincrement=True) user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE')) - server_id = Column(Integer, ForeignKey('servers.id')) + server_id = Column(Integer, ForeignKey('servers.id', ondelete='SET NULL')) server = relationship(Server) state = Column(JSONDict) @@ -213,7 +213,7 @@ class Service(Base): api_tokens = relationship("APIToken", backref="service") # service-specific interface - _server_id = Column(Integer, ForeignKey('servers.id')) + _server_id = Column(Integer, ForeignKey('servers.id', ondelete='SET NULL')) server = relationship(Server, primaryjoin=_server_id == Server.id) pid = Column(Integer) diff --git a/jupyterhub/services/service.py b/jupyterhub/services/service.py --- a/jupyterhub/services/service.py +++ b/jupyterhub/services/service.py @@ -301,5 +301,8 @@ def stop(self): if not self.managed: raise RuntimeError("Cannot stop unmanaged service %s" % self) if self.spawner: + if self.orm.server: + self.db.delete(self.orm.server) + self.db.commit() self.spawner.stop_polling() return self.spawner.stop()
diff --git a/jupyterhub/tests/test_app.py b/jupyterhub/tests/test_app.py --- a/jupyterhub/tests/test_app.py +++ b/jupyterhub/tests/test_app.py @@ -8,9 +8,11 @@ from tempfile import NamedTemporaryFile, TemporaryDirectory from unittest.mock import patch +from tornado import gen import pytest from .mocking import MockHub +from .test_api import add_user from .. import orm from ..app import COOKIE_SECRET_BYTES @@ -161,3 +163,57 @@ def test_load_groups(): assert gold is not None assert sorted([ u.name for u in gold.users ]) == sorted(to_load['gold']) + [email protected]_test +def test_resume_spawners(tmpdir, request): + if not os.getenv('JUPYTERHUB_TEST_DB_URL'): + p = patch.dict(os.environ, { + 'JUPYTERHUB_TEST_DB_URL': 'sqlite:///%s' % tmpdir.join('jupyterhub.sqlite'), + }) + p.start() + request.addfinalizer(p.stop) + @gen.coroutine + def new_hub(): + app = MockHub() + app.config.ConfigurableHTTPProxy.should_start = False + yield app.initialize([]) + return app + app = yield new_hub() + db = app.db + # spawn a user's server + name = 'kurt' + user = add_user(db, app, name=name) + yield user.spawn() + proc = user.spawner.proc + assert proc is not None + + # stop the Hub without cleaning up servers + app.cleanup_servers = False + yield app.stop() + + # proc is still running + assert proc.poll() is None + + # resume Hub, should still be running + app = yield new_hub() + db = app.db + user = app.users[name] + assert user.running + assert user.spawner.server is not None + + # stop the Hub without cleaning up servers + app.cleanup_servers = False + yield app.stop() + + # stop the server while the Hub is down. BAMF! + proc.terminate() + proc.wait(timeout=10) + assert proc.poll() is not None + + # resume Hub, should be stopped + app = yield new_hub() + db = app.db + user = app.users[name] + assert not user.running + assert user.spawner.server is None + assert list(db.query(orm.Server)) == [] diff --git a/jupyterhub/tests/test_db.py b/jupyterhub/tests/test_db.py --- a/jupyterhub/tests/test_db.py +++ b/jupyterhub/tests/test_db.py @@ -46,4 +46,3 @@ def test_upgrade_entrypoint(tmpdir): # run tokenapp again, it should work tokenapp.start() - \ No newline at end of file diff --git a/jupyterhub/tests/test_spawner.py b/jupyterhub/tests/test_spawner.py --- a/jupyterhub/tests/test_spawner.py +++ b/jupyterhub/tests/test_spawner.py @@ -299,7 +299,7 @@ def test_spawner_reuse_api_token(db, app): @pytest.mark.gen_test -def test_spawner_insert_api_token(db, app): +def test_spawner_insert_api_token(app): """Token provided by spawner is not in the db Insert token into db as a user-provided token. @@ -326,7 +326,7 @@ def test_spawner_insert_api_token(db, app): @pytest.mark.gen_test -def test_spawner_bad_api_token(db, app): +def test_spawner_bad_api_token(app): """Tokens are revoked when a Spawner gets another user's token""" # we need two users for this one user = add_user(app.db, app, name='antimone') @@ -346,3 +346,37 @@ def test_spawner_bad_api_token(db, app): yield user.spawn() assert orm.APIToken.find(app.db, other_token) is None assert other_user.api_tokens == [] + + [email protected]_test +def test_spawner_delete_server(app): + """Test deleting spawner.server + + This can occur during app startup if their server has been deleted. + """ + db = app.db + user = add_user(app.db, app, name='gaston') + spawner = user.spawner + orm_server = orm.Server() + db.add(orm_server) + db.commit() + server_id = orm_server.id + spawner.server = Server.from_orm(orm_server) + db.commit() + + assert spawner.server is not None + assert spawner.orm_spawner.server is not None + + # trigger delete via db + db.delete(spawner.orm_spawner.server) + db.commit() + assert spawner.orm_spawner.server is None + + # setting server = None also triggers delete + spawner.server = None + db.commit() + # verify that the server was actually deleted from the db + assert db.query(orm.Server).filter(orm.Server.id == server_id).first() is None + # verify that both ORM and top-level references are None + assert spawner.orm_spawner.server is None + assert spawner.server is None
JupyterHub crashing with invalid database state It looks like JupyterHub can go into a state where the state of the db is wrong / order of deletion is not right. This causes the hub to never start. ``` singleuser.cmd jupyterhub-singleuser Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 1623, in launch_instance_async yield self.initialize(argv) File "/usr/lib/python3.5/types.py", line 179, in throw return self.__wrapped.throw(tp, *rest) File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 1385, in initialize yield self.init_spawners() File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 1240, in init_spawners db.commit() File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/session.py", line 906, in commit self.transaction.commit() File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/session.py", line 461, in commit self._prepare_impl() File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/session.py", line 441, in _prepare_impl self.session.flush() File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/session.py", line 2171, in flush self._flush(objects) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/session.py", line 2291, in _flush transaction.rollback(_capture_exception=True) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__ compat.reraise(exc_type, exc_value, exc_tb) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/compat.py", line 187, in reraise raise value File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/session.py", line 2255, in _flush flush_context.execute() File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/unitofwork.py", line 389, in execute rec.execute(self) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/unitofwork.py", line 577, in execute uow File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/persistence.py", line 258, in delete_obj cached_connections, mapper, table, delete) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/persistence.py", line 931, in _emit_delete_statements c = connection.execute(statement, del_objects) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 945, in execute return meth(self, multiparams, params) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/sql/elements.py", line 263, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1053, in _execute_clauseelement compiled_sql, distilled_params File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context context) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception exc_info File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/compat.py", line 186, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context context) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/default.py", line 470, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) update or delete on table "servers" violates foreign key constraint "spawners_server_id_fkey" on table "spawners" DETAIL: Key (id)=(24433) is still referenced from table "spawners". [SQL: 'DELETE FROM servers WHERE servers.id = %(id)s'] [parameters: {'id': 24433}] ```
This just happened again :( First outage of our season. About 6-10 users had this problem, and I had to: 1. Wait for pod to start 2. Wait for it to crash 3. Find id of spawner that crashed 4. Manually remove it from db Do you have more logs from the incident? I want to see what actions are failing. My guess is that there's a missing or incorrect ondelete.
2017-09-14T11:16:57Z
[]
[]
jupyterhub/jupyterhub
1,439
jupyterhub__jupyterhub-1439
[ "1438" ]
afc6789c7464a0a66f2bb061805349bb9ed34d67
diff --git a/examples/service-whoami-flask/whoami-oauth.py b/examples/service-whoami-flask/whoami-oauth.py --- a/examples/service-whoami-flask/whoami-oauth.py +++ b/examples/service-whoami-flask/whoami-oauth.py @@ -59,7 +59,7 @@ def oauth_callback(): # validate state field arg_state = request.args.get('state', None) cookie_state = request.cookies.get(auth.state_cookie_name) - if arg_state != cookie_state: + if arg_state is None or arg_state != cookie_state: # state doesn't match return 403 diff --git a/jupyterhub/services/auth.py b/jupyterhub/services/auth.py --- a/jupyterhub/services/auth.py +++ b/jupyterhub/services/auth.py @@ -13,8 +13,10 @@ import base64 import json import os +import random import re import socket +import string import time from urllib.parse import quote, urlencode import uuid @@ -531,22 +533,37 @@ def set_state_cookie(self, handler, next_url=None): ------- state (str): The OAuth state that has been stored in the cookie (url safe, base64-encoded) """ - b64_state = self.generate_state(next_url) + extra_state = {} + if handler.get_cookie(self.state_cookie_name): + # oauth state cookie is already set + # use a randomized cookie suffix to avoid collisions + # in case of concurrent logins + app_log.warning("Detected unused OAuth state cookies") + cookie_suffix = ''.join(random.choice(string.ascii_letters) for i in range(8)) + cookie_name = '{}-{}'.format(self.state_cookie_name, cookie_suffix) + extra_state['cookie_name'] = cookie_name + else: + cookie_name = self.state_cookie_name + b64_state = self.generate_state(next_url, **extra_state) kwargs = { 'path': self.base_url, 'httponly': True, - 'expires_days': 1, + # Expire oauth state cookie in ten minutes. + # Usually this will be cleared by completed login + # in less than a few seconds. + # OAuth that doesn't complete shouldn't linger too long. + 'max_age': 600, } if handler.request.protocol == 'https': kwargs['secure'] = True handler.set_secure_cookie( - self.state_cookie_name, + cookie_name, b64_state, **kwargs ) return b64_state - def generate_state(self, next_url=None): + def generate_state(self, next_url=None, **extra_state): """Generate a state string, given a next_url redirect target Parameters @@ -557,16 +574,27 @@ def generate_state(self, next_url=None): ------- state (str): The base64-encoded state string. """ - return self._encode_state({ + state = { 'uuid': uuid.uuid4().hex, - 'next_url': next_url - }) + 'next_url': next_url, + } + state.update(extra_state) + return self._encode_state(state) def get_next_url(self, b64_state=''): """Get the next_url for redirection, given an encoded OAuth state""" state = self._decode_state(b64_state) return state.get('next_url') or self.base_url + def get_state_cookie_name(self, b64_state=''): + """Get the cookie name for oauth state, given an encoded OAuth state + + Cookie name is stored in the state itself because the cookie name + is randomized to deal with races between concurrent oauth sequences. + """ + state = self._decode_state(b64_state) + return state.get('cookie_name') or self.state_cookie_name + def set_cookie(self, handler, access_token): """Set a cookie recording OAuth result""" kwargs = { @@ -769,18 +797,19 @@ def get(self): # validate OAuth state arg_state = self.get_argument("state", None) - cookie_state = self.get_secure_cookie(self.hub_auth.state_cookie_name) - next_url = None - if arg_state or cookie_state: - # clear cookie state now that we've consumed it - self.clear_cookie(self.hub_auth.state_cookie_name, path=self.hub_auth.base_url) - if isinstance(cookie_state, bytes): - cookie_state = cookie_state.decode('ascii', 'replace') - # check that state matches - if arg_state != cookie_state: - app_log.debug("oauth state %r != %r", arg_state, cookie_state) - raise HTTPError(403, "oauth state does not match") - next_url = self.hub_auth.get_next_url(cookie_state) + if arg_state is None: + raise HTTPError("oauth state is missing. Try logging in again.") + cookie_name = self.hub_auth.get_state_cookie_name(arg_state) + cookie_state = self.get_secure_cookie(cookie_name) + # clear cookie state now that we've consumed it + self.clear_cookie(cookie_name, path=self.hub_auth.base_url) + if isinstance(cookie_state, bytes): + cookie_state = cookie_state.decode('ascii', 'replace') + # check that state matches + if arg_state != cookie_state: + app_log.warning("oauth state %r != %r", arg_state, cookie_state) + raise HTTPError(403, "oauth state does not match. Try logging in again.") + next_url = self.hub_auth.get_next_url(cookie_state) # TODO: make async (in a Thread?) token = self.hub_auth.token_for_code(code) user_model = self.hub_auth.user_for_token(token)
diff --git a/jupyterhub/tests/test_services_auth.py b/jupyterhub/tests/test_services_auth.py --- a/jupyterhub/tests/test_services_auth.py +++ b/jupyterhub/tests/test_services_auth.py @@ -368,3 +368,61 @@ def test_oauth_service(app, mockservice_url): reply = r.json() assert reply['name'] == name + [email protected]_test +def test_oauth_cookie_collision(app, mockservice_url): + service = mockservice_url + url = url_path_join(public_url(app, mockservice_url) + 'owhoami/') + print(url) + s = requests.Session() + name = 'mypha' + s.cookies = yield app.login_user(name) + # run session.get in async_requests thread + s_get = lambda *args, **kwargs: async_requests.executor.submit(s.get, *args, **kwargs) + state_cookie_name = 'service-%s-oauth-state' % service.name + service_cookie_name = 'service-%s' % service.name + oauth_1 = yield s_get(url, allow_redirects=False) + print(oauth_1.headers) + print(oauth_1.cookies, oauth_1.url, url) + assert state_cookie_name in s.cookies + state_cookies = [ s for s in s.cookies.keys() if s.startswith(state_cookie_name) ] + # only one state cookie + assert state_cookies == [state_cookie_name] + state_1 = s.cookies[state_cookie_name] + + # start second oauth login before finishing the first + oauth_2 = yield s_get(url, allow_redirects=False) + state_cookies = [ s for s in s.cookies.keys() if s.startswith(state_cookie_name) ] + assert len(state_cookies) == 2 + # get the random-suffix cookie name + state_cookie_2 = sorted(state_cookies)[-1] + # we didn't clobber the default cookie + assert s.cookies[state_cookie_name] == state_1 + + # finish oauth 2 + url = oauth_2.headers['Location'] + if not urlparse(url).netloc: + url = public_host(app) + url + r = yield s_get(url) + r.raise_for_status() + # after finishing, state cookie is cleared + assert state_cookie_2 not in s.cookies + # service login cookie is set + assert service_cookie_name in s.cookies + service_cookie_2 = s.cookies[service_cookie_name] + + # finish oauth 1 + url = oauth_1.headers['Location'] + if not urlparse(url).netloc: + url = public_host(app) + url + r = yield s_get(url) + r.raise_for_status() + # after finishing, state cookie is cleared (again) + assert state_cookie_name not in s.cookies + # service login cookie is set (again, to a different value) + assert service_cookie_name in s.cookies + assert s.cookies[service_cookie_name] != service_cookie_2 + + # after completing both OAuth logins, no OAuth state cookies remain + state_cookies = [ s for s in s.cookies.keys() if s.startswith(state_cookie_name) ] + assert state_cookies == []
Redirect to login url on mismatched oauth state A few of our users have reported seeing the error "oauth state does not match" from auth.py#L782. One reported that the error was cleared when "erased all the caches" in her browser. Should the hub redirect to the login URL instead of displaying the error? helm chart version v0.5.0-4f7cb71.
2017-09-21T11:01:29Z
[]
[]
jupyterhub/jupyterhub
1,454
jupyterhub__jupyterhub-1454
[ "1453" ]
6bbfcdfe4f616c804cfccdddcb3b9bd7f927e3c9
diff --git a/jupyterhub/handlers/login.py b/jupyterhub/handlers/login.py --- a/jupyterhub/handlers/login.py +++ b/jupyterhub/handlers/login.py @@ -20,7 +20,7 @@ def get(self): self.clear_login_cookie() self.statsd.incr('logout') if self.authenticator.auto_login: - self.render('logout.html') + self.render_template('logout.html') else: self.redirect(self.settings['login_url'], permanent=False)
diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -344,6 +344,19 @@ def get(self): r = yield async_requests.get(base_url) assert r.url == public_url(app, path='hub/dummy') [email protected]_test +def test_auto_login_logout(app): + name = 'burnham' + cookies = yield app.login_user(name) + + with mock.patch.dict(app.tornado_application.settings, { + 'authenticator': Authenticator(auto_login=True), + }): + r = yield async_requests.get(public_host(app) + app.tornado_settings['logout_url'], cookies=cookies) + r.raise_for_status() + logout_url = public_host(app) + app.tornado_settings['logout_url'] + assert r.url == logout_url + assert r.cookies == {} @pytest.mark.gen_test def test_logout(app):
Exception when logout with auto_login=True **How to reproduce the issue** Press logout button **What you expected to happen** Shows logout.html **What actually happens** Exception: ``` Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/tornado/web.py", line 1509, in _execute result = method(*self.path_args, **self.path_kwargs) File "/usr/local/lib/python3.5/dist-packages/jupyterhub/handlers/login.py", line 23, in get self.render('logout.html') File "/usr/local/lib/python3.5/dist-packages/tornado/web.py", line 724, in render html = self.render_string(template_name, **kwargs) File "/usr/local/lib/python3.5/dist-packages/tornado/web.py", line 857, in render_string if template_path not in RequestHandler._template_loaders: TypeError: unhashable type: 'list' ``` **Share what version of JupyterHub you are using** Jupyterhub 0.8 with auto_login=True Running `jupyter troubleshoot` from the command line, if possible, and posting its output would also be helpful. ``` $PATH: /usr/local/bin /usr/local/sbin /usr/local/bin /usr/sbin /usr/bin /sbin /bin sys.path: /usr/local/bin /srv/jupyterhub /usr/lib/python35.zip /usr/lib/python3.5 /usr/lib/python3.5/plat-x86_64-linux-gnu /usr/lib/python3.5/lib-dynload /usr/local/lib/python3.5/dist-packages /usr/lib/python3/dist-packages sys.executable: /usr/bin/python3 sys.version: 3.5.3 (default, Jan 19 2017, 14:11:04) [GCC 6.3.0 20170118] platform.platform(): Linux-4.4.52+-x86_64-with-Ubuntu-17.04-zesty which -a jupyter: /usr/local/bin/jupyter /usr/local/bin/jupyter ```
2017-09-27T12:30:16Z
[]
[]
jupyterhub/jupyterhub
1,455
jupyterhub__jupyterhub-1455
[ "1448" ]
f79b71727b4b87db8300ca62feaf7b604b4974d2
diff --git a/jupyterhub/alembic/versions/3ec6993fe20c_encrypted_auth_state.py b/jupyterhub/alembic/versions/3ec6993fe20c_encrypted_auth_state.py --- a/jupyterhub/alembic/versions/3ec6993fe20c_encrypted_auth_state.py +++ b/jupyterhub/alembic/versions/3ec6993fe20c_encrypted_auth_state.py @@ -36,6 +36,10 @@ def upgrade(): # drop some columns no longer in use try: op.drop_column('users', 'auth_state') + # mysql cannot drop _server_id without also dropping + # implicitly created foreign key + if op.get_context().dialect.name == 'mysql': + op.drop_constraint('users_ibfk_1', 'users', type_='foreignkey') op.drop_column('users', '_server_id') except sa.exc.OperationalError: # this won't be a problem moving forward, but downgrade will fail diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -23,6 +23,7 @@ from jinja2 import Environment, FileSystemLoader +from sqlalchemy import create_engine from sqlalchemy.exc import OperationalError from tornado.httpclient import AsyncHTTPClient @@ -189,6 +190,13 @@ def start(self): db_file = hub.db_url.split(':///', 1)[1] self._backup_db_file(db_file) self.log.info("Upgrading %s", hub.db_url) + # run check-db-revision first + engine = create_engine(hub.db_url) + try: + orm.check_db_revision(engine) + except orm.DatabaseSchemaMismatch: + # ignore mismatch error because that's what we are here for! + pass dbutil.upgrade(hub.db_url)
diff --git a/jupyterhub/tests/test_db.py b/jupyterhub/tests/test_db.py --- a/jupyterhub/tests/test_db.py +++ b/jupyterhub/tests/test_db.py @@ -4,6 +4,7 @@ import pytest from pytest import raises +from traitlets.config import Config from ..dbutil import upgrade from ..app import NewToken, UpgradeDB, JupyterHub @@ -21,28 +22,35 @@ def generate_old_db(path): def test_upgrade(tmpdir): print(tmpdir) db_url = generate_old_db(str(tmpdir)) - print(db_url) upgrade(db_url) @pytest.mark.gen_test def test_upgrade_entrypoint(tmpdir): - generate_old_db(str(tmpdir)) + db_url = os.getenv('JUPYTERHUB_TEST_UPGRADE_DB_URL') + if not db_url: + # default: sqlite + db_url = generate_old_db(str(tmpdir)) + cfg = Config() + cfg.JupyterHub.db_url = db_url + tmpdir.chdir() - tokenapp = NewToken() + tokenapp = NewToken(config=cfg) tokenapp.initialize(['kaylee']) with raises(SystemExit): tokenapp.start() - sqlite_files = glob(os.path.join(str(tmpdir), 'jupyterhub.sqlite*')) - assert len(sqlite_files) == 1 + if 'sqlite' in db_url: + sqlite_files = glob(os.path.join(str(tmpdir), 'jupyterhub.sqlite*')) + assert len(sqlite_files) == 1 - upgradeapp = UpgradeDB() + upgradeapp = UpgradeDB(config=cfg) yield upgradeapp.initialize([]) upgradeapp.start() # check that backup was created: - sqlite_files = glob(os.path.join(str(tmpdir), 'jupyterhub.sqlite*')) - assert len(sqlite_files) == 2 + if 'sqlite' in db_url: + sqlite_files = glob(os.path.join(str(tmpdir), 'jupyterhub.sqlite*')) + assert len(sqlite_files) == 2 # run tokenapp again, it should work tokenapp.start()
Error when running jupyterhub upgrade-db **How to reproduce the issue** Run `jupyterhub upgrade-db --db=mysql+pymysql://db_url_xxx` **What you expected to happen** DB is upgraded for 0.8 **What actually happens** ``` INFO [alembic.runtime.migration] Context impl MySQLImpl. INFO [alembic.runtime.migration] Will assume non-transactional DDL. INFO [alembic.runtime.migration] Running upgrade -> 19c0846f6344, base revision for 0.5 INFO [alembic.runtime.migration] Running upgrade 19c0846f6344 -> eeb276e51423, auth_state Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context context) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/default.py", line 470, in do_execute cursor.execute(statement, parameters) File "/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py", line 166, in execute result = self._query(query) File "/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py", line 322, in _query conn.query(q) File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 856, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 1057, in _read_query_result result.read() File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 1340, in read first_packet = self.connection._read_packet() File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 1014, in _read_packet packet.check_error() File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 393, in check_error err.raise_mysql_exception(self._data) File "/usr/local/lib/python3.5/dist-packages/pymysql/err.py", line 107, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.InternalError: (1060, "Duplicate column name 'auth_state'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/bin/alembic", line 11, in <module> load_entry_point('alembic==0.9.5', 'console_scripts', 'alembic')() File "/usr/local/lib/python3.5/dist-packages/alembic/config.py", line 479, in main CommandLine(prog=prog).main(argv=argv) File "/usr/local/lib/python3.5/dist-packages/alembic/config.py", line 473, in main self.run_cmd(cfg, options) File "/usr/local/lib/python3.5/dist-packages/alembic/config.py", line 456, in run_cmd **dict((k, getattr(options, k, None)) for k in kwarg) File "/usr/local/lib/python3.5/dist-packages/alembic/command.py", line 254, in upgrade script.run_env() File "/usr/local/lib/python3.5/dist-packages/alembic/script/base.py", line 425, in run_env util.load_python_file(self.dir, 'env.py') File "/usr/local/lib/python3.5/dist-packages/alembic/util/pyfiles.py", line 93, in load_python_file module = load_module_py(module_id, path) File "/usr/local/lib/python3.5/dist-packages/alembic/util/compat.py", line 64, in load_module_py module_id, path).load_module(module_id) File "<frozen importlib._bootstrap_external>", line 396, in _check_name_wrapper File "<frozen importlib._bootstrap_external>", line 817, in load_module File "<frozen importlib._bootstrap_external>", line 676, in load_module File "<frozen importlib._bootstrap>", line 268, in _load_module_shim File "<frozen importlib._bootstrap>", line 693, in _load File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 673, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/usr/local/lib/python3.5/dist-packages/jupyterhub/alembic/env.py", line 70, in <module> run_migrations_online() File "/usr/local/lib/python3.5/dist-packages/jupyterhub/alembic/env.py", line 65, in run_migrations_online context.run_migrations() File "<string>", line 8, in run_migrations File "/usr/local/lib/python3.5/dist-packages/alembic/runtime/environment.py", line 836, in run_migrations self.get_context().run_migrations(**kw) File "/usr/local/lib/python3.5/dist-packages/alembic/runtime/migration.py", line 330, in run_migrations step.migration_fn(**kw) File "/usr/local/lib/python3.5/dist-packages/jupyterhub/alembic/versions/eeb276e51423_auth_state.py", line 21, in upgrade op.add_column('users', sa.Column('auth_state', JSONDict)) File "<string>", line 8, in add_column File "<string>", line 3, in add_column File "/usr/local/lib/python3.5/dist-packages/alembic/operations/ops.py", line 1565, in add_column return operations.invoke(op) File "/usr/local/lib/python3.5/dist-packages/alembic/operations/base.py", line 318, in invoke return fn(self, operation) File "/usr/local/lib/python3.5/dist-packages/alembic/operations/toimpl.py", line 123, in add_column schema=schema File "/usr/local/lib/python3.5/dist-packages/alembic/ddl/impl.py", line 172, in add_column self._exec(base.AddColumn(table_name, column, schema=schema)) File "/usr/local/lib/python3.5/dist-packages/alembic/ddl/impl.py", line 118, in _exec return conn.execute(construct, *multiparams, **params) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 945, in execute return meth(self, multiparams, params) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/sql/ddl.py", line 68, in _execute_on_connection return connection._execute_ddl(self, multiparams, params) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1002, in _execute_ddl compiled File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context context) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception exc_info File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/compat.py", line 186, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context context) File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/default.py", line 470, in do_execute cursor.execute(statement, parameters) File "/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py", line 166, in execute result = self._query(query) File "/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py", line 322, in _query conn.query(q) File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 856, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 1057, in _read_query_result result.read() File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 1340, in read first_packet = self.connection._read_packet() File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 1014, in _read_packet packet.check_error() File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py", line 393, in check_error err.raise_mysql_exception(self._data) File "/usr/local/lib/python3.5/dist-packages/pymysql/err.py", line 107, in raise_mysql_exception raise errorclass(errno, errval) sqlalchemy.exc.InternalError: (pymysql.err.InternalError) (1060, "Duplicate column name 'auth_state'") [SQL: 'ALTER TABLE users ADD COLUMN auth_state TEXT'] [E 2017-09-25 21:15:42.980 JupyterHub app:1527] Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 1525, in launch_instance_async yield self.start() File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 1436, in start self.subapp.start() File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 185, in start dbutil.upgrade(hub.db_url) File "/usr/local/lib/python3.5/dist-packages/jupyterhub/dbutil.py", line 80, in upgrade ['alembic', '-c', alembic_ini, 'upgrade', revision] File "/usr/lib/python3.5/subprocess.py", line 271, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['alembic', '-c', '/tmp/tmptsm58x_8/alembic.ini', 'upgrade', 'head']' returned non-zero exit status 1 ``` **Share what version of JupyterHub you are using** Jupyterhub 0.7.2 ->0.8.0rc2 Running `jupyter troubleshoot` from the command line, if possible, and posting its output would also be helpful. ``` $PATH: /usr/local/bin /usr/local/sbin /usr/local/bin /usr/sbin /usr/bin /sbin /bin sys.path: /usr/local/bin /srv/jupyterhub /usr/lib/python35.zip /usr/lib/python3.5 /usr/lib/python3.5/plat-x86_64-linux-gnu /usr/lib/python3.5/lib-dynload /usr/local/lib/python3.5/dist-packages /usr/lib/python3/dist-packages sys.executable: /usr/bin/python3 sys.version: 3.5.3 (default, Jan 19 2017, 14:11:04) [GCC 6.3.0 20170118] platform.platform(): Linux-4.4.52+-x86_64-with-Ubuntu-17.04-zesty which -a jupyter: /usr/local/bin/jupyter /usr/local/bin/jupyter ```
same error as #1162 which is closed It probably can be solved by call check_db_revision before dbutil.upgrade(hub.db_url). Got another error when running `jupyterhub upgrade-db --db=mysql+pymysql://db_url_xxx` after executed below sql to set alembic_version. ``` CREATE TABLE alembic_version (version_num VARCHAR(32) NOT NULL); INSERT INTO alembic_version (version_num) VALUES ('af4cbdb2d13c'); ``` ``` [I 2017-09-26 10:29:41.865 alembic.runtime.migration migration:117] Context impl MySQLImpl. [I 2017-09-26 10:29:41.866 alembic.runtime.migration migration:122] Will assume non-transactional DDL. [I 2017-09-26 10:29:42.060 alembic.runtime.migration migration:327] Running upgrade af4cbdb2d13c -> 3ec6993fe20c, 0.8 changes Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context context) File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 504, in do_execute cursor.execute(statement, parameters) File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 166, in execute result = self._query(query) File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 322, in _query conn.query(q) File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 856, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1057, in _read_query_result result.read() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1340, in read first_packet = self.connection._read_packet() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1014, in _read_packet packet.check_error() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 393, in check_error err.raise_mysql_exception(self._data) File "/usr/local/lib/python3.6/site-packages/pymysql/err.py", line 107, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.InternalError: (1553, "Cannot drop index '_server_id': needed in a foreign key constraint") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/bin/alembic", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python3.6/site-packages/alembic/config.py", line 479, in main CommandLine(prog=prog).main(argv=argv) File "/usr/local/lib/python3.6/site-packages/alembic/config.py", line 473, in main self.run_cmd(cfg, options) File "/usr/local/lib/python3.6/site-packages/alembic/config.py", line 456, in run_cmd **dict((k, getattr(options, k, None)) for k in kwarg) File "/usr/local/lib/python3.6/site-packages/alembic/command.py", line 254, in upgrade script.run_env() File "/usr/local/lib/python3.6/site-packages/alembic/script/base.py", line 425, in run_env util.load_python_file(self.dir, 'env.py') File "/usr/local/lib/python3.6/site-packages/alembic/util/pyfiles.py", line 93, in load_python_file module = load_module_py(module_id, path) File "/usr/local/lib/python3.6/site-packages/alembic/util/compat.py", line 64, in load_module_py module_id, path).load_module(module_id) File "<frozen importlib._bootstrap_external>", line 399, in _check_name_wrapper File "<frozen importlib._bootstrap_external>", line 823, in load_module File "<frozen importlib._bootstrap_external>", line 682, in load_module File "<frozen importlib._bootstrap>", line 251, in _load_module_shim File "<frozen importlib._bootstrap>", line 675, in _load File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/usr/local/lib/python3.6/site-packages/jupyterhub/alembic/env.py", line 89, in <module> run_migrations_online() File "/usr/local/lib/python3.6/site-packages/jupyterhub/alembic/env.py", line 84, in run_migrations_online context.run_migrations() File "<string>", line 8, in run_migrations File "/usr/local/lib/python3.6/site-packages/alembic/runtime/environment.py", line 836, in run_migrations self.get_context().run_migrations(**kw) File "/usr/local/lib/python3.6/site-packages/alembic/runtime/migration.py", line 330, in run_migrations step.migration_fn(**kw) File "/usr/local/lib/python3.6/site-packages/jupyterhub/alembic/versions/3ec6993fe20c_encrypted_auth_state.py", line 39, in upgrade op.drop_column('users', '_server_id') File "<string>", line 8, in drop_column File "<string>", line 3, in drop_column File "/usr/local/lib/python3.6/site-packages/alembic/operations/ops.py", line 1667, in drop_column return operations.invoke(op) File "/usr/local/lib/python3.6/site-packages/alembic/operations/base.py", line 318, in invoke return fn(self, operation) File "/usr/local/lib/python3.6/site-packages/alembic/operations/toimpl.py", line 81, in drop_column **operation.kw File "/usr/local/lib/python3.6/site-packages/alembic/ddl/impl.py", line 175, in drop_column self._exec(base.DropColumn(table_name, column, schema=schema)) File "/usr/local/lib/python3.6/site-packages/alembic/ddl/impl.py", line 118, in _exec return conn.execute(construct, *multiparams, **params) File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 945, in execute return meth(self, multiparams, params) File "/usr/local/lib/python3.6/site-packages/sqlalchemy/sql/ddl.py", line 68, in _execute_on_connection return connection._execute_ddl(self, multiparams, params) File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1002, in _execute_ddl compiled File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context context) File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception exc_info File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 186, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context context) File "/usr/local/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 504, in do_execute cursor.execute(statement, parameters) File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 166, in execute result = self._query(query) File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 322, in _query conn.query(q) File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 856, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1057, in _read_query_result result.read() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1340, in read first_packet = self.connection._read_packet() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1014, in _read_packet packet.check_error() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 393, in check_error err.raise_mysql_exception(self._data) File "/usr/local/lib/python3.6/site-packages/pymysql/err.py", line 107, in raise_mysql_exception raise errorclass(errno, errval) sqlalchemy.exc.InternalError: (pymysql.err.InternalError) (1553, "Cannot drop index '_server_id': needed in a foreign key constraint") [SQL: 'ALTER TABLE users DROP COLUMN _server_id'] [E 2017-09-26 10:29:44.002 JupyterHub app:1626] Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/jupyterhub/app.py", line 1624, in launch_instance_async yield self.start() File "/usr/local/lib/python3.6/site-packages/jupyterhub/app.py", line 1514, in start self.subapp.start() File "/usr/local/lib/python3.6/site-packages/jupyterhub/app.py", line 192, in start dbutil.upgrade(hub.db_url) File "/usr/local/lib/python3.6/site-packages/jupyterhub/dbutil.py", line 83, in upgrade ['alembic', '-c', alembic_ini, 'upgrade', revision] File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 291, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['alembic', '-c', '/var/folders/vv/szpdwz315wd9z0h6gvw4cqcm0000gq/T/tmp5u3sy1q7/alembic.ini', 'upgrade', 'head']' returned non-zero exit status 1. ``` Here are SQL need to run before upgrading: ``` CREATE TABLE alembic_version (version_num VARCHAR(32) NOT NULL); INSERT INTO alembic_version (version_num) VALUES ('af4cbdb2d13c'); ALTER TABLE users DROP FOREIGN KEY users_ibfk_1; ```
2017-09-27T17:10:00Z
[]
[]
jupyterhub/jupyterhub
1,577
jupyterhub__jupyterhub-1577
[ "1491", "1491" ]
e81764610ee6096ad81db545c5692536d7769c23
diff --git a/jupyterhub/alembic/env.py b/jupyterhub/alembic/env.py --- a/jupyterhub/alembic/env.py +++ b/jupyterhub/alembic/env.py @@ -30,11 +30,9 @@ else: fileConfig(config.config_file_name) -# add your model's MetaData object here -# for 'autogenerate' support -# from myapp import mymodel -# target_metadata = mymodel.Base.metadata -target_metadata = None +# add your model's MetaData object here for 'autogenerate' support +from jupyterhub import orm +target_metadata = orm.Base.metadata # other values from the config, defined by the needs of env.py, # can be acquired: diff --git a/jupyterhub/alembic/versions/1cebaf56856c_session_id.py b/jupyterhub/alembic/versions/1cebaf56856c_session_id.py new file mode 100644 --- /dev/null +++ b/jupyterhub/alembic/versions/1cebaf56856c_session_id.py @@ -0,0 +1,42 @@ +"""Add session_id to auth tokens + +Revision ID: 1cebaf56856c +Revises: 3ec6993fe20c +Create Date: 2017-12-07 14:43:51.500740 + +""" + +# revision identifiers, used by Alembic. +revision = '1cebaf56856c' +down_revision = '3ec6993fe20c' +branch_labels = None +depends_on = None + +import logging +logger = logging.getLogger('alembic') + +from alembic import op +import sqlalchemy as sa + +tables = ('oauth_access_tokens', 'oauth_codes') + + +def add_column_if_table_exists(table, column): + engine = op.get_bind().engine + if table not in engine.table_names(): + # table doesn't exist, no need to upgrade + # because jupyterhub will create it on launch + logger.warning("Skipping upgrade of absent table: %s", table) + return + op.add_column(table, column) + + +def upgrade(): + for table in tables: + add_column_if_table_exists(table, sa.Column('session_id', sa.Unicode(255))) + + +def downgrade(): + # sqlite cannot downgrade because of limited ALTER TABLE support (no DROP COLUMN) + for table in tables: + op.drop_column(table, 'session_id') diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -8,6 +8,7 @@ from datetime import timedelta from http.client import responses from urllib.parse import urlparse, urlunparse, parse_qs, urlencode +import uuid from jinja2 import TemplateNotFound @@ -34,6 +35,9 @@ 'error': "Failed to start your server. Please contact admin.", } +# constant, not configurable +SESSION_COOKIE_NAME = 'jupyterhub-session-id' + class BaseHandler(RequestHandler): """Base Handler class with access to common methods and properties.""" @@ -77,6 +81,7 @@ def users(self): @property def services(self): return self.settings.setdefault('services', {}) + @property def hub(self): return self.settings['hub'] @@ -255,10 +260,40 @@ def clear_login_cookie(self, name=None): kwargs = {} if self.subdomain_host: kwargs['domain'] = self.domain + user = self.get_current_user_cookie() + session_id = self.get_session_cookie() + if session_id: + # clear session id + self.clear_cookie(SESSION_COOKIE_NAME, **kwargs) + + if user: + # user is logged in, clear any tokens associated with the current session + # don't clear session tokens if not logged in, + # because that could be a malicious logout request! + count = 0 + for access_token in ( + self.db.query(orm.OAuthAccessToken) + .filter(orm.OAuthAccessToken.user_id==user.id) + .filter(orm.OAuthAccessToken.session_id==session_id) + ): + self.db.delete(access_token) + count += 1 + if count: + self.log.debug("Deleted %s access tokens for %s", count, user.name) + self.db.commit() + + + # clear hub cookie self.clear_cookie(self.hub.cookie_name, path=self.hub.base_url, **kwargs) - self.clear_cookie('jupyterhub-services', path=url_path_join(self.base_url, 'services')) + # clear services cookie + self.clear_cookie('jupyterhub-services', path=url_path_join(self.base_url, 'services'), **kwargs) - def _set_user_cookie(self, user, server): + def _set_cookie(self, key, value, encrypted=True, **overrides): + """Setting any cookie should go through here + + if encrypted use tornado's set_secure_cookie, + otherwise set plaintext cookies. + """ # tornado <4.2 have a bug that consider secure==True as soon as # 'secure' kwarg is passed to set_secure_cookie kwargs = { @@ -270,14 +305,45 @@ def _set_user_cookie(self, user, server): kwargs['domain'] = self.domain kwargs.update(self.settings.get('cookie_options', {})) - self.log.debug("Setting cookie for %s: %s, %s", user.name, server.cookie_name, kwargs) - self.set_secure_cookie( + kwargs.update(overrides) + + if encrypted: + set_cookie = self.set_secure_cookie + else: + set_cookie = self.set_cookie + + self.log.debug("Setting cookie %s: %s", key, kwargs) + set_cookie(key, value, **kwargs) + + + def _set_user_cookie(self, user, server): + self.log.debug("Setting cookie for %s: %s", user.name, server.cookie_name) + self._set_cookie( server.cookie_name, user.cookie_id, + encrypted=True, path=server.base_url, - **kwargs ) + def get_session_cookie(self): + """Get the session id from a cookie + + Returns None if no session id is stored + """ + return self.get_cookie(SESSION_COOKIE_NAME, None) + + def set_session_cookie(self): + """Set a new session id cookie + + new session id is returned + + Session id cookie is *not* encrypted, + so other services on this domain can read it. + """ + session_id = uuid.uuid4().hex + self._set_cookie(SESSION_COOKIE_NAME, session_id, encrypted=False) + return session_id + def set_service_cookie(self, user): """set the login cookie for services""" self._set_user_cookie(user, orm.Server( @@ -300,6 +366,9 @@ def set_login_cookie(self, user): if self.db.query(orm.Service).filter(orm.Service.server != None).first(): self.set_service_cookie(user) + if not self.get_session_cookie(): + self.set_session_cookie() + # create and set a new cookie token for the hub if not self.get_current_user_cookie(): self.set_hub_cookie(user) diff --git a/jupyterhub/oauth/store.py b/jupyterhub/oauth/store.py --- a/jupyterhub/oauth/store.py +++ b/jupyterhub/oauth/store.py @@ -39,15 +39,19 @@ def render_auth_page(self, request, response, environ, scopes, client): def authenticate(self, request, environ, scopes, client): handler = request.handler user = handler.get_current_user() + # ensure session_id is set + session_id = handler.get_session_cookie() + if session_id is None: + session_id = handler.set_session_cookie() if user: - return {}, user.id + return {'session_id': session_id}, user.id else: raise UserNotAuthenticated() def user_has_denied_access(self, request): # user can't deny access return False - + class HubDBMixin(object): """Mixin for connecting to the hub database""" @@ -65,7 +69,7 @@ def save_token(self, access_token): :param access_token: An instance of :class:`oauth2.datatype.AccessToken`. """ - + user = self.db.query(orm.User).filter(orm.User.id == access_token.user_id).first() if user is None: raise ValueError("No user for access token: %s" % access_token.user_id) @@ -76,6 +80,7 @@ def save_token(self, access_token): refresh_token=access_token.refresh_token, refresh_expires_at=access_token.refresh_expires_at, token=access_token.token, + session_id=access_token.data['session_id'], user=user, ) self.db.add(orm_access_token) @@ -110,6 +115,7 @@ def fetch_by_code(self, code): redirect_uri=orm_code.redirect_uri, scopes=[], user_id=orm_code.user_id, + data={'session_id': orm_code.session_id}, ) @@ -126,6 +132,7 @@ def save_code(self, authorization_code): expires_at=authorization_code.expires_at, user_id=authorization_code.user_id, redirect_uri=authorization_code.redirect_uri, + session_id=authorization_code.data.get('session_id', ''), ) self.db.add(orm_code) self.db.commit() diff --git a/jupyterhub/orm.py b/jupyterhub/orm.py --- a/jupyterhub/orm.py +++ b/jupyterhub/orm.py @@ -412,10 +412,13 @@ class OAuthAccessToken(Hashed, Base): user = relationship(User) service = None # for API-equivalence with APIToken + # the browser session id associated with a given token + session_id = Column(Unicode(255)) + # from Hashed hashed = Column(Unicode(255), unique=True) prefix = Column(Unicode(16), index=True) - + def __repr__(self): return "<{cls}('{prefix}...', user='{user}'>".format( cls=self.__class__.__name__, @@ -431,6 +434,7 @@ class OAuthCode(Base): code = Column(Unicode(36)) expires_at = Column(Integer) redirect_uri = Column(Unicode(1023)) + session_id = Column(Unicode(255)) user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE')) diff --git a/jupyterhub/services/auth.py b/jupyterhub/services/auth.py --- a/jupyterhub/services/auth.py +++ b/jupyterhub/services/auth.py @@ -29,7 +29,7 @@ from tornado.httputil import url_concat from tornado.web import HTTPError, RequestHandler -from traitlets.config import Configurable +from traitlets.config import SingletonConfigurable from traitlets import Unicode, Integer, Instance, default, observe, validate from ..utils import url_path_join @@ -57,6 +57,17 @@ def __setitem__(self, key, value): self.timestamps[key] = time.monotonic() self.values[key] = value + def __repr__(self): + """include values and timestamps in repr""" + now = time.monotonic() + return repr({ + key: '{value} (age={age:.0f}s)'.format( + value=repr(value)[:16] + '...', + age=now-self.timestamps[key], + ) + for key, value in self.values.items() + }) + def _check_age(self, key): """Check timestamp for a key""" if key not in self.values: @@ -86,7 +97,7 @@ def get(self, key, default=None): return default -class HubAuth(Configurable): +class HubAuth(SingletonConfigurable): """A class for authenticating with JupyterHub This can be used by any application. @@ -227,6 +238,8 @@ def _check_hub_authorization(self, url, cache_key=None, use_cache=True): cached = self.cache.get(cache_key) if cached is not None: return cached + else: + app_log.debug("Cache miss: %s" % cache_key) data = self._api_request('GET', url, allow_404=True) if data is None: @@ -274,7 +287,7 @@ def _api_request(self, method, url, **kwargs): return data - def user_for_cookie(self, encrypted_cookie, use_cache=True): + def user_for_cookie(self, encrypted_cookie, use_cache=True, session_id=''): """Ask the Hub to identify the user for a given cookie. Args: @@ -291,11 +304,11 @@ def user_for_cookie(self, encrypted_cookie, use_cache=True): "authorizations/cookie", self.cookie_name, quote(encrypted_cookie, safe='')), - cache_key='cookie:%s' % encrypted_cookie, + cache_key='cookie:{}:{}'.format(session_id, encrypted_cookie), use_cache=use_cache, ) - def user_for_token(self, token, use_cache=True): + def user_for_token(self, token, use_cache=True, session_id=''): """Ask the Hub to identify the user for a given token. Args: @@ -311,10 +324,10 @@ def user_for_token(self, token, use_cache=True): url=url_path_join(self.api_url, "authorizations/token", quote(token, safe='')), - cache_key='token:%s' % token, + cache_key='token:{}:{}'.format(session_id, token), use_cache=use_cache, ) - + auth_header_name = 'Authorization' auth_header_pat = re.compile('token\s+(.+)', re.IGNORECASE) @@ -336,8 +349,16 @@ def get_token(self, handler): def _get_user_cookie(self, handler): """Get the user model from a cookie""" encrypted_cookie = handler.get_cookie(self.cookie_name) + session_id = self.get_session_id(handler) if encrypted_cookie: - return self.user_for_cookie(encrypted_cookie) + return self.user_for_cookie(encrypted_cookie, session_id=session_id) + + def get_session_id(self, handler): + """Get the jupyterhub session id + + from the jupyterhub-session-id cookie. + """ + return handler.get_cookie('jupyterhub-session-id', '') def get_user(self, handler): """Get the Hub user for a given tornado handler. @@ -360,11 +381,12 @@ def get_user(self, handler): return handler._cached_hub_user handler._cached_hub_user = user_model = None + session_id = self.get_session_id(handler) # check token first token = self.get_token(handler) if token: - user_model = self.user_for_token(token) + user_model = self.user_for_token(token, session_id=session_id) if user_model: handler._token_authenticated = True @@ -414,8 +436,10 @@ def state_cookie_name(self): def _get_user_cookie(self, handler): token = handler.get_secure_cookie(self.cookie_name) + session_id = self.get_session_id(handler) if token: - user_model = self.user_for_token(token) + token = token.decode('ascii', 'replace') + user_model = self.user_for_token(token, session_id=session_id) if user_model is None: app_log.warning("Token stored in cookie may have expired") handler.clear_cookie(self.cookie_name) @@ -493,7 +517,7 @@ def token_for_code(self, code): def _encode_state(self, state): """Encode a state dict as url-safe base64""" - # trim trailing `=` because + # trim trailing `=` because = is itself not url-safe! json_state = json.dumps(state) return base64.urlsafe_b64encode( json_state.encode('utf8') @@ -675,7 +699,7 @@ def allow_all(self): @property def hub_auth(self): if self._hub_auth is None: - self._hub_auth = self.hub_auth_class() + self._hub_auth = self.hub_auth_class.instance() return self._hub_auth @hub_auth.setter @@ -812,7 +836,8 @@ def get(self): next_url = self.hub_auth.get_next_url(cookie_state) # TODO: make async (in a Thread?) token = self.hub_auth.token_for_code(code) - user_model = self.hub_auth.user_for_token(token) + session_id = self.hub_auth.get_session_id(self) + user_model = self.hub_auth.user_for_token(token, session_id=session_id) if user_model is None: raise HTTPError(500, "oauth callback failed to identify a user") app_log.info("Logged-in user %s", user_model)
diff --git a/jupyterhub/tests/test_services_auth.py b/jupyterhub/tests/test_services_auth.py --- a/jupyterhub/tests/test_services_auth.py +++ b/jupyterhub/tests/test_services_auth.py @@ -1,4 +1,5 @@ from binascii import hexlify +import copy import json import os from queue import Queue @@ -17,6 +18,7 @@ from tornado.web import RequestHandler, Application, authenticated, HTTPError from tornado.httputil import url_concat +from .. import orm from ..services.auth import _ExpiringDict, HubAuth, HubAuthenticated from ..utils import url_path_join from .mocking import public_url, public_host @@ -198,7 +200,7 @@ def finish_thread(): allow_redirects=False, ) assert r.status_code == 403 - + # pass group whitelist TestHandler.hub_groups = {'lions'} r = requests.get('http://127.0.0.1:%i' % port, @@ -319,7 +321,6 @@ def test_oauth_service(app, mockservice_url): service = mockservice_url url = url_path_join(public_url(app, mockservice_url) + 'owhoami/?arg=x') # first request is only going to set login cookie - # FIXME: redirect to originating URL (OAuth loses this info) s = requests.Session() name = 'link' s.cookies = yield app.login_user(name) @@ -371,7 +372,7 @@ def test_oauth_service(app, mockservice_url): @pytest.mark.gen_test def test_oauth_cookie_collision(app, mockservice_url): service = mockservice_url - url = url_path_join(public_url(app, mockservice_url) + 'owhoami/') + url = url_path_join(public_url(app, mockservice_url), 'owhoami/') print(url) s = requests.Session() name = 'mypha' @@ -425,3 +426,93 @@ def test_oauth_cookie_collision(app, mockservice_url): # after completing both OAuth logins, no OAuth state cookies remain state_cookies = [ s for s in s.cookies.keys() if s.startswith(state_cookie_name) ] assert state_cookies == [] + + [email protected]_test +def test_oauth_logout(app, mockservice_url): + """Verify that logout via the Hub triggers logout for oauth services + + 1. clears session id cookie + 2. revokes oauth tokens + 3. cleared session id ensures cached auth miss + 4. cache hit + """ + service = mockservice_url + service_cookie_name = 'service-%s' % service.name + url = url_path_join(public_url(app, mockservice_url), 'owhoami/?foo=bar') + # first request is only going to set login cookie + s = requests.Session() + name = 'propha' + app_user = add_user(app.db, app=app, name=name) + def auth_tokens(): + """Return list of OAuth access tokens for the user""" + return list( + app.db.query(orm.OAuthAccessToken).filter( + orm.OAuthAccessToken.user_id == app_user.id) + ) + + # ensure we start empty + assert auth_tokens() == [] + + s.cookies = yield app.login_user(name) + assert 'jupyterhub-session-id' in s.cookies + # run session.get in async_requests thread + s_get = lambda *args, **kwargs: async_requests.executor.submit(s.get, *args, **kwargs) + r = yield s_get(url) + r.raise_for_status() + assert r.url == url + # second request should be authenticated + r = yield s_get(url, allow_redirects=False) + r.raise_for_status() + assert r.status_code == 200 + reply = r.json() + sub_reply = { + key: reply.get(key, 'missing') + for key in ('kind', 'name') + } + assert sub_reply == { + 'name': name, + 'kind': 'user', + } + # save cookies to verify cache + saved_cookies = copy.deepcopy(s.cookies) + session_id = s.cookies['jupyterhub-session-id'] + + assert len(auth_tokens()) == 1 + + # hit hub logout URL + r = yield s_get(public_url(app, path='hub/logout')) + r.raise_for_status() + # verify that all cookies other than the service cookie are cleared + assert list(s.cookies.keys()) == [service_cookie_name] + # verify that clearing session id invalidates service cookie + # i.e. redirect back to login page + r = yield s_get(url) + r.raise_for_status() + assert r.url.split('?')[0] == public_url(app, path='hub/login') + + # verify that oauth tokens have been revoked + assert auth_tokens() == [] + + # double check that if we hadn't cleared session id + # login would have been cached. + # it's not important that the old login is still cached, + # but what is important is that the above logout was successful + # due to session-id causing a cache miss + # and not a failure to cache auth at all. + s.cookies = saved_cookies + # check that we got the old session id back + assert session_id == s.cookies['jupyterhub-session-id'] + + r = yield s_get(url, allow_redirects=False) + r.raise_for_status() + assert r.status_code == 200 + reply = r.json() + sub_reply = { + key: reply.get(key, 'missing') + for key in ('kind', 'name') + } + assert sub_reply == { + 'name': name, + 'kind': 'user', + }
User logout does not invalidate cookies for services It seems that if you log in as a user that has access to the server, and then logout, this does not invalidate the cookie or token for that service and so you can still gain access to it. This is an annoyance with testing, and potentially a security issue (if a user was using JupyterHub on a public machine). **How to reproduce the issue** 1. Create a `jupyterhub_config.py` with a service, e.g. ``` c = get_config() c.Authenticator.whitelist = [ 'instructor1' ] c.JupyterHub.load_groups = { 'formgrader-course101': [ 'instructor1' ] } c.JupyterHub.services = [ { 'name': 'course101', 'url': 'http://127.0.0.1:9999', 'command': [ 'jupyterhub-singleuser', '--group=formgrader-course101', '--debug', ], 'user': 'grader-course101', 'cwd': '/home/grader-course101' } ] ``` 2. Go to the service url, e.g. `/services/course101`. Observe that you get redirected to the login page (good!). 3. Now log in as the user, and go to the service url. Observe you can access it. 4. Go back to the user's server, and click "log out". Go back to the service url and observe that you can still access it. **What you expected to happen** After the user logs out, they should no longer have access to the service. **What actually happens** After the user logs out, they still have access to the service. **Share what version of JupyterHub you are using** 0.8.0 User logout does not invalidate cookies for services It seems that if you log in as a user that has access to the server, and then logout, this does not invalidate the cookie or token for that service and so you can still gain access to it. This is an annoyance with testing, and potentially a security issue (if a user was using JupyterHub on a public machine). **How to reproduce the issue** 1. Create a `jupyterhub_config.py` with a service, e.g. ``` c = get_config() c.Authenticator.whitelist = [ 'instructor1' ] c.JupyterHub.load_groups = { 'formgrader-course101': [ 'instructor1' ] } c.JupyterHub.services = [ { 'name': 'course101', 'url': 'http://127.0.0.1:9999', 'command': [ 'jupyterhub-singleuser', '--group=formgrader-course101', '--debug', ], 'user': 'grader-course101', 'cwd': '/home/grader-course101' } ] ``` 2. Go to the service url, e.g. `/services/course101`. Observe that you get redirected to the login page (good!). 3. Now log in as the user, and go to the service url. Observe you can access it. 4. Go back to the user's server, and click "log out". Go back to the service url and observe that you can still access it. **What you expected to happen** After the user logs out, they should no longer have access to the service. **What actually happens** After the user logs out, they still have access to the service. **Share what version of JupyterHub you are using** 0.8.0
This is a consequence of the new OAuth setup. When you login to something with OAuth, an OAuth token is allocated and stored in a cookie *set by the service*. So you have separate cookies set by each service/server you are logged in to. To properly logout of all of these, we would need to either: 1. somehow know all cookies of all services and clear them (easy for notebooks, hard in general), or 2. know which tokens have been allocated for this browser session and revoke them on logout. I suspect we need to have a separate domain-wide, world-readable session id that we use purely to associate tokens with a browser session. With that, we should be able to revoke tokens. This is a consequence of the new OAuth setup. When you login to something with OAuth, an OAuth token is allocated and stored in a cookie *set by the service*. So you have separate cookies set by each service/server you are logged in to. To properly logout of all of these, we would need to either: 1. somehow know all cookies of all services and clear them (easy for notebooks, hard in general), or 2. know which tokens have been allocated for this browser session and revoke them on logout. I suspect we need to have a separate domain-wide, world-readable session id that we use purely to associate tokens with a browser session. With that, we should be able to revoke tokens.
2017-12-07T14:54:51Z
[]
[]
jupyterhub/jupyterhub
1,609
jupyterhub__jupyterhub-1609
[ "1608" ]
691c4c158f01934d74f50c4b488a879f145516cc
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -1625,10 +1625,7 @@ def stop(self): if not self.io_loop: return if self.http_server: - if self.io_loop._running: - self.io_loop.add_callback(self.http_server.stop) - else: - self.http_server.stop() + self.http_server.stop() self.io_loop.add_callback(self.io_loop.stop) @gen.coroutine diff --git a/jupyterhub/services/auth.py b/jupyterhub/services/auth.py --- a/jupyterhub/services/auth.py +++ b/jupyterhub/services/auth.py @@ -778,7 +778,14 @@ def get_current_user(self): except UserNotAllowed as e: # cache None, in case get_user is called again while processing the error self._hub_auth_user_cache = None - raise HTTPError(403, "{kind} {name} is not allowed.".format(**e.model)) + # Override redirect so if/when tornado @web.authenticated + # tries to redirect to login URL, 403 will be raised instead. + # This is not the best, but avoids problems that can be caused + # when get_current_user is allowed to raise. + def raise_on_redirect(*args, **kwargs): + raise HTTPError(403, "{kind} {name} is not allowed.".format(**user_model)) + self.redirect = raise_on_redirect + return except Exception: self._hub_auth_user_cache = None raise
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -1,5 +1,6 @@ """mock utilities for testing""" +from concurrent.futures import ThreadPoolExecutor import os import sys from tempfile import NamedTemporaryFile @@ -202,11 +203,11 @@ def _port_default(self): @default('authenticator_class') def _authenticator_class_default(self): return MockPAMAuthenticator - + @default('spawner_class') def _spawner_class_default(self): return MockSpawner - + def init_signal(self): pass @@ -229,11 +230,25 @@ def initialize(self, argv=None): def stop(self): super().stop() - IOLoop().run_sync(self.cleanup) + + # run cleanup in a background thread + # to avoid multiple eventloops in the same thread errors from asyncio + + def cleanup(): + loop = IOLoop.current() + loop.run_sync(self.cleanup) + loop.close() + + pool = ThreadPoolExecutor(1) + f = pool.submit(cleanup) + # wait for cleanup to finish + f.result() + pool.shutdown() + # ignore the call that will fire in atexit self.cleanup = lambda : None self.db_file.close() - + @gen.coroutine def login_user(self, name): """Login a user by name, returning her cookies."""
Support tornado 5 Tests are failing with tornado 5a1. This is likely due to tornado 5 running on asyncio by default. It's my suspicion that the issue lies only in the test suite and not the application, which I've been running locally on tornado master from time to time.
2018-01-03T13:13:46Z
[]
[]
jupyterhub/jupyterhub
1,660
jupyterhub__jupyterhub-1660
[ "1629" ]
7550e63fd0910ad2f33a9dee59628186cef25af3
diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -702,9 +702,11 @@ def get_template(self, name): return self.settings['jinja2_env'].get_template(name) def render_template(self, name, **ns): - ns.update(self.template_namespace) + template_ns = {} + template_ns.update(self.template_namespace) + template_ns.update(ns) template = self.get_template(name) - return template.render(**ns) + return template.render(**template_ns) @property def template_namespace(self): @@ -796,8 +798,30 @@ def get(self, name, user_path): if not user_path: user_path = '/' current_user = self.get_current_user() + if ( + current_user + and current_user.name != name + and current_user.admin + and self.settings.get('admin_access', False) + ): + # allow admins to spawn on behalf of users + user = self.find_user(name) + if user is None: + # no such user + raise web.HTTPError(404, "No such user %s" % name) + self.log.info("Admin %s requesting spawn on behalf of %s", + current_user.name, user.name) + admin_spawn = True + should_spawn = True + else: + user = current_user + admin_spawn = False + # For non-admins, we should spawn if the user matches + # otherwise redirect users to their own server + should_spawn = (current_user and current_user.name == name) + - if current_user and current_user.name == name: + if should_spawn: # if spawning fails for any reason, point users to /hub/home to retry self.extra_error_html = self.spawn_home_error @@ -816,8 +840,8 @@ def get(self, name, user_path): Make sure to connect to the proxied public URL %s """, self.request.full_url(), self.proxy.public_url) - # logged in as correct user, check for pending spawn - spawner = current_user.spawner + # logged in as valid user, check for pending spawn + spawner = user.spawner # First, check for previous failure. if ( @@ -850,7 +874,7 @@ def get(self, name, user_path): self.log.info("%s is pending %s", spawner._log_name, spawner.pending) # spawn has started, but not finished self.statsd.incr('redirects.user_spawn_pending', 1) - html = self.render_template("spawn_pending.html", user=current_user) + html = self.render_template("spawn_pending.html", user=user) self.finish(html) return @@ -863,24 +887,28 @@ def get(self, name, user_path): # server is not running, trigger spawn if status is not None: if spawner.options_form: - self.redirect(url_concat(url_path_join(self.hub.base_url, 'spawn'), + url_parts = [self.hub.base_url, 'spawn'] + if current_user.name != user.name: + # spawning on behalf of another user + url_parts.append(user.name) + self.redirect(url_concat(url_path_join(*url_parts), {'next': self.request.uri})) return else: - yield self.spawn_single_user(current_user) + yield self.spawn_single_user(user) # spawn didn't finish, show pending page if spawner.pending: self.log.info("%s is pending %s", spawner._log_name, spawner.pending) # spawn has started, but not finished self.statsd.incr('redirects.user_spawn_pending', 1) - html = self.render_template("spawn_pending.html", user=current_user) + html = self.render_template("spawn_pending.html", user=user) self.finish(html) return # We do exponential backoff here - since otherwise we can get stuck in a redirect loop! # This is important in many distributed proxy implementations - those are often eventually - # consistent and can take upto a couple of seconds to actually apply throughout the cluster. + # consistent and can take up to a couple of seconds to actually apply throughout the cluster. try: redirects = int(self.get_argument('redirects', 0)) except ValueError: @@ -905,12 +933,10 @@ def get(self, name, user_path): ) raise web.HTTPError(500, msg) - # set login cookie anew - self.set_login_cookie(current_user) without_prefix = self.request.uri[len(self.hub.base_url):] target = url_path_join(self.base_url, without_prefix) if self.subdomain_host: - target = current_user.host + target + target = user.host + target # record redirect count in query parameter if redirects: @@ -945,13 +971,13 @@ def get(self, name, user_path): class UserRedirectHandler(BaseHandler): """Redirect requests to user servers. - + Allows public linking to "this file on your server". - + /user-redirect/path/to/foo will redirect to /user/:name/path/to/foo - + If the user is not logged in, send to login URL, redirecting back here. - + .. versionadded:: 0.7 """ @web.authenticated diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -34,7 +34,7 @@ def get(self): next_url = '' if next_url and next_url.startswith(url_path_join(self.base_url, 'user/')): # add /hub/ prefix, to ensure we redirect to the right user's server. - # The next request will be handled by UserSpawnHandler, + # The next request will be handled by SpawnHandler, # ultimately redirecting to the logged-in user's server. without_prefix = next_url[len(self.base_url):] next_url = url_path_join(self.hub.base_url, without_prefix) @@ -88,11 +88,11 @@ class SpawnHandler(BaseHandler): Only enabled when Spawner.options_form is defined. """ @gen.coroutine - def _render_form(self, message=''): - user = self.get_current_user() + def _render_form(self, message='', for_user=None): + user = for_user or self.get_current_user() spawner_options_form = yield user.spawner.get_options_form() return self.render_template('spawn.html', - user=user, + for_user=for_user, spawner_options_form=spawner_options_form, error_message=message, url=self.request.uri, @@ -100,19 +100,27 @@ def _render_form(self, message=''): @web.authenticated @gen.coroutine - def get(self): + def get(self, for_user=None): """GET renders form for spawning with user-specified options or triggers spawn via redirect if there is no form. """ - user = self.get_current_user() + user = current_user = self.get_current_user() + if for_user is not None and for_user != user.name: + if not user.admin: + raise web.HTTPError(403, "Only admins can spawn on behalf of other users") + + user = self.find_user(for_user) + if user is None: + raise web.HTTPError(404, "No such user: %s" % for_user) + if not self.allow_named_servers and user.running: url = user.url self.log.debug("User is running: %s", url) self.redirect(url) return if user.spawner.options_form: - form = yield self._render_form() + form = yield self._render_form(for_user=user) self.finish(form) else: # Explicit spawn request: clear _spawn_future @@ -125,9 +133,15 @@ def get(self): @web.authenticated @gen.coroutine - def post(self): + def post(self, for_user=None): """POST spawns with user-specified options""" - user = self.get_current_user() + user = current_user = self.get_current_user() + if for_user is not None and for_user != user.name: + if not user.admin: + raise web.HTTPError(403, "Only admins can spawn on behalf of other users") + user = self.find_user(for_user) + if user is None: + raise web.HTTPError(404, "No such user: %s" % for_user) if not self.allow_named_servers and user.running: url = user.url self.log.warning("User is already running: %s", url) @@ -147,9 +161,11 @@ def post(self): yield self.spawn_single_user(user, options=options) except Exception as e: self.log.error("Failed to spawn single-user server with form", exc_info=True) - self.finish(self._render_form(str(e))) + form = yield self._render_form(message=str(e), for_usr=user) + self.finish(form) return - self.set_login_cookie(user) + if current_user is user: + self.set_login_cookie(user) url = user.url next_url = self.get_argument('next', '') @@ -160,6 +176,7 @@ def post(self): self.redirect(url) + class AdminHandler(BaseHandler): """Render the admin page.""" @@ -268,6 +285,7 @@ def get(self, status_code_s): (r'/home', HomeHandler), (r'/admin', AdminHandler), (r'/spawn', SpawnHandler), + (r'/spawn/([^/]+)', SpawnHandler), (r'/token', TokenPageHandler), (r'/error/(\d+)', ProxyErrorHandler), ]
diff --git a/jupyterhub/tests/conftest.py b/jupyterhub/tests/conftest.py --- a/jupyterhub/tests/conftest.py +++ b/jupyterhub/tests/conftest.py @@ -50,6 +50,7 @@ def _close(): request.addfinalizer(_close) return io_loop + @fixture(scope='module') def app(request, io_loop): """Mock a jupyterhub app for testing""" @@ -129,7 +130,7 @@ def mockservice_url(request, app): @fixture def no_patience(app): """Set slow-spawning timeouts to zero""" - with mock.patch.dict(app.tornado_application.settings, + with mock.patch.dict(app.tornado_settings, {'slow_spawn_timeout': 0, 'slow_stop_timeout': 0}): yield @@ -166,3 +167,10 @@ def slow_bad_spawn(app): {'spawner_class': mocking.SlowBadSpawner}): yield + +@fixture +def admin_access(app): + """Grant admin-access with this fixture""" + with mock.patch.dict(app.tornado_settings, + {'admin_access': True}): + yield diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -214,6 +214,11 @@ def init_signal(self): def load_config_file(self, *args, **kwargs): pass + def init_tornado_application(self): + """Instantiate the tornado Application object""" + super().init_tornado_application() + # reconnect tornado_settings so that mocks can update the real thing + self.tornado_settings = self.users.settings = self.tornado_application.settings @gen.coroutine def initialize(self, argv=None): diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -67,8 +67,7 @@ def add_user(db, app=None, **kwargs): setattr(orm_user, attr, value) db.commit() if app: - user = app.users[orm_user.id] = User(orm_user, app.tornado_settings) - return user + return app.users[orm_user.id] else: return orm_user @@ -519,7 +518,6 @@ def test_never_spawn(app, no_patience, never_spawn): @mark.gen_test def test_bad_spawn(app, no_patience, bad_spawn): - settings = app.tornado_application.settings db = app.db name = 'prim' user = add_user(db, app=app, name=name) @@ -530,7 +528,6 @@ def test_bad_spawn(app, no_patience, bad_spawn): @mark.gen_test def test_slow_bad_spawn(app, no_patience, slow_bad_spawn): - settings = app.tornado_application.settings db = app.db name = 'zaphod' user = add_user(db, app=app, name=name) @@ -546,11 +543,10 @@ def test_slow_bad_spawn(app, no_patience, slow_bad_spawn): @mark.gen_test def test_spawn_limit(app, no_patience, slow_spawn, request): db = app.db - settings = app.tornado_application.settings - settings['concurrent_spawn_limit'] = 2 - def _restore_limit(): - settings['concurrent_spawn_limit'] = 100 - request.addfinalizer(_restore_limit) + p = mock.patch.dict(app.tornado_settings, + {'concurrent_spawn_limit': 2}) + p.start() + request.addfinalizer(p.stop) # start two pending spawns names = ['ykka', 'hjarka'] @@ -598,11 +594,10 @@ def _restore_limit(): @mark.gen_test def test_active_server_limit(app, request): db = app.db - settings = app.tornado_application.settings - settings['active_server_limit'] = 2 - def _restore_limit(): - settings['active_server_limit'] = 0 - request.addfinalizer(_restore_limit) + p = mock.patch.dict(app.tornado_settings, + {'active_server_limit': 2}) + p.start() + request.addfinalizer(p.stop) # start two pending spawns names = ['ykka', 'hjarka'] diff --git a/jupyterhub/tests/test_named_servers.py b/jupyterhub/tests/test_named_servers.py --- a/jupyterhub/tests/test_named_servers.py +++ b/jupyterhub/tests/test_named_servers.py @@ -1,4 +1,6 @@ """Tests for named servers""" +from unittest import mock + import pytest from ..utils import url_path_join @@ -9,12 +11,9 @@ @pytest.fixture def named_servers(app): - key = 'allow_named_servers' - app.tornado_application.settings[key] = app.tornado_settings[key] = True - try: - yield True - finally: - app.tornado_application.settings[key] = app.tornado_settings[key] = False + with mock.patch.dict(app.tornado_settings, + {'allow_named_servers': True}): + yield @pytest.mark.gen_test diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -13,7 +13,7 @@ import pytest from .mocking import FormSpawner, public_url, public_host -from .test_api import api_request +from .test_api import api_request, add_user from .utils import async_requests def get_page(path, app, hub=True, **kw): @@ -109,20 +109,20 @@ def test_spawn_redirect(app): name = 'wash' cookies = yield app.login_user(name) u = app.users[orm.User.find(app.db, name)] - + # ensure wash's server isn't running: r = yield api_request(app, 'users', name, 'server', method='delete', cookies=cookies) r.raise_for_status() status = yield u.spawner.poll() assert status is not None - + # test spawn page when no server is running r = yield get_page('spawn', app, cookies=cookies) r.raise_for_status() print(urlparse(r.url)) path = urlparse(r.url).path assert path == ujoin(app.base_url, 'user/%s/' % name) - + # should have started server status = yield u.spawner.poll() assert status is None @@ -145,6 +145,22 @@ def test_spawn_redirect(app): assert path == ujoin(app.base_url, '/user/%s/' % name) [email protected]_test +def test_spawn_admin_access(app, admin_access): + """GET /user/:name as admin with admin-access spawns user's server""" + cookies = yield app.login_user('admin') + name = 'mariel' + user = add_user(app.db, app=app, name=name) + app.db.commit() + r = yield get_page('user/' + name, app, cookies=cookies) + r.raise_for_status() + assert (r.url.split('?')[0] + '/').startswith(public_url(app, user)) + r = yield get_page('user/{}/env'.format(name), app, hub=False, cookies=cookies) + r.raise_for_status() + env = r.json() + assert env['JUPYTERHUB_USER'] == name + + @pytest.mark.gen_test def test_spawn_page(app): with mock.patch.dict(app.users.settings, {'spawner_class': FormSpawner}): @@ -158,6 +174,17 @@ def test_spawn_page(app): assert FormSpawner.options_form in r.text [email protected]_test +def test_spawn_page_admin(app, admin_access): + with mock.patch.dict(app.users.settings, {'spawner_class': FormSpawner}): + cookies = yield app.login_user('admin') + u = add_user(app.db, app=app, name='melanie') + r = yield get_page('spawn/' + u.name, app, cookies=cookies) + assert r.url.endswith('/spawn/' + u.name) + assert FormSpawner.options_form in r.text + assert "Spawning server for {}".format(u.name) in r.text + + @pytest.mark.gen_test def test_spawn_form(app): with mock.patch.dict(app.users.settings, {'spawner_class': FormSpawner}): @@ -166,15 +193,13 @@ def test_spawn_form(app): orm_u = orm.User.find(app.db, 'jones') u = app.users[orm_u] yield u.stop() - + r = yield async_requests.post(ujoin(base_url, 'spawn?next=/user/jones/tree'), cookies=cookies, data={ 'bounds': ['-1', '1'], 'energy': '511keV', }) r.raise_for_status() assert r.history - print(u.spawner) - print(u.spawner.user_options) assert u.spawner.user_options == { 'energy': '511keV', 'bounds': [-1, 1], @@ -182,9 +207,32 @@ def test_spawn_form(app): } [email protected]_test +def test_spawn_form_admin_access(app, admin_access): + with mock.patch.dict(app.tornado_settings, {'spawner_class': FormSpawner}): + base_url = ujoin(public_host(app), app.hub.base_url) + cookies = yield app.login_user('admin') + u = add_user(app.db, app=app, name='martha') + + r = yield async_requests.post( + ujoin(base_url, 'spawn/{0}?next=/user/{0}/tree'.format(u.name)), + cookies=cookies, data={ + 'bounds': ['-3', '3'], + 'energy': '938MeV', + }) + r.raise_for_status() + assert r.history + assert r.url.startswith(public_url(app, u)) + assert u.spawner.user_options == { + 'energy': '938MeV', + 'bounds': [-3, 3], + 'notspecified': 5, + } + + @pytest.mark.gen_test def test_spawn_form_with_file(app): - with mock.patch.dict(app.users.settings, {'spawner_class': FormSpawner}): + with mock.patch.dict(app.tornado_settings, {'spawner_class': FormSpawner}): base_url = ujoin(public_host(app), app.hub.base_url) cookies = yield app.login_user('jones') orm_u = orm.User.find(app.db, 'jones') @@ -338,7 +386,7 @@ def get(self): authenticator = Authenticator(auto_login=True) authenticator.login_url = lambda base_url: ujoin(base_url, 'dummy') - with mock.patch.dict(app.tornado_application.settings, { + with mock.patch.dict(app.tornado_settings, { 'authenticator': authenticator, }): r = yield async_requests.get(base_url) @@ -349,7 +397,7 @@ def test_auto_login_logout(app): name = 'burnham' cookies = yield app.login_user(name) - with mock.patch.dict(app.tornado_application.settings, { + with mock.patch.dict(app.tornado_settings, { 'authenticator': Authenticator(auto_login=True), }): r = yield async_requests.get(public_host(app) + app.tornado_settings['logout_url'], cookies=cookies)
Spawner.options_form is not shown when servers are started from the admin panel which prevents servers from spawning, because the `user_options` is empty and throws `KeyError` when the spawner tries to get values from it. **How to reproduce the issue** 1. Enable `admin_access` and add (an) admin user(s) 2. Add an `options_form` to spawner and use some field value from the form in the spawner by accessing `user_options`. 3. Log in as admin and go to admin panel 4. Push the `start server` button. **What you expected to happen** The form is shown. **What actually happens** An `API request failed (500): error` error raised, because an attempt to use the `user_options` in the Spawner ended with the `KeyError` exception. **Share what version of JupyterHub you are using** From the `jupyterhub/jupyterhub:latest` docker image.
I suspect I am seeing the same issue but in different scenario. I am using ``ProfilesSpawner`` with JupyterHub. So: ``` c.JupyterHub.spawner_class = 'wrapspawner.ProfilesSpawner' ``` Then something like: ``` c.ProfilesSpawner.profiles = [ ( "Jupyter Project - Minimal Notebook", 'minimal-notebook', 'kubespawner.KubeSpawner', dict(singleuser_image_spec='minimal-notebook:latest', singleuser_supplemental_gids=[100]) ), ( "Jupyter Project - SciPy Notebook", 'scipy-notebook', 'kubespawner.KubeSpawner', dict(singleuser_image_spec='scipy-notebook:latest', singleuser_supplemental_gids=[100]) ), ... ] ``` When you are on the Admin dashboard and select start server for a different user, it results in an error: ``` Traceback (most recent call last): --   | File "/opt/app-root/lib/python3.5/site-packages/tornado/web.py", line 1512, in _execute   | result = yield result   | File "/opt/app-root/lib64/python3.5/types.py", line 179, in throw   | return self.__wrapped.throw(tp, *rest)   | File "/opt/app-root/lib/python3.5/site-packages/jupyterhub/apihandlers/users.py", line 209, in post   | yield self.spawn_single_user(user, server_name, options=options)   | File "/opt/app-root/lib/python3.5/site-packages/jupyterhub/handlers/base.py", line 475, in spawn_single_user   | yield gen.with_timeout(timedelta(seconds=self.slow_spawn_timeout), finish_spawn_future)   | File "/opt/app-root/lib/python3.5/site-packages/jupyterhub/handlers/base.py", line 445, in finish_user_spawn   | yield spawn_future   | File "/opt/app-root/lib/python3.5/site-packages/jupyterhub/user.py", line 439, in spawn   | raise e   | File "/opt/app-root/lib/python3.5/site-packages/jupyterhub/user.py", line 378, in spawn   | ip_port = yield gen.with_timeout(timedelta(seconds=spawner.start_timeout), f)   | File "/opt/app-root/lib64/python3.5/types.py", line 243, in wrapped   | coro = func(*args, **kwargs)   | File "/opt/app-root/lib/python3.5/site-packages/jupyterhub/spawner.py", line 968, in start   | env = self.get_env()   | File "/opt/app-root/lib/python3.5/site-packages/jupyterhub/spawner.py", line 960, in get_env   | env = self.user_env(env)   | File "/opt/app-root/lib/python3.5/site-packages/jupyterhub/spawner.py", line 947, in user_env   | home = pwd.getpwnam(self.user.name).pw_dir   | KeyError: 'getpwnam(): name not found: ncoghlan' ``` My guess is that is caused by same issue as here. The form is never presented to provide the option of selecting from profiles defined by ``ProfilesSpawner`` configuration. The result is that it goes into ``ProfilesSpawner`` and triggers the code: ``` def select_profile(self, profile): # Select matching profile, or do nothing (leaving previous or default config in place) for p in self.profiles: if p[1] == profile: self.child_class = p[2] self.child_config = p[3] break def construct_child(self): self.child_profile = self.user_options.get('profile', "") self.select_profile(self.child_profile) super().construct_child() ``` The ``self.user_options.get('profile', "")`` can't find a ``profile`` option and so results in empty string. When this is used to ``select_profile`` it doesn't find a match and thus doesn't overrwrite ``self.child_class`` with anything from the profile list. The default ``child_class`` from ``WrapSpawner`` base class is: ``` child_class = Type(LocalProcessSpawner, Spawner, config=True, help="""The class to wrap for spawning single-user servers. Should be a subclass of Spawner. """ ) ``` So rather than creating a ``KubeSpawner`` as ultimately wanted, it creates instance of ``LocalProcessSpawner`` which then fires off the code: ``` def user_env(self, env): """Augment environment of spawned process with user specific env variables.""" import pwd env['USER'] = self.user.name home = pwd.getpwnam(self.user.name).pw_dir shell = pwd.getpwnam(self.user.name).pw_shell # These will be empty if undefined, # in which case don't set the env: if home: env['HOME'] = home if shell: env['SHELL'] = shell return env ``` which fails, because ``self.user.name`` in my case is going to be a GitHub username as I am using OAuth against GitHub. I don't know what code to start looking at as to why it doesn't flow into display form for user options. So if you can point me to the correct spot I can dig further. FWIW, I am using: ``` jupyterhub==0.8.1 #jupyterhub-kubespawner==0.8.1 git+https://github.com/jupyter-on-openshift/kubespawner#egg=jupyterhub-kubespawner git+https://github.com/jupyterhub/wrapspawner jupyterhub-tmpauthenticator oauthenticator psycopg2 ``` The ``KubeSpawner`` fork is because of pending PR: * https://github.com/jupyterhub/kubespawner/pull/134 So using from Git repo rather than ``jupyterhub-kubespawner==0.8.1``. There are two things here. First, I agree that launching from the admin panel ought to show the options form. That's going to be a *little* tricky, as we need to make sure that we serve a page that's launching for one user while authenticating as another, which the current spawn page doesn't handle. Second, though, is that is should be a best practice for any Spawner that supports options_form to accept sensible defaults for missing fields in user_options. Launching Spawners can be done via the API (as is done with the admin panel), and it should generally be possible to omit user_options unless there really are no defaults that make sense, which should be rare. I can possibly solve the default option by adding configuration: ``` c.WrapSpawner.child_class = 'kubespawner.KubeSpawner' c.KubeSpawner.singleuser_image_spec = 'something' ``` so it doesn't at least crash, but doesn't really get the desired result, because in the case you are using ``ProfilesSpawner`` to select the image to deploy, as well as possibly other per image settings relates to persistent volumes, working directories for image etc. Anyway, it seems you answer the question at least to say that right now one can't expect to get the form as the code isn't there to do that. Okay. I used: ``` c.WrapSpawner.child_class = 'kubespawner.KubeSpawner' ``` and did not set ``singleuser_image_spec``. It didn't error this time and started up the default image of ``jupyterhub/singleuser:latest``. When you click on access server it brings up a new tab which gives error: ``` 403 : Forbidden The error was: user grahamdumpleton is not allowed. ``` So this probably also relates to what you said about launching for one user while authenticating as another. One other strange thing did happen. The first time I tried, because that image will not run in this environment without the: ``` c.KubeSpawner.singleuser_supplemental_gids = [100] ``` the image was failing to start. I didn't realise it was failing. In that case when I clicked on access server, it showed the user options for selection based on profiles in ``ProfilesSpawner``. So definitely some weird flow happening in all this. Getting a 403 suggests to me that admin-access isn't properly implemented, and that the container was launched without admin-access enabled. Do you see JUPYTERHUB_ADMIN_ACCESS=1 in the pod environment? As for the strange failure, here's my guess of the sequence of events: 1. request spawn from API 2. request succeeds, but spawn ultimately fails (can happen if failure occurs after slow_spawn_timeout) 3. access server link sends you to `/user/:name` URL, but that server isn't running, so it serves the page `/hub/user/:name`. This is the page that normally serves the spawn form. 4. This is probably where it's not doing what you expect/desire. When visiting `/hub/user/:name`, if you are not authenticated as that user, you are redirected to `/hub/user/:yourname`. 5. At this point, you are actually served the options form, but it is *for your own server*, not the server for which you requested access. I think the fixes are mostly in step 4, which is: 1. when requesting `/hub/user/:name`, rather than checking if you *are* `:name`, check if you should have access to their server (i.e. same_user or (is_admin and admin_access)). Only redirect away if you don't have access to the given server. 2. allow serving the spawn form if you are admin (same as above, minus the requirement for admin_access)
2018-02-13T14:32:44Z
[]
[]
jupyterhub/jupyterhub
1,687
jupyterhub__jupyterhub-1687
[ "1686" ]
a58bea6d933b7bc0bcfe4b08dfff4f31dd2b5909
diff --git a/examples/external-oauth/jupyterhub_config.py b/examples/external-oauth/jupyterhub_config.py --- a/examples/external-oauth/jupyterhub_config.py +++ b/examples/external-oauth/jupyterhub_config.py @@ -7,6 +7,7 @@ raise ValueError("Make sure to `export JUPYTERHUB_API_TOKEN=$(openssl rand -hex 32)`") # tell JupyterHub to register the service as an external oauth client + c.JupyterHub.services = [ { 'name': 'external-oauth', diff --git a/examples/external-oauth/whoami-oauth-basic.py b/examples/external-oauth/whoami-oauth-basic.py new file mode 100644 --- /dev/null +++ b/examples/external-oauth/whoami-oauth-basic.py @@ -0,0 +1,135 @@ +"""Basic implementation of OAuth without any inheritance + +Implements OAuth handshake manually +so all URLs and requests necessary for OAuth with JupyterHub should be in one place +""" + +import json +import os +import sys +from urllib.parse import urlencode, urlparse + +from tornado.auth import OAuth2Mixin +from tornado.httpclient import AsyncHTTPClient, HTTPRequest +from tornado.httputil import url_concat +from tornado.ioloop import IOLoop +from tornado import log +from tornado import web + + +class JupyterHubLoginHandler(web.RequestHandler): + """Login Handler + + this handler both begins and ends the OAuth process + """ + + async def token_for_code(self, code): + """Complete OAuth by requesting an access token for an oauth code""" + params = dict( + client_id=self.settings['client_id'], + client_secret=self.settings['api_token'], + grant_type='authorization_code', + code=code, + redirect_uri=self.settings['redirect_uri'], + ) + req = HTTPRequest(self.settings['token_url'], method='POST', + body=urlencode(params).encode('utf8'), + headers={ + 'Content-Type': 'application/x-www-form-urlencoded', + }, + ) + response = await AsyncHTTPClient().fetch(req) + data = json.loads(response.body.decode('utf8', 'replace')) + return data['access_token'] + + async def get(self): + code = self.get_argument('code', None) + if code: + # code is set, we are the oauth callback + # complete oauth + token = await self.token_for_code(code) + # login successful, set cookie and redirect back to home + self.set_secure_cookie('whoami-oauth-token', token) + self.redirect('/') + else: + # we are the login handler, + # begin oauth process which will come back later with an + # authorization_code + self.redirect(url_concat( + self.settings['authorize_url'], + dict( + redirect_uri=self.settings['redirect_uri'], + client_id=self.settings['client_id'], + response_type='code', + ) + )) + + +class WhoAmIHandler(web.RequestHandler): + """Serve the JSON model for the authenticated user""" + + def get_current_user(self): + """The login handler stored a JupyterHub API token in a cookie + + @web.authenticated calls this method. + If a Falsy value is returned, the request is redirected to `login_url`. + If a Truthy value is returned, the request is allowed to proceed. + """ + token = self.get_secure_cookie('whoami-oauth-token') + + if token: + # secure cookies are bytes, decode to str + return token.decode('ascii', 'replace') + + async def user_for_token(self, token): + """Retrieve the user for a given token, via /hub/api/user""" + + req = HTTPRequest( + self.settings['user_url'], + headers={ + 'Authorization': f'token {token}' + }, + ) + response = await AsyncHTTPClient().fetch(req) + return json.loads(response.body.decode('utf8', 'replace')) + + @web.authenticated + async def get(self): + user_token = self.get_current_user() + user_model = await self.user_for_token(user_token) + self.set_header('content-type', 'application/json') + self.write(json.dumps(user_model, indent=1, sort_keys=True)) + + +def main(): + log.enable_pretty_logging() + + # construct OAuth URLs from jupyterhub base URL + hub_api = os.environ['JUPYTERHUB_URL'].rstrip('/') + '/hub/api' + authorize_url = hub_api + '/oauth2/authorize' + token_url = hub_api + '/oauth2/token' + user_url = hub_api + '/user' + + app = web.Application([ + ('/oauth_callback', JupyterHubLoginHandler), + ('/', WhoAmIHandler), + ], + login_url='/oauth_callback', + cookie_secret=os.urandom(32), + api_token=os.environ['JUPYTERHUB_API_TOKEN'], + client_id=os.environ['JUPYTERHUB_CLIENT_ID'], + redirect_uri=os.environ['JUPYTERHUB_SERVICE_URL'].rstrip('/') + '/oauth_callback', + authorize_url=authorize_url, + token_url=token_url, + user_url=user_url, + ) + + url = urlparse(os.environ['JUPYTERHUB_SERVICE_URL']) + log.app_log.info("Running basic whoami service on %s", + os.environ['JUPYTERHUB_SERVICE_URL']) + app.listen(url.port, url.hostname) + IOLoop.current().start() + + +if __name__ == '__main__': + main() diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -17,7 +17,6 @@ class SelfAPIHandler(APIHandler): Based on the authentication info. Acts as a 'whoami' for auth tokens. """ - @web.authenticated def get(self): user = self.get_current_user() if user is None:
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -6,6 +6,7 @@ import sys from unittest import mock from urllib.parse import urlparse, quote +import uuid import pytest from pytest import mark @@ -186,7 +187,6 @@ def test_referer_check(app): # User API tests # -------------- - @mark.user @mark.gen_test def test_get_users(app): @@ -222,6 +222,40 @@ def test_get_users(app): assert r.status_code == 403 [email protected] [email protected]_test +def test_get_self(app): + db = app.db + + # basic get self + r = yield api_request(app, 'user') + r.raise_for_status() + assert r.json()['kind'] == 'user' + + # identifying user via oauth token works + u = add_user(db, app=app, name='orpheus') + token = uuid.uuid4().hex + oauth_token = orm.OAuthAccessToken( + user=u.orm_user, + token=token, + grant_type=orm.GrantType.authorization_code, + ) + db.add(oauth_token) + db.commit() + r = yield api_request(app, 'user', headers={ + 'Authorization': 'token ' + token, + }) + r.raise_for_status() + model = r.json() + assert model['name'] == u.name + + # invalid auth gets 403 + r = yield api_request(app, 'user', headers={ + 'Authorization': 'token notvalid', + }) + assert r.status_code == 403 + + @mark.user @mark.gen_test def test_add_user(app):
External OAuth Client unable to access API Hi, So I'm testing the recently merged "enable external oauth client" but unfortunately my oauth client is unable to access the API after retrieving the token and is being redirected to the login page (see logs below). **How to reproduce the issue** I am using my self hosted Gitlab as an external oauth client **What you expected to happen** The API request to `/jupyterhub/hub/api/user` with oauth token should be able to retrieve the user info. **What actually happens** The request is being redirected to the login page **Share what version of JupyterHub you are using** : latest Jupyterhub logs ``` jupyterhub | [I 2018-02-27 16:18:07.927 JupyterHub log:124] 302 GET /jupyterhub/hub/api/oauth2/authorize?client_id=gitlab-oauth&redirect_uri=http%3A%2F%2Fhost.domain%2Fgitlab%2Fusers%2Fauth%2FJupyterhub%2Fcallback&response_type=code&state=[state] -> http://host.domain/gitlab/users/auth/Jupyterhub/callback?code=[code]&state=[state] ([user]@194.199.19.22) 14.87ms jupyterhub | [I 2018-02-27 16:18:08.108 JupyterHub log:124] 200 POST /jupyterhub/hub/api/oauth2/token (@172.18.0.1) 40.60ms jupyterhub | [I 2018-02-27 16:18:08.134 JupyterHub log:124] 302 GET /jupyterhub/hub/api/user -> /jupyterhub/hub/login?next=%2Fjupyterhub%2Fhub%2Fapi%2Fuser (@172.18.0.1) 4.79ms jupyterhub | [I 2018-02-27 16:18:08.143 JupyterHub log:124] 302 GET /jupyterhub/hub/login?next=%2Fjupyterhub%2Fhub%2Fapi%2Fuser -> /jupyterhub/hub/lti/launch?next=%2Fjupyterhub%2Fhub%2Fapi%2Fuser (@172.18.0.1) 2.19ms jupyterhub | [W 2018-02-27 16:18:08.205 JupyterHub log:124] 405 GET /jupyterhub/hub/lti/launch?next=%2Fjupyterhub%2Fhub%2Fapi%2Fuser (@172.18.0.1) 53.75ms ``` Am I missing something ?
Can you show how you are making the `/api/user` requests?
2018-02-28T13:23:35Z
[]
[]
jupyterhub/jupyterhub
1,696
jupyterhub__jupyterhub-1696
[ "1118" ]
7a1fa786327759bb40e2b4c6679e5975faad8be3
diff --git a/jupyterhub/apihandlers/auth.py b/jupyterhub/apihandlers/auth.py --- a/jupyterhub/apihandlers/auth.py +++ b/jupyterhub/apihandlers/auth.py @@ -38,15 +38,14 @@ def get(self, token): self.db.commit() self.write(json.dumps(model)) - @gen.coroutine - def post(self): + async def post(self): requester = user = self.get_current_user() if user is None: # allow requesting a token with username and password # for authenticators where that's possible data = self.get_json_body() try: - requester = user = yield self.login_user(data) + requester = user = await self.login_user(data) except Exception as e: self.log.error("Failure trying to authenticate with form data: %s" % e) user = None diff --git a/jupyterhub/apihandlers/groups.py b/jupyterhub/apihandlers/groups.py --- a/jupyterhub/apihandlers/groups.py +++ b/jupyterhub/apihandlers/groups.py @@ -51,8 +51,7 @@ def get(self, name): self.write(json.dumps(self.group_model(group))) @admin_only - @gen.coroutine - def post(self, name): + async def post(self, name): """POST creates a group by name""" model = self.get_json_body() if model is None: @@ -109,9 +108,8 @@ def post(self, name): self.db.commit() self.write(json.dumps(self.group_model(group))) - @gen.coroutine @admin_only - def delete(self, name): + async def delete(self, name): """DELETE removes users from a group""" group = self.find_group(name) data = self.get_json_body() diff --git a/jupyterhub/apihandlers/proxy.py b/jupyterhub/apihandlers/proxy.py --- a/jupyterhub/apihandlers/proxy.py +++ b/jupyterhub/apihandlers/proxy.py @@ -14,52 +14,48 @@ class ProxyAPIHandler(APIHandler): - + @admin_only - @gen.coroutine - def get(self): + async def get(self): """GET /api/proxy fetches the routing table This is the same as fetching the routing table directly from the proxy, but without clients needing to maintain separate """ - routes = yield self.proxy.get_all_routes() + routes = await self.proxy.get_all_routes() self.write(json.dumps(routes)) @admin_only - @gen.coroutine - def post(self): + async def post(self): """POST checks the proxy to ensure that it's up to date. Can be used to jumpstart a newly launched proxy without waiting for the check_routes interval. """ - yield self.proxy.check_routes(self.users, self.services) - + await self.proxy.check_routes(self.users, self.services) + @admin_only - @gen.coroutine - def patch(self): + async def patch(self): """PATCH updates the location of the proxy - + Can be used to notify the Hub that a new proxy is in charge """ if not self.request.body: raise web.HTTPError(400, "need JSON body") - + try: model = json.loads(self.request.body.decode('utf8', 'replace')) except ValueError: raise web.HTTPError(400, "Request body must be JSON dict") if not isinstance(model, dict): raise web.HTTPError(400, "Request body must be JSON dict") - + if 'api_url' in model: self.proxy.api_url = model['api_url'] if 'auth_token' in model: self.proxy.auth_token = model['auth_token'] self.log.info("Updated proxy at %s", self.proxy) - yield self.proxy.check_routes(self.users, self.services) - + await self.proxy.check_routes(self.users, self.services) default_handlers = [ diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -8,13 +8,13 @@ from tornado import gen, web from .. import orm -from ..utils import admin_only +from ..utils import admin_only, maybe_future from .base import APIHandler class SelfAPIHandler(APIHandler): """Return the authenticated user's model - + Based on the authentication info. Acts as a 'whoami' for auth tokens. """ @web.authenticated @@ -33,14 +33,13 @@ class UserListAPIHandler(APIHandler): def get(self): data = [ self.user_model(u) for u in self.db.query(orm.User) ] self.write(json.dumps(data)) - + @admin_only - @gen.coroutine - def post(self): + async def post(self): data = self.get_json_body() if not data or not isinstance(data, dict) or not data.get('usernames'): raise web.HTTPError(400, "Must specify at least one user to create") - + usernames = data.pop('usernames') self._check_user_model(data) # admin is set for all users @@ -59,17 +58,17 @@ def post(self): self.log.warning("User %s already exists" % name) else: to_create.append(name) - + if invalid_names: if len(invalid_names) == 1: msg = "Invalid username: %s" % invalid_names[0] else: msg = "Invalid usernames: %s" % ', '.join(invalid_names) raise web.HTTPError(400, msg) - + if not to_create: raise web.HTTPError(400, "All %i users already exist" % len(usernames)) - + created = [] for name in to_create: user = self.user_from_username(name) @@ -77,14 +76,14 @@ def post(self): user.admin = True self.db.commit() try: - yield gen.maybe_future(self.authenticator.add_user(user)) + await maybe_future(self.authenticator.add_user(user)) except Exception as e: self.log.error("Failed to create user: %s" % name, exc_info=True) self.users.delete(user) raise web.HTTPError(400, "Failed to create user %s: %s" % (name, str(e))) else: created.append(user) - + self.write(json.dumps([ self.user_model(u) for u in created ])) self.set_status(201) @@ -105,29 +104,28 @@ def m(self, name, *args, **kwargs): return m class UserAPIHandler(APIHandler): - + @admin_or_self def get(self, name): user = self.find_user(name) self.write(json.dumps(self.user_model(user))) - + @admin_only - @gen.coroutine - def post(self, name): + async def post(self, name): data = self.get_json_body() user = self.find_user(name) if user is not None: raise web.HTTPError(400, "User %s already exists" % name) - + user = self.user_from_username(name) if data: self._check_user_model(data) if 'admin' in data: user.admin = data['admin'] self.db.commit() - + try: - yield gen.maybe_future(self.authenticator.add_user(user)) + await maybe_future(self.authenticator.add_user(user)) except Exception: self.log.error("Failed to create user: %s" % name, exc_info=True) # remove from registry @@ -138,8 +136,7 @@ def post(self, name): self.set_status(201) @admin_only - @gen.coroutine - def delete(self, name): + async def delete(self, name): user = self.find_user(name) if user is None: raise web.HTTPError(404) @@ -148,11 +145,11 @@ def delete(self, name): if user.spawner._stop_pending: raise web.HTTPError(400, "%s's server is in the process of stopping, please wait." % name) if user.running: - yield self.stop_single_user(user) + await self.stop_single_user(user) if user.spawner._stop_pending: raise web.HTTPError(400, "%s's server is in the process of stopping, please wait." % name) - yield gen.maybe_future(self.authenticator.delete_user(user)) + await maybe_future(self.authenticator.delete_user(user)) # remove from registry self.users.delete(user) @@ -178,9 +175,8 @@ def patch(self, name): class UserServerAPIHandler(APIHandler): """Start and stop single-user servers""" - @gen.coroutine @admin_or_self - def post(self, name, server_name=''): + async def post(self, name, server_name=''): user = self.find_user(name) if server_name and not self.allow_named_servers: raise web.HTTPError(400, "Named servers are not enabled.") @@ -198,21 +194,20 @@ def post(self, name, server_name=''): # set _spawn_pending flag to prevent races while we wait spawner._spawn_pending = True try: - state = yield spawner.poll_and_notify() + state = await spawner.poll_and_notify() finally: spawner._spawn_pending = False if state is None: raise web.HTTPError(400, "%s is already running" % spawner._log_name) options = self.get_json_body() - yield self.spawn_single_user(user, server_name, options=options) + await self.spawn_single_user(user, server_name, options=options) status = 202 if spawner.pending == 'spawn' else 201 self.set_header('Content-Type', 'text/plain') self.set_status(status) - @gen.coroutine @admin_or_self - def delete(self, name, server_name=''): + async def delete(self, name, server_name=''): user = self.find_user(name) if server_name: if not self.allow_named_servers: @@ -233,10 +228,10 @@ def delete(self, name, server_name=''): (spawner._log_name, '(pending: %s)' % spawner.pending if spawner.pending else '') ) # include notify, so that a server that died is noticed immediately - status = yield spawner.poll_and_notify() + status = await spawner.poll_and_notify() if status is not None: raise web.HTTPError(400, "%s is not running" % spawner._log_name) - yield self.stop_single_user(user, server_name) + await self.stop_single_user(user, server_name) status = 202 if spawner._stop_pending else 204 self.set_header('Content-Type', 'text/plain') self.set_status(status) @@ -244,7 +239,7 @@ def delete(self, name, server_name=''): class UserAdminAccessAPIHandler(APIHandler): """Grant admins access to single-user servers - + This handler sets the necessary cookie for an admin to login to a single-user server. """ @admin_only diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -4,8 +4,10 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. +import asyncio import atexit import binascii +from concurrent.futures import ThreadPoolExecutor from datetime import datetime from getpass import getuser import logging @@ -55,6 +57,7 @@ from .proxy import Proxy, ConfigurableHTTPProxy from .traitlets import URLPrefix, Command from .utils import ( + maybe_future, url_path_join, ISO8601_ms, ISO8601_s, print_stacks, print_ps_info, @@ -149,7 +152,10 @@ def start(self): hub = JupyterHub(parent=self) hub.load_config_file(hub.config_file) hub.init_db() - hub.init_users() + def init_users(): + loop = asyncio.new_event_loop() + loop.run_until_complete(hub.init_users()) + ThreadPoolExecutor(1).submit(init_users).result() user = orm.User.find(hub.db, self.name) if user is None: print("No such user: %s" % self.name, file=sys.stderr) @@ -558,7 +564,9 @@ def _deprecate_api_tokens(self, change): - constructor takes one kwarg: `config`, the IPython config object. - - is a tornado.gen.coroutine + with an authenticate method that: + + - is a coroutine (asyncio or tornado) - returns username on success, None on failure - takes two arguments: (handler, data), where `handler` is the calling web.RequestHandler, @@ -968,8 +976,7 @@ def init_hub(self): if self.hub_connect_port: self.hub.connect_port = self.hub_connect_port - @gen.coroutine - def init_users(self): + async def init_users(self): """Load users into and from the database""" db = self.db @@ -1045,7 +1052,7 @@ def init_users(self): # and persist across sessions. for user in db.query(orm.User): try: - yield gen.maybe_future(self.authenticator.add_user(user)) + await maybe_future(self.authenticator.add_user(user)) except Exception: self.log.exception("Error adding user %s already in db", user.name) if self.authenticator.delete_invalid_users: @@ -1066,8 +1073,7 @@ def init_users(self): # From this point on, any user changes should be done simultaneously # to the whitelist set and user db, unless the whitelist is empty (all users allowed). - @gen.coroutine - def init_groups(self): + async def init_groups(self): """Load predefined groups into the database""" db = self.db for name, usernames in self.load_groups.items(): @@ -1077,7 +1083,7 @@ def init_groups(self): db.add(group) for username in usernames: username = self.authenticator.normalize_username(username) - if not (yield gen.maybe_future(self.authenticator.check_whitelist(username))): + if not (await maybe_future(self.authenticator.check_whitelist(username))): raise ValueError("Username %r is not in whitelist" % username) user = orm.User.find(db, name=username) if user is None: @@ -1088,8 +1094,7 @@ def init_groups(self): group.users.append(user) db.commit() - @gen.coroutine - def _add_tokens(self, token_dict, kind): + async def _add_tokens(self, token_dict, kind): """Add tokens for users or services to the database""" if kind == 'user': Class = orm.User @@ -1102,7 +1107,7 @@ def _add_tokens(self, token_dict, kind): for token, name in token_dict.items(): if kind == 'user': name = self.authenticator.normalize_username(name) - if not (yield gen.maybe_future(self.authenticator.check_whitelist(name))): + if not (await maybe_future(self.authenticator.check_whitelist(name))): raise ValueError("Token name %r is not in whitelist" % name) if not self.authenticator.validate_username(name): raise ValueError("Token name %r is not valid" % name) @@ -1131,11 +1136,10 @@ def _add_tokens(self, token_dict, kind): self.log.debug("Not duplicating token %s", orm_token) db.commit() - @gen.coroutine - def init_api_tokens(self): + async def init_api_tokens(self): """Load predefined API tokens (for services) into database""" - yield self._add_tokens(self.service_tokens, kind='service') - yield self._add_tokens(self.api_tokens, kind='user') + await self._add_tokens(self.service_tokens, kind='service') + await self._add_tokens(self.api_tokens, kind='user') def init_services(self): self._service_map.clear() @@ -1217,21 +1221,19 @@ def init_services(self): self.db.delete(service) self.db.commit() - @gen.coroutine - def check_services_health(self): + async def check_services_health(self): """Check connectivity of all services""" for name, service in self._service_map.items(): if not service.url: continue try: - yield Server.from_orm(service.orm.server).wait_up(timeout=1) + await Server.from_orm(service.orm.server).wait_up(timeout=1) except TimeoutError: self.log.warning("Cannot connect to %s service %s at %s", service.kind, name, service.url) else: self.log.debug("%s service %s running at %s", service.kind.title(), name, service.url) - @gen.coroutine - def init_spawners(self): + async def init_spawners(self): db = self.db def _user_summary(user): @@ -1244,22 +1246,20 @@ def _user_summary(user): parts.append('%s:%s running at %s' % (user.name, name, spawner.server)) return ' '.join(parts) - @gen.coroutine - def user_stopped(user, server_name): + async def user_stopped(user, server_name): spawner = user.spawners[server_name] - status = yield spawner.poll() + status = await spawner.poll() self.log.warning("User %s server stopped with exit code: %s", user.name, status, ) - yield self.proxy.delete_user(user, server_name) - yield user.stop(server_name) + await self.proxy.delete_user(user, server_name) + await user.stop(server_name) - @gen.coroutine - def check_spawner(user, name, spawner): + async def check_spawner(user, name, spawner): status = 0 if spawner.server: try: - status = yield spawner.poll() + status = await spawner.poll() except Exception: self.log.exception("Failed to poll spawner for %s, assuming the spawner is not running.", spawner._log_name) @@ -1291,11 +1291,11 @@ def check_spawner(user, name, spawner): # spawner should be running # instantiate Spawner wrapper and check if it's still alive spawner = user.spawners[name] - f = check_spawner(user, name, spawner) + f = asyncio.ensure_future(check_spawner(user, name, spawner)) check_futures.append(f) # await checks after submitting them all - yield gen.multi(check_futures) + await gen.multi(check_futures) db.commit() # only perform this query if we are going to log it @@ -1439,9 +1439,8 @@ def write_pid_file(self): with open(self.pid_file, 'w') as f: f.write('%i' % pid) - @gen.coroutine @catch_config_error - def initialize(self, *args, **kwargs): + async def initialize(self, *args, **kwargs): super().initialize(*args, **kwargs) if self.generate_config or self.subapp: return @@ -1464,18 +1463,17 @@ def initialize(self, *args, **kwargs): self.init_hub() self.init_proxy() self.init_oauth() - yield self.init_users() - yield self.init_groups() + await self.init_users() + await self.init_groups() self.init_services() - yield self.init_api_tokens() + await self.init_api_tokens() self.init_tornado_settings() - yield self.init_spawners() + await self.init_spawners() self.cleanup_oauth_clients() self.init_handlers() self.init_tornado_application() - @gen.coroutine - def cleanup(self): + async def cleanup(self): """Shutdown managed services and various subprocesses. Cleanup runtime files.""" futures = [] @@ -1484,7 +1482,7 @@ def cleanup(self): if managed_services: self.log.info("Cleaning up %i services...", len(managed_services)) for service in managed_services: - futures.append(service.stop()) + futures.append(asyncio.ensure_future(service.stop())) if self.cleanup_servers: self.log.info("Cleaning up single-user servers...") @@ -1492,14 +1490,14 @@ def cleanup(self): for uid, user in self.users.items(): for name, spawner in list(user.spawners.items()): if spawner.active: - futures.append(user.stop(name)) + futures.append(asyncio.ensure_future(user.stop(name))) else: self.log.info("Leaving single-user servers running") # clean up proxy while single-user servers are shutting down if self.cleanup_proxy: if self.proxy.should_start: - yield gen.maybe_future(self.proxy.stop()) + await maybe_future(self.proxy.stop()) else: self.log.info("I didn't start the proxy, I can't clean it up") else: @@ -1508,7 +1506,7 @@ def cleanup(self): # wait for the requests to stop finish: for f in futures: try: - yield f + await f except Exception as e: self.log.error("Failed to stop user: %s", e) @@ -1552,10 +1550,9 @@ def ask(): with open(self.config_file, mode='w') as f: f.write(config_text) - @gen.coroutine - def update_last_activity(self): + async def update_last_activity(self): """Update User.last_activity timestamps from the proxy""" - routes = yield self.proxy.get_all_routes() + routes = await self.proxy.get_all_routes() users_count = 0 active_users_count = 0 now = datetime.utcnow() @@ -1591,10 +1588,9 @@ def update_last_activity(self): self.statsd.gauge('users.active', active_users_count) self.db.commit() - yield self.proxy.check_routes(self.users, self._service_map, routes) + await self.proxy.check_routes(self.users, self._service_map, routes) - @gen.coroutine - def start(self): + async def start(self): """Start the whole thing""" self.io_loop = loop = IOLoop.current() @@ -1621,7 +1617,7 @@ def start(self): # start the proxy if self.proxy.should_start: try: - yield self.proxy.start() + await self.proxy.start() except Exception as e: self.log.critical("Failed to start proxy", exc_info=True) self.exit(1) @@ -1645,10 +1641,10 @@ def start(self): tries = 10 if service.managed else 1 for i in range(tries): try: - yield Server.from_orm(service.orm.server).wait_up(http=True, timeout=1) + await Server.from_orm(service.orm.server).wait_up(http=True, timeout=1) except TimeoutError: if service.managed: - status = yield service.spawner.poll() + status = await service.spawner.poll() if status is not None: self.log.error("Service %s exited with status %s", service_name, status) break @@ -1657,7 +1653,7 @@ def start(self): else: self.log.error("Cannot connect to %s service %s at %s. Is it running?", service.kind, service_name, service.url) - yield self.proxy.check_routes(self.users, self._service_map) + await self.proxy.check_routes(self.users, self._service_map) if self.service_check_interval and any(s.url for s in self._service_map.values()): @@ -1710,11 +1706,10 @@ def stop(self): self.http_server.stop() self.io_loop.add_callback(self.io_loop.stop) - @gen.coroutine - def launch_instance_async(self, argv=None): + async def launch_instance_async(self, argv=None): try: - yield self.initialize(argv) - yield self.start() + await self.initialize(argv) + await self.start() except Exception as e: self.log.exception("") self.exit(1) diff --git a/jupyterhub/auth.py b/jupyterhub/auth.py --- a/jupyterhub/auth.py +++ b/jupyterhub/auth.py @@ -23,11 +23,10 @@ from traitlets import Bool, Set, Unicode, Dict, Any, default, observe from .handlers.login import LoginHandler -from .utils import url_path_join +from .utils import maybe_future, url_path_join from .traitlets import Command - def getgrnam(name): """Wrapper function to protect against `grp` not being available on Windows @@ -206,8 +205,7 @@ def check_whitelist(self, username): return True return username in self.whitelist - @gen.coroutine - def get_authenticated_user(self, handler, data): + async def get_authenticated_user(self, handler, data): """Authenticate the user who is attempting to log in Returns user dict if successful, None otherwise. @@ -223,11 +221,11 @@ def get_authenticated_user(self, handler, data): - `authenticate` turns formdata into a username - `normalize_username` normalizes the username - `check_whitelist` checks against the user whitelist - + .. versionchanged:: 0.8 return dict instead of username """ - authenticated = yield self.authenticate(handler, data) + authenticated = await self.authenticate(handler, data) if authenticated is None: return if isinstance(authenticated, dict): @@ -246,15 +244,14 @@ def get_authenticated_user(self, handler, data): self.log.warning("Disallowing invalid username %r.", username) return - whitelist_pass = yield gen.maybe_future(self.check_whitelist(username)) + whitelist_pass = await maybe_future(self.check_whitelist(username)) if whitelist_pass: return authenticated else: self.log.warning("User %r not in whitelist.", username) return - @gen.coroutine - def authenticate(self, handler, data): + async def authenticate(self, handler, data): """Authenticate a user with login form data This must be a tornado gen.coroutine. @@ -479,20 +476,19 @@ def check_group_whitelist(self, username): return True return False - @gen.coroutine - def add_user(self, user): + async def add_user(self, user): """Hook called whenever a new user is added If self.create_system_users, the user will attempt to be created if it doesn't exist. """ - user_exists = yield gen.maybe_future(self.system_user_exists(user)) + user_exists = await maybe_future(self.system_user_exists(user)) if not user_exists: if self.create_system_users: - yield gen.maybe_future(self.add_system_user(user)) + await maybe_future(self.add_system_user(user)) else: raise KeyError("User %s does not exist." % user.name) - yield gen.maybe_future(super().add_user(user)) + await maybe_future(super().add_user(user)) @staticmethod def system_user_exists(user): diff --git a/jupyterhub/crypto.py b/jupyterhub/crypto.py --- a/jupyterhub/crypto.py +++ b/jupyterhub/crypto.py @@ -19,6 +19,7 @@ class InvalidToken(Exception): pass +from .utils import maybe_future KEY_ENV = 'JUPYTERHUB_CRYPT_KEY' @@ -104,7 +105,7 @@ def _keys_default(self): def _ensure_bytes(self, proposal): # cast str to bytes return [ _validate_key(key) for key in proposal.value ] - + fernet = Any() def _fernet_default(self): if cryptography is None or not self.keys: @@ -123,7 +124,7 @@ def check_available(self): def _encrypt(self, data): """Actually do the encryption. Runs in a background thread. - + data is serialized to bytes with pickle. bytes are returned. """ @@ -132,7 +133,7 @@ def _encrypt(self, data): def encrypt(self, data): """Encrypt an object with cryptography""" self.check_available() - return self.executor.submit(self._encrypt, data) + return maybe_future(self.executor.submit(self._encrypt, data)) def _decrypt(self, encrypted): decrypted = self.fernet.decrypt(encrypted) @@ -141,12 +142,12 @@ def _decrypt(self, encrypted): def decrypt(self, encrypted): """Decrypt an object with cryptography""" self.check_available() - return self.executor.submit(self._decrypt, encrypted) + return maybe_future(self.executor.submit(self._decrypt, encrypted)) def encrypt(data): """encrypt some data with the crypt keeper. - + data will be serialized with pickle. Returns a Future whose result will be bytes. """ @@ -158,4 +159,3 @@ def decrypt(data): Returns a Future whose result will be the decrypted, deserialized data. """ return CryptKeeper.instance().decrypt(data) - \ No newline at end of file diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -23,7 +23,7 @@ from .. import orm from ..objects import Server from ..spawner import LocalProcessSpawner -from ..utils import url_path_join +from ..utils import maybe_future, url_path_join from ..metrics import ( SERVER_SPAWN_DURATION_SECONDS, ServerSpawnStatus, PROXY_ADD_DURATION_SECONDS, ProxyAddStatus @@ -387,11 +387,11 @@ def set_login_cookie(self, user): self.set_hub_cookie(user) def authenticate(self, data): - return gen.maybe_future(self.authenticator.get_authenticated_user(self, data)) + return maybe_future(self.authenticator.get_authenticated_user(self, data)) def get_next_url(self, user=None): """Get the next_url for login redirect - + Defaults to hub base_url /hub/ if user is not running, otherwise user.url. """ @@ -408,11 +408,10 @@ def get_next_url(self, user=None): next_url = self.hub.base_url return next_url - @gen.coroutine - def login_user(self, data=None): + async def login_user(self, data=None): """Login a user""" auth_timer = self.statsd.timer('login.authenticate').start() - authenticated = yield self.authenticate(data) + authenticated = await self.authenticate(data) auth_timer.stop(send=False) if authenticated: @@ -422,7 +421,7 @@ def login_user(self, data=None): new_user = username not in self.users user = self.user_from_username(username) if new_user: - yield gen.maybe_future(self.authenticator.add_user(user)) + await maybe_future(self.authenticator.add_user(user)) # Only set `admin` if the authenticator returned an explicit value. if admin is not None and admin != user.admin: user.admin = admin @@ -433,7 +432,7 @@ def login_user(self, data=None): if not self.authenticator.enable_auth_state: # auth_state is not enabled. Force None. auth_state = None - yield user.save_auth_state(auth_state) + await user.save_auth_state(auth_state) self.db.commit() self.set_login_cookie(user) self.statsd.incr('login.success') @@ -470,8 +469,7 @@ def concurrent_spawn_limit(self): def active_server_limit(self): return self.settings.get('active_server_limit', 0) - @gen.coroutine - def spawn_single_user(self, user, server_name='', options=None): + async def spawn_single_user(self, user, server_name='', options=None): # in case of error, include 'try again from /hub/home' message spawn_start_time = time.perf_counter() self.extra_error_html = self.spawn_home_error @@ -539,15 +537,14 @@ def spawn_single_user(self, user, server_name='', options=None): # while we are waiting for _proxy_pending to be set spawner._spawn_pending = True - @gen.coroutine - def finish_user_spawn(): + async def finish_user_spawn(): """Finish the user spawn by registering listeners and notifying the proxy. If the spawner is slow to start, this is passed as an async callback, otherwise it is called immediately. """ # wait for spawn Future - yield spawn_future + await spawn_future toc = IOLoop.current().time() self.log.info("User %s took %.3f seconds to start", user_server_name, toc-tic) self.statsd.timing('spawner.success', (toc - tic) * 1000) @@ -557,7 +554,7 @@ def finish_user_spawn(): proxy_add_start_time = time.perf_counter() spawner._proxy_pending = True try: - yield self.proxy.add_user(user, server_name) + await self.proxy.add_user(user, server_name) PROXY_ADD_DURATION_SECONDS.labels( status='success' @@ -567,7 +564,7 @@ def finish_user_spawn(): except Exception: self.log.exception("Failed to add %s to proxy!", user_server_name) self.log.error("Stopping %s to avoid inconsistent state", user_server_name) - yield user.stop() + await user.stop() PROXY_ADD_DURATION_SECONDS.labels( status='failure' ).observe( @@ -580,7 +577,7 @@ def finish_user_spawn(): # hook up spawner._spawn_future so that other requests can await # this result - finish_spawn_future = spawner._spawn_future = finish_user_spawn() + finish_spawn_future = spawner._spawn_future = maybe_future(finish_user_spawn()) def _clear_spawn_future(f): # clear spawner._spawn_future when it's done # keep an exception around, though, to prevent repeated implicit spawns @@ -592,7 +589,7 @@ def _clear_spawn_future(f): finish_spawn_future.add_done_callback(_clear_spawn_future) try: - yield gen.with_timeout(timedelta(seconds=self.slow_spawn_timeout), finish_spawn_future) + await gen.with_timeout(timedelta(seconds=self.slow_spawn_timeout), finish_spawn_future) except gen.TimeoutError: # waiting_for_response indicates server process has started, # but is yet to become responsive. @@ -605,7 +602,7 @@ def _clear_spawn_future(f): # start has finished, but the server hasn't come up # check if the server died while we were waiting - status = yield spawner.poll() + status = await spawner.poll() if status is not None: toc = IOLoop.current().time() self.statsd.timing('spawner.failure', (toc - tic) * 1000) @@ -629,21 +626,19 @@ def _clear_spawn_future(f): self.log.warning("User %s is slow to be added to the proxy (timeout=%s)", user_server_name, self.slow_spawn_timeout) - @gen.coroutine - def user_stopped(self, user, server_name): + async def user_stopped(self, user, server_name): """Callback that fires when the spawner has stopped""" spawner = user.spawners[server_name] - status = yield spawner.poll() + status = await spawner.poll() if status is None: status = 'unknown' self.log.warning("User %s server stopped, with exit code: %s", user.name, status, ) - yield self.proxy.delete_user(user, server_name) - yield user.stop(server_name) + await self.proxy.delete_user(user, server_name) + await user.stop(server_name) - @gen.coroutine - def stop_single_user(self, user, name=''): + async def stop_single_user(self, user, name=''): if name not in user.spawners: raise KeyError("User %s has no such spawner %r", user.name, name) spawner = user.spawners[name] @@ -653,8 +648,7 @@ def stop_single_user(self, user, name=''): # to avoid races spawner._stop_pending = True - @gen.coroutine - def stop(): + async def stop(): """Stop the server 1. remove it from the proxy @@ -663,8 +657,8 @@ def stop(): """ tic = IOLoop.current().time() try: - yield self.proxy.delete_user(user, name) - yield user.stop(name) + await self.proxy.delete_user(user, name) + await user.stop(name) finally: spawner._stop_pending = False toc = IOLoop.current().time() @@ -672,7 +666,7 @@ def stop(): self.statsd.timing('spawner.stop', (toc - tic) * 1000) try: - yield gen.with_timeout(timedelta(seconds=self.slow_stop_timeout), stop()) + await gen.with_timeout(timedelta(seconds=self.slow_stop_timeout), stop()) except gen.TimeoutError: if spawner._stop_pending: # hit timeout, but stop is still pending @@ -793,8 +787,7 @@ class UserSpawnHandler(BaseHandler): which will in turn send her to /user/alice/notebooks/mynotebook.ipynb. """ - @gen.coroutine - def get(self, name, user_path): + async def get(self, name, user_path): if not user_path: user_path = '/' current_user = self.get_current_user() @@ -864,7 +857,7 @@ def get(self, name, user_path): # wait on the pending spawn self.log.debug("Waiting for %s pending %s", spawner._log_name, spawner.pending) try: - yield gen.with_timeout(timedelta(seconds=self.slow_spawn_timeout), spawner._spawn_future) + await gen.with_timeout(timedelta(seconds=self.slow_spawn_timeout), spawner._spawn_future) except gen.TimeoutError: self.log.info("Pending spawn for %s didn't finish in %.1f seconds", spawner._log_name, self.slow_spawn_timeout) pass @@ -880,7 +873,7 @@ def get(self, name, user_path): # spawn has supposedly finished, check on the status if spawner.ready: - status = yield spawner.poll() + status = await spawner.poll() else: status = 0 @@ -895,7 +888,7 @@ def get(self, name, user_path): {'next': self.request.uri})) return else: - yield self.spawn_single_user(user) + await self.spawn_single_user(user) # spawn didn't finish, show pending page if spawner.pending: @@ -942,7 +935,7 @@ def get(self, name, user_path): if redirects: self.log.warning("Redirect loop detected on %s", self.request.uri) # add capped exponential backoff where cap is 10s - yield gen.sleep(min(1 * (2 ** redirects), 10)) + await gen.sleep(min(1 * (2 ** redirects), 10)) # rewrite target url with new `redirects` query value url_parts = urlparse(target) query_parts = parse_qs(url_parts.query) diff --git a/jupyterhub/handlers/login.py b/jupyterhub/handlers/login.py --- a/jupyterhub/handlers/login.py +++ b/jupyterhub/handlers/login.py @@ -42,8 +42,7 @@ def _render(self, login_error=None, username=None): ), ) - @gen.coroutine - def get(self): + async def get(self): self.statsd.incr('login.request') user = self.get_current_user() if user: @@ -58,7 +57,7 @@ def get(self): # auto_login without a custom login handler # means that auth info is already in the request # (e.g. REMOTE_USER header) - user = yield self.login_user() + user = await self.login_user() if user is None: # auto_login failed, just 403 raise web.HTTPError(403) @@ -72,26 +71,25 @@ def get(self): username = self.get_argument('username', default='') self.finish(self._render(username=username)) - @gen.coroutine - def post(self): + async def post(self): # parse the arguments dict data = {} for arg in self.request.arguments: data[arg] = self.get_argument(arg, strip=False) auth_timer = self.statsd.timer('login.authenticate').start() - user = yield self.login_user(data) + user = await self.login_user(data) auth_timer.stop(send=False) if user: already_running = False if user.spawner.ready: - status = yield user.spawner.poll() + status = await user.spawner.poll() already_running = (status is None) if not already_running and not user.spawner.options_form \ and not user.spawner.pending: # logging in triggers spawn - yield self.spawn_single_user(user) + await self.spawn_single_user(user) self.redirect(self.get_next_url()) else: html = self._render( diff --git a/jupyterhub/handlers/metrics.py b/jupyterhub/handlers/metrics.py --- a/jupyterhub/handlers/metrics.py +++ b/jupyterhub/handlers/metrics.py @@ -7,8 +7,7 @@ class MetricsHandler(BaseHandler): """ Handler to serve Prometheus metrics """ - @gen.coroutine - def get(self): + async def get(self): self.set_header('Content-Type', CONTENT_TYPE_LATEST) self.write(generate_latest(REGISTRY)) diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -62,12 +62,11 @@ class HomeHandler(BaseHandler): """Render the user's home page.""" @web.authenticated - @gen.coroutine - def get(self): + async def get(self): user = self.get_current_user() if user.running: # trigger poll_and_notify event in case of a server that died - yield user.spawner.poll_and_notify() + await user.spawner.poll_and_notify() # send the user to /spawn if they aren't running or pending a spawn, # to establish that this is an explicit spawn request rather @@ -87,10 +86,9 @@ class SpawnHandler(BaseHandler): Only enabled when Spawner.options_form is defined. """ - @gen.coroutine - def _render_form(self, message='', for_user=None): + async def _render_form(self, message='', for_user=None): user = for_user or self.get_current_user() - spawner_options_form = yield user.spawner.get_options_form() + spawner_options_form = await user.spawner.get_options_form() return self.render_template('spawn.html', for_user=for_user, spawner_options_form=spawner_options_form, @@ -99,8 +97,7 @@ def _render_form(self, message='', for_user=None): ) @web.authenticated - @gen.coroutine - def get(self, for_user=None): + async def get(self, for_user=None): """GET renders form for spawning with user-specified options or triggers spawn via redirect if there is no form. @@ -120,7 +117,7 @@ def get(self, for_user=None): self.redirect(url) return if user.spawner.options_form: - form = yield self._render_form(for_user=user) + form = await self._render_form(for_user=user) self.finish(form) else: # Explicit spawn request: clear _spawn_future @@ -132,8 +129,7 @@ def get(self, for_user=None): self.redirect(user.url) @web.authenticated - @gen.coroutine - def post(self, for_user=None): + async def post(self, for_user=None): """POST spawns with user-specified options""" user = current_user = self.get_current_user() if for_user is not None and for_user != user.name: @@ -158,10 +154,10 @@ def post(self, for_user=None): form_options["%s_file"%key] = byte_list try: options = user.spawner.options_from_form(form_options) - yield self.spawn_single_user(user, options=options) + await self.spawn_single_user(user, options=options) except Exception as e: self.log.error("Failed to spawn single-user server with form", exc_info=True) - form = yield self._render_form(message=str(e), for_usr=user) + form = await self._render_form(message=str(e), for_user=user) self.finish(form) return if current_user is user: diff --git a/jupyterhub/proxy.py b/jupyterhub/proxy.py --- a/jupyterhub/proxy.py +++ b/jupyterhub/proxy.py @@ -99,13 +99,13 @@ def stop(self): Will be called during teardown if should_start is True. - **Subclasses must define this method** + **Subclasses must define this method** if the proxy is to be started by the Hub """ - + def validate_routespec(self, routespec): """Validate a routespec - + - Checks host value vs host-based routing. - Ensures trailing slash on path. """ @@ -125,8 +125,7 @@ def validate_routespec(self, routespec): else: return routespec - @gen.coroutine - def add_route(self, routespec, target, data): + async def add_route(self, routespec, target, data): """Add a route to the proxy. **Subclasses must define this method** @@ -146,16 +145,14 @@ def add_route(self, routespec, target, data): """ pass - @gen.coroutine - def delete_route(self, routespec): + async def delete_route(self, routespec): """Delete a route with a given routespec if it exists. - + **Subclasses must define this method** """ pass - @gen.coroutine - def get_all_routes(self): + async def get_all_routes(self): """Fetch and return all the routes associated by JupyterHub from the proxy. @@ -172,8 +169,7 @@ def get_all_routes(self): """ pass - @gen.coroutine - def get_route(self, routespec): + async def get_route(self, routespec): """Return the route info for a given routespec. Args: @@ -184,7 +180,7 @@ def get_route(self, routespec): Returns: result (dict): dict with the following keys:: - + 'routespec': The normalized route specification passed in to add_route ([host]/path/) 'target': The target host for this route (proto://host) @@ -195,13 +191,12 @@ def get_route(self, routespec): """ # default implementation relies on get_all_routes routespec = self.validate_routespec(routespec) - routes = yield self.get_all_routes() + routes = await self.get_all_routes() return routes.get(routespec) # Most basic implementers must only implement above methods - @gen.coroutine - def add_service(self, service, client=None): + async def add_service(self, service, client=None): """Add a service's server to the proxy table.""" if not service.server: raise RuntimeError( @@ -211,20 +206,18 @@ def add_service(self, service, client=None): service.name, service.proxy_spec, service.server.host, ) - yield self.add_route( + await self.add_route( service.proxy_spec, service.server.host, {'service': service.name} ) - @gen.coroutine - def delete_service(self, service, client=None): + async def delete_service(self, service, client=None): """Remove a service's server from the proxy table.""" self.log.info("Removing service %s from proxy", service.name) - yield self.delete_route(service.proxy_spec) + await self.delete_route(service.proxy_spec) - @gen.coroutine - def add_user(self, user, server_name='', client=None): + async def add_user(self, user, server_name='', client=None): """Add a user's server to the proxy table.""" spawner = user.spawners[server_name] self.log.info("Adding user %s to proxy %s => %s", @@ -236,7 +229,7 @@ def add_user(self, user, server_name='', client=None): "%s is pending %s, shouldn't be added to the proxy yet!" % (spawner._log_name, spawner.pending) ) - yield self.add_route( + await self.add_route( spawner.proxy_spec, spawner.server.host, { @@ -245,17 +238,15 @@ def add_user(self, user, server_name='', client=None): } ) - @gen.coroutine - def delete_user(self, user, server_name=''): + async def delete_user(self, user, server_name=''): """Remove a user's server from the proxy table.""" routespec = user.proxy_spec if server_name: routespec = url_path_join(user.proxy_spec, server_name, '/') self.log.info("Removing user %s from proxy (%s)", user.name, routespec) - yield self.delete_route(routespec) + await self.delete_route(routespec) - @gen.coroutine - def add_all_services(self, service_dict): + async def add_all_services(self, service_dict): """Update the proxy table from the database. Used when loading up a new proxy. @@ -266,10 +257,9 @@ def add_all_services(self, service_dict): if service.server: futures.append(self.add_service(service)) # wait after submitting them all - yield gen.multi(futures) + await gen.multi(futures) - @gen.coroutine - def add_all_users(self, user_dict): + async def add_all_users(self, user_dict): """Update the proxy table from the database. Used when loading up a new proxy. @@ -281,13 +271,12 @@ def add_all_users(self, user_dict): if spawner.ready: futures.append(self.add_user(user, name)) # wait after submitting them all - yield gen.multi(futures) + await gen.multi(futures) - @gen.coroutine - def check_routes(self, user_dict, service_dict, routes=None): + async def check_routes(self, user_dict, service_dict, routes=None): """Check that all users are properly routed on the proxy.""" if not routes: - routes = yield self.get_all_routes() + routes = await self.get_all_routes() user_routes = {path for path, r in routes.items() if 'user' in r['data']} futures = [] @@ -352,19 +341,18 @@ def check_routes(self, user_dict, service_dict, routes=None): futures.append(self.delete_route(routespec)) for f in futures: - yield f + await f def add_hub_route(self, hub): """Add the default route for the Hub""" self.log.info("Adding default route for Hub: / => %s", hub.host) return self.add_route('/', self.hub.host, {'hub': True}) - @gen.coroutine - def restore_routes(self): + async def restore_routes(self): self.log.info("Setting up routes on new proxy") - yield self.add_hub_route(self.app.hub) - yield self.add_all_users(self.app.users) - yield self.add_all_services(self.app._service_map) + await self.add_hub_route(self.app.hub) + await self.add_all_users(self.app.users) + await self.add_all_services(self.app._service_map) self.log.info("New proxy back up and good to go") @@ -415,8 +403,7 @@ def _auth_token_default(self): _check_running_callback = Any(help="PeriodicCallback to check if the proxy is running") - @gen.coroutine - def start(self): + async def start(self): public_server = Server.from_url(self.public_url) api_server = Server.from_url(self.api_url) env = os.environ.copy() @@ -448,7 +435,7 @@ def start(self): " I hope there is SSL termination happening somewhere else...") self.log.info("Starting proxy @ %s", public_server.bind_url) self.log.debug("Proxy cmd: %s", cmd) - shell = os.name == 'nt' + shell = os.name == 'nt' try: self.proxy_process = Popen(cmd, env=env, start_new_session=True, shell=shell) except FileNotFoundError as e: @@ -472,12 +459,12 @@ def _check_process(): for i in range(10): _check_process() try: - yield server.wait_up(1) + await server.wait_up(1) except TimeoutError: continue else: break - yield server.wait_up(1) + await server.wait_up(1) _check_process() self.log.debug("Proxy started and appears to be up") pc = PeriodicCallback(self.check_running, 1e3 * self.check_running_interval) @@ -494,16 +481,15 @@ def stop(self): except Exception as e: self.log.error("Failed to terminate proxy process: %s", e) - @gen.coroutine - def check_running(self): + async def check_running(self): """Check if the proxy is still running""" if self.proxy_process.poll() is None: return self.log.error("Proxy stopped with exit code %r", 'unknown' if self.proxy_process is None else self.proxy_process.poll() ) - yield self.start() - yield self.restore_routes() + await self.start() + await self.restore_routes() def _routespec_to_chp_path(self, routespec): """Turn a routespec into a CHP API path @@ -521,7 +507,7 @@ def _routespec_to_chp_path(self, routespec): def _routespec_from_chp_path(self, chp_path): """Turn a CHP route into a route spec - + In the JSON API, CHP route keys are unescaped, so re-escape them to raw URLs and ensure slashes are in the right places. """ @@ -585,11 +571,10 @@ def _reformat_routespec(self, routespec, chp_data): 'target': target, 'data': chp_data, } - - @gen.coroutine - def get_all_routes(self, client=None): + + async def get_all_routes(self, client=None): """Fetch the proxy's routes.""" - resp = yield self.api_request('', client=client) + resp = await self.api_request('', client=client) chp_routes = json.loads(resp.body.decode('utf8', 'replace')) all_routes = {} for chp_path, chp_data in chp_routes.items(): diff --git a/jupyterhub/singleuser.py b/jupyterhub/singleuser.py --- a/jupyterhub/singleuser.py +++ b/jupyterhub/singleuser.py @@ -337,8 +337,7 @@ def _validate_static_custom_path(self, proposal): path = list(_exclude_home(path)) return path - @gen.coroutine - def check_hub_version(self): + async def check_hub_version(self): """Test a connection to my Hub - exit if I can't connect at all @@ -348,11 +347,11 @@ def check_hub_version(self): RETRIES = 5 for i in range(1, RETRIES+1): try: - resp = yield client.fetch(self.hub_api_url) + resp = await client.fetch(self.hub_api_url) except Exception: self.log.exception("Failed to connect to my Hub at %s (attempt %i/%i). Is it running?", self.hub_api_url, i, RETRIES) - yield gen.sleep(min(2**i, 16)) + await gen.sleep(min(2**i, 16)) else: break else: diff --git a/jupyterhub/spawner.py b/jupyterhub/spawner.py --- a/jupyterhub/spawner.py +++ b/jupyterhub/spawner.py @@ -28,7 +28,7 @@ from .objects import Server from .traitlets import Command, ByteSpecification, Callable -from .utils import random_port, url_path_join, exponential_backoff +from .utils import maybe_future, random_port, url_path_join, exponential_backoff class Spawner(LoggingConfigurable): @@ -258,8 +258,7 @@ def name(self): so using this functionality might cause your JupyterHub upgrades to break. """).tag(config=True) - @gen.coroutine - def get_options_form(self): + async def get_options_form(self): """Get the options form Returns: @@ -270,7 +269,7 @@ def get_options_form(self): Introduced. """ if callable(self.options_form): - options_form = yield gen.maybe_future(self.options_form(self)) + options_form = await maybe_future(self.options_form(self)) else: options_form = self.options_form @@ -687,8 +686,7 @@ def run_pre_spawn_hook(self): if self.pre_spawn_hook: return self.pre_spawn_hook(self) - @gen.coroutine - def start(self): + async def start(self): """Start the single-user server Returns: @@ -699,8 +697,7 @@ def start(self): """ raise NotImplementedError("Override in subclass. Must be a Tornado gen.coroutine.") - @gen.coroutine - def stop(self, now=False): + async def stop(self, now=False): """Stop the single-user server If `now` is False (default), shutdown the server as gracefully as possible, @@ -713,8 +710,7 @@ def stop(self, now=False): """ raise NotImplementedError("Override in subclass. Must be a Tornado gen.coroutine.") - @gen.coroutine - def poll(self): + async def poll(self): """Check if the single-user process is running Returns: @@ -773,10 +769,9 @@ def start_polling(self): ) self._poll_callback.start() - @gen.coroutine - def poll_and_notify(self): + async def poll_and_notify(self): """Used as a callback to periodically poll the process and notify any watchers""" - status = yield self.poll() + status = await self.poll() if status is None: # still running, nothing to do here return @@ -788,22 +783,20 @@ def poll_and_notify(self): for callback in callbacks: try: - yield gen.maybe_future(callback()) + await maybe_future(callback()) except Exception: self.log.exception("Unhandled error in poll callback for %s", self) return status death_interval = Float(0.1) - @gen.coroutine - def wait_for_death(self, timeout=10): + async def wait_for_death(self, timeout=10): """Wait for the single-user server to die, up to timeout seconds""" - @gen.coroutine - def _wait_for_death(): - status = yield self.poll() + async def _wait_for_death(): + status = await self.poll() return status is not None try: - r = yield exponential_backoff( + r = await exponential_backoff( _wait_for_death, 'Process did not die in {timeout} seconds'.format(timeout=timeout), start_wait=self.death_interval, @@ -1001,8 +994,7 @@ def get_env(self): env = self.user_env(env) return env - @gen.coroutine - def start(self): + async def start(self): """Start the single-user server.""" self.port = random_port() cmd = [] @@ -1048,8 +1040,7 @@ def start(self): self.server.port = self.port return (self.ip or '127.0.0.1', self.port) - @gen.coroutine - def poll(self): + async def poll(self): """Poll the spawned process to see if it is still running. If the process is still running, we return None. If it is not running, @@ -1072,15 +1063,14 @@ def poll(self): # send signal 0 to check if PID exists # this doesn't work on Windows, but that's okay because we don't support Windows. - alive = yield self._signal(0) + alive = await self._signal(0) if not alive: self.clear_state() return 0 else: return None - @gen.coroutine - def _signal(self, sig): + async def _signal(self, sig): """Send given signal to a single-user server's process. Returns True if the process still exists, False otherwise. @@ -1096,8 +1086,7 @@ def _signal(self, sig): raise return True # process exists - @gen.coroutine - def stop(self, now=False): + async def stop(self, now=False): """Stop the single-user server process for the current user. If `now` is False (default), shutdown the server as gracefully as possible, @@ -1107,30 +1096,30 @@ def stop(self, now=False): The coroutine should return when the process is no longer running. """ if not now: - status = yield self.poll() + status = await self.poll() if status is not None: return self.log.debug("Interrupting %i", self.pid) - yield self._signal(signal.SIGINT) - yield self.wait_for_death(self.interrupt_timeout) + await self._signal(signal.SIGINT) + await self.wait_for_death(self.interrupt_timeout) # clean shutdown failed, use TERM - status = yield self.poll() + status = await self.poll() if status is not None: return self.log.debug("Terminating %i", self.pid) - yield self._signal(signal.SIGTERM) - yield self.wait_for_death(self.term_timeout) + await self._signal(signal.SIGTERM) + await self.wait_for_death(self.term_timeout) # TERM failed, use KILL - status = yield self.poll() + status = await self.poll() if status is not None: return self.log.debug("Killing %i", self.pid) - yield self._signal(signal.SIGKILL) - yield self.wait_for_death(self.kill_timeout) + await self._signal(signal.SIGKILL) + await self.wait_for_death(self.kill_timeout) - status = yield self.poll() + status = await self.poll() if status is None: # it all failed, zombie process self.log.warning("Process %i never died", self.pid) diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -12,7 +12,7 @@ from tornado.log import app_log from traitlets import HasTraits, Any, Dict, default -from .utils import url_path_join +from .utils import maybe_future, url_path_join from . import orm from ._version import _check_version, __version__ @@ -157,23 +157,21 @@ def authenticator(self): def spawner_class(self): return self.settings.get('spawner_class', LocalProcessSpawner) - @gen.coroutine - def save_auth_state(self, auth_state): + async def save_auth_state(self, auth_state): """Encrypt and store auth_state""" if auth_state is None: self.encrypted_auth_state = None else: - self.encrypted_auth_state = yield encrypt(auth_state) + self.encrypted_auth_state = await encrypt(auth_state) self.db.commit() - @gen.coroutine - def get_auth_state(self): + async def get_auth_state(self): """Retrieve and decrypt auth_state for the user""" encrypted = self.encrypted_auth_state if encrypted is None: return None try: - auth_state = yield decrypt(encrypted) + auth_state = await decrypt(encrypted) except (ValueError, InvalidToken, EncryptionUnavailable) as e: self.log.warning("Failed to retrieve encrypted auth_state for %s because %s", self.name, e, @@ -183,7 +181,7 @@ def get_auth_state(self): if auth_state: # Crypt has multiple keys, store again with new key for rotation. if len(CryptKeeper.instance().keys) > 1: - yield self.save_auth_state(auth_state) + await self.save_auth_state(auth_state) return auth_state def _new_spawner(self, name, spawner_class=None, **kwargs): @@ -322,16 +320,15 @@ def url(self): else: return self.base_url - @gen.coroutine - def spawn(self, server_name='', options=None): + async def spawn(self, server_name='', options=None): """Start the user's spawner - + depending from the value of JupyterHub.allow_named_servers - + if False: JupyterHub expects only one single-server per user url of the server will be /user/:name - + if True: JupyterHub expects more than one single-server per user url of the server will be /user/:name/:server_name @@ -381,17 +378,17 @@ def spawn(self, server_name='', options=None): # trigger pre-spawn hook on authenticator authenticator = self.authenticator if (authenticator): - yield gen.maybe_future(authenticator.pre_spawn_start(self, spawner)) + await maybe_future(authenticator.pre_spawn_start(self, spawner)) spawner._start_pending = True # wait for spawner.start to return try: # run optional preparation work to bootstrap the notebook - yield gen.maybe_future(spawner.run_pre_spawn_hook()) - f = spawner.start() + await maybe_future(spawner.run_pre_spawn_hook()) + f = maybe_future(spawner.start()) # commit any changes in spawner.start (always commit db changes before yield) db.commit() - ip_port = yield gen.with_timeout(timedelta(seconds=spawner.start_timeout), f) + ip_port = await gen.with_timeout(timedelta(seconds=spawner.start_timeout), f) if ip_port: # get ip, port info from return value of start() server.ip, server.port = ip_port @@ -448,7 +445,7 @@ def spawn(self, server_name='', options=None): self.settings['statsd'].incr('spawner.failure.error') e.reason = 'error' try: - yield self.stop() + await self.stop() except Exception: self.log.error("Failed to cleanup {user}'s server that failed to start".format( user=self.name, @@ -466,7 +463,7 @@ def spawn(self, server_name='', options=None): db.commit() spawner._waiting_for_response = True try: - resp = yield server.wait_up(http=True, timeout=spawner.http_timeout) + resp = await server.wait_up(http=True, timeout=spawner.http_timeout) except Exception as e: if isinstance(e, TimeoutError): self.log.warning( @@ -486,7 +483,7 @@ def spawn(self, server_name='', options=None): )) self.settings['statsd'].incr('spawner.failure.http_error') try: - yield self.stop() + await self.stop() except Exception: self.log.error("Failed to cleanup {user}'s server that failed to start".format( user=self.name, @@ -504,8 +501,7 @@ def spawn(self, server_name='', options=None): spawner._start_pending = False return self - @gen.coroutine - def stop(self, server_name=''): + async def stop(self, server_name=''): """Stop the user's spawner and cleanup after it. @@ -517,9 +513,9 @@ def stop(self, server_name=''): spawner._stop_pending = True try: api_token = spawner.api_token - status = yield spawner.poll() + status = await spawner.poll() if status is None: - yield spawner.stop() + await spawner.stop() spawner.clear_state() spawner.orm_spawner.state = spawner.get_state() self.last_activity = spawner.orm_spawner.last_activity = datetime.utcnow() @@ -537,7 +533,7 @@ def stop(self, server_name=''): auth = spawner.authenticator try: if auth: - yield gen.maybe_future( + await maybe_future( auth.post_spawn_stop(self, spawner) ) except Exception: diff --git a/jupyterhub/utils.py b/jupyterhub/utils.py --- a/jupyterhub/utils.py +++ b/jupyterhub/utils.py @@ -3,11 +3,14 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. +import asyncio from binascii import b2a_hex +import concurrent.futures import random import errno import hashlib from hmac import compare_digest +import inspect import os import socket import sys @@ -16,7 +19,8 @@ import uuid import warnings -from tornado import web, gen, ioloop +from tornado import gen, ioloop, web +from tornado.platform.asyncio import to_asyncio_future from tornado.httpclient import AsyncHTTPClient, HTTPError from tornado.log import app_log @@ -51,8 +55,7 @@ def can_connect(ip, port): else: return True [email protected] -def exponential_backoff( +async def exponential_backoff( pass_func, fail_message, start_wait=0.2, @@ -120,7 +123,7 @@ def exponential_backoff( deadline = random.uniform(deadline - tol, deadline + tol) scale = 1 while True: - ret = yield gen.maybe_future(pass_func(*args, **kwargs)) + ret = await maybe_future(pass_func(*args, **kwargs)) # Truthy! if ret: return ret @@ -133,33 +136,30 @@ def exponential_backoff( # too many things dt = min(max_wait, remaining, random.uniform(0, start_wait * scale)) scale *= scale_factor - yield gen.sleep(dt) + await gen.sleep(dt) raise TimeoutError(fail_message) [email protected] -def wait_for_server(ip, port, timeout=10): +async def wait_for_server(ip, port, timeout=10): """Wait for any server to show up at ip:port.""" if ip in {'', '0.0.0.0'}: ip = '127.0.0.1' - yield exponential_backoff( + await exponential_backoff( lambda: can_connect(ip, port), "Server at {ip}:{port} didn't respond in {timeout} seconds".format(ip=ip, port=port, timeout=timeout), timeout=timeout ) [email protected] -def wait_for_http_server(url, timeout=10): +async def wait_for_http_server(url, timeout=10): """Wait for an HTTP Server to respond at url. Any non-5XX response code will do, even 404. """ client = AsyncHTTPClient() - @gen.coroutine - def is_reachable(): + async def is_reachable(): try: - r = yield client.fetch(url, follow_redirects=False) + r = await client.fetch(url, follow_redirects=False) return r except HTTPError as e: if e.code >= 500: @@ -176,7 +176,7 @@ def is_reachable(): if e.errno not in {errno.ECONNABORTED, errno.ECONNREFUSED, errno.ECONNRESET}: app_log.warning("Failed to connect to %s (%s)", url, e) return False - re = yield exponential_backoff( + re = await exponential_backoff( is_reachable, "Server at {url} didn't respond in {timeout} seconds".format(url=url, timeout=timeout), timeout=timeout @@ -413,3 +413,25 @@ def print_stacks(file=sys.stderr): for task in tasks: task.print_stack(file=file) + +def maybe_future(obj): + """Return an asyncio Future + + Use instead of gen.maybe_future + + For our compatibility, this must accept: + + - asyncio coroutine (gen.maybe_future doesn't work in tornado < 5) + - tornado coroutine (asyncio.ensure_future doesn't work) + - scalar (asyncio.ensure_future doesn't work) + - concurrent.futures.Future (asyncio.ensure_future doesn't work) + - tornado Future (works both ways) + - asyncio Future (works both ways) + """ + if inspect.isawaitable(obj): + # already awaitable, use ensure_future + return asyncio.ensure_future(obj) + elif isinstance(obj, concurrent.futures.Future): + return asyncio.wrap_future(obj) + else: + return to_asyncio_future(gen.maybe_future(obj)) diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -15,8 +15,8 @@ import sys v = sys.version_info -if v[:2] < (3,4): - error = "ERROR: JupyterHub requires Python version 3.4 or above." +if v[:2] < (3, 5): + error = "ERROR: JupyterHub requires Python version 3.5 or above." print(error, file=sys.stderr) sys.exit(1) @@ -100,7 +100,7 @@ def get_package_data(): license = "BSD", platforms = "Linux, Mac OS X", keywords = ['Interactive', 'Interpreter', 'Shell', 'Web'], - python_requires = ">=3.4", + python_requires = ">=3.5", classifiers = [ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators',
diff --git a/jupyterhub/tests/conftest.py b/jupyterhub/tests/conftest.py --- a/jupyterhub/tests/conftest.py +++ b/jupyterhub/tests/conftest.py @@ -103,7 +103,8 @@ def start(): service.start() io_loop.run_sync(start) def cleanup(): - service.stop() + import asyncio + asyncio.get_event_loop().run_until_complete(service.stop()) app.services[:] = [] app._service_map.clear() request.addfinalizer(cleanup) @@ -131,8 +132,8 @@ def mockservice_url(request, app): def no_patience(app): """Set slow-spawning timeouts to zero""" with mock.patch.dict(app.tornado_settings, - {'slow_spawn_timeout': 0, - 'slow_stop_timeout': 0}): + {'slow_spawn_timeout': 0.1, + 'slow_stop_timeout': 0.1}): yield diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -586,7 +586,7 @@ def test_spawn_limit(app, no_patience, slow_spawn, request): for u in users: u.spawner.delay = 0 r = yield api_request(app, 'users', u.name, 'server', method='delete') - yield r.raise_for_status() + r.raise_for_status() while any(u.spawner.active for u in users): yield gen.sleep(0.1) diff --git a/jupyterhub/tests/test_auth.py b/jupyterhub/tests/test_auth.py --- a/jupyterhub/tests/test_auth.py +++ b/jupyterhub/tests/test_auth.py @@ -132,16 +132,16 @@ def test_add_system_user(): authenticator = auth.PAMAuthenticator(whitelist={'mal'}) authenticator.create_system_users = True authenticator.add_user_cmd = ['echo', '/home/USERNAME'] - + record = {} class DummyPopen: def __init__(self, cmd, *args, **kwargs): record['cmd'] = cmd self.returncode = 0 - + def wait(self): return - + with mock.patch.object(auth, 'Popen', DummyPopen): yield authenticator.add_user(user) assert record['cmd'] == ['echo', '/home/lioness4321', 'lioness4321'] @@ -151,9 +151,9 @@ def wait(self): def test_delete_user(): user = orm.User(name='zoe') a = MockPAMAuthenticator(whitelist={'mal'}) - + assert 'zoe' not in a.whitelist - a.add_user(user) + yield a.add_user(user) assert 'zoe' in a.whitelist a.delete_user(user) assert 'zoe' not in a.whitelist diff --git a/jupyterhub/tests/test_services.py b/jupyterhub/tests/test_services.py --- a/jupyterhub/tests/test_services.py +++ b/jupyterhub/tests/test_services.py @@ -88,8 +88,8 @@ def test_external_service(app): 'url': env['JUPYTERHUB_SERVICE_URL'], 'api_token': env['JUPYTERHUB_API_TOKEN'], }] - app.init_services() - app.init_api_tokens() + yield app.init_services() + yield app.init_api_tokens() yield app.proxy.add_all_services(app._service_map) service = app._service_map[name]
async syntax We're using tornado as our async runner and `@gen.coroutine` all over the place. We could be using Python 3.5's `async def` and `await` syntax instead of `@gen.coroutine` and `yield`. There's no practical change in behavior that I know of (we'd still use tornado, just not tornado's Python 2-compatible syntax). I don't have a good sense for how many folks are relying on Python 3.4 to run JupyterHub, though (current minimum Python is officially 3.3).
Could we put this change in 0.8 and put Python 3.5 as requirement? As they say on the website (http://www.tornadoweb.org/en/stable/guide/coroutines.html) we should also see speed improvements. Potentially. What I don't know (and don't know how to discern) is how many people are running with 3.4 or earlier who would have difficulty upgrading to 3.5. In the context of JupyterHub, the performance difference should be pretty negligible, given that database operations and the like will generally dominate any Python call overhead. I think marking this for 0.9 probably makes sense. We'll likely get info about 3.4/3.5 usage at PyCon. I doubt many folks are using 3.3 still. I think 0.9 makes sense with an open door to pull into 0.8 if it simplifies reliability and testing during development and production. I'd be happy with 3.5 being the minimum requirement for 0.8... but that's because I've already moved to 3.6 so it's easy for me to say. I think there are still packages which don't work for 3.6 which is holding back adoption but the same isn't true for 3.5 - it's probably the best supported version currently so I don't see that there's much barrier to anyone upgrading from 3.4 --> 3.5. I think 0.9 is the minimum we should do (and ideally I'd prefer 0.10). Debian Jessie ships with 3.4 (not 3.5), and so does EPEL for Centos 7 (last time I checked). We aren't using any of the 3.5 syntaxes now, and we're pretty close to 0.8. Let's defer the decision until after 0.8? :) agree with @yuvipanda 👍 to setting minimum to 3.4 for 0.8 and re-evaluating 3.5 in a release or two. While it would have been nice to have async/await from the beginning, now that the Hub is ~all written, they honestly don't provide much benefit over `@coroutine` and `yield`. So we can wait for a more compelling reason to come along and trigger the next transition.
2018-03-02T10:39:39Z
[]
[]
jupyterhub/jupyterhub
1,722
jupyterhub__jupyterhub-1722
[ "1721" ]
e81eb9a5f88c3f25e7b83373ba4d8fed05c51fdc
diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -392,20 +392,35 @@ def authenticate(self, data): def get_next_url(self, user=None): """Get the next_url for login redirect - Defaults to hub base_url /hub/ if user is not running, - otherwise user.url. + Default URL after login: + + - if redirect_to_server (default): send to user's own server + - else: /hub/home """ next_url = self.get_argument('next', default='') if (next_url + '/').startswith('%s://%s/' % (self.request.protocol, self.request.host)): # treat absolute URLs for our host as absolute paths: next_url = urlparse(next_url).path - if not next_url.startswith('/'): + if next_url and not next_url.startswith('/'): + self.log.warning("Disallowing redirect outside JupyterHub: %r", next_url) next_url = '' + if next_url and next_url.startswith(url_path_join(self.base_url, 'user/')): + # add /hub/ prefix, to ensure we redirect to the right user's server. + # The next request will be handled by SpawnHandler, + # ultimately redirecting to the logged-in user's server. + without_prefix = next_url[len(self.base_url):] + next_url = url_path_join(self.hub.base_url, without_prefix) + self.log.warning("Redirecting %s to %s. For sharing public links, use /user-redirect/", + self.request.uri, next_url, + ) + if not next_url: - if user and user.running and self.redirect_to_server: + # default URL after login + # if self.redirect_to_server, default login URL initiates spawn + if user and self.redirect_to_server: next_url = user.url else: - next_url = self.hub.base_url + next_url = url_path_join(self.hub.base_url, 'home') return next_url async def login_user(self, data=None): diff --git a/jupyterhub/handlers/login.py b/jupyterhub/handlers/login.py --- a/jupyterhub/handlers/login.py +++ b/jupyterhub/handlers/login.py @@ -82,15 +82,9 @@ async def post(self): auth_timer.stop(send=False) if user: - already_running = False - if user.spawner.ready: - status = await user.spawner.poll() - already_running = (status is None) - if not already_running and not user.spawner.options_form \ - and not user.spawner.pending: - # logging in triggers spawn - await self.spawn_single_user(user) - self.redirect(self.get_next_url()) + # register current user for subsequent requests to user (e.g. logging the request) + self.get_current_user = lambda: user + self.redirect(self.get_next_url(user)) else: html = self._render( login_error='Invalid username or password', diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -22,37 +22,15 @@ class RootHandler(BaseHandler): If logged in, redirects to: - - single-user server if running + - single-user server if settings.redirect_to_server (default) - hub home, otherwise Otherwise, renders login page. """ def get(self): - next_url = self.get_argument('next', '') - if next_url and not next_url.startswith('/'): - self.log.warning("Disallowing redirect outside JupyterHub: %r", next_url) - next_url = '' - if next_url and next_url.startswith(url_path_join(self.base_url, 'user/')): - # add /hub/ prefix, to ensure we redirect to the right user's server. - # The next request will be handled by SpawnHandler, - # ultimately redirecting to the logged-in user's server. - without_prefix = next_url[len(self.base_url):] - next_url = url_path_join(self.hub.base_url, without_prefix) - self.log.warning("Redirecting %s to %s. For sharing public links, use /user-redirect/", - self.request.uri, next_url, - ) - self.redirect(next_url) - return user = self.get_current_user() if user: - url = url_path_join(self.hub.base_url, 'home') - if user.running: - if self.redirect_to_server: - url = user.url - self.log.debug("User is running: %s", user.url) - self.set_login_cookie(user) # set cookie - else: - self.log.debug("User is not running: %s", url) + url = self.get_next_url(user) else: url = self.settings['login_url'] self.redirect(url) @@ -71,7 +49,7 @@ async def get(self): # send the user to /spawn if they aren't running or pending a spawn, # to establish that this is an explicit spawn request rather # than an implicit one, which can be caused by any link to `/user/:name` - url = user.url if user.running or user.spawner.pending else url_path_join(self.hub.base_url, 'spawn') + url = user.url if user.spawner.active else url_path_join(self.hub.base_url, 'spawn') html = self.render_template('home.html', user=user, url=url,
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -143,10 +143,6 @@ def test_referer_check(app): if user is None: user = add_user(app.db, name='admin', admin=True) cookies = yield app.login_user('admin') - app_user = app.users[user] - # stop the admin's server so we don't mess up future tests - yield app.proxy.delete_user(app_user) - yield app_user.stop() r = yield api_request(app, 'users', headers={ diff --git a/jupyterhub/tests/test_named_servers.py b/jupyterhub/tests/test_named_servers.py --- a/jupyterhub/tests/test_named_servers.py +++ b/jupyterhub/tests/test_named_servers.py @@ -99,13 +99,13 @@ def test_create_named_server(app, named_servers): 'kind': 'user', 'admin': False, 'pending': None, - 'server': user.url, + 'server': None, 'servers': { - name: { + servername: { 'name': name, 'url': url_path_join(user.url, name, '/'), } - for name in ['', servername] + for name in [servername] }, } @@ -127,7 +127,7 @@ def test_delete_named_server(app, named_servers): r = yield api_request(app, 'users', username) r.raise_for_status() - + user_model = r.json() user_model.pop('last_activity') assert user_model == { @@ -136,13 +136,13 @@ def test_delete_named_server(app, named_servers): 'kind': 'user', 'admin': False, 'pending': None, - 'server': user.url, + 'server': None, 'servers': { name: { 'name': name, 'url': url_path_join(user.url, name, '/'), } - for name in [''] + for name in [] }, } diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -38,7 +38,7 @@ def test_root_auth(app): cookies = yield app.login_user('river') r = yield async_requests.get(public_url(app), cookies=cookies) r.raise_for_status() - assert r.url == public_url(app, app.users['river']) + assert r.url.startswith(public_url(app, app.users['river'])) @pytest.mark.gen_test @@ -341,7 +341,7 @@ def mock_authenticate(handler, data): data=form_data, allow_redirects=False, ) - + assert called_with == [form_data] @@ -361,7 +361,7 @@ def test_login_redirect(app): r = yield get_page('login', app, cookies=cookies, allow_redirects=False) r.raise_for_status() assert r.status_code == 302 - assert '/hub/' in r.headers['Location'] + assert '/user/river' in r.headers['Location'] # next URL given, use it r = yield get_page('login?next=/hub/admin', app, cookies=cookies, allow_redirects=False) diff --git a/jupyterhub/tests/test_singleuser.py b/jupyterhub/tests/test_singleuser.py --- a/jupyterhub/tests/test_singleuser.py +++ b/jupyterhub/tests/test_singleuser.py @@ -2,6 +2,7 @@ from subprocess import check_output import sys +from urllib.parse import urlparse import pytest @@ -17,25 +18,25 @@ def test_singleuser_auth(app): # use StubSingleUserSpawner to launch a single-user app in a thread app.spawner_class = StubSingleUserSpawner app.tornado_settings['spawner_class'] = StubSingleUserSpawner - + # login, start the server cookies = yield app.login_user('nandy') user = app.users['nandy'] if not user.running: yield user.spawn() url = public_url(app, user) - + # no cookies, redirects to login page r = yield async_requests.get(url) r.raise_for_status() assert '/hub/login' in r.url - + # with cookies, login successful r = yield async_requests.get(url, cookies=cookies) r.raise_for_status() - assert r.url.rstrip('/').endswith('/user/nandy/tree') + assert urlparse(r.url).path.rstrip('/').endswith('/user/nandy/tree') assert r.status_code == 200 - + # logout r = yield async_requests.get(url_path_join(url, 'logout'), cookies=cookies) assert len(r.cookies) == 0
audit default URLs and redirects Currently, there are too many different initial states that can affect how users arrive at the Hub and where they end up. In particular, the biggest source of confusion is the "if the server is running, default to their server, otherwise default to /hub/home" behavior. This is implemented separately and slightly differently in the root handler and the login handler. The current state of things, as far as I can tell: - `/` -> `/hub/` - not logged in: redirect to `/hub/login` - logged in - ready: send to running server at `/user/:name` - not ready: send to /hub/home - `/hub/login` - not running: trigger launch - ready: send to running server at `/user/:name` - not ready (e.g. slow spawn): send to `/hub/home` Two common sources of confusion with this: 1. where the user ends up on login is sensitive to whether spawn is quick or not 2. visiting the same URL with the Hub in the same state sends the user to a different location, depending on whether the user was already logged in or not: 1. not logged in -> login -> triggers spawn -> /user/:name 2. logged in -> doesn't trigger spawn -> /hub/home Proposal: - always or never send users to their server from `/hub/` and `/hub/login`. #1648 added `.redirect_to_server` setting which covers the 'never' case. We can use this to implement the 'always' case as well, rather than the current state-dependent behavior. - ensure /hub/ and /hub/login use the same code for picking destinations (`.get_next_url()`) - remove implicit spawn from /hub/login, instead relying on `/hub/user/:name` handler to trigger spawn (or render spawn form), so that requests sending users to /hub/home don't trigger spawn This should result in more consistent behavior that's easier for everyone to follow. cc @ppLorins who brought up default-url confusion most recently
2018-03-14T14:37:47Z
[]
[]
jupyterhub/jupyterhub
1,743
jupyterhub__jupyterhub-1743
[ "1724" ]
6474a5530257ffc577dbcd0a3c50bffa6e46b5f6
diff --git a/jupyterhub/apihandlers/auth.py b/jupyterhub/apihandlers/auth.py --- a/jupyterhub/apihandlers/auth.py +++ b/jupyterhub/apihandlers/auth.py @@ -92,7 +92,7 @@ def get(self, cookie_name, cookie_value=None): class OAuthHandler(BaseHandler, OAuth2Handler): """Implement OAuth provider handlers - + OAuth2Handler sets `self.provider` in initialize, but we are already passing the Provider object via settings. """ diff --git a/jupyterhub/apihandlers/base.py b/jupyterhub/apihandlers/base.py --- a/jupyterhub/apihandlers/base.py +++ b/jupyterhub/apihandlers/base.py @@ -71,7 +71,7 @@ def get_json_body(self): self.log.error("Couldn't parse JSON", exc_info=True) raise web.HTTPError(400, 'Invalid JSON in body of request') return model - + def write_error(self, status_code, **kwargs): """Write JSON errors instead of HTML""" exc_info = kwargs.get('exc_info') @@ -142,6 +142,7 @@ def service_model(self, service): 'name': str, 'admin': bool, 'groups': list, + 'auth_state': dict, } _group_model_types = { @@ -151,7 +152,7 @@ def service_model(self, service): def _check_model(self, model, model_types, name): """Check a model provided by a REST API request - + Args: model (dict): user-provided model model_types (dict): dict of key:type used to validate types and keys diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -17,7 +17,7 @@ class SelfAPIHandler(APIHandler): Based on the authentication info. Acts as a 'whoami' for auth tokens. """ - def get(self): + async def get(self): user = self.get_current_user() if user is None: # whoami can be accessed via oauth token @@ -44,7 +44,7 @@ async def post(self): # admin is set for all users # to create admin and non-admin users requires at least two API requests admin = data.get('admin', False) - + to_create = [] invalid_names = [] for name in usernames: @@ -95,7 +95,7 @@ def m(self, name, *args, **kwargs): raise web.HTTPError(403) if not (current.name == name or current.admin): raise web.HTTPError(403) - + # raise 404 if not found if not self.find_user(name): raise web.HTTPError(404) @@ -105,9 +105,17 @@ def m(self, name, *args, **kwargs): class UserAPIHandler(APIHandler): @admin_or_self - def get(self, name): + async def get(self, name): user = self.find_user(name) - self.write(json.dumps(self.user_model(user))) + user_ = self.user_model(user) + # auth state will only be shown if the requestor is an admin + # this means users can't see their own auth state unless they + # are admins, Hub admins often are also marked as admins so they + # will see their auth state but normal users won't + requestor = self.get_current_user() + if requestor.admin: + user_['auth_state'] = await user.get_auth_state() + self.write(json.dumps(user_)) @admin_only async def post(self, name): @@ -155,7 +163,7 @@ async def delete(self, name): self.set_status(204) @admin_only - def patch(self, name): + async def patch(self, name): user = self.find_user(name) if user is None: raise web.HTTPError(404) @@ -166,9 +174,14 @@ def patch(self, name): if self.find_user(data['name']): raise web.HTTPError(400, "User %s already exists, username must be unique" % data['name']) for key, value in data.items(): - setattr(user, key, value) + if key == 'auth_state': + await user.save_auth_state(value) + else: + setattr(user, key, value) self.db.commit() - self.write(json.dumps(self.user_model(user))) + user_ = self.user_model(user) + user_['auth_state'] = await user.get_auth_state() + self.write(json.dumps(user_)) class UserServerAPIHandler(APIHandler):
diff --git a/jupyterhub/tests/conftest.py b/jupyterhub/tests/conftest.py --- a/jupyterhub/tests/conftest.py +++ b/jupyterhub/tests/conftest.py @@ -3,6 +3,7 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. +import os import logging from getpass import getuser from subprocess import TimeoutExpired @@ -12,6 +13,7 @@ from tornado import ioloop, gen from .. import orm +from .. import crypto from ..utils import random_port from . import mocking @@ -70,6 +72,23 @@ def fin(): return mocked_app +@fixture +def auth_state_enabled(app): + app.authenticator.auth_state = { + 'who': 'cares', + } + app.authenticator.enable_auth_state = True + ck = crypto.CryptKeeper.instance() + before_keys = ck.keys + ck.keys = [os.urandom(32)] + try: + yield + finally: + ck.keys = before_keys + app.authenticator.enable_auth_state = False + app.authenticator.auth_state = None + + # mock services for testing. # Shorter intervals, etc. class MockServiceSpawner(jupyterhub.services.service._ServiceSpawner): diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -52,9 +52,13 @@ def new_func(app, *args, **kwargs): return new_func -def find_user(db, name): +def find_user(db, name, app=None): """Find user in database.""" - return db.query(orm.User).filter(orm.User.name == name).first() + orm_user = db.query(orm.User).filter(orm.User.name == name).first() + if app is None: + return orm_user + else: + return app.users[orm_user.id] def add_user(db, app=None, **kwargs): @@ -280,6 +284,8 @@ def test_get_user(app): 'admin': False, 'server': None, 'pending': None, + # auth state is present because requestor is an admin + 'auth_state': None } @@ -420,6 +426,84 @@ def test_make_admin(app): assert user.admin [email protected] [email protected]_test +def test_set_auth_state(app, auth_state_enabled): + auth_state = {'secret': 'hello'} + db = app.db + name = 'admin' + user = find_user(db, name, app=app) + assert user is not None + assert user.name == name + + r = yield api_request(app, 'users', name, method='patch', + data=json.dumps({'auth_state': auth_state}) + ) + + assert r.status_code == 200 + users_auth_state = yield user.get_auth_state() + assert users_auth_state == auth_state + + [email protected] [email protected]_test +def test_user_set_auth_state(app, auth_state_enabled): + auth_state = {'secret': 'hello'} + db = app.db + name = 'user' + user = find_user(db, name, app=app) + assert user is not None + assert user.name == name + user_auth_state = yield user.get_auth_state() + assert user_auth_state is None + + r = yield api_request( + app, 'users', name, method='patch', + data=json.dumps({'auth_state': auth_state}), + headers=auth_header(app.db, name), + ) + + assert r.status_code == 403 + user_auth_state = yield user.get_auth_state() + assert user_auth_state is None + + [email protected] [email protected]_test +def test_admin_get_auth_state(app, auth_state_enabled): + auth_state = {'secret': 'hello'} + db = app.db + name = 'admin' + user = find_user(db, name, app=app) + assert user is not None + assert user.name == name + yield user.save_auth_state(auth_state) + + r = yield api_request(app, 'users', name) + + assert r.status_code == 200 + assert r.json()['auth_state'] == auth_state + + [email protected] [email protected]_test +def test_user_get_auth_state(app, auth_state_enabled): + # explicitly check that a user will not get their own auth state via the API + auth_state = {'secret': 'hello'} + db = app.db + name = 'user' + user = find_user(db, name, app=app) + assert user is not None + assert user.name == name + yield user.save_auth_state(auth_state) + + r = yield api_request(app, 'users', name, + headers=auth_header(app.db, name)) + + assert r.status_code == 200 + assert 'auth_state' not in r.json() + + @mark.gen_test def test_spawn(app): db = app.db @@ -593,7 +677,7 @@ def test_spawn_limit(app, no_patience, slow_spawn, request): user.spawner._start_future = Future() r = yield api_request(app, 'users', name, 'server', method='post') assert r.status_code == 429 - + # allow ykka to start users[0].spawner._start_future.set_result(None) # wait for ykka to finish diff --git a/jupyterhub/tests/test_auth.py b/jupyterhub/tests/test_auth.py --- a/jupyterhub/tests/test_auth.py +++ b/jupyterhub/tests/test_auth.py @@ -22,7 +22,7 @@ def test_pam_auth(): 'password': 'match', }) assert authorized['name'] == 'match' - + authorized = yield authenticator.get_authenticated_user(None, { 'username': 'match', 'password': 'nomatch', @@ -61,13 +61,13 @@ def test_pam_auth_whitelist(): 'password': 'kaylee', }) assert authorized['name'] == 'kaylee' - + authorized = yield authenticator.get_authenticated_user(None, { 'username': 'wash', 'password': 'nomatch', }) assert authorized is None - + authorized = yield authenticator.get_authenticated_user(None, { 'username': 'mal', 'password': 'mal', @@ -85,9 +85,9 @@ def test_pam_auth_group_whitelist(): g = MockGroup('kaylee') def getgrnam(name): return g - + authenticator = MockPAMAuthenticator(group_whitelist={'group'}) - + with mock.patch.object(auth, 'getgrnam', getgrnam): authorized = yield authenticator.get_authenticated_user(None, { 'username': 'kaylee', @@ -128,21 +128,21 @@ def test_cant_add_system_user(): authenticator = auth.PAMAuthenticator(whitelist={'mal'}) authenticator.add_user_cmd = ['jupyterhub-fake-command'] authenticator.create_system_users = True - + class DummyFile: def read(self): return b'dummy error' - + class DummyPopen: def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs self.returncode = 1 self.stdout = DummyFile() - + def wait(self): return - + with mock.patch.object(auth, 'Popen', DummyPopen): with pytest.raises(RuntimeError) as exc: yield authenticator.add_user(user) @@ -196,23 +196,6 @@ def test_handlers(app): assert handlers[0][0] == '/login' [email protected] -def auth_state_enabled(app): - app.authenticator.auth_state = { - 'who': 'cares', - } - app.authenticator.enable_auth_state = True - ck = crypto.CryptKeeper.instance() - before_keys = ck.keys - ck.keys = [os.urandom(32)] - try: - yield - finally: - ck.keys = before_keys - app.authenticator.enable_auth_state = False - app.authenticator.auth_state = None - - @pytest.mark.gen_test def test_auth_state(app, auth_state_enabled): """auth_state enabled and available""" @@ -270,7 +253,7 @@ def test_auth_admin_retained_if_unset(app): @pytest.fixture def auth_state_unavailable(auth_state_enabled): """auth_state enabled at the Authenticator level, - + but unavailable due to no crypto keys. """ crypto.CryptKeeper.instance().keys = [] @@ -343,5 +326,3 @@ def test_validate_names(): a = auth.PAMAuthenticator(username_pattern='w.*') assert not a.validate_username('xander') assert a.validate_username('willow') - - diff --git a/jupyterhub/tests/test_named_servers.py b/jupyterhub/tests/test_named_servers.py --- a/jupyterhub/tests/test_named_servers.py +++ b/jupyterhub/tests/test_named_servers.py @@ -36,6 +36,7 @@ def test_default_server(app, named_servers): 'kind': 'user', 'admin': False, 'pending': None, + 'auth_state': None, 'server': user.url, 'servers': { '': { @@ -63,6 +64,7 @@ def test_default_server(app, named_servers): 'pending': None, 'server': None, 'servers': {}, + 'auth_state': None, } @@ -99,6 +101,7 @@ def test_create_named_server(app, named_servers): 'kind': 'user', 'admin': False, 'pending': None, + 'auth_state': None, 'server': None, 'servers': { servername: { @@ -136,6 +139,7 @@ def test_delete_named_server(app, named_servers): 'kind': 'user', 'admin': False, 'pending': None, + 'auth_state': None, 'server': None, 'servers': { name: {
Update user's auth state from a running notebook server I have a hub where we forward the oauth2 token from the login to the user's notebook server ([like so](https://github.com/jupyterhub/oauthenticator/blob/master/examples/auth_state/jupyterhub_config.py)). There they can use it to make auth'ed requests to a few services. My question is what do others do to keep the token that the notebook server has fresh? The oauth2 token is only valid for ~24h which is much shorter than the "logout time" for the hub (14days by default?). Right now I have a nb server extension that periodically refreshes the token but as soon as you do that the auth state that the hub has is outdated (the oauth refresh token there becomes invalid). So I am thinking of writing a hub service that the nbserver extension can talk to. Once it refreshes the tokens it then uses the service to update what the hub's user object contains. But this sounds quite convoluted so wondering what others do in this situation.
+1 I'm facing the exact same use case in our corporate auth system.
2018-03-21T09:17:34Z
[]
[]
jupyterhub/jupyterhub
1,750
jupyterhub__jupyterhub-1750
[ "1730" ]
50944487628ddc735772e392ed8222080d910bc2
diff --git a/jupyterhub/proxy.py b/jupyterhub/proxy.py --- a/jupyterhub/proxy.py +++ b/jupyterhub/proxy.py @@ -365,7 +365,7 @@ class ConfigurableHTTPProxy(Proxy): If the proxy should not be run as a subprocess of the Hub, (e.g. in a separate container), set:: - + c.ConfigurableHTTPProxy.should_start = False """ @@ -383,14 +383,10 @@ class ConfigurableHTTPProxy(Proxy): @default('auth_token') def _auth_token_default(self): - token = os.environ.get('CONFIGPROXY_AUTH_TOKEN', None) - if not token: - self.log.warning('\n'.join([ - "", - "Generating CONFIGPROXY_AUTH_TOKEN. Restarting the Hub will require restarting the proxy.", - "Set CONFIGPROXY_AUTH_TOKEN env or JupyterHub.proxy_auth_token config to avoid this message.", - "", - ])) + token = os.environ.get('CONFIGPROXY_AUTH_TOKEN', '') + if self.should_start and not token: + # generating tokens is fine if the Hub is starting the proxy + self.log.info("Generating new CONFIGPROXY_AUTH_TOKEN") token = utils.new_token() return token @@ -403,6 +399,17 @@ def _auth_token_default(self): _check_running_callback = Any(help="PeriodicCallback to check if the proxy is running") + def __init__(self, **kwargs): + super().__init__(**kwargs) + # check for required token if proxy is external + if not self.auth_token and not self.should_start: + raise ValueError( + "%s.auth_token or CONFIGPROXY_AUTH_TOKEN env is required" + " if Proxy.should_start is False" % self.__class__.__name__ + ) + + + async def start(self): public_server = Server.from_url(self.public_url) api_server = Server.from_url(self.api_url)
diff --git a/jupyterhub/tests/test_app.py b/jupyterhub/tests/test_app.py --- a/jupyterhub/tests/test_app.py +++ b/jupyterhub/tests/test_app.py @@ -176,6 +176,7 @@ def test_resume_spawners(tmpdir, request): def new_hub(): app = MockHub() app.config.ConfigurableHTTPProxy.should_start = False + app.config.ConfigurableHTTPProxy.auth_token = 'unused' yield app.initialize([]) return app app = yield new_hub()
two flags on start up here is the output from terminal: ``` [I 2018-03-16 10:39:28.004 JupyterHub app:834] Loading cookie_secret from /srv/jupyterhub/jupyterhub_cookie_secret [I 2018-03-16 10:39:28.124 JupyterHub app:1528] Hub API listening on http://127.0.0.1:8081/hub/ [W 2018-03-16 10:39:28.125 JupyterHub proxy:415] Generating CONFIGPROXY_AUTH_TOKEN. Restarting the Hub will require restarting the proxy. Set CONFIGPROXY_AUTH_TOKEN env or JupyterHub.proxy_auth_token config to avoid this message. [I 2018-03-16 10:39:28.126 JupyterHub proxy:458] Starting proxy @ https://*:8000/ 10:39:28.338 - info: [ConfigProxy] Proxying https://*:8000 to (no default) 10:39:28.341 - info: [ConfigProxy] Proxy API at http://127.0.0.1:8001/api/routes 10:39:28.679 - info: [ConfigProxy] 200 GET /api/routes [W 2018-03-16 10:39:28.680 JupyterHub proxy:304] Adding missing default route [I 2018-03-16 10:39:28.680 JupyterHub proxy:370] Adding default route for Hub: / => http://127.0.0.1:8081 10:39:28.728 - info: [ConfigProxy] Adding route / -> http://127.0.0.1:8081 10:39:28.729 - info: [ConfigProxy] 201 POST /api/routes/ [I 2018-03-16 10:39:28.730 JupyterHub app:1581] JupyterHub is now running at https://:8000/ ``` everything starts up fine and is totally useable but the two flags im getting: Generating CONFIGPROXY_AUTH_TOKEN. Adding missing default route how can i generate a proxy auth token? I have googled to the end but only seem to find deprecated info second how can i get a default route set?
To generate the `CONFIGPROXY_AUTH_TOKEN` take a look at the [security section](http://jupyterhub.readthedocs.io/en/latest/getting-started/security-basics.html#proxy-authentication-token) of the documentation. I don't think the default route message is anything to worry about. When the proxy starts up there are no routes set and it automatically configures itself. I have looked into the security part and the first part of the docs : c.JupyterHub.proxy_auth_token is deprecated. the second option export CONFIGPROXY_AUTH_TOKEN='openssl rand -hex 32' . but im not sure where to put this? if I put it into the .config as is, it throws all sorts of errors.
2018-03-23T11:58:03Z
[]
[]
jupyterhub/jupyterhub
1,820
jupyterhub__jupyterhub-1820
[ "1796" ]
2517afcee0b1d3f692dd59537601227156844a03
diff --git a/jupyterhub/alembic/versions/56cc5a70207e_token_tracking.py b/jupyterhub/alembic/versions/56cc5a70207e_token_tracking.py --- a/jupyterhub/alembic/versions/56cc5a70207e_token_tracking.py +++ b/jupyterhub/alembic/versions/56cc5a70207e_token_tracking.py @@ -15,6 +15,9 @@ from alembic import op import sqlalchemy as sa +import logging +logger = logging.getLogger('alembic') + def upgrade(): tables = op.get_bind().engine.table_names() @@ -24,8 +27,11 @@ def upgrade(): if 'oauth_access_tokens' in tables: op.add_column('oauth_access_tokens', sa.Column('created', sa.DateTime(), nullable=True)) op.add_column('oauth_access_tokens', sa.Column('last_activity', sa.DateTime(), nullable=True)) - op.create_foreign_key(None, 'oauth_access_tokens', 'oauth_clients', ['client_id'], ['identifier'], ondelete='CASCADE') - op.create_foreign_key(None, 'oauth_codes', 'oauth_clients', ['client_id'], ['identifier'], ondelete='CASCADE') + if op.get_context().dialect.name == 'sqlite': + logger.warning("sqlite cannot use ALTER TABLE to create foreign keys. Upgrade will be incomplete.") + else: + op.create_foreign_key(None, 'oauth_access_tokens', 'oauth_clients', ['client_id'], ['identifier'], ondelete='CASCADE') + op.create_foreign_key(None, 'oauth_codes', 'oauth_clients', ['client_id'], ['identifier'], ondelete='CASCADE') def downgrade(): diff --git a/jupyterhub/alembic/versions/99a28a4418e1_user_created.py b/jupyterhub/alembic/versions/99a28a4418e1_user_created.py --- a/jupyterhub/alembic/versions/99a28a4418e1_user_created.py +++ b/jupyterhub/alembic/versions/99a28a4418e1_user_created.py @@ -37,7 +37,7 @@ def upgrade(): c.execute(""" UPDATE spawners SET started='%s' - WHERE server_id NOT NULL + WHERE server_id IS NOT NULL """ % (now,) )
diff --git a/jupyterhub/tests/old-jupyterhub.sqlite b/jupyterhub/tests/old-jupyterhub.sqlite deleted file mode 100644 Binary files a/jupyterhub/tests/old-jupyterhub.sqlite and /dev/null differ diff --git a/jupyterhub/tests/populate_db.py b/jupyterhub/tests/populate_db.py new file mode 100644 --- /dev/null +++ b/jupyterhub/tests/populate_db.py @@ -0,0 +1,98 @@ +"""script to populate a jupyterhub database + +Run with old versions of jupyterhub to test upgrade/downgrade + +used in test_db.py +""" + +from datetime import datetime +import os + +import jupyterhub +from jupyterhub import orm + + +def populate_db(url): + """Populate a jupyterhub database""" + db = orm.new_session_factory(url)() + # create some users + admin = orm.User(name='admin', admin=True) + db.add(admin) + user = orm.User(name='has-server') + db.add(user) + db.commit() + + # create a group + g = orm.Group(name='group') + db.add(g) + db.commit() + g.users.append(user) + db.commit() + + service = orm.Service(name='service') + db.add(service) + db.commit() + + # create some API tokens + user.new_api_token() + admin.new_api_token() + + # services got API tokens in 0.7 + if jupyterhub.version_info >= (0, 7): + # create a group + service.new_api_token() + + # Create a Spawner for user + if jupyterhub.version_info >= (0, 8): + # create spawner for user + spawner = orm.Spawner(name='', user=user) + db.add(spawner) + db.commit() + spawner.server = orm.Server() + db.commit() + + # admin's spawner is not running + spawner = orm.Spawner(name='', user=admin) + db.add(spawner) + db.commit() + else: + user.server = orm.Server() + db.commit() + + # create some oauth objects + if jupyterhub.version_info >= (0, 8): + # create oauth client + client = orm.OAuthClient(identifier='oauth-client') + db.add(client) + db.commit() + code = orm.OAuthCode(client_id=client.identifier) + db.add(code) + db.commit() + access_token = orm.OAuthAccessToken( + client_id=client.identifier, + user_id=user.id, + grant_type=orm.GrantType.authorization_code, + ) + db.add(access_token) + db.commit() + + # set some timestamps added in 0.9 + if jupyterhub.version_info >= (0, 9): + assert user.created + assert admin.created + # set last_activity + user.last_activity = datetime.utcnow() + spawner = user.orm_spawners[''] + spawner.started = datetime.utcnow() + spawner.last_activity = datetime.utcnow() + db.commit() + + +if __name__ == '__main__': + import sys + if len(sys.argv) > 1: + url = sys.argv[1] + else: + url = 'sqlite:///jupyterhub.sqlite' + + populate_db(url) diff --git a/jupyterhub/tests/test_db.py b/jupyterhub/tests/test_db.py --- a/jupyterhub/tests/test_db.py +++ b/jupyterhub/tests/test_db.py @@ -1,45 +1,70 @@ from glob import glob import os -import shutil +from subprocess import check_call +import sys +import tempfile import pytest from pytest import raises from traitlets.config import Config -from ..dbutil import upgrade from ..app import NewToken, UpgradeDB, JupyterHub -here = os.path.dirname(__file__) -old_db = os.path.join(here, 'old-jupyterhub.sqlite') +here = os.path.abspath(os.path.dirname(__file__)) +populate_db = os.path.join(here, 'populate_db.py') -def generate_old_db(path): - db_path = os.path.join(path, "jupyterhub.sqlite") - print(old_db, db_path) - shutil.copy(old_db, db_path) - return 'sqlite:///%s' % db_path -def test_upgrade(tmpdir): - print(tmpdir) - db_url = generate_old_db(str(tmpdir)) - upgrade(db_url) +def generate_old_db(env_dir, hub_version, db_url): + """Generate an old jupyterhub database + Installs a particular jupyterhub version in a virtualenv + and runs populate_db.py to populate a database + """ + env_pip = os.path.join(env_dir, 'bin', 'pip') + env_py = os.path.join(env_dir, 'bin', 'python') + check_call([sys.executable, '-m', 'virtualenv', env_dir]) + pkgs = ['jupyterhub==' + hub_version] + if 'mysql' in db_url: + pkgs.append('mysql-connector<2.2') + elif 'postgres' in db_url: + pkgs.append('psycopg2') + check_call([env_pip, 'install'] + pkgs) + check_call([env_py, populate_db, db_url]) + + [email protected]( + 'hub_version', + [ + '0.7.2', + '0.8.1', + ], +) @pytest.mark.gen_test -def test_upgrade_entrypoint(tmpdir): - db_url = os.getenv('JUPYTERHUB_TEST_UPGRADE_DB_URL') - if not db_url: - # default: sqlite - db_url = generate_old_db(str(tmpdir)) +def test_upgrade(tmpdir, hub_version): + db_url = os.getenv('JUPYTERHUB_TEST_DB_URL') + if db_url: + db_url += '_upgrade_' + hub_version.replace('.', '') + else: + db_url = 'sqlite:///jupyterhub.sqlite' + tmpdir.chdir() + + # use persistent temp env directory + # to reuse across multiple runs + env_dir = os.path.join(tempfile.gettempdir(), 'test-hub-upgrade-%s' % hub_version) + + generate_old_db(env_dir, hub_version, db_url) + cfg = Config() cfg.JupyterHub.db_url = db_url - tmpdir.chdir() tokenapp = NewToken(config=cfg) - tokenapp.initialize(['kaylee']) + tokenapp.initialize(['admin']) with raises(SystemExit): tokenapp.start() if 'sqlite' in db_url: + fname = db_url.split(':///')[1] sqlite_files = glob(os.path.join(str(tmpdir), 'jupyterhub.sqlite*')) assert len(sqlite_files) == 1
Running jupyterhub upgrade-db with PostgreSQL database fails **How to reproduce the issue** Run `jupyterhub upgrade-db` with a PostgreSQL database to upgrade to 99a28a4418e1. **What you expected to happen** Successful schema update. **What actually happens** It fails with an sqlalchemy `ProgrammingError` message that originates here: https://github.com/jupyterhub/jupyterhub/blob/master/jupyterhub/alembic/versions/99a28a4418e1_user_created.py#L40 in particular I think that should be `IS NOT NULL` not just `NOT NULL`. I substituted this live and it allowed the upgrade to proceed. **Share what version of JupyterHub you are using** Latest master.
2018-04-23T13:22:37Z
[]
[]
jupyterhub/jupyterhub
1,850
jupyterhub__jupyterhub-1850
[ "1446" ]
3558ce958e02854118b741d0e58714f407fe7759
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -17,11 +17,13 @@ import signal import sys from textwrap import dedent -from urllib.parse import urlparse +from urllib.parse import unquote, urlparse, urlunparse + if sys.version_info[:2] < (3, 3): raise ValueError("Python < 3.3 not supported: %s" % sys.version) + from dateutil.parser import parse as parse_date from jinja2 import Environment, FileSystemLoader, PrefixLoader, ChoiceLoader from sqlalchemy.exc import OperationalError @@ -33,6 +35,7 @@ import tornado.options from tornado import gen, web from tornado.platform.asyncio import AsyncIOMainLoop +from tornado.netutil import bind_unix_socket from traitlets import ( Unicode, Integer, Dict, TraitError, List, Bool, Any, @@ -84,6 +87,7 @@ 'y': 'JupyterHub.answer_yes', 'ssl-key': 'JupyterHub.ssl_key', 'ssl-cert': 'JupyterHub.ssl_cert', + 'url': 'JupyterHub.bind_url', 'ip': 'JupyterHub.ip', 'port': 'JupyterHub.port', 'pid-file': 'JupyterHub.pid_file', @@ -299,14 +303,69 @@ def _template_paths_default(self): """ ).tag(config=True) ip = Unicode('', - help="""The public facing ip of the whole JupyterHub application + help="""The public facing ip of the whole JupyterHub application (specifically referred to as the proxy). - - This is the address on which the proxy will listen. The default is to - listen on all interfaces. This is the only address through which JupyterHub - should be accessed by users. """ + + This is the address on which the proxy will listen. The default is to + listen on all interfaces. This is the only address through which JupyterHub + should be accessed by users. + + .. deprecated: 0.9 + """ + ).tag(config=True) + + port = Integer(8000, + help="""The public facing port of the proxy. + + This is the port on which the proxy will listen. + This is the only port through which JupyterHub + should be accessed by users. + + .. deprecated: 0.9 + Use JupyterHub.bind_url + """ + ).tag(config=True) + + @observe('ip', 'port') + def _ip_port_changed(self, change): + urlinfo = urlparse(self.bind_url) + urlinfo = urlinfo._replace(netloc='%s:%i' % (self.ip, self.port)) + self.bind_url = urlunparse(urlinfo) + + bind_url = Unicode( + "http://127.0.0.1:8000", + help="""The public facing URL of the whole JupyterHub application. + + This is the address on which the proxy will bind. + Sets protocol, ip, base_url + + .. deprecated: 0.9 + Use JupyterHub.bind_url + """ ).tag(config=True) + @observe('bind_url') + def _bind_url_changed(self, change): + urlinfo = urlparse(change.new) + self.base_url = urlinfo.path + + base_url = URLPrefix('/', + help="""The base URL of the entire application. + + Add this to the beginning of all JupyterHub URLs. + Use base_url to run JupyterHub within an existing website. + + .. deprecated: 0.9 + Use JupyterHub.bind_url + """ + ).tag(config=True) + + @default('base_url') + def _default_base_url(self): + # call validate to ensure leading/trailing slashes + print(self.bind_url) + return JupyterHub.base_url.validate(self, urlparse(self.bind_url).path) + subdomain_host = Unicode('', help="""Run single-user servers on subdomains of this host. @@ -338,21 +397,6 @@ def _domain_default(self): return '' return urlparse(self.subdomain_host).hostname - port = Integer(8000, - help="""The public facing port of the proxy. - - This is the port on which the proxy will listen. - This is the only port through which JupyterHub - should be accessed by users. - """ - ).tag(config=True) - base_url = URLPrefix('/', - help="""The base URL of the entire application. - - Add this to the begining of all JupyterHub URLs. - Use base_url to run JupyterHub within an existing website. - """ - ).tag(config=True) logo_file = Unicode('', help="Specify path to a logo image to override the Jupyter logo in the banner." ).tag(config=True) @@ -407,7 +451,7 @@ def _deprecated_proxy_api(self, change): hub_port = Integer(8081, help="""The internal port for the Hub process. - + This is the internal port of the hub itself. It should never be accessed directly. See JupyterHub.port for the public port to use when accessing jupyterhub. It is rare that this port should be set except in cases of port conflict. @@ -415,7 +459,7 @@ def _deprecated_proxy_api(self, change): ).tag(config=True) hub_ip = Unicode('127.0.0.1', help="""The ip address for the Hub process to *bind* to. - + By default, the hub listens on localhost only. This address must be accessible from the proxy and user servers. You may need to set this to a public ip or '' for all interfaces if the proxy or user servers are in containers or on a different host. @@ -440,14 +484,49 @@ def _deprecated_proxy_api(self, change): """ ).tag(config=True) + hub_connect_url = Unicode( + help=""" + The URL for connecting to the Hub. + Spawners, services, and the proxy will use this URL + to talk to the Hub. + + Only needs to be specified if the default hub URL is not + connectable (e.g. using a unix+http:// bind url). + + .. seealso:: + JupyterHub.hub_connect_ip + JupyterHub.hub_bind_url + .. versionadded:: 0.9 + """ + ) + hub_bind_url = Unicode( + help=""" + The URL on which the Hub will listen. + This is a private URL for internal communication. + Typically set in combination with hub_connect_url. + If a unix socket, hub_connect_url **must** also be set. + + For example: + + "http://127.0.0.1:8081" + "unix+http://%2Fsrv%2Fjupyterhub%2Fjupyterhub.sock" + + .. versionadded:: 0.9 + """, + config=True, + ) + hub_connect_port = Integer( 0, help=""" - The port for proxies & spawners to connect to the hub on. + DEPRECATED - Used alongside `hub_connect_ip` and only when different from hub_port. + Use hub_connect_url .. versionadded:: 0.8 + + .. deprecated:: 0.9 + Use hub_connect_url """ ).tag(config=True) @@ -825,10 +904,6 @@ def init_logging(self): logger.parent = self.log logger.setLevel(self.log.level) - def init_ports(self): - if self.hub_port == self.port: - raise TraitError("The hub and proxy cannot both listen on port %i" % self.port) - @staticmethod def add_url_prefix(prefix, handlers): """add a url prefix to handlers""" @@ -969,17 +1044,30 @@ def init_db(self): self.exit(e) def init_hub(self): - """Load the Hub config into the database""" - self.hub = Hub( - ip=self.hub_ip, - port=self.hub_port, + """Load the Hub URL config""" + hub_args = dict( base_url=self.hub_prefix, public_host=self.subdomain_host, ) + if self.hub_bind_url: + hub_args['bind_url'] = self.hub_bind_url + else: + hub_args['ip'] = self.hub_ip + hub_args['port'] = self.hub_port + self.hub = Hub(**hub_args) + if self.hub_connect_ip: self.hub.connect_ip = self.hub_connect_ip if self.hub_connect_port: self.hub.connect_port = self.hub_connect_port + self.log.warning( + "JupyterHub.hub_connect_port is deprecated as of 0.9." + " Use JupyterHub.hub_connect_url to fully specify" + " the URL for connecting to the Hub." + ) + + if self.hub_connect_url: + self.hub.connect_url = self.hub_connect_url async def init_users(self): """Load users into and from the database""" @@ -1346,15 +1434,9 @@ def cleanup_oauth_clients(self): def init_proxy(self): """Load the Proxy config""" # FIXME: handle deprecated config here - public_url = 'http{s}://{ip}:{port}{base_url}'.format( - s='s' if self.ssl_cert else '', - ip=self.ip, - port=self.port, - base_url=self.base_url, - ) self.proxy = self.proxy_class( db_factory=lambda: self.db, - public_url=public_url, + public_url=self.bind_url, parent=self, app=self, log=self.log, @@ -1469,7 +1551,6 @@ async def initialize(self, *args, **kwargs): self.update_config(cfg) self.write_pid_file() self.init_pycurl() - self.init_ports() self.init_secrets() self.init_db() self.init_hub() @@ -1626,13 +1707,26 @@ async def start(self): # start the webserver self.http_server = tornado.httpserver.HTTPServer(self.tornado_application, xheaders=True) + bind_url = urlparse(self.hub.bind_url) try: - self.http_server.listen(self.hub_port, address=self.hub_ip) + if bind_url.scheme.startswith('unix+'): + socket = bind_unix_socket(unquote(bind_url.netloc)) + self.http_server.add_socket(socket) + else: + ip = bind_url.hostname + port = bind_url.port + if not port: + if bind_url.scheme == 'https': + port = 443 + else: + port = 80 + self.http_server.listen(port, address=ip) + self.log.info("Hub API listening on %s", self.hub.bind_url) + if self.hub.url != self.hub.bind_url: + self.log.info("Private Hub API connect url %s", self.hub.url) except Exception: self.log.error("Failed to bind hub to %s", self.hub.bind_url) raise - else: - self.log.info("Hub API listening on %s", self.hub.bind_url) # start the proxy if self.proxy.should_start: diff --git a/jupyterhub/objects.py b/jupyterhub/objects.py --- a/jupyterhub/objects.py +++ b/jupyterhub/objects.py @@ -33,6 +33,19 @@ class Server(HasTraits): port = Integer() base_url = URLPrefix('/') cookie_name = Unicode('') + connect_url = Unicode('') + bind_url = Unicode('') + + @default('bind_url') + def bind_url_default(self): + """representation of URL used for binding + + Never used in APIs, only logging, + since it can be non-connectable value, such as '', meaning all interfaces. + """ + if self.ip in {'', '0.0.0.0'}: + return self.url.replace(self._connect_ip, self.ip or '*', 1) + return self.url @property def _connect_ip(self): @@ -107,6 +120,12 @@ def _change(self, change): @property def host(self): + if self.connect_url: + parsed = urlparse(self.connect_url) + return "{proto}://{host}".format( + proto=parsed.scheme, + host=parsed.netloc, + ) return "{proto}://{ip}:{port}".format( proto=self.proto, ip=self._connect_ip, @@ -115,22 +134,13 @@ def host(self): @property def url(self): + if self.connect_url: + return self.connect_url return "{host}{uri}".format( host=self.host, uri=self.base_url, ) - @property - def bind_url(self): - """representation of URL used for binding - - Never used in APIs, only logging, - since it can be non-connectable value, such as '', meaning all interfaces. - """ - if self.ip in {'', '0.0.0.0'}: - return self.url.replace(self._connect_ip, self.ip or '*', 1) - return self.url - def wait_up(self, timeout=10, http=False): """Wait for this server to come up""" if http: diff --git a/jupyterhub/proxy.py b/jupyterhub/proxy.py --- a/jupyterhub/proxy.py +++ b/jupyterhub/proxy.py @@ -305,7 +305,6 @@ async def check_routes(self, user_dict, service_dict, routes=None): hub = self.app.hub if '/' not in routes: - self.log.warning("Adding default route") futures.append(self.add_hub_route(hub)) else: route = routes['/'] diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -401,15 +401,30 @@ async def spawn(self, server_name='', options=None): f = maybe_future(spawner.start()) # commit any changes in spawner.start (always commit db changes before yield) db.commit() - ip_port = await gen.with_timeout(timedelta(seconds=spawner.start_timeout), f) - if ip_port: + url = await gen.with_timeout(timedelta(seconds=spawner.start_timeout), f) + if url: # get ip, port info from return value of start() - server.ip, server.port = ip_port + if isinstance(url, str): + # >= 0.9 can return a full URL string + pass + else: + # >= 0.7 returns (ip, port) + url = 'http://%s:%i' % url + urlinfo = urlparse(url) + server.proto = urlinfo.scheme + server.ip = urlinfo.hostname + port = urlinfo.port + if not port: + if urlinfo.scheme == 'https': + port = 443 + else: + port = 80 + server.port = port db.commit() else: # prior to 0.7, spawners had to store this info in user.server themselves. # Handle < 0.7 behavior with a warning, assuming info was stored in db by the Spawner. - self.log.warning("DEPRECATION: Spawner.start should return (ip, port) in JupyterHub >= 0.7") + self.log.warning("DEPRECATION: Spawner.start should return a url or (ip, port) tuple in JupyterHub >= 0.9") if spawner.api_token and spawner.api_token != api_token: # Spawner re-used an API token, discard the unused api_token orm_token = orm.APIToken.find(self.db, api_token)
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -213,17 +213,21 @@ class MockHub(JupyterHub): """Hub with various mock bits""" db_file = None - last_activity_interval = 2 - - base_url = '/@/space%20word/' - log_datefmt = '%M:%S' - + @default('subdomain_host') def _subdomain_host_default(self): return os.environ.get('JUPYTERHUB_TEST_SUBDOMAIN_HOST', '') - + + @default('bind_url') + def _default_bind_url(self): + if self.subdomain_host: + port = urlparse(self.subdomain_host).port + else: + port = random_port() + return 'http://127.0.0.1:%i/@/space%%20word/' % port + @default('ip') def _ip_default(self): return '127.0.0.1'
hub_connect_* assumes HTTP, can't use HTTPS While trying out 0.8.0rc1, I've hit a roadblock relating to the new `hub_connect_*` settings. On boot I see the message ``` Adding default route for Hub: / => http://... ``` My problem is that my server redirects to HTTPS, but tornado's httpclient does not redirect by default, resulting in ``` tornado.httpclient.HTTPError: HTTP 301: Moved Permanently ``` Services don't start and the browser just reports that the page isn't redirecting properly. The `http` is comming from `Server.proto` in `objects.py`, but the `proto` trait is not configurable. As discussed in #1289, I believe `connect_url` should be added.
2018-05-03T15:09:38Z
[]
[]
jupyterhub/jupyterhub
1,852
jupyterhub__jupyterhub-1852
[ "1851" ]
6a47123ec92be15d5872fd5833c6a57b376dff1e
diff --git a/jupyterhub/apihandlers/services.py b/jupyterhub/apihandlers/services.py --- a/jupyterhub/apihandlers/services.py +++ b/jupyterhub/apihandlers/services.py @@ -23,6 +23,7 @@ def service_model(service): 'prefix': service.server.base_url if service.server else '', 'command': service.command, 'pid': service.proc.pid if service.proc else 0, + 'info': service.info } class ServiceListAPIHandler(APIHandler): diff --git a/jupyterhub/services/service.py b/jupyterhub/services/service.py --- a/jupyterhub/services/service.py +++ b/jupyterhub/services/service.py @@ -175,6 +175,13 @@ class Service(LoggingConfigurable): If unspecified, an API token will be generated for managed services. """ ).tag(input=True) + + info = Dict( + help="""Provide a place to include miscellaneous information about the service, + provided through the configuration + """ + ).tag(input=True) + # Managed service API: spawner = Any()
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -1500,6 +1500,7 @@ def test_get_services(app, mockservice_url): 'pid': mockservice.proc.pid, 'prefix': mockservice.server.base_url, 'url': mockservice.url, + 'info': {}, } } @@ -1526,6 +1527,7 @@ def test_get_service(app, mockservice_url): 'pid': mockservice.proc.pid, 'prefix': mockservice.server.base_url, 'url': mockservice.url, + 'info': {}, } r = yield api_request(app, 'services/%s' % mockservice.name,
It would be helpful to be able to add configurable metadata to services In my use case, we have services by their design have a specific URL, but I'd like to pass along additional information to present a more friendly interface to the end user. In our specific case we have a tool which is associated with a database. It is more efficient at the low level to use an shortened form to refer to the database. However, I want to present to the end user a descriptive name. My propose solution is to add a "info" trait to the service object (I initially called it metadata and found out that it collides with a property). So to deploy a service my YAML section of my config.yaml looks like: ``` services: whoami: apiToken: < blah> url: http://whoami.kubernetes:8080 admin: false info: databases: my_db: "My Database" your_db: "Your Database as saved last January" ``` I've already made the change to jupyterhub in my local copy and will be pushing a pull request shortly. Thought I'd open an issue in the event there are some greater issues at play here.
2018-05-03T16:41:37Z
[]
[]
jupyterhub/jupyterhub
1,871
jupyterhub__jupyterhub-1871
[ "1869" ]
7ced657d79eef0bfe22345889f6592b97d66aa74
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -359,7 +359,6 @@ def _bind_url_changed(self, change): @default('base_url') def _default_base_url(self): # call validate to ensure leading/trailing slashes - print(self.bind_url) return JupyterHub.base_url.validate(self, urlparse(self.bind_url).path) subdomain_host = Unicode('', @@ -451,16 +450,20 @@ def _deprecated_proxy_api(self, change): This is the internal port of the hub itself. It should never be accessed directly. See JupyterHub.port for the public port to use when accessing jupyterhub. It is rare that this port should be set except in cases of port conflict. + + See also `hub_ip` for the ip and `hub_bind_url` for setting the full bind URL. """ ).tag(config=True) + hub_ip = Unicode('127.0.0.1', help="""The ip address for the Hub process to *bind* to. - By default, the hub listens on localhost only. This address must be accessible from - the proxy and user servers. You may need to set this to a public ip or '' for all + By default, the hub listens on localhost only. This address must be accessible from + the proxy and user servers. You may need to set this to a public ip or '' for all interfaces if the proxy or user servers are in containers or on a different host. - See `hub_connect_ip` for cases where the bind and connect address should differ. + See `hub_connect_ip` for cases where the bind and connect address should differ, + or `hub_bind_url` for setting the full bind URL. """ ).tag(config=True) @@ -492,10 +495,12 @@ def _deprecated_proxy_api(self, change): .. seealso:: JupyterHub.hub_connect_ip JupyterHub.hub_bind_url + .. versionadded:: 0.9 """, config=True ) + hub_bind_url = Unicode( help=""" The URL on which the Hub will listen. @@ -1064,6 +1069,11 @@ def init_hub(self): public_host=self.subdomain_host, ) if self.hub_bind_url: + # ensure hub_prefix is set on bind_url + self.hub_bind_url = urlunparse( + urlparse(self.hub_bind_url) + ._replace(path=self.hub_prefix) + ) hub_args['bind_url'] = self.hub_bind_url else: hub_args['ip'] = self.hub_ip @@ -1081,6 +1091,11 @@ def init_hub(self): ) if self.hub_connect_url: + # ensure hub_prefix is on connect_url + self.hub_connect_url = urlunparse( + urlparse(self.hub_connect_url) + ._replace(path=self.hub_prefix) + ) self.hub.connect_url = self.hub_connect_url async def init_users(self): diff --git a/jupyterhub/objects.py b/jupyterhub/objects.py --- a/jupyterhub/objects.py +++ b/jupyterhub/objects.py @@ -4,12 +4,12 @@ # Distributed under the terms of the Modified BSD License. import socket -from urllib.parse import urlparse +from urllib.parse import urlparse, urlunparse import warnings from traitlets import ( HasTraits, Instance, Integer, Unicode, - default, observe, + default, observe, validate, ) from .traitlets import URLPrefix from . import orm @@ -47,6 +47,28 @@ def bind_url_default(self): return self.url.replace(self._connect_ip, self.ip or '*', 1) return self.url + @observe('bind_url') + def _bind_url_changed(self, change): + urlinfo = urlparse(change.new) + self.proto = urlinfo.scheme + self.ip = urlinfo.hostname or '' + port = urlinfo.port + if port is None: + if self.proto == 'https': + port = 443 + else: + port = 80 + self.port = port + + @validate('connect_url') + def _connect_url_add_prefix(self, proposal): + """Ensure connect_url includes base_url""" + urlinfo = urlparse(proposal.value) + if not urlinfo.path.startswith(self.base_url): + urlinfo = urlinfo._replace(path=self.base_url) + return urlunparse(urlinfo) + return proposal.value + @property def _connect_ip(self): """The address to use when connecting to this server @@ -83,16 +105,7 @@ def from_orm(cls, orm_server): @classmethod def from_url(cls, url): """Create a Server from a given URL""" - urlinfo = urlparse(url) - proto = urlinfo.scheme - ip = urlinfo.hostname or '' - port = urlinfo.port - if not port: - if proto == 'https': - port = 443 - else: - port = 80 - return cls(proto=proto, ip=ip, port=port, base_url=urlinfo.path) + return cls(bind_url=url, base_url=urlparse(url).path) @default('port') def _default_port(self):
diff --git a/jupyterhub/tests/test_objects.py b/jupyterhub/tests/test_objects.py new file mode 100644 --- /dev/null +++ b/jupyterhub/tests/test_objects.py @@ -0,0 +1,70 @@ +"""Tests for basic object-wrappers""" + +import socket +import pytest + +from jupyterhub.objects import Server + + [email protected]( + 'bind_url, attrs', + [ + ( + 'http://abc:123', + { + 'ip': 'abc', + 'port': 123, + 'host': 'http://abc:123', + 'url': 'http://abc:123/x/', + } + ), + ( + 'https://abc', + { + 'ip': 'abc', + 'port': 443, + 'proto': 'https', + 'host': 'https://abc:443', + 'url': 'https://abc:443/x/', + } + ), + ] +) +def test_bind_url(bind_url, attrs): + s = Server(bind_url=bind_url, base_url='/x/') + for attr, value in attrs.items(): + assert getattr(s, attr) == value + + +_hostname = socket.gethostname() + + [email protected]( + 'ip, port, attrs', + [ + ( + '', 123, + { + 'ip': '', + 'port': 123, + 'host': 'http://{}:123'.format(_hostname), + 'url': 'http://{}:123/x/'.format(_hostname), + 'bind_url': 'http://*:123/x/', + } + ), + ( + '127.0.0.1', 999, + { + 'ip': '127.0.0.1', + 'port': 999, + 'host': 'http://127.0.0.1:999', + 'url': 'http://127.0.0.1:999/x/', + 'bind_url': 'http://127.0.0.1:999/x/', + } + ), + ] +) +def test_ip_port(ip, port, attrs): + s = Server(ip=ip, port=port, base_url='/x/') + for attr, value in attrs.items(): + assert getattr(s, attr) == value
Configuration problems with v0.9 (ECONNREFUSED) I'm trying to update my below configuration to no use deprecated attributes. The below configuration works: ``` IPADDRESS = public_ips()[0] c.JupyterHub.ip = IPADDRESS c.JupyterHub.hub_ip = '0.0.0.0' c.JupyterHub.hub_port = 8081 c.JupyterHub.hub_connect_ip = IPADDRESS ``` **Output:** ``` [I 2018-05-07 15:35:18.032 JupyterHub app:981] Loading cookie_secret from C:\JupyterHub\jupyterhub_cookie_secret [I 2018-05-07 15:35:18.097 JupyterHub proxy:429] Generating new CONFIGPROXY_AUTH_TOKEN [I 2018-05-07 15:35:18.186 JupyterHub app:1145] Not using whitelist. Any authenticated user will be allowed. [I 2018-05-07 15:35:18.236 JupyterHub app:1742] Hub API listening on http://0.0.0.0:8081/hub/ [I 2018-05-07 15:35:18.240 JupyterHub app:1744] Private Hub API connect url http://IPADDRESS:8081/hub/ [W 2018-05-07 15:35:18.243 JupyterHub proxy:481] Running JupyterHub without SSL. I hope there is SSL termination happening somewhere else... [I 2018-05-07 15:35:18.243 JupyterHub proxy:483] Starting proxy @ http://IPADDRESS:8000/ 15:35:18.566 - info: [ConfigProxy] Proxying http://IPADDRESS:8000 to (no default) 15:35:18.569 - info: [ConfigProxy] Proxy API at http://127.0.0.1:8001/api/routes 15:35:18.778 - info: [ConfigProxy] 200 GET /api/routes [I 2018-05-07 15:35:18.952 JupyterHub proxy:299] Checking routes [I 2018-05-07 15:35:18.953 JupyterHub proxy:368] Adding default route for Hub: / => http://IPADDRESS:8081 15:35:18.957 - info: [ConfigProxy] Adding route / -> http://IPADDRESS:8081 15:35:18.959 - info: [ConfigProxy] 201 POST /api/routes/ [I 2018-05-07 15:35:19.749 JupyterHub app:1799] JupyterHub is now running at http://IPADDRESS:8000 [I 2018-05-07 15:35:31.038 JupyterHub log:158] 302 GET / -> /hub (@10.200.18.81) 2.00ms [I 2018-05-07 15:35:31.266 JupyterHub log:158] 302 GET /hub -> /hub/login (@10.200.18.81) 1.00ms [I 2018-05-07 15:35:32.331 JupyterHub log:158] 302 GET /hub/login -> /user/dhirschf/ ([email protected]) 92.00ms [I 2018-05-07 15:35:32.335 JupyterHub log:158] 302 GET /user/dhirschf/ -> /hub/user/dhirschf/ (@10.200.18.81) 2.00ms ...server starts up fine. ``` ---- The updated config below results in an `ECONNREFUSED` error: ``` IPADDRESS = public_ips()[0] c.JupyterHub.bind_url = 'http://0.0.0.0:8000' c.JupyterHub.hub_bind_url = 'http://0.0.0.0:8081' c.JupyterHub.hub_connect_ip = IPADDRESS ``` **Output:** ``` [I 2018-05-07 15:26:22.318 JupyterHub app:981] Loading cookie_secret from C:\JupyterHub\jupyterhub_cookie_secret [I 2018-05-07 15:26:22.377 JupyterHub proxy:429] Generating new CONFIGPROXY_AUTH_TOKEN [I 2018-05-07 15:26:22.451 JupyterHub app:1145] Not using whitelist. Any authenticated user will be allowed. [I 2018-05-07 15:26:22.494 JupyterHub app:1742] Hub API listening on http://0.0.0.0:8081 [I 2018-05-07 15:26:22.496 JupyterHub app:1744] Private Hub API connect url http://IPADDRESS:63171/hub/ [W 2018-05-07 15:26:22.499 JupyterHub proxy:481] Running JupyterHub without SSL. I hope there is SSL termination happening somewhere else... [I 2018-05-07 15:26:22.499 JupyterHub proxy:483] Starting proxy @ http://0.0.0.0:8000/ 15:26:22.806 - info: [ConfigProxy] Proxying http://0.0.0.0:8000 to (no default) 15:26:22.809 - info: [ConfigProxy] Proxy API at http://127.0.0.1:8001/api/routes 15:26:28.532 - info: [ConfigProxy] 200 GET /api/routes 15:26:28.728 - info: [ConfigProxy] Adding route / -> http://IPADDRESS:63171 [I 2018-05-07 15:26:28.724 JupyterHub proxy:299] Checking routes [I 2018-05-07 15:26:28.725 JupyterHub proxy:368] Adding default route for Hub: / => http://IPADDRESS:63171 15:26:28.730 - info: [ConfigProxy] 201 POST /api/routes/ [I 2018-05-07 15:26:29.521 JupyterHub app:1799] JupyterHub is now running at http://0.0.0.0:8000 15:26:36.135 - error: [ConfigProxy] 503 GET / connect ECONNREFUSED IPADDRESS:63171 15:26:37.142 - error: [ConfigProxy] Failed to get custom error page Error: connect ECONNREFUSED IPADDRESS:63171 at Object.exports._errnoException (util.js:1020:11) at exports._exceptionWithHostPort (util.js:1043:20) at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1105:14) ...Service Unavailable web page ```
I'll continue to try and get to the bottom of it, but if anything jumps out at anyone I'll gladly take any suggestions! ### Note: > I'm running JupyterHub on win64/py36 I'm not sure where the 63171 port is coming from in the bad config: **Good:** ``` [I 2018-05-07 15:35:18.952 JupyterHub proxy:299] Checking routes [I 2018-05-07 15:35:18.953 JupyterHub proxy:368] Adding default route for Hub: / => http://IPADDRESS:8081 15:35:18.957 - info: [ConfigProxy] Adding route / -> http://IPADDRESS:8081 ``` **Bad:** ``` 15:26:28.728 - info: [ConfigProxy] Adding route / -> http://IPADDRESS:63171 [I 2018-05-07 15:26:28.724 JupyterHub proxy:299] Checking routes [I 2018-05-07 15:26:28.725 JupyterHub proxy:368] Adding default route for Hub: / => http://IPADDRESS:63171 ```
2018-05-07T08:44:25Z
[]
[]
jupyterhub/jupyterhub
1,891
jupyterhub__jupyterhub-1891
[ "1886" ]
02468f4625398f596a04fda8746150aa22c56cf4
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -315,6 +315,7 @@ def _template_paths_default(self): should be accessed by users. .. deprecated: 0.9 + Use JupyterHub.bind_url """ ).tag(config=True) @@ -330,26 +331,6 @@ def _template_paths_default(self): """ ).tag(config=True) - @observe('ip', 'port') - def _ip_port_changed(self, change): - urlinfo = urlparse(self.bind_url) - urlinfo = urlinfo._replace(netloc='%s:%i' % (self.ip, self.port)) - self.bind_url = urlunparse(urlinfo) - - bind_url = Unicode( - "http://127.0.0.1:8000", - help="""The public facing URL of the whole JupyterHub application. - - This is the address on which the proxy will bind. - Sets protocol, ip, base_url - """ - ).tag(config=True) - - @observe('bind_url') - def _bind_url_changed(self, change): - urlinfo = urlparse(change.new) - self.base_url = urlinfo.path - base_url = URLPrefix('/', help="""The base URL of the entire application. @@ -366,6 +347,25 @@ def _default_base_url(self): # call validate to ensure leading/trailing slashes return JupyterHub.base_url.validate(self, urlparse(self.bind_url).path) + @observe('ip', 'port', 'base_url') + def _url_part_changed(self, change): + """propagate deprecated ip/port/base_url config to the bind_url""" + urlinfo = urlparse(self.bind_url) + urlinfo = urlinfo._replace(netloc='%s:%i' % (self.ip, self.port)) + urlinfo = urlinfo._replace(path=self.base_url) + bind_url = urlunparse(urlinfo) + if bind_url != self.bind_url: + self.bind_url = bind_url + + bind_url = Unicode( + "http://127.0.0.1:8000", + help="""The public facing URL of the whole JupyterHub application. + + This is the address on which the proxy will bind. + Sets protocol, ip, base_url + """ + ).tag(config=True) + subdomain_host = Unicode('', help="""Run single-user servers on subdomains of this host.
diff --git a/jupyterhub/tests/test_app.py b/jupyterhub/tests/test_app.py --- a/jupyterhub/tests/test_app.py +++ b/jupyterhub/tests/test_app.py @@ -8,19 +8,22 @@ from tempfile import NamedTemporaryFile, TemporaryDirectory from unittest.mock import patch -from tornado import gen import pytest +from tornado import gen +from traitlets.config import Config from .mocking import MockHub from .test_api import add_user from .. import orm -from ..app import COOKIE_SECRET_BYTES +from ..app import COOKIE_SECRET_BYTES, JupyterHub + def test_help_all(): out = check_output([sys.executable, '-m', 'jupyterhub', '--help-all']).decode('utf8', 'replace') assert '--ip' in out assert '--JupyterHub.ip' in out + def test_token_app(): cmd = [sys.executable, '-m', 'jupyterhub', 'token'] out = check_output(cmd + ['--help-all']).decode('utf8', 'replace') @@ -30,6 +33,7 @@ def test_token_app(): out = check_output(cmd + ['user'], cwd=td).decode('utf8', 'replace').strip() assert re.match(r'^[a-z0-9]+$', out) + def test_generate_config(): with NamedTemporaryFile(prefix='jupyterhub_config', suffix='.py') as tf: cfg_file = tf.name @@ -218,3 +222,41 @@ def new_hub(): assert not user.running assert user.spawner.server is None assert list(db.query(orm.Server)) == [] + + [email protected]( + 'hub_config, expected', + [ + ( + {'ip': '0.0.0.0'}, + {'bind_url': 'http://0.0.0.0:8000/'}, + ), + ( + {'port': 123, 'base_url': '/prefix'}, + { + 'bind_url': 'http://:123/prefix/', + 'base_url': '/prefix/', + }, + ), + ( + {'bind_url': 'http://0.0.0.0:12345/sub'}, + {'base_url': '/sub/'}, + ), + ] +) +def test_url_config(hub_config, expected): + # construct the config object + cfg = Config() + for key, value in hub_config.items(): + cfg.JupyterHub[key] = value + + # instantiate the Hub and load config + app = JupyterHub(config=cfg) + # validate config + for key, value in hub_config.items(): + if key not in expected: + assert getattr(app, key) == value + + # validate additional properties + for key, value in expected.items(): + assert getattr(app, key) == value
Base url not respected in 0.9.0b1 Hi! Thanks for using JupyterHub. If you are reporting an issue with JupyterHub: - Please use the [GitHub issue](https://github.com/jupyterhub/jupyterhub/issues) search feature to check if your issue has been asked already. If it has, please add your comments to the existing issue. - Where applicable, please fill out the details below to help us troubleshoot the issue that you are facing. Please be as thorough as you are able to provide details on the issue. **How to reproduce the issue** Update to 0.9.0b1 with a `JupyterHub.bind_url` set and attempt to reach the hub at https://hostname/base_url/hub **What you expected to happen** Access hub home page **What actually happens** Redirected to https://hostname/hub/base_url/hub were an understandable 404 is given. **Share what version of JupyterHub you are using** 0.9.0b1 It is also notable that https://hostname/hub/ does lead to the hub home page. Seeing the introduction of `JupyterHub.bind_url`, this may be only a documentation issue, is `JupyterHub.base_url` deprecated?
Thanks for the report @chicocvenancio. Yes, we definitely need to improve documentation about bind_url. @minrk I'm doing a quick scan of issues, but this one seems like we need to look a bit closer at the behavior or tests to make sure we're catching url combinations correctly now that bind_url is introduced. IIUC @athornton was having some issues with `base_url` so perhaps he can shed some light on the problem... What's the exact config? Have you set *both* bind_url and base_url? and if so to what? @minrk https://github.com/chicocvenancio/paws/blob/dev/paws/values.yaml is the public part of the z2jh config used. Only `base_url` is set.
2018-05-15T08:51:44Z
[]
[]
jupyterhub/jupyterhub
1,910
jupyterhub__jupyterhub-1910
[ "1903" ]
09cd37feee7611d5ae9f97c7525e23c760734cc4
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -358,7 +358,7 @@ def _url_part_changed(self, change): self.bind_url = bind_url bind_url = Unicode( - "http://127.0.0.1:8000", + "http://:8000", help="""The public facing URL of the whole JupyterHub application. This is the address on which the proxy will bind.
diff --git a/jupyterhub/tests/test_app.py b/jupyterhub/tests/test_app.py --- a/jupyterhub/tests/test_app.py +++ b/jupyterhub/tests/test_app.py @@ -242,6 +242,16 @@ def new_hub(): {'bind_url': 'http://0.0.0.0:12345/sub'}, {'base_url': '/sub/'}, ), + ( + # no config, test defaults + {}, + { + 'base_url': '/', + 'bind_url': 'http://:8000', + 'ip': '', + 'port': 8000, + }, + ), ] ) def test_url_config(hub_config, expected):
Update README.md The default localhost does not work for docker. `0.0.0.0` is necessary to forward docker inside to outside.
Hi @aisensiy, Thanks for the PR. Instead of adding the ip for a specific use case, it would be better to leave the command as is, and add a sentence after that directs readers to the documentation http://jupyterhub.readthedocs.io/en/latest/getting-started/networking-basics.html#set-the-proxy-s-ip-address-and-port and http://jupyterhub.readthedocs.io/en/latest/quickstart-docker.html#starting-jupyterhub-with-docker Thanks.
2018-05-22T07:55:33Z
[]
[]
jupyterhub/jupyterhub
1,912
jupyterhub__jupyterhub-1912
[ "1908" ]
791dd5fb9fe8982619a9b81a1e16dbd6f66e13b9
diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -417,10 +417,20 @@ def get_next_url(self, user=None): - else: /hub/home """ next_url = self.get_argument('next', default='') - if (next_url + '/').startswith('%s://%s/' % (self.request.protocol, self.request.host)): + if (next_url + '/').startswith( + ( + '%s://%s/' % (self.request.protocol, self.request.host), + '//%s/' % self.request.host, + ) + ): # treat absolute URLs for our host as absolute paths: - next_url = urlparse(next_url).path - if next_url and not next_url.startswith('/'): + parsed = urlparse(next_url) + next_url = parsed.path + if parsed.query: + next_url = next_url + '?' + parsed.query + if parsed.hash: + next_url = next_url + '#' + parsed.hash + if next_url and (urlparse(next_url).netloc or not next_url.startswith('/')): self.log.warning("Disallowing redirect outside JupyterHub: %r", next_url) next_url = '' if next_url and next_url.startswith(url_path_join(self.base_url, 'user/')):
diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -3,6 +3,7 @@ from urllib.parse import urlencode, urlparse from tornado import gen +from tornado.httputil import url_concat from ..handlers import BaseHandler from ..utils import url_path_join as ujoin @@ -366,29 +367,50 @@ def mock_authenticate(handler, data): assert called_with == [form_data] [email protected]( + 'running, next_url, location', + [ + # default URL if next not specified, for both running and not + (True, '', ''), + (False, '', ''), + # next_url is respected + (False, '/hub/admin', '/hub/admin'), + (False, '/user/other', '/hub/user/other'), + (False, '/absolute', '/absolute'), + (False, '/has?query#andhash', '/has?query#andhash'), + + # next_url outside is not allowed + (False, 'https://other.domain', ''), + (False, 'ftp://other.domain', ''), + (False, '//other.domain', ''), + ] +) @pytest.mark.gen_test -def test_login_redirect(app): +def test_login_redirect(app, running, next_url, location): cookies = yield app.login_user('river') user = app.users['river'] - # no next_url, server running - yield user.spawn() - r = yield get_page('login', app, cookies=cookies, allow_redirects=False) - r.raise_for_status() - assert r.status_code == 302 - assert '/user/river' in r.headers['Location'] - - # no next_url, server not running - yield user.stop() - r = yield get_page('login', app, cookies=cookies, allow_redirects=False) - r.raise_for_status() - assert r.status_code == 302 - assert '/user/river' in r.headers['Location'] - - # next URL given, use it - r = yield get_page('login?next=/hub/admin', app, cookies=cookies, allow_redirects=False) + if location: + location = ujoin(app.base_url, location) + else: + # use default url + location = user.url + + url = 'login' + if next_url: + if '//' not in next_url: + next_url = ujoin(app.base_url, next_url, '') + url = url_concat(url, dict(next=next_url)) + + if running and not user.active: + # ensure running + yield user.spawn() + elif user.active and not running: + # ensure not running + yield user.stop() + r = yield get_page(url, app, cookies=cookies, allow_redirects=False) r.raise_for_status() assert r.status_code == 302 - assert r.headers['Location'].endswith('/hub/admin') + assert location == r.headers['Location'] @pytest.mark.gen_test
Open redirect during login Hi! Thanks for using JupyterHub. If you are reporting an issue with JupyterHub: **How to reproduce the issue** Login to JupyterHub with a URL like: https://hub.jupyter.com/hub/login?next=%2f%2fbaddomain.com **What you expected to happen** Parameters should be validated before sending the 302, preventing potential phishing attacks or tricking users into visiting malicious sites. **What actually happens** Users are redirected. **Share what version of JupyterHub you are using** 0.9.0
2018-05-22T13:41:17Z
[]
[]
jupyterhub/jupyterhub
1,926
jupyterhub__jupyterhub-1926
[ "1717" ]
f364661363f0948db1054217f16eb5dd0ee693a1
diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -282,7 +282,7 @@ def server(self): @property def escaped_name(self): """My name, escaped for use in URLs, cookies, etc.""" - return quote(self.name, safe='@') + return quote(self.name, safe='@~') @property def proxy_spec(self): @@ -295,15 +295,17 @@ def proxy_spec(self): @property def domain(self): """Get the domain for my server.""" - # FIXME: escaped_name probably isn't escaped enough in general for a domain fragment - return self.escaped_name + '.' + self.settings['domain'] + # use underscore as escape char for domains + return quote(self.name).replace('%', '_').lower() + '.' + self.settings['domain'] @property def host(self): """Get the *host* for my server (proto://domain[:port])""" # FIXME: escaped_name probably isn't escaped enough in general for a domain fragment parsed = urlparse(self.settings['subdomain_host']) - h = '%s://%s.%s' % (parsed.scheme, self.escaped_name, parsed.netloc) + h = '%s://%s' % (parsed.scheme, self.domain) + if parsed.port: + h += ':%i' % parsed.port return h @property
diff --git a/jupyterhub/tests/test_spawner.py b/jupyterhub/tests/test_spawner.py --- a/jupyterhub/tests/test_spawner.py +++ b/jupyterhub/tests/test_spawner.py @@ -11,6 +11,7 @@ import tempfile import time from unittest import mock +from urllib.parse import urlparse import pytest from tornado import gen @@ -20,7 +21,8 @@ from .. import spawner as spawnermod from ..spawner import LocalProcessSpawner, Spawner from ..user import User -from ..utils import new_token +from ..utils import new_token, url_path_join +from .mocking import public_url from .test_api import add_user from .utils import async_requests @@ -304,7 +306,7 @@ def test_spawner_reuse_api_token(db, app): @pytest.mark.gen_test def test_spawner_insert_api_token(app): """Token provided by spawner is not in the db - + Insert token into db as a user-provided token. """ # setup: new user, double check that they don't have any tokens registered @@ -379,3 +381,28 @@ def test_spawner_delete_server(app): # verify that both ORM and top-level references are None assert spawner.orm_spawner.server is None assert spawner.server is None + + [email protected]( + "name", + [ + "has@x", + "has~x", + "has%x", + "has%40x", + ] +) [email protected]_test +def test_spawner_routing(app, name): + """Test routing of names with special characters""" + db = app.db + with mock.patch.dict(app.config.LocalProcessSpawner, {'cmd': [sys.executable, '-m', 'jupyterhub.tests.mocksu']}): + user = add_user(app.db, app, name=name) + yield user.spawn() + yield wait_for_spawner(user.spawner) + yield app.proxy.add_user(user) + url = url_path_join(public_url(app, user), "test/url") + r = yield async_requests.get(url, allow_redirects=False) + r.raise_for_status() + assert r.url == url + assert r.text == urlparse(url).path
Users with some special characters can't connect to their servers with Chrome Chrome is substituting a few url encoded characters for the literal characters in URLs. The tilde is such a character, so it will substitute `%7E` for `~` in the request. This will make the notebook respond with a 404 to the request. Using another browser (eg Firefox), does not run into the same issue. **How to reproduce the issue** Create an user with a tilde in it and attempt to access your server in a jupyterhub deployment with Google Chrome. **What you expected to happen** Get a 200 response with the notebook server interface. **What actually happens** Get a 404 response. **Share what version of JupyterHub you are using** [email protected] so `jupyterhub==0.8.1` See https://phabricator.wikimedia.org/T189525
I'm going to label this as a bug so we recheck Chrome for 0.9 Still present in 0.9b3
2018-05-28T11:47:25Z
[]
[]
jupyterhub/jupyterhub
2,127
jupyterhub__jupyterhub-2127
[ "1849" ]
246f9f9044d04ddb3a8516c90e4f2c548b2c53db
diff --git a/jupyterhub/apihandlers/auth.py b/jupyterhub/apihandlers/auth.py --- a/jupyterhub/apihandlers/auth.py +++ b/jupyterhub/apihandlers/auth.py @@ -5,14 +5,20 @@ from datetime import datetime import json -from urllib.parse import quote +from urllib.parse import ( + parse_qsl, + quote, + urlencode, + urlparse, + urlunparse, +) -from oauth2.web.tornado import OAuth2Handler +from oauthlib import oauth2 from tornado import web from .. import orm from ..user import User -from ..utils import token_authenticated +from ..utils import token_authenticated, compare_token from .base import BaseHandler, APIHandler @@ -98,24 +104,190 @@ def get(self, cookie_name, cookie_value=None): self.write(json.dumps(self.user_model(user))) -class OAuthHandler(BaseHandler, OAuth2Handler): - """Implement OAuth provider handlers +class OAuthHandler: + def extract_oauth_params(self): + """extract oauthlib params from a request - OAuth2Handler sets `self.provider` in initialize, - but we are already passing the Provider object via settings. - """ - @property - def provider(self): - return self.settings['oauth_provider'] + Returns: - def initialize(self): - pass + (uri, http_method, body, headers) + """ + return ( + self.request.uri, + self.request.method, + self.request.body, + self.request.headers, + ) + + def make_absolute_redirect_uri(self, uri): + """Make absolute redirect URIs + + internal redirect uris, e.g. `/user/foo/oauth_handler` + are allowed in jupyterhub, but oauthlib prohibits them. + Add `$HOST` header to redirect_uri to make them acceptable. + + Currently unused in favor of monkeypatching + oauthlib.is_absolute_uri to skip the check + """ + redirect_uri = self.get_argument('redirect_uri') + if not redirect_uri or not redirect_uri.startswith('/'): + return uri + # make absolute local redirects full URLs + # to satisfy oauthlib's absolute URI requirement + redirect_uri = self.request.protocol + "://" + self.request.headers['Host'] + redirect_uri + parsed_url = urlparse(uri) + query_list = parse_qsl(parsed_url.query, keep_blank_values=True) + for idx, item in enumerate(query_list): + if item[0] == 'redirect_uri': + query_list[idx] = ('redirect_uri', redirect_uri) + break + + return urlunparse( + urlparse(uri) + ._replace(query=urlencode(query_list)) + ) + + def add_credentials(self, credentials=None): + """Add oauth credentials + + Adds user, session_id, client to oauth credentials + """ + if credentials is None: + credentials = {} + else: + credentials = credentials.copy() + + session_id = self.get_session_cookie() + if session_id is None: + session_id = self.set_session_cookie() + + user = self.get_current_user() + + # Extra credentials we need in the validator + credentials.update({ + 'user': user, + 'handler': self, + 'session_id': session_id, + }) + return credentials + + def send_oauth_response(self, headers, body, status): + """Send oauth response from provider return values + + Provider methods return headers, body, and status + to be set on the response. + + This method applies these values to the Handler + and sends the response. + """ + self.set_status(status) + for key, value in headers.items(): + self.set_header(key, value) + if body: + self.write(body) + + +class OAuthAuthorizeHandler(OAuthHandler, BaseHandler): + """Implement OAuth authorization endpoint(s)""" + + def _complete_login(self, uri, headers, scopes, credentials): + try: + headers, body, status = self.oauth_provider.create_authorization_response( + uri, 'POST', '', headers, scopes, credentials) + + except oauth2.FatalClientError as e: + # TODO: human error page + raise + self.send_oauth_response(headers, body, status) + + @web.authenticated + def get(self): + """GET /oauth/authorization + + Render oauth confirmation page: + "Server at ... would like permission to ...". + + Users accessing their own server will skip confirmation. + """ + + uri, http_method, body, headers = self.extract_oauth_params() + try: + scopes, credentials = self.oauth_provider.validate_authorization_request( + uri, http_method, body, headers) + credentials = self.add_credentials(credentials) + client = self.oauth_provider.fetch_by_client_id(credentials['client_id']) + if client.redirect_uri.startswith(self.get_current_user().url): + self.log.debug( + "Skipping oauth confirmation for %s accessing %s", + self.get_current_user(), client.description, + ) + # access to my own server doesn't require oauth confirmation + # this is the pre-1.0 behavior for all oauth + self._complete_login(uri, headers, scopes, credentials) + return + + # Render oauth 'Authorize application...' page + self.write( + self.render_template( + "oauth.html", + scopes=scopes, + oauth_client=client, + ) + ) + + # Errors that should be shown to the user on the provider website + except oauth2.FatalClientError as e: + raise web.HTTPError(e.status_code, e.description) + + # Errors embedded in the redirect URI back to the client + except oauth2.OAuth2Error as e: + self.log.error("OAuth error: %s", e.description) + self.redirect(e.in_uri(e.redirect_uri)) + + @web.authenticated + def post(self): + uri, http_method, body, headers = self.extract_oauth_params() + referer = self.request.headers.get('Referer', 'no referer') + full_url = self.request.full_url() + if referer != full_url: + # OAuth post must be made to the URL it came from + self.log.error("OAuth POST from %s != %s", referer, full_url) + raise web.HTTPError(403, "Authorization form must be sent from authorization page") + + # The scopes the user actually authorized, i.e. checkboxes + # that were selected. + scopes = self.get_arguments('scopes') + # credentials we need in the validator + credentials = self.add_credentials() + + try: + headers, body, status = self.oauth_provider.create_authorization_response( + uri, http_method, body, headers, scopes, credentials, + ) + except oauth2.FatalClientError as e: + raise web.HTTPError(e.status_code, e.description) + else: + self.send_oauth_response(headers, body, status) + + +class OAuthTokenHandler(OAuthHandler, APIHandler): + def post(self): + uri, http_method, body, headers = self.extract_oauth_params() + credentials = {} + + try: + headers, body, status = self.oauth_provider.create_token_response( + uri, http_method, body, headers, credentials) + except oauth2.FatalClientError as e: + raise web.HTTPError(e.status_code, e.description) + else: + self.send_oauth_response(headers, body, status) default_handlers = [ (r"/api/authorizations/cookie/([^/]+)(?:/([^/]+))?", CookieAPIHandler), (r"/api/authorizations/token/([^/]+)", TokenAPIHandler), (r"/api/authorizations/token", TokenAPIHandler), - (r"/api/oauth2/authorize", OAuthHandler), - (r"/api/oauth2/token", OAuthHandler), + (r"/api/oauth2/authorize", OAuthAuthorizeHandler), + (r"/api/oauth2/token", OAuthTokenHandler), ] diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -54,7 +54,7 @@ from . import crypto from . import dbutil, orm from .user import UserDict -from .oauth.store import make_provider +from .oauth.provider import make_provider from ._data import DATA_FILES_PATH from .log import CoroutineLogFormatter, log_request from .proxy import Proxy, ConfigurableHTTPProxy @@ -1331,7 +1331,7 @@ def init_services(self): host = '%s://services.%s' % (parsed.scheme, parsed.netloc) else: domain = host = '' - client_store = self.oauth_provider.client_authenticator.client_store + for spec in self.services: if 'name' not in spec: raise ValueError('service spec must have a name: %r' % spec) @@ -1389,7 +1389,7 @@ def init_services(self): service.orm.server = None if service.oauth_available: - client_store.add_client( + self.oauth_provider.add_client( client_id=service.oauth_client_id, client_secret=service.api_token, redirect_uri=service.oauth_redirect_uri, @@ -1489,9 +1489,9 @@ async def check_spawner(user, name, spawner): def init_oauth(self): base_url = self.hub.base_url self.oauth_provider = make_provider( - lambda : self.db, + lambda: self.db, url_prefix=url_path_join(base_url, 'api/oauth2'), - login_url=url_path_join(base_url, 'login') + login_url=url_path_join(base_url, 'login'), ) def cleanup_oauth_clients(self): @@ -1507,7 +1507,6 @@ def cleanup_oauth_clients(self): for spawner in user.spawners.values(): oauth_client_ids.add(spawner.oauth_client_id) - client_store = self.oauth_provider.client_authenticator.client_store for i, oauth_client in enumerate(self.db.query(orm.OAuthClient)): if oauth_client.identifier not in oauth_client_ids: self.log.warning("Deleting OAuth client %s", oauth_client.identifier) diff --git a/jupyterhub/oauth/provider.py b/jupyterhub/oauth/provider.py new file mode 100644 --- /dev/null +++ b/jupyterhub/oauth/provider.py @@ -0,0 +1,591 @@ +"""Utilities for hooking up oauth2 to JupyterHub's database + +implements https://oauthlib.readthedocs.io/en/latest/oauth2/server.html +""" + +from datetime import datetime +from urllib.parse import urlparse + +from oauthlib.oauth2 import RequestValidator, WebApplicationServer + +from sqlalchemy.orm import scoped_session +from tornado.escape import url_escape +from tornado.log import app_log +from tornado import web + +from .. import orm +from ..utils import url_path_join, hash_token, compare_token + + +# patch absolute-uri check +# because we want to allow relative uri oauth +# for internal services +from oauthlib.oauth2.rfc6749.grant_types import authorization_code +authorization_code.is_absolute_uri = lambda uri: True + + +class JupyterHubRequestValidator(RequestValidator): + + def __init__(self, db): + self.db = db + super().__init__() + + def authenticate_client(self, request, *args, **kwargs): + """Authenticate client through means outside the OAuth 2 spec. + Means of authentication is negotiated beforehand and may for example + be `HTTP Basic Authentication Scheme`_ which utilizes the Authorization + header. + Headers may be accesses through request.headers and parameters found in + both body and query can be obtained by direct attribute access, i.e. + request.client_id for client_id in the URL query. + :param request: oauthlib.common.Request + :rtype: True or False + Method is used by: + - Authorization Code Grant + - Resource Owner Password Credentials Grant (may be disabled) + - Client Credentials Grant + - Refresh Token Grant + .. _`HTTP Basic Authentication Scheme`: https://tools.ietf.org/html/rfc1945#section-11.1 + """ + app_log.debug("authenticate_client %s", request) + client_id = request.client_id + client_secret = request.client_secret + oauth_client = ( + self.db + .query(orm.OAuthClient) + .filter_by(identifier=client_id) + .first() + ) + if oauth_client is None: + return False + if not compare_token(oauth_client.secret, client_secret): + app_log.warning("Client secret mismatch for %s", client_id) + return False + + request.client = oauth_client + return True + + def authenticate_client_id(self, client_id, request, *args, **kwargs): + """Ensure client_id belong to a non-confidential client. + A non-confidential client is one that is not required to authenticate + through other means, such as using HTTP Basic. + Note, while not strictly necessary it can often be very convenient + to set request.client to the client object associated with the + given client_id. + :param request: oauthlib.common.Request + :rtype: True or False + Method is used by: + - Authorization Code Grant + """ + orm_client = ( + self.db + .query(orm.OAuthClient) + .filter_by(identifier=client_id) + .first() + ) + if orm_client is None: + app_log.warning("No such oauth client %s", client_id) + return False + request.client = orm_client + return True + + def confirm_redirect_uri(self, client_id, code, redirect_uri, client, + *args, **kwargs): + """Ensure that the authorization process represented by this authorization + code began with this 'redirect_uri'. + If the client specifies a redirect_uri when obtaining code then that + redirect URI must be bound to the code and verified equal in this + method, according to RFC 6749 section 4.1.3. Do not compare against + the client's allowed redirect URIs, but against the URI used when the + code was saved. + :param client_id: Unicode client identifier + :param code: Unicode authorization_code. + :param redirect_uri: Unicode absolute URI + :param client: Client object set by you, see authenticate_client. + :rtype: True or False + Method is used by: + - Authorization Code Grant (during token request) + """ + # TODO: record redirect_uri used during oauth + # if we ever support multiple destinations + app_log.debug("confirm_redirect_uri: client_id=%s, redirect_uri=%s", + client_id, redirect_uri, + ) + if redirect_uri == client.redirect_uri: + return True + else: + app_log.warning("Redirect uri %s != %s", redirect_uri, client.redirect_uri) + return False + + def get_default_redirect_uri(self, client_id, request, *args, **kwargs): + """Get the default redirect URI for the client. + :param client_id: Unicode client identifier + :param request: The HTTP Request (oauthlib.common.Request) + :rtype: The default redirect URI for the client + Method is used by: + - Authorization Code Grant + - Implicit Grant + """ + orm_client = ( + self.db + .query(orm.OAuthClient) + .filter_by(identifier=client_id) + .first() + ) + if orm_client is None: + raise KeyError(client_id) + return orm_client.redirect_uri + + def get_default_scopes(self, client_id, request, *args, **kwargs): + """Get the default scopes for the client. + :param client_id: Unicode client identifier + :param request: The HTTP Request (oauthlib.common.Request) + :rtype: List of default scopes + Method is used by all core grant types: + - Authorization Code Grant + - Implicit Grant + - Resource Owner Password Credentials Grant + - Client Credentials grant + """ + return ['identify'] + + def get_original_scopes(self, refresh_token, request, *args, **kwargs): + """Get the list of scopes associated with the refresh token. + :param refresh_token: Unicode refresh token + :param request: The HTTP Request (oauthlib.common.Request) + :rtype: List of scopes. + Method is used by: + - Refresh token grant + """ + raise NotImplementedError() + + def is_within_original_scope(self, request_scopes, refresh_token, request, *args, **kwargs): + """Check if requested scopes are within a scope of the refresh token. + When access tokens are refreshed the scope of the new token + needs to be within the scope of the original token. This is + ensured by checking that all requested scopes strings are on + the list returned by the get_original_scopes. If this check + fails, is_within_original_scope is called. The method can be + used in situations where returning all valid scopes from the + get_original_scopes is not practical. + :param request_scopes: A list of scopes that were requested by client + :param refresh_token: Unicode refresh_token + :param request: The HTTP Request (oauthlib.common.Request) + :rtype: True or False + Method is used by: + - Refresh token grant + """ + raise NotImplementedError() + + def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs): + """Invalidate an authorization code after use. + :param client_id: Unicode client identifier + :param code: The authorization code grant (request.code). + :param request: The HTTP Request (oauthlib.common.Request) + Method is used by: + - Authorization Code Grant + """ + app_log.debug("Deleting oauth code %s... for %s", code[:3], client_id) + orm_code = self.db.query(orm.OAuthCode).filter_by(code=code).first() + if orm_code is not None: + self.db.delete(orm_code) + self.db.commit() + + def revoke_token(self, token, token_type_hint, request, *args, **kwargs): + """Revoke an access or refresh token. + :param token: The token string. + :param token_type_hint: access_token or refresh_token. + :param request: The HTTP Request (oauthlib.common.Request) + Method is used by: + - Revocation Endpoint + """ + app_log.debug("Revoking %s %s", token_type_hint, token[:3] + '...') + raise NotImplementedError('Subclasses must implement this method.') + + def save_authorization_code(self, client_id, code, request, *args, **kwargs): + """Persist the authorization_code. + The code should at minimum be stored with: + - the client_id (client_id) + - the redirect URI used (request.redirect_uri) + - a resource owner / user (request.user) + - the authorized scopes (request.scopes) + - the client state, if given (code.get('state')) + The 'code' argument is actually a dictionary, containing at least a + 'code' key with the actual authorization code: + {'code': 'sdf345jsdf0934f'} + It may also have a 'state' key containing a nonce for the client, if it + chose to send one. That value should be saved and used in + 'validate_code'. + It may also have a 'claims' parameter which, when present, will be a dict + deserialized from JSON as described at + http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter + This value should be saved in this method and used again in 'validate_code'. + :param client_id: Unicode client identifier + :param code: A dict of the authorization code grant and, optionally, state. + :param request: The HTTP Request (oauthlib.common.Request) + Method is used by: + - Authorization Code Grant + """ + log_code = code.get('code', 'undefined')[:3] + '...' + app_log.debug("Saving authorization code %s, %s, %s, %s", client_id, log_code, args, kwargs) + orm_client = ( + self.db + .query(orm.OAuthClient) + .filter_by(identifier=client_id) + .first() + ) + if orm_client is None: + raise ValueError("No such client: %s" % client_id) + + orm_code = orm.OAuthCode( + client=orm_client, + code=code['code'], + # oauth has 5 minutes to complete + expires_at=int(datetime.utcnow().timestamp() + 300), + # TODO: persist oauth scopes + # scopes=request.scopes, + user=request.user.orm_user, + redirect_uri=orm_client.redirect_uri, + session_id=request.session_id, + ) + self.db.add(orm_code) + self.db.commit() + + def get_authorization_code_scopes(self, client_id, code, redirect_uri, request): + """ Extracts scopes from saved authorization code. + The scopes returned by this method is used to route token requests + based on scopes passed to Authorization Code requests. + With that the token endpoint knows when to include OpenIDConnect + id_token in token response only based on authorization code scopes. + Only code param should be sufficient to retrieve grant code from + any storage you are using, `client_id` and `redirect_uri` can gave a + blank value `""` don't forget to check it before using those values + in a select query if a database is used. + :param client_id: Unicode client identifier + :param code: Unicode authorization code grant + :param redirect_uri: Unicode absolute URI + :return: A list of scope + Method is used by: + - Authorization Token Grant Dispatcher + """ + raise NotImplementedError("TODO") + + def save_token(self, token, request, *args, **kwargs): + """Persist the token with a token type specific method. + Currently, only save_bearer_token is supported. + """ + return self.save_bearer_token(token, request, *args, **kwargs) + + def save_bearer_token(self, token, request, *args, **kwargs): + """Persist the Bearer token. + The Bearer token should at minimum be associated with: + - a client and it's client_id, if available + - a resource owner / user (request.user) + - authorized scopes (request.scopes) + - an expiration time + - a refresh token, if issued + - a claims document, if present in request.claims + The Bearer token dict may hold a number of items:: + { + 'token_type': 'Bearer', + 'access_token': 'askfjh234as9sd8', + 'expires_in': 3600, + 'scope': 'string of space separated authorized scopes', + 'refresh_token': '23sdf876234', # if issued + 'state': 'given_by_client', # if supplied by client + } + Note that while "scope" is a string-separated list of authorized scopes, + the original list is still available in request.scopes. + The token dict is passed as a reference so any changes made to the dictionary + will go back to the user. If additional information must return to the client + user, and it is only possible to get this information after writing the token + to storage, it should be added to the token dictionary. If the token + dictionary must be modified but the changes should not go back to the user, + a copy of the dictionary must be made before making the changes. + Also note that if an Authorization Code grant request included a valid claims + parameter (for OpenID Connect) then the request.claims property will contain + the claims dict, which should be saved for later use when generating the + id_token and/or UserInfo response content. + :param token: A Bearer token dict + :param request: The HTTP Request (oauthlib.common.Request) + :rtype: The default redirect URI for the client + Method is used by all core grant types issuing Bearer tokens: + - Authorization Code Grant + - Implicit Grant + - Resource Owner Password Credentials Grant (might not associate a client) + - Client Credentials grant + """ + log_token = {} + log_token.update(token) + scopes = token['scope'].split(' ') + # TODO: + if scopes != ['identify']: + raise ValueError("Only 'identify' scope is supported") + # redact sensitive keys in log + for key in ('access_token', 'refresh_token', 'state'): + if key in token: + value = token[key] + if isinstance(value, str): + log_token[key] = 'REDACTED' + app_log.debug("Saving bearer token %s", log_token) + if request.user is None: + raise ValueError("No user for access token: %s" % request.user) + client = self.db.query(orm.OAuthClient).filter_by(identifier=request.client.client_id).first() + orm_access_token = orm.OAuthAccessToken( + client=client, + grant_type=orm.GrantType.authorization_code, + expires_at=datetime.utcnow().timestamp() + token['expires_in'], + refresh_token=token['refresh_token'], + # TODO: save scopes, + # scopes=scopes, + token=token['access_token'], + session_id=request.session_id, + user=request.user, + ) + self.db.add(orm_access_token) + self.db.commit() + return client.redirect_uri + + def validate_bearer_token(self, token, scopes, request): + """Ensure the Bearer token is valid and authorized access to scopes. + :param token: A string of random characters. + :param scopes: A list of scopes associated with the protected resource. + :param request: The HTTP Request (oauthlib.common.Request) + A key to OAuth 2 security and restricting impact of leaked tokens is + the short expiration time of tokens, *always ensure the token has not + expired!*. + Two different approaches to scope validation: + 1) all(scopes). The token must be authorized access to all scopes + associated with the resource. For example, the + token has access to ``read-only`` and ``images``, + thus the client can view images but not upload new. + Allows for fine grained access control through + combining various scopes. + 2) any(scopes). The token must be authorized access to one of the + scopes associated with the resource. For example, + token has access to ``read-only-images``. + Allows for fine grained, although arguably less + convenient, access control. + A powerful way to use scopes would mimic UNIX ACLs and see a scope + as a group with certain privileges. For a restful API these might + map to HTTP verbs instead of read, write and execute. + Note, the request.user attribute can be set to the resource owner + associated with this token. Similarly the request.client and + request.scopes attribute can be set to associated client object + and authorized scopes. If you then use a decorator such as the + one provided for django these attributes will be made available + in all protected views as keyword arguments. + :param token: Unicode Bearer token + :param scopes: List of scopes (defined by you) + :param request: The HTTP Request (oauthlib.common.Request) + :rtype: True or False + Method is indirectly used by all core Bearer token issuing grant types: + - Authorization Code Grant + - Implicit Grant + - Resource Owner Password Credentials Grant + - Client Credentials Grant + """ + raise NotImplementedError('Subclasses must implement this method.') + + def validate_client_id(self, client_id, request, *args, **kwargs): + """Ensure client_id belong to a valid and active client. + Note, while not strictly necessary it can often be very convenient + to set request.client to the client object associated with the + given client_id. + :param request: oauthlib.common.Request + :rtype: True or False + Method is used by: + - Authorization Code Grant + - Implicit Grant + """ + app_log.debug("Validating client id %s", client_id) + orm_client = ( + self.db + .query(orm.OAuthClient) + .filter_by(identifier=client_id) + .first() + ) + if orm_client is None: + return False + request.client = orm_client + return True + + def validate_code(self, client_id, code, client, request, *args, **kwargs): + """Verify that the authorization_code is valid and assigned to the given + client. + Before returning true, set the following based on the information stored + with the code in 'save_authorization_code': + - request.user + - request.state (if given) + - request.scopes + - request.claims (if given) + OBS! The request.user attribute should be set to the resource owner + associated with this authorization code. Similarly request.scopes + must also be set. + The request.claims property, if it was given, should assigned a dict. + :param client_id: Unicode client identifier + :param code: Unicode authorization code + :param client: Client object set by you, see authenticate_client. + :param request: The HTTP Request (oauthlib.common.Request) + :rtype: True or False + Method is used by: + - Authorization Code Grant + """ + orm_code = ( + self.db + .query(orm.OAuthCode) + .filter_by(code=code) + .first() + ) + if orm_code is None: + app_log.debug("No such code: %s", code) + return False + if orm_code.client_id != client_id: + app_log.debug( + "OAuth code client id mismatch: %s != %s", + client_id, orm_code.client_id, + ) + return False + request.user = orm_code.user + request.session_id = orm_code.session_id + # TODO: record state on oauth codes + # TODO: specify scopes + request.scopes = ['identify'] + return True + + def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs): + """Ensure client is authorized to use the grant_type requested. + :param client_id: Unicode client identifier + :param grant_type: Unicode grant type, i.e. authorization_code, password. + :param client: Client object set by you, see authenticate_client. + :param request: The HTTP Request (oauthlib.common.Request) + :rtype: True or False + Method is used by: + - Authorization Code Grant + - Resource Owner Password Credentials Grant + - Client Credentials Grant + - Refresh Token Grant + """ + return grant_type == 'authorization_code' + + def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs): + """Ensure client is authorized to redirect to the redirect_uri requested. + All clients should register the absolute URIs of all URIs they intend + to redirect to. The registration is outside of the scope of oauthlib. + :param client_id: Unicode client identifier + :param redirect_uri: Unicode absolute URI + :param request: The HTTP Request (oauthlib.common.Request) + :rtype: True or False + Method is used by: + - Authorization Code Grant + - Implicit Grant + """ + app_log.debug("validate_redirect_uri: client_id=%s, redirect_uri=%s", + client_id, redirect_uri, + ) + orm_client = ( + self.db + .query(orm.OAuthClient) + .filter_by(identifier=client_id) + .first() + ) + if orm_client is None: + app_log.warning("No such oauth client %s", client_id) + return False + if redirect_uri == orm_client.redirect_uri: + return True + else: + app_log.warning("Redirect uri %s != %s", redirect_uri, orm_client.redirect_uri) + return False + + def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs): + """Ensure the Bearer token is valid and authorized access to scopes. + OBS! The request.user attribute should be set to the resource owner + associated with this refresh token. + :param refresh_token: Unicode refresh token + :param client: Client object set by you, see authenticate_client. + :param request: The HTTP Request (oauthlib.common.Request) + :rtype: True or False + Method is used by: + - Authorization Code Grant (indirectly by issuing refresh tokens) + - Resource Owner Password Credentials Grant (also indirectly) + - Refresh Token Grant + """ + return False + raise NotImplementedError('Subclasses must implement this method.') + + def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs): + """Ensure client is authorized to use the response_type requested. + :param client_id: Unicode client identifier + :param response_type: Unicode response type, i.e. code, token. + :param client: Client object set by you, see authenticate_client. + :param request: The HTTP Request (oauthlib.common.Request) + :rtype: True or False + Method is used by: + - Authorization Code Grant + - Implicit Grant + """ + # TODO + return True + + def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs): + """Ensure the client is authorized access to requested scopes. + :param client_id: Unicode client identifier + :param scopes: List of scopes (defined by you) + :param client: Client object set by you, see authenticate_client. + :param request: The HTTP Request (oauthlib.common.Request) + :rtype: True or False + Method is used by all core grant types: + - Authorization Code Grant + - Implicit Grant + - Resource Owner Password Credentials Grant + - Client Credentials Grant + """ + return True + + +class JupyterHubOAuthServer(WebApplicationServer): + def __init__(self, db, validator, *args, **kwargs): + self.db = db + super().__init__(validator, *args, **kwargs) + + def add_client(self, client_id, client_secret, redirect_uri, description=''): + """Add a client + + hash its client_secret before putting it in the database. + """ + # clear existing clients with same ID + for orm_client in ( + self.db + .query(orm.OAuthClient)\ + .filter_by(identifier=client_id) + ): + self.db.delete(orm_client) + self.db.commit() + + orm_client = orm.OAuthClient( + identifier=client_id, + secret=hash_token(client_secret), + redirect_uri=redirect_uri, + description=description, + ) + self.db.add(orm_client) + self.db.commit() + + def fetch_by_client_id(self, client_id): + """Find a client by its id""" + return ( + self.db + .query(orm.OAuthClient) + .filter_by(identifier=client_id) + .first() + ) + + +def make_provider(session_factory, url_prefix, login_url): + """Make an OAuth provider""" + db = session_factory() + validator = JupyterHubRequestValidator(db) + server = JupyterHubOAuthServer(db, validator) + return server + diff --git a/jupyterhub/oauth/store.py b/jupyterhub/oauth/store.py deleted file mode 100644 --- a/jupyterhub/oauth/store.py +++ /dev/null @@ -1,262 +0,0 @@ -"""Utilities for hooking up oauth2 to JupyterHub's database - -implements https://python-oauth2.readthedocs.io/en/latest/store.html -""" - -import threading - -from oauth2.datatype import Client, AuthorizationCode -from oauth2.error import AuthCodeNotFound, ClientNotFoundError, UserNotAuthenticated -from oauth2.grant import AuthorizationCodeGrant -from oauth2.web import AuthorizationCodeGrantSiteAdapter -import oauth2.store -from oauth2 import Provider -from oauth2.tokengenerator import Uuid4 as UUID4 - -from sqlalchemy.orm import scoped_session -from tornado.escape import url_escape - -from .. import orm -from ..utils import url_path_join, hash_token, compare_token - - -class JupyterHubSiteAdapter(AuthorizationCodeGrantSiteAdapter): - """ - This adapter renders a confirmation page so the user can confirm the auth - request. - """ - def __init__(self, login_url): - self.login_url = login_url - - def render_auth_page(self, request, response, environ, scopes, client): - """Auth page is a redirect to login page""" - response.status_code = 302 - response.headers['Location'] = self.login_url + '?next={}'.format( - url_escape(request.handler.request.path + '?' + request.handler.request.query) - ) - return response - - def authenticate(self, request, environ, scopes, client): - handler = request.handler - user = handler.get_current_user() - # ensure session_id is set - session_id = handler.get_session_cookie() - if session_id is None: - session_id = handler.set_session_cookie() - if user: - return {'session_id': session_id}, user.id - else: - raise UserNotAuthenticated() - - def user_has_denied_access(self, request): - # user can't deny access - return False - - -class HubDBMixin(object): - """Mixin for connecting to the hub database""" - def __init__(self, session_factory): - self.db = session_factory() - - -class AccessTokenStore(HubDBMixin, oauth2.store.AccessTokenStore): - """OAuth2 AccessTokenStore, storing data in the Hub database""" - - def save_token(self, access_token): - """ - Stores an access token in the database. - - :param access_token: An instance of :class:`oauth2.datatype.AccessToken`. - - """ - - user = self.db.query(orm.User).filter_by(id=access_token.user_id).first() - if user is None: - raise ValueError("No user for access token: %s" % access_token.user_id) - client = self.db.query(orm.OAuthClient).filter_by(identifier=access_token.client_id).first() - orm_access_token = orm.OAuthAccessToken( - client=client, - grant_type=access_token.grant_type, - expires_at=access_token.expires_at, - refresh_token=access_token.refresh_token, - refresh_expires_at=access_token.refresh_expires_at, - token=access_token.token, - session_id=access_token.data['session_id'], - user=user, - ) - self.db.add(orm_access_token) - self.db.commit() - - -class AuthCodeStore(HubDBMixin, oauth2.store.AuthCodeStore): - """ - OAuth2 AuthCodeStore, storing data in the Hub database - """ - def fetch_by_code(self, code): - """ - Returns an AuthorizationCode fetched from a storage. - - :param code: The authorization code. - :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. - :raises: :class:`oauth2.error.AuthCodeNotFound` if no data could be retrieved for - given code. - - """ - orm_code = ( - self.db - .query(orm.OAuthCode) - .filter_by(code=code) - .first() - ) - if orm_code is None: - raise AuthCodeNotFound() - else: - return AuthorizationCode( - client_id=orm_code.client_id, - code=code, - expires_at=orm_code.expires_at, - redirect_uri=orm_code.redirect_uri, - scopes=[], - user_id=orm_code.user_id, - data={'session_id': orm_code.session_id}, - ) - - def save_code(self, authorization_code): - """ - Stores the data belonging to an authorization code token. - - :param authorization_code: An instance of - :class:`oauth2.datatype.AuthorizationCode`. - """ - orm_client = ( - self.db - .query(orm.OAuthClient) - .filter_by(identifier=authorization_code.client_id) - .first() - ) - if orm_client is None: - raise ValueError("No such client: %s" % authorization_code.client_id) - - orm_user = ( - self.db - .query(orm.User) - .filter_by(id=authorization_code.user_id) - .first() - ) - if orm_user is None: - raise ValueError("No such user: %s" % authorization_code.user_id) - - orm_code = orm.OAuthCode( - client=orm_client, - code=authorization_code.code, - expires_at=authorization_code.expires_at, - user=orm_user, - redirect_uri=authorization_code.redirect_uri, - session_id=authorization_code.data.get('session_id', ''), - ) - self.db.add(orm_code) - self.db.commit() - - - def delete_code(self, code): - """ - Deletes an authorization code after its use per section 4.1.2. - - http://tools.ietf.org/html/rfc6749#section-4.1.2 - - :param code: The authorization code. - """ - orm_code = self.db.query(orm.OAuthCode).filter_by(code=code).first() - if orm_code is not None: - self.db.delete(orm_code) - self.db.commit() - - -class HashComparable: - """An object for storing hashed tokens - - Overrides `==` so that it compares as equal to its unhashed original - - Needed for storing hashed client_secrets - because python-oauth2 uses:: - - secret == client.client_secret - - and we don't want to store unhashed secrets in the database. - """ - def __init__(self, hashed_token): - self.hashed_token = hashed_token - - def __repr__(self): - return "<{} '{}'>".format(self.__class__.__name__, self.hashed_token) - - def __eq__(self, other): - return compare_token(self.hashed_token, other) - - -class ClientStore(HubDBMixin, oauth2.store.ClientStore): - """OAuth2 ClientStore, storing data in the Hub database""" - - def fetch_by_client_id(self, client_id): - """Retrieve a client by its identifier. - - :param client_id: Identifier of a client app. - :return: An instance of :class:`oauth2.datatype.Client`. - :raises: :class:`oauth2.error.ClientNotFoundError` if no data could be retrieved for - given client_id. - """ - orm_client = ( - self.db - .query(orm.OAuthClient) - .filter_by(identifier=client_id) - .first() - ) - if orm_client is None: - raise ClientNotFoundError() - return Client(identifier=client_id, - redirect_uris=[orm_client.redirect_uri], - secret=HashComparable(orm_client.secret), - ) - - def add_client(self, client_id, client_secret, redirect_uri, description=''): - """Add a client - - hash its client_secret before putting it in the database. - """ - # clear existing clients with same ID - for orm_client in ( - self.db - .query(orm.OAuthClient)\ - .filter_by(identifier=client_id) - ): - self.db.delete(orm_client) - self.db.commit() - - orm_client = orm.OAuthClient( - identifier=client_id, - secret=hash_token(client_secret), - redirect_uri=redirect_uri, - description=description, - ) - self.db.add(orm_client) - self.db.commit() - - -def make_provider(session_factory, url_prefix, login_url): - """Make an OAuth provider""" - token_store = AccessTokenStore(session_factory) - code_store = AuthCodeStore(session_factory) - client_store = ClientStore(session_factory) - - provider = Provider( - access_token_store=token_store, - auth_code_store=code_store, - client_store=client_store, - token_generator=UUID4(), - ) - provider.token_path = url_path_join(url_prefix, 'token') - provider.authorize_path = url_path_join(url_prefix, 'authorize') - site_adapter = JupyterHubSiteAdapter(login_url=login_url) - provider.add_grant(AuthorizationCodeGrant(site_adapter=site_adapter)) - return provider - diff --git a/jupyterhub/orm.py b/jupyterhub/orm.py --- a/jupyterhub/orm.py +++ b/jupyterhub/orm.py @@ -469,6 +469,7 @@ def api_id(self): grant_type = Column(Enum(GrantType), nullable=False) expires_at = Column(Integer) refresh_token = Column(Unicode(255)) + # TODO: drop refresh_expires_at. Refresh tokens shouldn't expire refresh_expires_at = Column(Integer) user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE')) service = None # for API-equivalence with APIToken @@ -513,6 +514,7 @@ class OAuthCode(Base): expires_at = Column(Integer) redirect_uri = Column(Unicode(1023)) session_id = Column(Unicode(255)) + # state = Column(Unicode(1023)) user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE')) @@ -524,6 +526,10 @@ class OAuthClient(Base): secret = Column(Unicode(255)) redirect_uri = Column(Unicode(1023)) + @property + def client_id(self): + return self.identifier + access_tokens = relationship( OAuthAccessToken, backref='client', diff --git a/jupyterhub/services/auth.py b/jupyterhub/services/auth.py --- a/jupyterhub/services/auth.py +++ b/jupyterhub/services/auth.py @@ -302,7 +302,15 @@ def _api_request(self, method, url, **kwargs): elif r.status_code >= 400: app_log.warning("Failed to check authorization: [%i] %s", r.status_code, r.reason) app_log.warning(r.text) - raise HTTPError(500, "Failed to check authorization") + msg = "Failed to check authorization" + # pass on error_description from oauth failure + try: + description = r.json().get("error_description") + except Exception: + pass + else: + msg += ": " + description + raise HTTPError(500, msg) else: data = r.json() @@ -847,6 +855,11 @@ class HubOAuthCallbackHandler(HubOAuthenticated, RequestHandler): @coroutine def get(self): + error = self.get_argument("error", False) + if error: + msg = self.get_argument("error_description", error) + raise HTTPError(400, "Error in oauth: %s" % msg) + code = self.get_argument("code", False) if not code: raise HTTPError(400, "oauth callback made without a token") diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -6,7 +6,6 @@ from urllib.parse import quote, urlparse import warnings -from oauth2.error import ClientNotFoundError from sqlalchemy import inspect from tornado import gen from tornado.log import app_log @@ -372,17 +371,14 @@ async def spawn(self, server_name='', options=None): client_id = spawner.oauth_client_id oauth_provider = self.settings.get('oauth_provider') if oauth_provider: - client_store = oauth_provider.client_authenticator.client_store - try: - oauth_client = client_store.fetch_by_client_id(client_id) - except ClientNotFoundError: - oauth_client = None + oauth_client = oauth_provider.fetch_by_client_id(client_id) # create a new OAuth client + secret on every launch # containers that resume will be updated below - client_store.add_client(client_id, api_token, - url_path_join(self.url, server_name, 'oauth_callback'), - description="Server at %s" % (url_path_join(self.base_url, server_name) + '/'), - ) + oauth_provider.add_client( + client_id, api_token, + url_path_join(self.url, server_name, 'oauth_callback'), + description="Server at %s" % (url_path_join(self.base_url, server_name) + '/'), + ) db.commit() # trigger pre-spawn hook on authenticator @@ -456,10 +452,10 @@ async def spawn(self, server_name='', options=None): ) # update OAuth client secret with updated API token if oauth_provider: - client_store = oauth_provider.client_authenticator.client_store - client_store.add_client(client_id, spawner.api_token, - url_path_join(self.url, server_name, 'oauth_callback'), - ) + oauth_provider.add_client( + client_id, spawner.api_token, + url_path_join(self.url, server_name, 'oauth_callback'), + ) db.commit() except Exception as e:
diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -573,6 +573,21 @@ def assert_announcement(name, text): assert_announcement("logout", r.text) [email protected]( + "params", + [ + "", + "redirect_uri=/noexist", + "redirect_uri=ok&client_id=nosuchthing", + ] +) [email protected]_test +def test_bad_oauth_get(app, params): + cookies = yield app.login_user("authorizer") + r = yield get_page("hub/api/oauth2/authorize?" + params, app, hub=False, cookies=cookies) + assert r.status_code == 400 + + @pytest.mark.gen_test def test_server_not_running_api_request(app): cookies = yield app.login_user("bees") diff --git a/jupyterhub/tests/test_services_auth.py b/jupyterhub/tests/test_services_auth.py --- a/jupyterhub/tests/test_services_auth.py +++ b/jupyterhub/tests/test_services_auth.py @@ -1,6 +1,8 @@ +"""Tests for service authentication""" import asyncio from binascii import hexlify import copy +from functools import partial import json import os from queue import Queue @@ -24,7 +26,7 @@ from ..utils import url_path_join from .mocking import public_url, public_host from .test_api import add_user -from .utils import async_requests +from .utils import async_requests, AsyncSession # mock for sending monotonic counter way into the future monotonic_future = mock.patch('time.monotonic', lambda : sys.maxsize) @@ -322,24 +324,29 @@ def test_hubauth_service_token(app, mockservice_url): def test_oauth_service(app, mockservice_url): service = mockservice_url url = url_path_join(public_url(app, mockservice_url) + 'owhoami/?arg=x') - # first request is only going to set login cookie - s = requests.Session() + # first request is only going to login and get us to the oauth form page + s = AsyncSession() name = 'link' s.cookies = yield app.login_user(name) - # run session.get in async_requests thread - s_get = lambda *args, **kwargs: async_requests.executor.submit(s.get, *args, **kwargs) - r = yield s_get(url) + + r = yield s.get(url) + r.raise_for_status() + # we should be looking at the oauth confirmation page + assert urlparse(r.url).path == app.base_url + 'hub/api/oauth2/authorize' + # verify oauth state cookie was set at some point + assert set(r.history[0].cookies.keys()) == {'service-%s-oauth-state' % service.name} + + # submit the oauth form to complete authorization + r = yield s.post(r.url, data={'scopes': ['identify']}, headers={'Referer': r.url}) r.raise_for_status() assert r.url == url # verify oauth cookie is set assert 'service-%s' % service.name in set(s.cookies.keys()) # verify oauth state cookie has been consumed assert 'service-%s-oauth-state' % service.name not in set(s.cookies.keys()) - # verify oauth state cookie was set at some point - assert set(r.history[0].cookies.keys()) == {'service-%s-oauth-state' % service.name} - # second request should be authenticated - r = yield s_get(url, allow_redirects=False) + # second request should be authenticated, which means no redirects + r = yield s.get(url, allow_redirects=False) r.raise_for_status() assert r.status_code == 200 reply = r.json() @@ -376,25 +383,23 @@ def test_oauth_cookie_collision(app, mockservice_url): service = mockservice_url url = url_path_join(public_url(app, mockservice_url), 'owhoami/') print(url) - s = requests.Session() + s = AsyncSession() name = 'mypha' s.cookies = yield app.login_user(name) - # run session.get in async_requests thread - s_get = lambda *args, **kwargs: async_requests.executor.submit(s.get, *args, **kwargs) state_cookie_name = 'service-%s-oauth-state' % service.name service_cookie_name = 'service-%s' % service.name - oauth_1 = yield s_get(url, allow_redirects=False) + oauth_1 = yield s.get(url) print(oauth_1.headers) print(oauth_1.cookies, oauth_1.url, url) assert state_cookie_name in s.cookies - state_cookies = [ s for s in s.cookies.keys() if s.startswith(state_cookie_name) ] + state_cookies = [ c for c in s.cookies.keys() if c.startswith(state_cookie_name) ] # only one state cookie assert state_cookies == [state_cookie_name] state_1 = s.cookies[state_cookie_name] # start second oauth login before finishing the first - oauth_2 = yield s_get(url, allow_redirects=False) - state_cookies = [ s for s in s.cookies.keys() if s.startswith(state_cookie_name) ] + oauth_2 = yield s.get(url) + state_cookies = [ c for c in s.cookies.keys() if c.startswith(state_cookie_name) ] assert len(state_cookies) == 2 # get the random-suffix cookie name state_cookie_2 = sorted(state_cookies)[-1] @@ -402,11 +407,14 @@ def test_oauth_cookie_collision(app, mockservice_url): assert s.cookies[state_cookie_name] == state_1 # finish oauth 2 - url = oauth_2.headers['Location'] - if not urlparse(url).netloc: - url = public_host(app) + url - r = yield s_get(url) + # submit the oauth form to complete authorization + r = yield s.post( + oauth_2.url, + data={'scopes': ['identify']}, + headers={'Referer': oauth_2.url}, + ) r.raise_for_status() + assert r.url == url # after finishing, state cookie is cleared assert state_cookie_2 not in s.cookies # service login cookie is set @@ -414,11 +422,14 @@ def test_oauth_cookie_collision(app, mockservice_url): service_cookie_2 = s.cookies[service_cookie_name] # finish oauth 1 - url = oauth_1.headers['Location'] - if not urlparse(url).netloc: - url = public_host(app) + url - r = yield s_get(url) + r = yield s.post( + oauth_1.url, + data={'scopes': ['identify']}, + headers={'Referer': oauth_1.url}, + ) r.raise_for_status() + assert r.url == url + # after finishing, state cookie is cleared (again) assert state_cookie_name not in s.cookies # service login cookie is set (again, to a different value) @@ -443,7 +454,7 @@ def test_oauth_logout(app, mockservice_url): service_cookie_name = 'service-%s' % service.name url = url_path_join(public_url(app, mockservice_url), 'owhoami/?foo=bar') # first request is only going to set login cookie - s = requests.Session() + s = AsyncSession() name = 'propha' app_user = add_user(app.db, app=app, name=name) def auth_tokens(): @@ -458,13 +469,16 @@ def auth_tokens(): s.cookies = yield app.login_user(name) assert 'jupyterhub-session-id' in s.cookies - # run session.get in async_requests thread - s_get = lambda *args, **kwargs: async_requests.executor.submit(s.get, *args, **kwargs) - r = yield s_get(url) + r = yield s.get(url) + r.raise_for_status() + assert urlparse(r.url).path.endswith('oauth2/authorize') + # submit the oauth form to complete authorization + r = yield s.post(r.url, data={'scopes': ['identify']}, headers={'Referer': r.url}) r.raise_for_status() assert r.url == url + # second request should be authenticated - r = yield s_get(url, allow_redirects=False) + r = yield s.get(url, allow_redirects=False) r.raise_for_status() assert r.status_code == 200 reply = r.json() @@ -483,13 +497,13 @@ def auth_tokens(): assert len(auth_tokens()) == 1 # hit hub logout URL - r = yield s_get(public_url(app, path='hub/logout')) + r = yield s.get(public_url(app, path='hub/logout')) r.raise_for_status() # verify that all cookies other than the service cookie are cleared assert list(s.cookies.keys()) == [service_cookie_name] # verify that clearing session id invalidates service cookie # i.e. redirect back to login page - r = yield s_get(url) + r = yield s.get(url) r.raise_for_status() assert r.url.split('?')[0] == public_url(app, path='hub/login') @@ -506,7 +520,7 @@ def auth_tokens(): # check that we got the old session id back assert session_id == s.cookies['jupyterhub-session-id'] - r = yield s_get(url, allow_redirects=False) + r = yield s.get(url, allow_redirects=False) r.raise_for_status() assert r.status_code == 200 reply = r.json() diff --git a/jupyterhub/tests/test_singleuser.py b/jupyterhub/tests/test_singleuser.py --- a/jupyterhub/tests/test_singleuser.py +++ b/jupyterhub/tests/test_singleuser.py @@ -10,7 +10,7 @@ from .mocking import StubSingleUserSpawner, public_url from ..utils import url_path_join -from .utils import async_requests +from .utils import async_requests, AsyncSession @pytest.mark.gen_test @@ -41,9 +41,20 @@ def test_singleuser_auth(app): r = yield async_requests.get(url_path_join(url, 'logout'), cookies=cookies) assert len(r.cookies) == 0 - # another user accessing should get 403, not redirect to login + # accessing another user's server hits the oauth confirmation page cookies = yield app.login_user('burgess') - r = yield async_requests.get(url, cookies=cookies) + s = AsyncSession() + s.cookies = cookies + r = yield s.get(url) + assert urlparse(r.url).path.endswith('/oauth2/authorize') + # submit the oauth form to complete authorization + r = yield s.post( + r.url, + data={'scopes': ['identify']}, + headers={'Referer': r.url}, + ) + assert urlparse(r.url).path.rstrip('/').endswith('/user/nandy/tree') + # user isn't authorized, should raise 403 assert r.status_code == 403 assert 'burgess' in r.text diff --git a/jupyterhub/tests/utils.py b/jupyterhub/tests/utils.py --- a/jupyterhub/tests/utils.py +++ b/jupyterhub/tests/utils.py @@ -3,7 +3,7 @@ class _AsyncRequests: """Wrapper around requests to return a Future from request methods - + A single thread is allocated to avoid blocking the IOLoop thread. """ def __init__(self): @@ -16,3 +16,7 @@ def __getattr__(self, name): # async_requests.get = requests.get returning a Future, etc. async_requests = _AsyncRequests() +class AsyncSession(requests.Session): + """requests.Session object that runs in the background thread""" + def request(self, *args, **kwargs): + return async_requests.executor.submit(super().request, *args, **kwargs)
switch to oauthlib I was investigating implementing an oauth confirmation page and found some significant impediments in our current oauth library, which isn't a very active project. I think we should switch to [oauthlib](http://oauthlib.readthedocs.io/en/latest/) which is a more widely used oauth implementation library. We would need to do most of the same things we have now, just translated to a slightly different API, but it shouldn't be too much. This should be a prerequisite for oauth scopes and login confirmation. This is for post-0.9.
2018-09-04T13:19:45Z
[]
[]
jupyterhub/jupyterhub
2,165
jupyterhub__jupyterhub-2165
[ "2146" ]
c87fcd9b71297923ebcfc604db2e4315fe2d41b5
diff --git a/jupyterhub/apihandlers/base.py b/jupyterhub/apihandlers/base.py --- a/jupyterhub/apihandlers/base.py +++ b/jupyterhub/apihandlers/base.py @@ -30,6 +30,9 @@ class APIHandler(BaseHandler): def content_security_policy(self): return '; '.join([super().content_security_policy, "default-src 'none'"]) + def get_content_type(self): + return 'application/json' + def check_referer(self): """Check Origin for cross-site API requests. @@ -265,3 +268,13 @@ def _check_group_model(self, model): def options(self, *args, **kwargs): self.finish() + + +class API404(APIHandler): + """404 for API requests + + Ensures JSON 404 errors for malformed URLs + """ + async def prepare(self): + await super().prepare() + raise web.HTTPError(404) diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -973,6 +973,8 @@ def init_handlers(self): h.extend(self.extra_handlers) h.append((r'/logo', LogoHandler, {'path': self.logo_file})) + h.append((r'/api/(.*)', apihandlers.base.API404)) + self.handlers = self.add_url_prefix(self.hub_prefix, h) # some extra handlers, outside hub_prefix self.handlers.extend([
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -100,6 +100,8 @@ def api_request(app, *api_path, **kwargs): assert "frame-ancestors 'self'" in resp.headers['Content-Security-Policy'] assert ujoin(app.hub.base_url, "security/csp-report") in resp.headers['Content-Security-Policy'] assert 'http' not in resp.headers['Content-Security-Policy'] + if not kwargs.get('stream', False) and resp.content: + assert resp.headers.get('content-type') == 'application/json' return resp @@ -746,6 +748,8 @@ def test_progress(request, app, no_patience, slow_spawn): r = yield api_request(app, 'users', name, 'server/progress', stream=True) r.raise_for_status() request.addfinalizer(r.close) + assert r.headers['content-type'] == 'text/event-stream' + ex = async_requests.executor line_iter = iter(r.iter_lines(decode_unicode=True)) evt = yield ex.submit(next_event, line_iter) @@ -807,6 +811,7 @@ def test_progress_ready(request, app): r = yield api_request(app, 'users', name, 'server/progress', stream=True) r.raise_for_status() request.addfinalizer(r.close) + assert r.headers['content-type'] == 'text/event-stream' ex = async_requests.executor line_iter = iter(r.iter_lines(decode_unicode=True)) evt = yield ex.submit(next_event, line_iter) @@ -826,6 +831,7 @@ def test_progress_bad(request, app, no_patience, bad_spawn): r = yield api_request(app, 'users', name, 'server/progress', stream=True) r.raise_for_status() request.addfinalizer(r.close) + assert r.headers['content-type'] == 'text/event-stream' ex = async_requests.executor line_iter = iter(r.iter_lines(decode_unicode=True)) evt = yield ex.submit(next_event, line_iter) @@ -847,6 +853,7 @@ def test_progress_bad_slow(request, app, no_patience, slow_bad_spawn): r = yield api_request(app, 'users', name, 'server/progress', stream=True) r.raise_for_status() request.addfinalizer(r.close) + assert r.headers['content-type'] == 'text/event-stream' ex = async_requests.executor line_iter = iter(r.iter_lines(decode_unicode=True)) evt = yield ex.submit(next_event, line_iter)
API handlers are returning text/html responses I've recently upgrade to v0.9.3 from v0.8.0. When I try to make a request to any of the API endpoints (`/hub/api/info` - for instance) I'm getting back the header Content-Type set to text/html instead of application/json as it used to be prior the upgrade. Should I use some configuration parameter, maybe related to tornado? Thanks!
Happens for me as well with `curl -v https://hub.mybinder.org/hub/api`. Not sure if something changed that by default you get `text/html` and have to send a header with your request to ask for JSON. Otherwise this seems like a regression. @betatim We tried to overcome this issue by forking the repo and setting the header on every API handler - though it'd be cleaner to use some kind of interceptor method. We'll keep watching for new updates. Do you want to make a PR to upstream your changes? Yes, I'll make it ASAP. The issue is that a `.get_content_type` method was [removed by accident](https://github.com/jupyterhub/jupyterhub/commit/a3ed3874559cfa551a2f0a1f915496210ed22f4f#diff-25c1b30b13352428653b89995c9ab459L21-L23) from `jupyterhub/apihandlers/base.py`. Adding back: ```python def get_content_type(self): return 'application/json' ``` to `jupyterhub.apihandlers.base.APIHandler` should fix this. @cristofercri are you planning to make that PR? If so, I will be happy to merge it and release 0.9.4 with the fix. @cristofercri do you have time for the PR in the next couple of days? If not, I'm happy to make it. Thanks for the report! @minrk since your fix seems simpler than mine, please go for it and make the PR. Thanks for your work!
2018-09-21T13:13:39Z
[]
[]
jupyterhub/jupyterhub
2,415
jupyterhub__jupyterhub-2415
[ "2390", "2390" ]
7c46fe74a50da4badc332ef671954e2fac406757
diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -1209,7 +1209,7 @@ async def get(self, user_name, user_path): status = 0 # server is not running, trigger spawn if status is not None: - if spawner.options_form: + if await spawner.get_options_form(): url_parts = [self.hub.base_url, 'spawn'] if current_user.name != user.name: # spawning on behalf of another user diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -74,11 +74,7 @@ class SpawnHandler(BaseHandler): Only enabled when Spawner.options_form is defined. """ - async def _render_form(self, message='', for_user=None): - # Note that 'user' is the authenticated user making the request and - # 'for_user' is the user whose server is being spawned. - user = for_user or self.get_current_user() - spawner_options_form = await user.spawner.get_options_form() + def _render_form(self, for_user, spawner_options_form, message=''): return self.render_template('spawn.html', for_user=for_user, spawner_options_form=spawner_options_form, @@ -107,10 +103,12 @@ async def get(self, for_user=None): self.log.debug("User is running: %s", url) self.redirect(url) return - if user.spawner.options_form: + + spawner_options_form = await user.spawner.get_options_form() + if spawner_options_form: # Add handler to spawner here so you can access query params in form rendering. user.spawner.handler = self - form = await self._render_form(for_user=user) + form = self._render_form(for_user=user, spawner_options_form=spawner_options_form) self.finish(form) else: # Explicit spawn request: clear _spawn_future @@ -154,7 +152,8 @@ async def post(self, for_user=None): await self.spawn_single_user(user, options=options) except Exception as e: self.log.error("Failed to spawn single-user server with form", exc_info=True) - form = await self._render_form(message=str(e), for_user=user) + spawner_options_form = await user.spawner.get_options_form() + form = self._render_form(for_user=user, spawner_options_form=spawner_options_form, message=str(e)) self.finish(form) return if current_user is user:
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -167,6 +167,11 @@ def options_from_form(self, form_data): options['hello'] = form_data['hello_file'][0] return options +class FalsyCallableFormSpawner(FormSpawner): + """A spawner that has a callable options form defined returning a falsy value""" + + options_form = lambda a, b: "" + class MockStructGroup: """Mock grp.struct_group""" diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -16,7 +16,7 @@ import pytest -from .mocking import FormSpawner +from .mocking import FormSpawner, FalsyCallableFormSpawner from .utils import ( async_requests, api_request, @@ -207,6 +207,13 @@ async def test_spawn_page(app): assert FormSpawner.options_form in r.text +async def test_spawn_page_falsy_callable(app): + with mock.patch.dict(app.users.settings, {'spawner_class': FalsyCallableFormSpawner}): + cookies = await app.login_user('erik') + r = await get_page('spawn', app, cookies=cookies) + assert 'user/erik' in r.url + + async def test_spawn_page_admin(app, admin_access): with mock.patch.dict(app.users.settings, {'spawner_class': FormSpawner}): cookies = await app.login_user('admin')
Configure options_form (or profile_list) for individual users # What I want I want to configure the users individual `spawner.options_form` (through KubeSpawner's `profile_list`) based on information provided by my identity provider for each authenticated user individually. # Why I want this When a user login, my JupyterHub currently receives information in a custom _claim_ called `gpu_access`. This is something that I've setup in [Okta](https://www.okta.com/) to be provided as a boolean based on if the user belongs to a specific group called GPU Access that I can manage nicely from an UI. I want to utilize this information to decide what options the user could choose from when spawning. Should the user for example be allowed to utilize a dedicated GPU node? # Code investigation These are conclusions drawn from investigating JupyterHub's source code: - The `pre_spawn_start` and `pre_spawn_hook` are called from within `spawn`. - `spawn` is called from within `spawn_single_user`. - `options_form` is evaluated before `spawn_single_user` is invoked in order to provide it with chosen options. ### auth.py / class Authenticator / pre_spawn_start() https://github.com/jupyterhub/jupyterhub/blob/0e6cf6a485b244c8b02e0da0269648c0de6370f7/jupyterhub/auth.py#L358-L362 ### auth.py / class Spawner / pre_spawn_hook() https://github.com/jupyterhub/jupyterhub/blob/392e432071c21070ab3d54ab2cb72c8bda09e6f4/jupyterhub/spawner.py#L541-L561 ### user.py / class User / spawn() This is where `pre_spawn_start` and `pre_spawn_hook` are invoked. https://github.com/jupyterhub/jupyterhub/blob/392e432071c21070ab3d54ab2cb72c8bda09e6f4/jupyterhub/user.py#L437-L451 ### base.py / class BaseHandler / spawn_single_user() This is where `spawn()` is invoked. https://github.com/jupyterhub/jupyterhub/blob/392e432071c21070ab3d54ab2cb72c8bda09e6f4/jupyterhub/handlers/base.py#L714 ### base.py / class UserSpawnHandler / get() https://github.com/jupyterhub/jupyterhub/blob/392e432071c21070ab3d54ab2cb72c8bda09e6f4/jupyterhub/handlers/base.py#L1188-L1199 # Request for input Before deciding to either support or not support configuring `options_form` on a per user basis, it seems reasonable to evaluate how it could be done first. So my request for input is regarding this how we could go about this. Would we add another hook? Where would we need to run it? What arguments would we pass it? ## Ideas Perhaps we could add a `user_refreshed_hook` on refreshed user state, that we would invoke from this method called `auth_to_user`? I think **this is my recommended solution**. But, I'm a bit uncertain, does this mean we need to allow the BaseHandler to be configurable with a traitlet? What is the @property fields doing? Hmmm... https://github.com/jupyterhub/jupyterhub/blob/392e432071c21070ab3d54ab2cb72c8bda09e6f4/jupyterhub/handlers/base.py#L560-L595 Perhaps we could add a `user_auth_state_updated_hook` whenever `auth_state` is updated/saved? The benefit of this is that we would do things whenever auth_state was updated, no matter if it was through a login etc or something else saved something to the users auth_state. The downside, is that perhaps we want to use a hook like this even though we don't save the auth_state. https://github.com/jupyterhub/jupyterhub/blob/392e432071c21070ab3d54ab2cb72c8bda09e6f4/jupyterhub/user.py#L161-L167 Configure options_form (or profile_list) for individual users # What I want I want to configure the users individual `spawner.options_form` (through KubeSpawner's `profile_list`) based on information provided by my identity provider for each authenticated user individually. # Why I want this When a user login, my JupyterHub currently receives information in a custom _claim_ called `gpu_access`. This is something that I've setup in [Okta](https://www.okta.com/) to be provided as a boolean based on if the user belongs to a specific group called GPU Access that I can manage nicely from an UI. I want to utilize this information to decide what options the user could choose from when spawning. Should the user for example be allowed to utilize a dedicated GPU node? # Code investigation These are conclusions drawn from investigating JupyterHub's source code: - The `pre_spawn_start` and `pre_spawn_hook` are called from within `spawn`. - `spawn` is called from within `spawn_single_user`. - `options_form` is evaluated before `spawn_single_user` is invoked in order to provide it with chosen options. ### auth.py / class Authenticator / pre_spawn_start() https://github.com/jupyterhub/jupyterhub/blob/0e6cf6a485b244c8b02e0da0269648c0de6370f7/jupyterhub/auth.py#L358-L362 ### auth.py / class Spawner / pre_spawn_hook() https://github.com/jupyterhub/jupyterhub/blob/392e432071c21070ab3d54ab2cb72c8bda09e6f4/jupyterhub/spawner.py#L541-L561 ### user.py / class User / spawn() This is where `pre_spawn_start` and `pre_spawn_hook` are invoked. https://github.com/jupyterhub/jupyterhub/blob/392e432071c21070ab3d54ab2cb72c8bda09e6f4/jupyterhub/user.py#L437-L451 ### base.py / class BaseHandler / spawn_single_user() This is where `spawn()` is invoked. https://github.com/jupyterhub/jupyterhub/blob/392e432071c21070ab3d54ab2cb72c8bda09e6f4/jupyterhub/handlers/base.py#L714 ### base.py / class UserSpawnHandler / get() https://github.com/jupyterhub/jupyterhub/blob/392e432071c21070ab3d54ab2cb72c8bda09e6f4/jupyterhub/handlers/base.py#L1188-L1199 # Request for input Before deciding to either support or not support configuring `options_form` on a per user basis, it seems reasonable to evaluate how it could be done first. So my request for input is regarding this how we could go about this. Would we add another hook? Where would we need to run it? What arguments would we pass it? ## Ideas Perhaps we could add a `user_refreshed_hook` on refreshed user state, that we would invoke from this method called `auth_to_user`? I think **this is my recommended solution**. But, I'm a bit uncertain, does this mean we need to allow the BaseHandler to be configurable with a traitlet? What is the @property fields doing? Hmmm... https://github.com/jupyterhub/jupyterhub/blob/392e432071c21070ab3d54ab2cb72c8bda09e6f4/jupyterhub/handlers/base.py#L560-L595 Perhaps we could add a `user_auth_state_updated_hook` whenever `auth_state` is updated/saved? The benefit of this is that we would do things whenever auth_state was updated, no matter if it was through a login etc or something else saved something to the users auth_state. The downside, is that perhaps we want to use a hook like this even though we don't save the auth_state. https://github.com/jupyterhub/jupyterhub/blob/392e432071c21070ab3d54ab2cb72c8bda09e6f4/jupyterhub/user.py#L161-L167
@minrk what do you think? If you think it make sense and provide a direction I'll write a PR for this. options_form is already configurable per-user, since it can be a callable, which can do arbitrary things based on `self.user`, including based on `await self.user.get_auth_state()`. `pre_spawn_start` doesn't seem like the right hook for something that doesn't happen prior to spawn, but instead happens prior to requesting the options form as *input* to the spawn. If we need a new hook for that, it should be added, but I suspect that the existing async `.options_form` hook is enough. For your case, it sounds like I would write this hook: ```python async def get_options_form(spawner): auth_state = await spawner.user.get_auth_state() has_gpu = auth_state.get('gpu-access') if has_gpu: return '<gpu form...>' else: return '<non-gpu form...>' c.MySpawner.options_form = get_options_form ``` Does that work for you? It doesn't sound like anything would be accomplished by the additional hooks, to me, and I'd like to keep them to a minimum if we can. @minrk thanks for taking the time to process my blob of text! This seems like an excellent example I did not consider! I'll investigate and follow up! Thanks for the help @minrk ! I wanted to utilize `profile_list` by `KubeSpawner` and found the following to be a working solution to do that. ```yaml hub: extraConfig: spawner: | from kubespawner import KubeSpawner class CustomKubeSpawner(KubeSpawner): # Override the options_form presented for users if they have gpu_access. # See: https://github.com/jupyterhub/jupyterhub/issues/2390 for related details async def options_form(self, spawner): auth_state = await self.user.get_auth_state() user_details = auth_state['oauth_user'] username = user_details['preferred_username'] gpu_access = user_details['gpu_access'] # type: bool # Dynamically provide a profile_list for those with GPU Access # ------------------------------------------------------------------ # NOTE: This is setup using a custom scope and claim called gpu_access # NOTE: Claims are info provided after requesting certain Scopes. # These are configurable in our Okta instance. if gpu_access: self.log.info(f'GPU access options will be presented for {username}.') self.profile_list = [ { 'default': True, 'display_name': 'Shared, 8 CPU cores', 'description': 'Your code will run on a shared machine. This will already be running and you should be up and running in 30 seconds or less.', }, { 'display_name': 'Personal, 4 CPU cores & 26GB RAM, 1 NVIDIA Tesla K80 GPU', 'description': 'Your code will run on a computer dedicated to you. No such computer is available ahead of time, so you need to wait 5-15 minutes before it is ready.', 'kubespawner_override': { 'image': 'eu.gcr.io/ds-platform/dsp-user-environment-gpu:c3959b5', 'extra_resource_limits': { 'nvidia.com/gpu': '1', }, 'node_selector': { 'gpu': 'k80', }, }, }, { 'display_name': "Personal, 4 CPU cores & 26GB RAM, 1 NVIDIA Tesla P100 GPU", 'description': 'Your code will run on a computer dedicated to you. No such computer is available ahead of time, so you need to wait 5-15 minutes before it is ready.', 'kubespawner_override': { 'image': 'eu.gcr.io/ds-platform/dsp-user-environment-gpu:c3959b5', 'extra_resource_limits': { 'nvidia.com/gpu': '1', }, 'node_selector': { 'gpu': 'p100', }, }, }, ] return super().options_form c.JupyterHub.spawner_class = CustomKubeSpawner ``` I still need to figure out how to avoid ending up with a blank choice screen if my profile_list is blank. ![image](https://user-images.githubusercontent.com/3837114/52693003-d13aba00-2f65-11e9-9379-968795b9cdda.png) --- __Backtracking:__ What matters is that a GET request to /spawn is made. This in turn results in an evaluation if `options_form` is truthy, but as I have overridden the traitlet with a function, it is. https://github.com/jupyterhub/jupyterhub/blob/919b6a8d6c1ac9577e27ee18fad451e975eedf18/jupyterhub/handlers/pages.py#L110-L114 This leads to the `_render_form` being executed: https://github.com/jupyterhub/jupyterhub/blob/919b6a8d6c1ac9577e27ee18fad451e975eedf18/jupyterhub/handlers/pages.py#L70-L88 This in turn leads to the base class Spawner's `get_options_form` is called: https://github.com/jupyterhub/jupyterhub/blob/7c46fe74a50da4badc332ef671954e2fac406757/jupyterhub/spawner.py#L308-L322 __Solution idea:__ I must do as KubeSpawner has done, I must provide a new default value of the traitlet `options_form` rather than overriding it with a truthy function. ## Struggling with my implementing solution idea I'm struggling as `_options_form_default` isn't defined with `async` and I would like to do something like this... ```python class CustomKubeSpawner(KubeSpawner): @default('options_form') def _options_form_default(self): auth_state = await self.user.get_auth_state() user_details = auth_state['oauth_user'] username = user_details['preferred_username'] gpu_access = user_details['gpu_access'] # type: bool # ... ``` ## Getting back to @minrk's idea If we assign this function to `options_form` we will make it truthy, and then we will end up rendering the blank template. ```python async def my_async_get_options_form(spawner): auth_state = await spawner.user.get_auth_state() has_gpu = auth_state.get('gpu-access') if has_gpu: return '<gpu form...>' else: return '<non-gpu form...>' c.MySpawner.options_form = my_async_get_options_form ``` ## Conclusion I think I need to override whats going on in the handler of web requests to the `/spawn` endpoint in order to resolve this... https://github.com/jupyterhub/jupyterhub/blob/919b6a8d6c1ac9577e27ee18fad451e975eedf18/jupyterhub/handlers/pages.py#L90-L126 This is because I need `options_form` to be falsy or truthy based awaiting information from `self.user.get_auth_state()`. But, only `get_options_form` could support this, but that will only be invoked if `options_form` is truthy. I think... ## Resolution? While I now have something somewhat functional. Currently I cannot redirect past the options based on information returned in `get_auth_state`, but I can decide to always show the form based on information returned in `get_auth_state`. I'm not sure how to proceed... ## Related issues #1681 - About making the `Spawner` function `get_options_form` async. Note that this function is only invoked if `options_form` is truthy, as checked from `SpawnHandler` defined in jupyterhub. Indeed, `_options_form_default` cannot be itself an async method (it can be called in init, so cannot be async). Instead, it can *return* an async method that will be called when options_form should be rendered, but that will be truthy. I think there is indeed a case here that hasn't been considered and isn't yet supported yet: defining an options form for some users, and having other users see *no* options form, rather than a different one. Is this actually your use case, or are you just testing right now? Do some users have no profile list, while others do? For now, I would recommend defining a default profile list with 'default', and then defining the gpu profiles as adding to that list. This should work right now. From what you have described, my sketch would not return a blank options form, because all cases return a non-empty form. What's different is that you are describing a case where the `get_options_form` may return no options form at all, which is not currently allowed. We can adjust this by actually completing the resolution of the async options form before considering its falsiness. > I think I need to override whats going on in the handler of web requests to the `/spawn` endpoint in order to resolve this... I don't think this is true. As long as async `.options_form` always returns a non-empty form, you should be okay. The worst case scenario for this is that users with only a default profile have an extra click to launch, but it has the *benefit* that they see there is an option-picking stage for their deployment, but they aren't entitled to more than one choice. @minrk ah yes my plan was indeed to provide options for some users while bypassing the options screen for other users. But, I'll make do with always showing this screen no matter what. It will add some complexity in the onboarding experience of my users, but this is not vital and could also help the new users understand whats going on and what may be possible for them if they request further permissions. I'm happy to work on supporting the use case of _bypassing the options form based on what `options_form` asynchronously returns_ if you think it could make sense. > if you think it could make sense. I think it could. It should work if we replace the boolean `if spawner.options_form` checks with async checks to `if await spawner.get_options_form()`. The only tricky bit will be if there are any such checks in places that can't be easily async. Perhaps we should make the `_render_form` non-async by passing it the awaited `get_spawner_option` results. I think the only place where `get_options_form` of the base Spawner class is called, is from within `_render_form` of the SpawnerHandler class. The `_render_form` is in turn called from the `post` request if an error occur or from `get` - both within the SpawnerHandler class. > The only tricky bit will be if there are any such checks in places that can't be easily async. I didn't grasp this very well. Do you mean it will be tricky if we have this blocking await check and this takes a while to evaluate? I meant replace all "is there an options form" checks, which are currently `if spawner.options_form` to `if await spawner.get_options_form()`, which returns the actual form, making it consistent with the old behavior of self.options_form when it could only be synchronously produced. > Do you mean it will be tricky if we have this blocking await check and this takes a while to evaluate? No, I mean syntactically. Not all places in the code are valid to add an `await` (`_options_form_default`, for example, cannot be made async). I'm not sure if there are any relevant places for this, but it could come up (inside a template render, for instance). This doesn't mean it can't be done, just that the change isn't just one line. This is, for instance, why `_render_form` calls get_options_form and passes the result to the render, because once you are inside render, no async methods can be called. The alternative is a smaller change in the spawn page logic, *only* doing the full render there: ```python options_form = await spawner.get_options_form() if options_form: render_form... else: # Explicit spawn request: ``` Now that I think of it, that's probably the way to go. @minrk okay I think we arrived at the same conclusion, PR coming up to make things easier to discuss further. @minrk what do you think? If you think it make sense and provide a direction I'll write a PR for this. options_form is already configurable per-user, since it can be a callable, which can do arbitrary things based on `self.user`, including based on `await self.user.get_auth_state()`. `pre_spawn_start` doesn't seem like the right hook for something that doesn't happen prior to spawn, but instead happens prior to requesting the options form as *input* to the spawn. If we need a new hook for that, it should be added, but I suspect that the existing async `.options_form` hook is enough. For your case, it sounds like I would write this hook: ```python async def get_options_form(spawner): auth_state = await spawner.user.get_auth_state() has_gpu = auth_state.get('gpu-access') if has_gpu: return '<gpu form...>' else: return '<non-gpu form...>' c.MySpawner.options_form = get_options_form ``` Does that work for you? It doesn't sound like anything would be accomplished by the additional hooks, to me, and I'd like to keep them to a minimum if we can. @minrk thanks for taking the time to process my blob of text! This seems like an excellent example I did not consider! I'll investigate and follow up! Thanks for the help @minrk ! I wanted to utilize `profile_list` by `KubeSpawner` and found the following to be a working solution to do that. ```yaml hub: extraConfig: spawner: | from kubespawner import KubeSpawner class CustomKubeSpawner(KubeSpawner): # Override the options_form presented for users if they have gpu_access. # See: https://github.com/jupyterhub/jupyterhub/issues/2390 for related details async def options_form(self, spawner): auth_state = await self.user.get_auth_state() user_details = auth_state['oauth_user'] username = user_details['preferred_username'] gpu_access = user_details['gpu_access'] # type: bool # Dynamically provide a profile_list for those with GPU Access # ------------------------------------------------------------------ # NOTE: This is setup using a custom scope and claim called gpu_access # NOTE: Claims are info provided after requesting certain Scopes. # These are configurable in our Okta instance. if gpu_access: self.log.info(f'GPU access options will be presented for {username}.') self.profile_list = [ { 'default': True, 'display_name': 'Shared, 8 CPU cores', 'description': 'Your code will run on a shared machine. This will already be running and you should be up and running in 30 seconds or less.', }, { 'display_name': 'Personal, 4 CPU cores & 26GB RAM, 1 NVIDIA Tesla K80 GPU', 'description': 'Your code will run on a computer dedicated to you. No such computer is available ahead of time, so you need to wait 5-15 minutes before it is ready.', 'kubespawner_override': { 'image': 'eu.gcr.io/ds-platform/dsp-user-environment-gpu:c3959b5', 'extra_resource_limits': { 'nvidia.com/gpu': '1', }, 'node_selector': { 'gpu': 'k80', }, }, }, { 'display_name': "Personal, 4 CPU cores & 26GB RAM, 1 NVIDIA Tesla P100 GPU", 'description': 'Your code will run on a computer dedicated to you. No such computer is available ahead of time, so you need to wait 5-15 minutes before it is ready.', 'kubespawner_override': { 'image': 'eu.gcr.io/ds-platform/dsp-user-environment-gpu:c3959b5', 'extra_resource_limits': { 'nvidia.com/gpu': '1', }, 'node_selector': { 'gpu': 'p100', }, }, }, ] return super().options_form c.JupyterHub.spawner_class = CustomKubeSpawner ``` I still need to figure out how to avoid ending up with a blank choice screen if my profile_list is blank. ![image](https://user-images.githubusercontent.com/3837114/52693003-d13aba00-2f65-11e9-9379-968795b9cdda.png) --- __Backtracking:__ What matters is that a GET request to /spawn is made. This in turn results in an evaluation if `options_form` is truthy, but as I have overridden the traitlet with a function, it is. https://github.com/jupyterhub/jupyterhub/blob/919b6a8d6c1ac9577e27ee18fad451e975eedf18/jupyterhub/handlers/pages.py#L110-L114 This leads to the `_render_form` being executed: https://github.com/jupyterhub/jupyterhub/blob/919b6a8d6c1ac9577e27ee18fad451e975eedf18/jupyterhub/handlers/pages.py#L70-L88 This in turn leads to the base class Spawner's `get_options_form` is called: https://github.com/jupyterhub/jupyterhub/blob/7c46fe74a50da4badc332ef671954e2fac406757/jupyterhub/spawner.py#L308-L322 __Solution idea:__ I must do as KubeSpawner has done, I must provide a new default value of the traitlet `options_form` rather than overriding it with a truthy function. ## Struggling with my implementing solution idea I'm struggling as `_options_form_default` isn't defined with `async` and I would like to do something like this... ```python class CustomKubeSpawner(KubeSpawner): @default('options_form') def _options_form_default(self): auth_state = await self.user.get_auth_state() user_details = auth_state['oauth_user'] username = user_details['preferred_username'] gpu_access = user_details['gpu_access'] # type: bool # ... ``` ## Getting back to @minrk's idea If we assign this function to `options_form` we will make it truthy, and then we will end up rendering the blank template. ```python async def my_async_get_options_form(spawner): auth_state = await spawner.user.get_auth_state() has_gpu = auth_state.get('gpu-access') if has_gpu: return '<gpu form...>' else: return '<non-gpu form...>' c.MySpawner.options_form = my_async_get_options_form ``` ## Conclusion I think I need to override whats going on in the handler of web requests to the `/spawn` endpoint in order to resolve this... https://github.com/jupyterhub/jupyterhub/blob/919b6a8d6c1ac9577e27ee18fad451e975eedf18/jupyterhub/handlers/pages.py#L90-L126 This is because I need `options_form` to be falsy or truthy based awaiting information from `self.user.get_auth_state()`. But, only `get_options_form` could support this, but that will only be invoked if `options_form` is truthy. I think... ## Resolution? While I now have something somewhat functional. Currently I cannot redirect past the options based on information returned in `get_auth_state`, but I can decide to always show the form based on information returned in `get_auth_state`. I'm not sure how to proceed... ## Related issues #1681 - About making the `Spawner` function `get_options_form` async. Note that this function is only invoked if `options_form` is truthy, as checked from `SpawnHandler` defined in jupyterhub. Indeed, `_options_form_default` cannot be itself an async method (it can be called in init, so cannot be async). Instead, it can *return* an async method that will be called when options_form should be rendered, but that will be truthy. I think there is indeed a case here that hasn't been considered and isn't yet supported yet: defining an options form for some users, and having other users see *no* options form, rather than a different one. Is this actually your use case, or are you just testing right now? Do some users have no profile list, while others do? For now, I would recommend defining a default profile list with 'default', and then defining the gpu profiles as adding to that list. This should work right now. From what you have described, my sketch would not return a blank options form, because all cases return a non-empty form. What's different is that you are describing a case where the `get_options_form` may return no options form at all, which is not currently allowed. We can adjust this by actually completing the resolution of the async options form before considering its falsiness. > I think I need to override whats going on in the handler of web requests to the `/spawn` endpoint in order to resolve this... I don't think this is true. As long as async `.options_form` always returns a non-empty form, you should be okay. The worst case scenario for this is that users with only a default profile have an extra click to launch, but it has the *benefit* that they see there is an option-picking stage for their deployment, but they aren't entitled to more than one choice. @minrk ah yes my plan was indeed to provide options for some users while bypassing the options screen for other users. But, I'll make do with always showing this screen no matter what. It will add some complexity in the onboarding experience of my users, but this is not vital and could also help the new users understand whats going on and what may be possible for them if they request further permissions. I'm happy to work on supporting the use case of _bypassing the options form based on what `options_form` asynchronously returns_ if you think it could make sense. > if you think it could make sense. I think it could. It should work if we replace the boolean `if spawner.options_form` checks with async checks to `if await spawner.get_options_form()`. The only tricky bit will be if there are any such checks in places that can't be easily async. Perhaps we should make the `_render_form` non-async by passing it the awaited `get_spawner_option` results. I think the only place where `get_options_form` of the base Spawner class is called, is from within `_render_form` of the SpawnerHandler class. The `_render_form` is in turn called from the `post` request if an error occur or from `get` - both within the SpawnerHandler class. > The only tricky bit will be if there are any such checks in places that can't be easily async. I didn't grasp this very well. Do you mean it will be tricky if we have this blocking await check and this takes a while to evaluate? I meant replace all "is there an options form" checks, which are currently `if spawner.options_form` to `if await spawner.get_options_form()`, which returns the actual form, making it consistent with the old behavior of self.options_form when it could only be synchronously produced. > Do you mean it will be tricky if we have this blocking await check and this takes a while to evaluate? No, I mean syntactically. Not all places in the code are valid to add an `await` (`_options_form_default`, for example, cannot be made async). I'm not sure if there are any relevant places for this, but it could come up (inside a template render, for instance). This doesn't mean it can't be done, just that the change isn't just one line. This is, for instance, why `_render_form` calls get_options_form and passes the result to the render, because once you are inside render, no async methods can be called. The alternative is a smaller change in the spawn page logic, *only* doing the full render there: ```python options_form = await spawner.get_options_form() if options_form: render_form... else: # Explicit spawn request: ``` Now that I think of it, that's probably the way to go. @minrk okay I think we arrived at the same conclusion, PR coming up to make things easier to discuss further.
2019-02-13T09:50:59Z
[]
[]
jupyterhub/jupyterhub
2,418
jupyterhub__jupyterhub-2418
[ "2416" ]
856923b35f8822f38ef43007914db7483a3cb452
diff --git a/docs/source/conf.py b/docs/source/conf.py --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -1,11 +1,8 @@ # -*- coding: utf-8 -*- # -import sys import os import shlex - -# For conversion from markdown to html -import recommonmark.parser +import sys # Set paths sys.path.insert(0, os.path.abspath('.')) @@ -21,7 +18,7 @@ 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon', 'autodoc_traits', - 'sphinx_copybutton' + 'sphinx_copybutton', ] templates_path = ['_templates'] @@ -68,6 +65,7 @@ # The theme to use for HTML and HTML Help pages. import alabaster_jupyterhub + html_theme = 'alabaster_jupyterhub' html_theme_path = [alabaster_jupyterhub.get_html_theme_path()] diff --git a/docs/sphinxext/autodoc_traits.py b/docs/sphinxext/autodoc_traits.py --- a/docs/sphinxext/autodoc_traits.py +++ b/docs/sphinxext/autodoc_traits.py @@ -1,8 +1,9 @@ """autodoc extension for configurable traits""" - -from traitlets import TraitType, Undefined from sphinx.domains.python import PyClassmember -from sphinx.ext.autodoc import ClassDocumenter, AttributeDocumenter +from sphinx.ext.autodoc import AttributeDocumenter +from sphinx.ext.autodoc import ClassDocumenter +from traitlets import TraitType +from traitlets import Undefined class ConfigurableDocumenter(ClassDocumenter): diff --git a/examples/bootstrap-script/jupyterhub_config.py b/examples/bootstrap-script/jupyterhub_config.py --- a/examples/bootstrap-script/jupyterhub_config.py +++ b/examples/bootstrap-script/jupyterhub_config.py @@ -5,24 +5,28 @@ # pylint: disable=import-error import os import shutil + from jupyter_client.localinterfaces import public_ips + def create_dir_hook(spawner): """ Create directory """ - username = spawner.user.name # get the username + username = spawner.user.name # get the username volume_path = os.path.join('/volumes/jupyterhub', username) if not os.path.exists(volume_path): os.mkdir(volume_path, 0o755) # now do whatever you think your user needs # ... + def clean_dir_hook(spawner): """ Delete directory """ - username = spawner.user.name # get the username + username = spawner.user.name # get the username temp_path = os.path.join('/volumes/jupyterhub', username, 'temp') if os.path.exists(temp_path) and os.path.isdir(temp_path): shutil.rmtree(temp_path) + # attach the hook functions to the spawner # pylint: disable=undefined-variable c.Spawner.pre_spawn_hook = create_dir_hook @@ -37,4 +41,4 @@ def clean_dir_hook(spawner): # You can now mount the volume to the docker container as we've # made sure the directory exists # pylint: disable=bad-whitespace -c.DockerSpawner.volumes = { '/volumes/jupyterhub/{username}/': '/home/jovyan/work' } +c.DockerSpawner.volumes = {'/volumes/jupyterhub/{username}/': '/home/jovyan/work'} diff --git a/examples/cull-idle/cull_idle_servers.py b/examples/cull-idle/cull_idle_servers.py --- a/examples/cull-idle/cull_idle_servers.py +++ b/examples/cull-idle/cull_idle_servers.py @@ -31,11 +31,11 @@ twice, just with different ``name``s, different values, and one with the ``--cull-users`` option. """ - -from datetime import datetime, timezone -from functools import partial import json import os +from datetime import datetime +from datetime import timezone +from functools import partial try: from urllib.parse import quote @@ -85,23 +85,21 @@ def format_td(td): @coroutine -def cull_idle(url, api_token, inactive_limit, cull_users=False, max_age=0, concurrency=10): +def cull_idle( + url, api_token, inactive_limit, cull_users=False, max_age=0, concurrency=10 +): """Shutdown idle single-user servers If cull_users, inactive *users* will be deleted as well. """ - auth_header = { - 'Authorization': 'token %s' % api_token, - } - req = HTTPRequest( - url=url + '/users', - headers=auth_header, - ) + auth_header = {'Authorization': 'token %s' % api_token} + req = HTTPRequest(url=url + '/users', headers=auth_header) now = datetime.now(timezone.utc) client = AsyncHTTPClient() if concurrency: semaphore = Semaphore(concurrency) + @coroutine def fetch(req): """client.fetch wrapped in a semaphore to limit concurrency""" @@ -110,6 +108,7 @@ def fetch(req): return (yield client.fetch(req)) finally: yield semaphore.release() + else: fetch = client.fetch @@ -129,8 +128,8 @@ def handle_server(user, server_name, server): log_name = '%s/%s' % (user['name'], server_name) if server.get('pending'): app_log.warning( - "Not culling server %s with pending %s", - log_name, server['pending']) + "Not culling server %s with pending %s", log_name, server['pending'] + ) return False # jupyterhub < 0.9 defined 'server.url' once the server was ready @@ -142,8 +141,8 @@ def handle_server(user, server_name, server): if not server.get('ready', bool(server['url'])): app_log.warning( - "Not culling not-ready not-pending server %s: %s", - log_name, server) + "Not culling not-ready not-pending server %s: %s", log_name, server + ) return False if server.get('started'): @@ -163,12 +162,13 @@ def handle_server(user, server_name, server): # for running servers inactive = age - should_cull = (inactive is not None and - inactive.total_seconds() >= inactive_limit) + should_cull = ( + inactive is not None and inactive.total_seconds() >= inactive_limit + ) if should_cull: app_log.info( - "Culling server %s (inactive for %s)", - log_name, format_td(inactive)) + "Culling server %s (inactive for %s)", log_name, format_td(inactive) + ) if max_age and not should_cull: # only check started if max_age is specified @@ -177,32 +177,34 @@ def handle_server(user, server_name, server): if age is not None and age.total_seconds() >= max_age: app_log.info( "Culling server %s (age: %s, inactive for %s)", - log_name, format_td(age), format_td(inactive)) + log_name, + format_td(age), + format_td(inactive), + ) should_cull = True if not should_cull: app_log.debug( "Not culling server %s (age: %s, inactive for %s)", - log_name, format_td(age), format_td(inactive)) + log_name, + format_td(age), + format_td(inactive), + ) return False if server_name: # culling a named server delete_url = url + "/users/%s/servers/%s" % ( - quote(user['name']), quote(server['name']) + quote(user['name']), + quote(server['name']), ) else: delete_url = url + '/users/%s/server' % quote(user['name']) - req = HTTPRequest( - url=delete_url, method='DELETE', headers=auth_header, - ) + req = HTTPRequest(url=delete_url, method='DELETE', headers=auth_header) resp = yield fetch(req) if resp.code == 202: - app_log.warning( - "Server %s is slow to stop", - log_name, - ) + app_log.warning("Server %s is slow to stop", log_name) # return False to prevent culling user with pending shutdowns return False return True @@ -245,7 +247,9 @@ def handle_user(user): if still_alive: app_log.debug( "Not culling user %s with %i servers still alive", - user['name'], still_alive) + user['name'], + still_alive, + ) return False should_cull = False @@ -265,12 +269,11 @@ def handle_user(user): # which introduces the 'created' field which is never None inactive = age - should_cull = (inactive is not None and - inactive.total_seconds() >= inactive_limit) + should_cull = ( + inactive is not None and inactive.total_seconds() >= inactive_limit + ) if should_cull: - app_log.info( - "Culling user %s (inactive for %s)", - user['name'], inactive) + app_log.info("Culling user %s (inactive for %s)", user['name'], inactive) if max_age and not should_cull: # only check created if max_age is specified @@ -279,19 +282,23 @@ def handle_user(user): if age is not None and age.total_seconds() >= max_age: app_log.info( "Culling user %s (age: %s, inactive for %s)", - user['name'], format_td(age), format_td(inactive)) + user['name'], + format_td(age), + format_td(inactive), + ) should_cull = True if not should_cull: app_log.debug( "Not culling user %s (created: %s, last active: %s)", - user['name'], format_td(age), format_td(inactive)) + user['name'], + format_td(age), + format_td(inactive), + ) return False req = HTTPRequest( - url=url + '/users/%s' % user['name'], - method='DELETE', - headers=auth_header, + url=url + '/users/%s' % user['name'], method='DELETE', headers=auth_header ) yield fetch(req) return True @@ -316,21 +323,31 @@ def handle_user(user): help="The JupyterHub API URL", ) define('timeout', default=600, help="The idle timeout (in seconds)") - define('cull_every', default=0, - help="The interval (in seconds) for checking for idle servers to cull") - define('max_age', default=0, - help="The maximum age (in seconds) of servers that should be culled even if they are active") - define('cull_users', default=False, - help="""Cull users in addition to servers. + define( + 'cull_every', + default=0, + help="The interval (in seconds) for checking for idle servers to cull", + ) + define( + 'max_age', + default=0, + help="The maximum age (in seconds) of servers that should be culled even if they are active", + ) + define( + 'cull_users', + default=False, + help="""Cull users in addition to servers. This is for use in temporary-user cases such as tmpnb.""", - ) - define('concurrency', default=10, - help="""Limit the number of concurrent requests made to the Hub. + ) + define( + 'concurrency', + default=10, + help="""Limit the number of concurrent requests made to the Hub. Deleting a lot of users at the same time can slow down the Hub, so limit the number of API requests we have outstanding at any given time. - """ - ) + """, + ) parse_command_line() if not options.cull_every: @@ -343,7 +360,8 @@ def handle_user(user): app_log.warning( "Could not load pycurl: %s\n" "pycurl is recommended if you have a large number of users.", - e) + e, + ) loop = IOLoop.current() cull = partial( diff --git a/examples/cull-idle/jupyterhub_config.py b/examples/cull-idle/jupyterhub_config.py --- a/examples/cull-idle/jupyterhub_config.py +++ b/examples/cull-idle/jupyterhub_config.py @@ -1,4 +1,7 @@ +import sys + # run cull-idle as a service + c.JupyterHub.services = [ { 'name': 'cull-idle', diff --git a/examples/external-oauth/jupyterhub_config.py b/examples/external-oauth/jupyterhub_config.py --- a/examples/external-oauth/jupyterhub_config.py +++ b/examples/external-oauth/jupyterhub_config.py @@ -4,7 +4,9 @@ # this could come from anywhere api_token = os.getenv("JUPYTERHUB_API_TOKEN") if not api_token: - raise ValueError("Make sure to `export JUPYTERHUB_API_TOKEN=$(openssl rand -hex 32)`") + raise ValueError( + "Make sure to `export JUPYTERHUB_API_TOKEN=$(openssl rand -hex 32)`" + ) # tell JupyterHub to register the service as an external oauth client @@ -14,5 +16,5 @@ 'oauth_client_id': "whoami-oauth-client-test", 'api_token': api_token, 'oauth_redirect_uri': 'http://127.0.0.1:5555/oauth_callback', - }, + } ] diff --git a/examples/external-oauth/whoami-oauth-basic.py b/examples/external-oauth/whoami-oauth-basic.py --- a/examples/external-oauth/whoami-oauth-basic.py +++ b/examples/external-oauth/whoami-oauth-basic.py @@ -3,18 +3,19 @@ Implements OAuth handshake manually so all URLs and requests necessary for OAuth with JupyterHub should be in one place """ - import json import os import sys -from urllib.parse import urlencode, urlparse +from urllib.parse import urlencode +from urllib.parse import urlparse +from tornado import log +from tornado import web from tornado.auth import OAuth2Mixin -from tornado.httpclient import AsyncHTTPClient, HTTPRequest +from tornado.httpclient import AsyncHTTPClient +from tornado.httpclient import HTTPRequest from tornado.httputil import url_concat from tornado.ioloop import IOLoop -from tornado import log -from tornado import web class JupyterHubLoginHandler(web.RequestHandler): @@ -32,11 +33,11 @@ async def token_for_code(self, code): code=code, redirect_uri=self.settings['redirect_uri'], ) - req = HTTPRequest(self.settings['token_url'], method='POST', - body=urlencode(params).encode('utf8'), - headers={ - 'Content-Type': 'application/x-www-form-urlencoded', - }, + req = HTTPRequest( + self.settings['token_url'], + method='POST', + body=urlencode(params).encode('utf8'), + headers={'Content-Type': 'application/x-www-form-urlencoded'}, ) response = await AsyncHTTPClient().fetch(req) data = json.loads(response.body.decode('utf8', 'replace')) @@ -55,14 +56,16 @@ async def get(self): # we are the login handler, # begin oauth process which will come back later with an # authorization_code - self.redirect(url_concat( - self.settings['authorize_url'], - dict( - redirect_uri=self.settings['redirect_uri'], - client_id=self.settings['client_id'], - response_type='code', + self.redirect( + url_concat( + self.settings['authorize_url'], + dict( + redirect_uri=self.settings['redirect_uri'], + client_id=self.settings['client_id'], + response_type='code', + ), ) - )) + ) class WhoAmIHandler(web.RequestHandler): @@ -85,10 +88,7 @@ async def user_for_token(self, token): """Retrieve the user for a given token, via /hub/api/user""" req = HTTPRequest( - self.settings['user_url'], - headers={ - 'Authorization': f'token {token}' - }, + self.settings['user_url'], headers={'Authorization': f'token {token}'} ) response = await AsyncHTTPClient().fetch(req) return json.loads(response.body.decode('utf8', 'replace')) @@ -110,23 +110,23 @@ def main(): token_url = hub_api + '/oauth2/token' user_url = hub_api + '/user' - app = web.Application([ - ('/oauth_callback', JupyterHubLoginHandler), - ('/', WhoAmIHandler), - ], + app = web.Application( + [('/oauth_callback', JupyterHubLoginHandler), ('/', WhoAmIHandler)], login_url='/oauth_callback', cookie_secret=os.urandom(32), api_token=os.environ['JUPYTERHUB_API_TOKEN'], client_id=os.environ['JUPYTERHUB_CLIENT_ID'], - redirect_uri=os.environ['JUPYTERHUB_SERVICE_URL'].rstrip('/') + '/oauth_callback', + redirect_uri=os.environ['JUPYTERHUB_SERVICE_URL'].rstrip('/') + + '/oauth_callback', authorize_url=authorize_url, token_url=token_url, user_url=user_url, ) url = urlparse(os.environ['JUPYTERHUB_SERVICE_URL']) - log.app_log.info("Running basic whoami service on %s", - os.environ['JUPYTERHUB_SERVICE_URL']) + log.app_log.info( + "Running basic whoami service on %s", os.environ['JUPYTERHUB_SERVICE_URL'] + ) app.listen(url.port, url.hostname) IOLoop.current().start() diff --git a/examples/postgres/hub/jupyterhub_config.py b/examples/postgres/hub/jupyterhub_config.py --- a/examples/postgres/hub/jupyterhub_config.py +++ b/examples/postgres/hub/jupyterhub_config.py @@ -8,10 +8,10 @@ # These environment variables are automatically supplied by the linked postgres # container. -import os; +import os + pg_pass = os.getenv('POSTGRES_ENV_JPY_PSQL_PASSWORD') pg_host = os.getenv('POSTGRES_PORT_5432_TCP_ADDR') c.JupyterHub.db_url = 'postgresql://jupyterhub:{}@{}:5432/jupyterhub'.format( - pg_pass, - pg_host, + pg_pass, pg_host ) diff --git a/examples/service-announcement/announcement.py b/examples/service-announcement/announcement.py --- a/examples/service-announcement/announcement.py +++ b/examples/service-announcement/announcement.py @@ -1,11 +1,14 @@ - import argparse import datetime import json import os +from tornado import escape +from tornado import gen +from tornado import ioloop +from tornado import web + from jupyterhub.services.auth import HubAuthenticated -from tornado import escape, gen, ioloop, web class AnnouncementRequestHandler(HubAuthenticated, web.RequestHandler): @@ -21,6 +24,7 @@ def initialize(self, storage): @web.authenticated def post(self): """Update announcement""" + user = self.current_user doc = escape.json_decode(self.request.body) self.storage["announcement"] = doc["announcement"] self.storage["timestamp"] = datetime.datetime.now().isoformat() @@ -52,19 +56,19 @@ def main(): def parse_arguments(): parser = argparse.ArgumentParser() - parser.add_argument("--api-prefix", "-a", - default=os.environ.get("JUPYTERHUB_SERVICE_PREFIX", "/"), - help="application API prefix") - parser.add_argument("--port", "-p", - default=8888, - help="port for API to listen on", - type=int) + parser.add_argument( + "--api-prefix", + "-a", + default=os.environ.get("JUPYTERHUB_SERVICE_PREFIX", "/"), + help="application API prefix", + ) + parser.add_argument( + "--port", "-p", default=8888, help="port for API to listen on", type=int + ) return parser.parse_args() -def create_application(api_prefix="/", - handler=AnnouncementRequestHandler, - **kwargs): +def create_application(api_prefix="/", handler=AnnouncementRequestHandler, **kwargs): storage = dict(announcement="", timestamp="", user="") return web.Application([(api_prefix, handler, dict(storage=storage))]) diff --git a/examples/service-announcement/jupyterhub_config.py b/examples/service-announcement/jupyterhub_config.py --- a/examples/service-announcement/jupyterhub_config.py +++ b/examples/service-announcement/jupyterhub_config.py @@ -1,12 +1,13 @@ +import sys # To run the announcement service managed by the hub, add this. c.JupyterHub.services = [ - { - 'name': 'announcement', - 'url': 'http://127.0.0.1:8888', - 'command': [sys.executable, "-m", "announcement"], - } + { + 'name': 'announcement', + 'url': 'http://127.0.0.1:8888', + 'command': [sys.executable, "-m", "announcement"], + } ] # The announcements need to get on the templates somehow, see page.html diff --git a/examples/service-notebook/external/jupyterhub_config.py b/examples/service-notebook/external/jupyterhub_config.py --- a/examples/service-notebook/external/jupyterhub_config.py +++ b/examples/service-notebook/external/jupyterhub_config.py @@ -1,18 +1,9 @@ # our user list -c.Authenticator.whitelist = [ - 'minrk', - 'ellisonbg', - 'willingc', -] +c.Authenticator.whitelist = ['minrk', 'ellisonbg', 'willingc'] # ellisonbg and willingc have access to a shared server: -c.JupyterHub.load_groups = { - 'shared': [ - 'ellisonbg', - 'willingc', - ] -} +c.JupyterHub.load_groups = {'shared': ['ellisonbg', 'willingc']} # start the notebook server as a service c.JupyterHub.services = [ @@ -21,4 +12,4 @@ 'url': 'http://127.0.0.1:9999', 'api_token': 'super-secret', } -] \ No newline at end of file +] diff --git a/examples/service-notebook/managed/jupyterhub_config.py b/examples/service-notebook/managed/jupyterhub_config.py --- a/examples/service-notebook/managed/jupyterhub_config.py +++ b/examples/service-notebook/managed/jupyterhub_config.py @@ -1,18 +1,9 @@ # our user list -c.Authenticator.whitelist = [ - 'minrk', - 'ellisonbg', - 'willingc', -] +c.Authenticator.whitelist = ['minrk', 'ellisonbg', 'willingc'] # ellisonbg and willingc have access to a shared server: -c.JupyterHub.load_groups = { - 'shared': [ - 'ellisonbg', - 'willingc', - ] -} +c.JupyterHub.load_groups = {'shared': ['ellisonbg', 'willingc']} service_name = 'shared-notebook' service_port = 9999 @@ -23,10 +14,6 @@ { 'name': service_name, 'url': 'http://127.0.0.1:{}'.format(service_port), - 'command': [ - 'jupyterhub-singleuser', - '--group=shared', - '--debug', - ], + 'command': ['jupyterhub-singleuser', '--group=shared', '--debug'], } -] \ No newline at end of file +] diff --git a/examples/service-whoami-flask/jupyterhub_config.py b/examples/service-whoami-flask/jupyterhub_config.py --- a/examples/service-whoami-flask/jupyterhub_config.py +++ b/examples/service-whoami-flask/jupyterhub_config.py @@ -6,16 +6,12 @@ 'name': 'whoami', 'url': 'http://127.0.0.1:10101', 'command': ['flask', 'run', '--port=10101'], - 'environment': { - 'FLASK_APP': 'whoami-flask.py', - } + 'environment': {'FLASK_APP': 'whoami-flask.py'}, }, { 'name': 'whoami-oauth', 'url': 'http://127.0.0.1:10201', 'command': ['flask', 'run', '--port=10201'], - 'environment': { - 'FLASK_APP': 'whoami-oauth.py', - } + 'environment': {'FLASK_APP': 'whoami-oauth.py'}, }, ] diff --git a/examples/service-whoami-flask/whoami-flask.py b/examples/service-whoami-flask/whoami-flask.py --- a/examples/service-whoami-flask/whoami-flask.py +++ b/examples/service-whoami-flask/whoami-flask.py @@ -2,29 +2,29 @@ """ whoami service authentication with the Hub """ - -from functools import wraps import json import os +from functools import wraps from urllib.parse import quote -from flask import Flask, redirect, request, Response +from flask import Flask +from flask import redirect +from flask import request +from flask import Response from jupyterhub.services.auth import HubAuth prefix = os.environ.get('JUPYTERHUB_SERVICE_PREFIX', '/') -auth = HubAuth( - api_token=os.environ['JUPYTERHUB_API_TOKEN'], - cache_max_age=60, -) +auth = HubAuth(api_token=os.environ['JUPYTERHUB_API_TOKEN'], cache_max_age=60) app = Flask(__name__) def authenticated(f): """Decorator for authenticating with the Hub""" + @wraps(f) def decorated(*args, **kwargs): cookie = request.cookies.get(auth.cookie_name) @@ -40,6 +40,7 @@ def decorated(*args, **kwargs): else: # redirect to login url on failed auth return redirect(auth.login_url + '?next=%s' % quote(request.path)) + return decorated @@ -47,7 +48,5 @@ def decorated(*args, **kwargs): @authenticated def whoami(user): return Response( - json.dumps(user, indent=1, sort_keys=True), - mimetype='application/json', - ) - + json.dumps(user, indent=1, sort_keys=True), mimetype='application/json' + ) diff --git a/examples/service-whoami-flask/whoami-oauth.py b/examples/service-whoami-flask/whoami-oauth.py --- a/examples/service-whoami-flask/whoami-oauth.py +++ b/examples/service-whoami-flask/whoami-oauth.py @@ -2,28 +2,29 @@ """ whoami service authentication with the Hub """ - -from functools import wraps import json import os +from functools import wraps -from flask import Flask, redirect, request, Response, make_response +from flask import Flask +from flask import make_response +from flask import redirect +from flask import request +from flask import Response from jupyterhub.services.auth import HubOAuth prefix = os.environ.get('JUPYTERHUB_SERVICE_PREFIX', '/') -auth = HubOAuth( - api_token=os.environ['JUPYTERHUB_API_TOKEN'], - cache_max_age=60, -) +auth = HubOAuth(api_token=os.environ['JUPYTERHUB_API_TOKEN'], cache_max_age=60) app = Flask(__name__) def authenticated(f): """Decorator for authenticating with the Hub via OAuth""" + @wraps(f) def decorated(*args, **kwargs): token = request.cookies.get(auth.cookie_name) @@ -39,6 +40,7 @@ def decorated(*args, **kwargs): response = make_response(redirect(auth.login_url + '&state=%s' % state)) response.set_cookie(auth.state_cookie_name, state) return response + return decorated @@ -46,9 +48,9 @@ def decorated(*args, **kwargs): @authenticated def whoami(user): return Response( - json.dumps(user, indent=1, sort_keys=True), - mimetype='application/json', - ) + json.dumps(user, indent=1, sort_keys=True), mimetype='application/json' + ) + @app.route(prefix + 'oauth_callback') def oauth_callback(): diff --git a/examples/service-whoami/whoami-oauth.py b/examples/service-whoami/whoami-oauth.py --- a/examples/service-whoami/whoami-oauth.py +++ b/examples/service-whoami/whoami-oauth.py @@ -4,18 +4,22 @@ authenticated with the Hub, showing the user their own info. """ -from getpass import getuser import json import os +from getpass import getuser from urllib.parse import urlparse -from tornado.ioloop import IOLoop from tornado.httpserver import HTTPServer -from tornado.web import RequestHandler, Application, authenticated +from tornado.ioloop import IOLoop +from tornado.web import Application +from tornado.web import authenticated +from tornado.web import RequestHandler -from jupyterhub.services.auth import HubOAuthenticated, HubOAuthCallbackHandler +from jupyterhub.services.auth import HubOAuthCallbackHandler +from jupyterhub.services.auth import HubOAuthenticated from jupyterhub.utils import url_path_join + class WhoAmIHandler(HubOAuthenticated, RequestHandler): # hub_users can be a set of users who are allowed to access the service # `getuser()` here would mean only the user who started the service @@ -29,13 +33,22 @@ def get(self): self.set_header('content-type', 'application/json') self.write(json.dumps(user_model, indent=1, sort_keys=True)) + def main(): - app = Application([ - (os.environ['JUPYTERHUB_SERVICE_PREFIX'], WhoAmIHandler), - (url_path_join(os.environ['JUPYTERHUB_SERVICE_PREFIX'], 'oauth_callback'), HubOAuthCallbackHandler), - (r'.*', WhoAmIHandler), - ], cookie_secret=os.urandom(32)) - + app = Application( + [ + (os.environ['JUPYTERHUB_SERVICE_PREFIX'], WhoAmIHandler), + ( + url_path_join( + os.environ['JUPYTERHUB_SERVICE_PREFIX'], 'oauth_callback' + ), + HubOAuthCallbackHandler, + ), + (r'.*', WhoAmIHandler), + ], + cookie_secret=os.urandom(32), + ) + http_server = HTTPServer(app) url = urlparse(os.environ['JUPYTERHUB_SERVICE_URL']) @@ -43,5 +56,6 @@ def main(): IOLoop.current().start() + if __name__ == '__main__': main() diff --git a/examples/service-whoami/whoami.py b/examples/service-whoami/whoami.py --- a/examples/service-whoami/whoami.py +++ b/examples/service-whoami/whoami.py @@ -2,14 +2,16 @@ This serves `/services/whoami/`, authenticated with the Hub, showing the user their own info. """ -from getpass import getuser import json import os +from getpass import getuser from urllib.parse import urlparse -from tornado.ioloop import IOLoop from tornado.httpserver import HTTPServer -from tornado.web import RequestHandler, Application, authenticated +from tornado.ioloop import IOLoop +from tornado.web import Application +from tornado.web import authenticated +from tornado.web import RequestHandler from jupyterhub.services.auth import HubAuthenticated @@ -27,12 +29,15 @@ def get(self): self.set_header('content-type', 'application/json') self.write(json.dumps(user_model, indent=1, sort_keys=True)) + def main(): - app = Application([ - (os.environ['JUPYTERHUB_SERVICE_PREFIX'] + '/?', WhoAmIHandler), - (r'.*', WhoAmIHandler), - ]) - + app = Application( + [ + (os.environ['JUPYTERHUB_SERVICE_PREFIX'] + '/?', WhoAmIHandler), + (r'.*', WhoAmIHandler), + ] + ) + http_server = HTTPServer(app) url = urlparse(os.environ['JUPYTERHUB_SERVICE_URL']) @@ -40,5 +45,6 @@ def main(): IOLoop.current().start() + if __name__ == '__main__': main() diff --git a/examples/spawn-form/jupyterhub_config.py b/examples/spawn-form/jupyterhub_config.py --- a/examples/spawn-form/jupyterhub_config.py +++ b/examples/spawn-form/jupyterhub_config.py @@ -5,6 +5,7 @@ from jupyterhub.spawner import LocalProcessSpawner + class DemoFormSpawner(LocalProcessSpawner): def _options_form_default(self): default_env = "YOURNAME=%s\n" % self.user.name @@ -13,34 +14,37 @@ def _options_form_default(self): <input name="args" placeholder="e.g. --debug"></input> <label for="env">Environment variables (one per line)</label> <textarea name="env">{env}</textarea> - """.format(env=default_env) - + """.format( + env=default_env + ) + def options_from_form(self, formdata): options = {} options['env'] = env = {} - + env_lines = formdata.get('env', ['']) for line in env_lines[0].splitlines(): if line: key, value = line.split('=', 1) env[key.strip()] = value.strip() - + arg_s = formdata.get('args', [''])[0].strip() if arg_s: options['argv'] = shlex.split(arg_s) return options - + def get_args(self): """Return arguments to pass to the notebook server""" argv = super().get_args() if self.user_options.get('argv'): argv.extend(self.user_options['argv']) return argv - + def get_env(self): env = super().get_env() if self.user_options.get('env'): env.update(self.user_options['env']) return env + c.JupyterHub.spawner_class = DemoFormSpawner diff --git a/jupyterhub/__init__.py b/jupyterhub/__init__.py --- a/jupyterhub/__init__.py +++ b/jupyterhub/__init__.py @@ -1 +1,2 @@ -from ._version import version_info, __version__ +from ._version import __version__ +from ._version import version_info diff --git a/jupyterhub/__main__.py b/jupyterhub/__main__.py --- a/jupyterhub/__main__.py +++ b/jupyterhub/__main__.py @@ -1,2 +1,3 @@ from .app import main + main() diff --git a/jupyterhub/_data.py b/jupyterhub/_data.py --- a/jupyterhub/_data.py +++ b/jupyterhub/_data.py @@ -5,6 +5,7 @@ def get_data_files(): """Walk up until we find share/jupyterhub""" import sys from os.path import join, abspath, dirname, exists, split + path = abspath(dirname(__file__)) starting_points = [path] if not path.startswith(sys.prefix): diff --git a/jupyterhub/_version.py b/jupyterhub/_version.py --- a/jupyterhub/_version.py +++ b/jupyterhub/_version.py @@ -1,5 +1,4 @@ """JupyterHub version info""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. @@ -23,16 +22,23 @@ def _check_version(hub_version, singleuser_version, log): """Compare Hub and single-user server versions""" if not hub_version: - log.warning("Hub has no version header, which means it is likely < 0.8. Expected %s", __version__) + log.warning( + "Hub has no version header, which means it is likely < 0.8. Expected %s", + __version__, + ) return if not singleuser_version: - log.warning("Single-user server has no version header, which means it is likely < 0.8. Expected %s", __version__) + log.warning( + "Single-user server has no version header, which means it is likely < 0.8. Expected %s", + __version__, + ) return # compare minor X.Y versions if hub_version != singleuser_version: from distutils.version import LooseVersion as V + hub_major_minor = V(hub_version).version[:2] singleuser_major_minor = V(singleuser_version).version[:2] extra = "" @@ -50,4 +56,6 @@ def _check_version(hub_version, singleuser_version, log): singleuser_version, ) else: - log.debug("jupyterhub and jupyterhub-singleuser both on version %s" % hub_version) + log.debug( + "jupyterhub and jupyterhub-singleuser both on version %s" % hub_version + ) diff --git a/jupyterhub/alembic/env.py b/jupyterhub/alembic/env.py --- a/jupyterhub/alembic/env.py +++ b/jupyterhub/alembic/env.py @@ -1,9 +1,10 @@ +import logging import sys +from logging.config import fileConfig from alembic import context -from sqlalchemy import engine_from_config, pool -import logging -from logging.config import fileConfig +from sqlalchemy import engine_from_config +from sqlalchemy import pool # this is the Alembic Config object, which provides # access to the values within the .ini file in use. @@ -14,6 +15,7 @@ if 'jupyterhub' in sys.modules: from traitlets.config import MultipleInstanceError from jupyterhub.app import JupyterHub + app = None if JupyterHub.initialized(): try: @@ -32,6 +34,7 @@ # add your model's MetaData object here for 'autogenerate' support from jupyterhub import orm + target_metadata = orm.Base.metadata # other values from the config, defined by the needs of env.py, @@ -53,8 +56,7 @@ def run_migrations_offline(): """ url = config.get_main_option("sqlalchemy.url") - context.configure( - url=url, target_metadata=target_metadata, literal_binds=True) + context.configure(url=url, target_metadata=target_metadata, literal_binds=True) with context.begin_transaction(): context.run_migrations() @@ -70,17 +72,16 @@ def run_migrations_online(): connectable = engine_from_config( config.get_section(config.config_ini_section), prefix='sqlalchemy.', - poolclass=pool.NullPool) + poolclass=pool.NullPool, + ) with connectable.connect() as connection: - context.configure( - connection=connection, - target_metadata=target_metadata - ) + context.configure(connection=connection, target_metadata=target_metadata) with context.begin_transaction(): context.run_migrations() + if context.is_offline_mode(): run_migrations_offline() else: diff --git a/jupyterhub/alembic/versions/19c0846f6344_base_revision_for_0_5.py b/jupyterhub/alembic/versions/19c0846f6344_base_revision_for_0_5.py --- a/jupyterhub/alembic/versions/19c0846f6344_base_revision_for_0_5.py +++ b/jupyterhub/alembic/versions/19c0846f6344_base_revision_for_0_5.py @@ -5,7 +5,6 @@ Create Date: 2016-04-11 16:05:34.873288 """ - # revision identifiers, used by Alembic. revision = '19c0846f6344' down_revision = None diff --git a/jupyterhub/alembic/versions/1cebaf56856c_session_id.py b/jupyterhub/alembic/versions/1cebaf56856c_session_id.py --- a/jupyterhub/alembic/versions/1cebaf56856c_session_id.py +++ b/jupyterhub/alembic/versions/1cebaf56856c_session_id.py @@ -5,7 +5,6 @@ Create Date: 2017-12-07 14:43:51.500740 """ - # revision identifiers, used by Alembic. revision = '1cebaf56856c' down_revision = '3ec6993fe20c' @@ -13,6 +12,7 @@ depends_on = None import logging + logger = logging.getLogger('alembic') from alembic import op diff --git a/jupyterhub/alembic/versions/3ec6993fe20c_encrypted_auth_state.py b/jupyterhub/alembic/versions/3ec6993fe20c_encrypted_auth_state.py --- a/jupyterhub/alembic/versions/3ec6993fe20c_encrypted_auth_state.py +++ b/jupyterhub/alembic/versions/3ec6993fe20c_encrypted_auth_state.py @@ -12,7 +12,6 @@ Create Date: 2017-07-28 16:44:40.413648 """ - # revision identifiers, used by Alembic. revision = '3ec6993fe20c' down_revision = 'af4cbdb2d13c' @@ -39,12 +38,14 @@ def upgrade(): # mysql cannot drop _server_id without also dropping # implicitly created foreign key if op.get_context().dialect.name == 'mysql': - op.drop_constraint('users_ibfk_1', 'users', type_='foreignkey') + op.drop_constraint('users_ibfk_1', 'users', type_='foreignkey') op.drop_column('users', '_server_id') except sa.exc.OperationalError: # this won't be a problem moving forward, but downgrade will fail if op.get_context().dialect.name == 'sqlite': - logger.warning("sqlite cannot drop columns. Leaving unused old columns in place.") + logger.warning( + "sqlite cannot drop columns. Leaving unused old columns in place." + ) else: raise @@ -54,15 +55,13 @@ def upgrade(): def downgrade(): # drop all the new tables engine = op.get_bind().engine - for table in ('oauth_clients', - 'oauth_codes', - 'oauth_access_tokens', - 'spawners'): + for table in ('oauth_clients', 'oauth_codes', 'oauth_access_tokens', 'spawners'): if engine.has_table(table): op.drop_table(table) op.drop_column('users', 'encrypted_auth_state') op.add_column('users', sa.Column('auth_state', JSONDict)) - op.add_column('users', sa.Column('_server_id', sa.Integer, sa.ForeignKey('servers.id'))) - + op.add_column( + 'users', sa.Column('_server_id', sa.Integer, sa.ForeignKey('servers.id')) + ) diff --git a/jupyterhub/alembic/versions/56cc5a70207e_token_tracking.py b/jupyterhub/alembic/versions/56cc5a70207e_token_tracking.py --- a/jupyterhub/alembic/versions/56cc5a70207e_token_tracking.py +++ b/jupyterhub/alembic/versions/56cc5a70207e_token_tracking.py @@ -5,7 +5,6 @@ Create Date: 2017-12-19 15:21:09.300513 """ - # revision identifiers, used by Alembic. revision = '56cc5a70207e' down_revision = '1cebaf56856c' @@ -16,22 +15,48 @@ import sqlalchemy as sa import logging + logger = logging.getLogger('alembic') def upgrade(): tables = op.get_bind().engine.table_names() op.add_column('api_tokens', sa.Column('created', sa.DateTime(), nullable=True)) - op.add_column('api_tokens', sa.Column('last_activity', sa.DateTime(), nullable=True)) - op.add_column('api_tokens', sa.Column('note', sa.Unicode(length=1023), nullable=True)) + op.add_column( + 'api_tokens', sa.Column('last_activity', sa.DateTime(), nullable=True) + ) + op.add_column( + 'api_tokens', sa.Column('note', sa.Unicode(length=1023), nullable=True) + ) if 'oauth_access_tokens' in tables: - op.add_column('oauth_access_tokens', sa.Column('created', sa.DateTime(), nullable=True)) - op.add_column('oauth_access_tokens', sa.Column('last_activity', sa.DateTime(), nullable=True)) + op.add_column( + 'oauth_access_tokens', sa.Column('created', sa.DateTime(), nullable=True) + ) + op.add_column( + 'oauth_access_tokens', + sa.Column('last_activity', sa.DateTime(), nullable=True), + ) if op.get_context().dialect.name == 'sqlite': - logger.warning("sqlite cannot use ALTER TABLE to create foreign keys. Upgrade will be incomplete.") + logger.warning( + "sqlite cannot use ALTER TABLE to create foreign keys. Upgrade will be incomplete." + ) else: - op.create_foreign_key(None, 'oauth_access_tokens', 'oauth_clients', ['client_id'], ['identifier'], ondelete='CASCADE') - op.create_foreign_key(None, 'oauth_codes', 'oauth_clients', ['client_id'], ['identifier'], ondelete='CASCADE') + op.create_foreign_key( + None, + 'oauth_access_tokens', + 'oauth_clients', + ['client_id'], + ['identifier'], + ondelete='CASCADE', + ) + op.create_foreign_key( + None, + 'oauth_codes', + 'oauth_clients', + ['client_id'], + ['identifier'], + ondelete='CASCADE', + ) def downgrade(): diff --git a/jupyterhub/alembic/versions/896818069c98_token_expires.py b/jupyterhub/alembic/versions/896818069c98_token_expires.py --- a/jupyterhub/alembic/versions/896818069c98_token_expires.py +++ b/jupyterhub/alembic/versions/896818069c98_token_expires.py @@ -5,7 +5,6 @@ Create Date: 2018-05-07 11:35:58.050542 """ - # revision identifiers, used by Alembic. revision = '896818069c98' down_revision = 'd68c98b66cd4' diff --git a/jupyterhub/alembic/versions/99a28a4418e1_user_created.py b/jupyterhub/alembic/versions/99a28a4418e1_user_created.py --- a/jupyterhub/alembic/versions/99a28a4418e1_user_created.py +++ b/jupyterhub/alembic/versions/99a28a4418e1_user_created.py @@ -5,7 +5,6 @@ Create Date: 2018-03-21 14:27:17.466841 """ - # revision identifiers, used by Alembic. revision = '99a28a4418e1' down_revision = '56cc5a70207e' @@ -18,15 +17,18 @@ from datetime import datetime + def upgrade(): op.add_column('users', sa.Column('created', sa.DateTime, nullable=True)) c = op.get_bind() # fill created date with current time now = datetime.utcnow() - c.execute(""" + c.execute( + """ UPDATE users SET created='%s' - """ % (now,) + """ + % (now,) ) tables = c.engine.table_names() @@ -34,11 +36,13 @@ def upgrade(): if 'spawners' in tables: op.add_column('spawners', sa.Column('started', sa.DateTime, nullable=True)) # fill started value with now for running servers - c.execute(""" + c.execute( + """ UPDATE spawners SET started='%s' WHERE server_id IS NOT NULL - """ % (now,) + """ + % (now,) ) diff --git a/jupyterhub/alembic/versions/af4cbdb2d13c_services.py b/jupyterhub/alembic/versions/af4cbdb2d13c_services.py --- a/jupyterhub/alembic/versions/af4cbdb2d13c_services.py +++ b/jupyterhub/alembic/versions/af4cbdb2d13c_services.py @@ -5,7 +5,6 @@ Create Date: 2016-07-28 16:16:38.245348 """ - # revision identifiers, used by Alembic. revision = 'af4cbdb2d13c' down_revision = 'eeb276e51423' diff --git a/jupyterhub/alembic/versions/d68c98b66cd4_client_description.py b/jupyterhub/alembic/versions/d68c98b66cd4_client_description.py --- a/jupyterhub/alembic/versions/d68c98b66cd4_client_description.py +++ b/jupyterhub/alembic/versions/d68c98b66cd4_client_description.py @@ -5,7 +5,6 @@ Create Date: 2018-04-13 10:50:17.968636 """ - # revision identifiers, used by Alembic. revision = 'd68c98b66cd4' down_revision = '99a28a4418e1' @@ -20,8 +19,7 @@ def upgrade(): tables = op.get_bind().engine.table_names() if 'oauth_clients' in tables: op.add_column( - 'oauth_clients', - sa.Column('description', sa.Unicode(length=1023)) + 'oauth_clients', sa.Column('description', sa.Unicode(length=1023)) ) diff --git a/jupyterhub/alembic/versions/eeb276e51423_auth_state.py b/jupyterhub/alembic/versions/eeb276e51423_auth_state.py --- a/jupyterhub/alembic/versions/eeb276e51423_auth_state.py +++ b/jupyterhub/alembic/versions/eeb276e51423_auth_state.py @@ -6,7 +6,6 @@ Revises: 19c0846f6344 Create Date: 2016-04-11 16:06:49.239831 """ - # revision identifiers, used by Alembic. revision = 'eeb276e51423' down_revision = '19c0846f6344' @@ -17,6 +16,7 @@ import sqlalchemy as sa from jupyterhub.orm import JSONDict + def upgrade(): op.add_column('users', sa.Column('auth_state', JSONDict)) diff --git a/jupyterhub/apihandlers/__init__.py b/jupyterhub/apihandlers/__init__.py --- a/jupyterhub/apihandlers/__init__.py +++ b/jupyterhub/apihandlers/__init__.py @@ -1,5 +1,10 @@ +from . import auth +from . import groups +from . import hub +from . import proxy +from . import services +from . import users from .base import * -from . import auth, hub, proxy, users, groups, services default_handlers = [] for mod in (auth, hub, proxy, users, groups, services): diff --git a/jupyterhub/apihandlers/auth.py b/jupyterhub/apihandlers/auth.py --- a/jupyterhub/apihandlers/auth.py +++ b/jupyterhub/apihandlers/auth.py @@ -1,25 +1,23 @@ """Authorization handlers""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - -from datetime import datetime import json -from urllib.parse import ( - parse_qsl, - quote, - urlencode, - urlparse, - urlunparse, -) +from datetime import datetime +from urllib.parse import parse_qsl +from urllib.parse import quote +from urllib.parse import urlencode +from urllib.parse import urlparse +from urllib.parse import urlunparse from oauthlib import oauth2 from tornado import web from .. import orm from ..user import User -from ..utils import token_authenticated, compare_token -from .base import BaseHandler, APIHandler +from ..utils import compare_token +from ..utils import token_authenticated +from .base import APIHandler +from .base import BaseHandler class TokenAPIHandler(APIHandler): @@ -70,7 +68,9 @@ async def post(self): if data and data.get('username'): user = self.find_user(data['username']) if user is not requester and not requester.admin: - raise web.HTTPError(403, "Only admins can request tokens for other users.") + raise web.HTTPError( + 403, "Only admins can request tokens for other users." + ) if requester.admin and user is None: raise web.HTTPError(400, "No such user '%s'" % data['username']) @@ -82,11 +82,11 @@ async def post(self): note += " by %s %s" % (kind, requester.name) api_token = user.new_api_token(note=note) - self.write(json.dumps({ - 'token': api_token, - 'warning': warn_msg, - 'user': self.user_model(user), - })) + self.write( + json.dumps( + {'token': api_token, 'warning': warn_msg, 'user': self.user_model(user)} + ) + ) class CookieAPIHandler(APIHandler): @@ -94,7 +94,9 @@ class CookieAPIHandler(APIHandler): def get(self, cookie_name, cookie_value=None): cookie_name = quote(cookie_name, safe='') if cookie_value is None: - self.log.warning("Cookie values in request body is deprecated, use `/cookie_name/cookie_value`") + self.log.warning( + "Cookie values in request body is deprecated, use `/cookie_name/cookie_value`" + ) cookie_value = self.request.body else: cookie_value = cookie_value.encode('utf8') @@ -134,7 +136,9 @@ def make_absolute_redirect_uri(self, uri): return uri # make absolute local redirects full URLs # to satisfy oauthlib's absolute URI requirement - redirect_uri = self.request.protocol + "://" + self.request.headers['Host'] + redirect_uri + redirect_uri = ( + self.request.protocol + "://" + self.request.headers['Host'] + redirect_uri + ) parsed_url = urlparse(uri) query_list = parse_qsl(parsed_url.query, keep_blank_values=True) for idx, item in enumerate(query_list): @@ -142,10 +146,7 @@ def make_absolute_redirect_uri(self, uri): query_list[idx] = ('redirect_uri', redirect_uri) break - return urlunparse( - urlparse(uri) - ._replace(query=urlencode(query_list)) - ) + return urlunparse(urlparse(uri)._replace(query=urlencode(query_list))) def add_credentials(self, credentials=None): """Add oauth credentials @@ -164,11 +165,7 @@ def add_credentials(self, credentials=None): user = self.current_user # Extra credentials we need in the validator - credentials.update({ - 'user': user, - 'handler': self, - 'session_id': session_id, - }) + credentials.update({'user': user, 'handler': self, 'session_id': session_id}) return credentials def send_oauth_response(self, headers, body, status): @@ -193,7 +190,8 @@ class OAuthAuthorizeHandler(OAuthHandler, BaseHandler): def _complete_login(self, uri, headers, scopes, credentials): try: headers, body, status = self.oauth_provider.create_authorization_response( - uri, 'POST', '', headers, scopes, credentials) + uri, 'POST', '', headers, scopes, credentials + ) except oauth2.FatalClientError as e: # TODO: human error page @@ -213,13 +211,15 @@ def get(self): uri, http_method, body, headers = self.extract_oauth_params() try: scopes, credentials = self.oauth_provider.validate_authorization_request( - uri, http_method, body, headers) + uri, http_method, body, headers + ) credentials = self.add_credentials(credentials) client = self.oauth_provider.fetch_by_client_id(credentials['client_id']) if client.redirect_uri.startswith(self.current_user.url): self.log.debug( "Skipping oauth confirmation for %s accessing %s", - self.current_user, client.description, + self.current_user, + client.description, ) # access to my own server doesn't require oauth confirmation # this is the pre-1.0 behavior for all oauth @@ -228,11 +228,7 @@ def get(self): # Render oauth 'Authorize application...' page self.write( - self.render_template( - "oauth.html", - scopes=scopes, - oauth_client=client, - ) + self.render_template("oauth.html", scopes=scopes, oauth_client=client) ) # Errors that should be shown to the user on the provider website @@ -252,7 +248,9 @@ def post(self): if referer != full_url: # OAuth post must be made to the URL it came from self.log.error("OAuth POST from %s != %s", referer, full_url) - raise web.HTTPError(403, "Authorization form must be sent from authorization page") + raise web.HTTPError( + 403, "Authorization form must be sent from authorization page" + ) # The scopes the user actually authorized, i.e. checkboxes # that were selected. @@ -262,7 +260,7 @@ def post(self): try: headers, body, status = self.oauth_provider.create_authorization_response( - uri, http_method, body, headers, scopes, credentials, + uri, http_method, body, headers, scopes, credentials ) except oauth2.FatalClientError as e: raise web.HTTPError(e.status_code, e.description) @@ -277,7 +275,8 @@ def post(self): try: headers, body, status = self.oauth_provider.create_token_response( - uri, http_method, body, headers, credentials) + uri, http_method, body, headers, credentials + ) except oauth2.FatalClientError as e: raise web.HTTPError(e.status_code, e.description) else: diff --git a/jupyterhub/apihandlers/base.py b/jupyterhub/apihandlers/base.py --- a/jupyterhub/apihandlers/base.py +++ b/jupyterhub/apihandlers/base.py @@ -1,10 +1,8 @@ """Base API handlers""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - -from datetime import datetime import json - +from datetime import datetime from http.client import responses from sqlalchemy.exc import SQLAlchemyError @@ -12,7 +10,8 @@ from .. import orm from ..handlers import BaseHandler -from ..utils import isoformat, url_path_join +from ..utils import isoformat +from ..utils import url_path_join class APIHandler(BaseHandler): @@ -55,8 +54,11 @@ def check_referer(self): host_path = url_path_join(host, self.hub.base_url) referer_path = referer.split('://', 1)[-1] if not (referer_path + '/').startswith(host_path): - self.log.warning("Blocking Cross Origin API request. Referer: %s, Host: %s", - referer, host_path) + self.log.warning( + "Blocking Cross Origin API request. Referer: %s, Host: %s", + referer, + host_path, + ) return False return True @@ -105,9 +107,13 @@ def write_error(self, status_code, **kwargs): if exception and isinstance(exception, SQLAlchemyError): try: exception_str = str(exception) - self.log.warning("Rolling back session due to database error %s", exception_str) + self.log.warning( + "Rolling back session due to database error %s", exception_str + ) except Exception: - self.log.warning("Rolling back session due to database error %s", type(exception)) + self.log.warning( + "Rolling back session due to database error %s", type(exception) + ) self.db.rollback() self.set_header('Content-Type', 'application/json') @@ -121,10 +127,9 @@ def write_error(self, status_code, **kwargs): # Content-Length must be recalculated. self.clear_header('Content-Length') - self.write(json.dumps({ - 'status': status_code, - 'message': message or status_message, - })) + self.write( + json.dumps({'status': status_code, 'message': message or status_message}) + ) def server_model(self, spawner, include_state=False): """Get the JSON model for a Spawner""" @@ -144,21 +149,17 @@ def token_model(self, token): expires_at = None if isinstance(token, orm.APIToken): kind = 'api_token' - extra = { - 'note': token.note, - } + extra = {'note': token.note} expires_at = token.expires_at elif isinstance(token, orm.OAuthAccessToken): kind = 'oauth' - extra = { - 'oauth_client': token.client.description or token.client.client_id, - } + extra = {'oauth_client': token.client.description or token.client.client_id} if token.expires_at: expires_at = datetime.fromtimestamp(token.expires_at) else: raise TypeError( - "token must be an APIToken or OAuthAccessToken, not %s" - % type(token)) + "token must be an APIToken or OAuthAccessToken, not %s" % type(token) + ) if token.user: owner_key = 'user' @@ -188,7 +189,7 @@ def user_model(self, user, include_servers=False, include_state=False): 'kind': 'user', 'name': user.name, 'admin': user.admin, - 'groups': [ g.name for g in user.groups ], + 'groups': [g.name for g in user.groups], 'server': user.url if user.running else None, 'pending': None, 'created': isoformat(user.created), @@ -214,28 +215,16 @@ def group_model(self, group): return { 'kind': 'group', 'name': group.name, - 'users': [ u.name for u in group.users ], + 'users': [u.name for u in group.users], } def service_model(self, service): """Get the JSON model for a Service object""" - return { - 'kind': 'service', - 'name': service.name, - 'admin': service.admin, - } + return {'kind': 'service', 'name': service.name, 'admin': service.admin} - _user_model_types = { - 'name': str, - 'admin': bool, - 'groups': list, - 'auth_state': dict, - } + _user_model_types = {'name': str, 'admin': bool, 'groups': list, 'auth_state': dict} - _group_model_types = { - 'name': str, - 'users': list, - } + _group_model_types = {'name': str, 'users': list} def _check_model(self, model, model_types, name): """Check a model provided by a REST API request @@ -251,24 +240,29 @@ def _check_model(self, model, model_types, name): raise web.HTTPError(400, "Invalid JSON keys: %r" % model) for key, value in model.items(): if not isinstance(value, model_types[key]): - raise web.HTTPError(400, "%s.%s must be %s, not: %r" % ( - name, key, model_types[key], type(value) - )) + raise web.HTTPError( + 400, + "%s.%s must be %s, not: %r" + % (name, key, model_types[key], type(value)), + ) def _check_user_model(self, model): """Check a request-provided user model from a REST API""" self._check_model(model, self._user_model_types, 'user') for username in model.get('users', []): if not isinstance(username, str): - raise web.HTTPError(400, ("usernames must be str, not %r", type(username))) + raise web.HTTPError( + 400, ("usernames must be str, not %r", type(username)) + ) def _check_group_model(self, model): """Check a request-provided group model from a REST API""" self._check_model(model, self._group_model_types, 'group') for groupname in model.get('groups', []): if not isinstance(groupname, str): - raise web.HTTPError(400, ("group names must be str, not %r", type(groupname))) - + raise web.HTTPError( + 400, ("group names must be str, not %r", type(groupname)) + ) def options(self, *args, **kwargs): self.finish() @@ -279,6 +273,7 @@ class API404(APIHandler): Ensures JSON 404 errors for malformed URLs """ + async def prepare(self): await super().prepare() raise web.HTTPError(404) diff --git a/jupyterhub/apihandlers/groups.py b/jupyterhub/apihandlers/groups.py --- a/jupyterhub/apihandlers/groups.py +++ b/jupyterhub/apihandlers/groups.py @@ -1,11 +1,10 @@ """Group handlers""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import json -from tornado import gen, web +from tornado import gen +from tornado import web from .. import orm from ..utils import admin_only @@ -34,11 +33,12 @@ def find_group(self, name): raise web.HTTPError(404, "No such group: %s", name) return group + class GroupListAPIHandler(_GroupAPIHandler): @admin_only def get(self): """List groups""" - data = [ self.group_model(g) for g in self.db.query(orm.Group) ] + data = [self.group_model(g) for g in self.db.query(orm.Group)] self.write(json.dumps(data)) @admin_only @@ -48,7 +48,7 @@ async def post(self): if not model or not isinstance(model, dict) or not model.get('groups'): raise web.HTTPError(400, "Must specify at least one group to create") - groupnames = model.pop("groups",[]) + groupnames = model.pop("groups", []) self._check_group_model(model) created = [] @@ -61,9 +61,7 @@ async def post(self): # check that users exist users = self._usernames_to_users(usernames) # create the group - self.log.info("Creating new group %s with %i users", - name, len(users), - ) + self.log.info("Creating new group %s with %i users", name, len(users)) self.log.debug("Users: %s", usernames) group = orm.Group(name=name, users=users) self.db.add(group) @@ -99,9 +97,7 @@ async def post(self, name): users = self._usernames_to_users(usernames) # create the group - self.log.info("Creating new group %s with %i users", - name, len(users), - ) + self.log.info("Creating new group %s with %i users", name, len(users)) self.log.debug("Users: %s", usernames) group = orm.Group(name=name, users=users) self.db.add(group) @@ -121,6 +117,7 @@ def delete(self, name): class GroupUsersAPIHandler(_GroupAPIHandler): """Modify a group's user list""" + @admin_only def post(self, name): """POST adds users to a group""" diff --git a/jupyterhub/apihandlers/hub.py b/jupyterhub/apihandlers/hub.py --- a/jupyterhub/apihandlers/hub.py +++ b/jupyterhub/apihandlers/hub.py @@ -1,21 +1,18 @@ """API handlers for administering the Hub itself""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import json import sys from tornado import web from tornado.ioloop import IOLoop +from .._version import __version__ from ..utils import admin_only from .base import APIHandler -from .._version import __version__ class ShutdownAPIHandler(APIHandler): - @admin_only def post(self): """POST /api/shutdown triggers a clean shutdown @@ -26,34 +23,36 @@ def post(self): - proxy: specify whether the proxy should be terminated """ from ..app import JupyterHub + app = JupyterHub.instance() - + data = self.get_json_body() if data: if 'proxy' in data: proxy = data['proxy'] if proxy not in {True, False}: - raise web.HTTPError(400, "proxy must be true or false, got %r" % proxy) + raise web.HTTPError( + 400, "proxy must be true or false, got %r" % proxy + ) app.cleanup_proxy = proxy if 'servers' in data: servers = data['servers'] if servers not in {True, False}: - raise web.HTTPError(400, "servers must be true or false, got %r" % servers) + raise web.HTTPError( + 400, "servers must be true or false, got %r" % servers + ) app.cleanup_servers = servers - + # finish the request self.set_status(202) - self.finish(json.dumps({ - "message": "Shutting down Hub" - })) - + self.finish(json.dumps({"message": "Shutting down Hub"})) + # stop the eventloop, which will trigger cleanup loop = IOLoop.current() loop.add_callback(loop.stop) class RootAPIHandler(APIHandler): - def get(self): """GET /api/ returns info about the Hub and its API. @@ -61,14 +60,11 @@ def get(self): For now, it just returns the version of JupyterHub itself. """ - data = { - 'version': __version__, - } + data = {'version': __version__} self.finish(json.dumps(data)) class InfoAPIHandler(APIHandler): - @admin_only def get(self): """GET /api/info returns detailed info about the Hub and its API. @@ -77,10 +73,11 @@ def get(self): For now, it just returns the version of JupyterHub itself. """ + def _class_info(typ): """info about a class (Spawner or Authenticator)""" info = { - 'class': '{mod}.{name}'.format(mod=typ.__module__, name=typ.__name__), + 'class': '{mod}.{name}'.format(mod=typ.__module__, name=typ.__name__) } pkg = typ.__module__.split('.')[0] try: diff --git a/jupyterhub/apihandlers/proxy.py b/jupyterhub/apihandlers/proxy.py --- a/jupyterhub/apihandlers/proxy.py +++ b/jupyterhub/apihandlers/proxy.py @@ -1,12 +1,11 @@ """Proxy handlers""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import json from urllib.parse import urlparse -from tornado import gen, web +from tornado import gen +from tornado import web from .. import orm from ..utils import admin_only @@ -14,7 +13,6 @@ class ProxyAPIHandler(APIHandler): - @admin_only async def get(self): """GET /api/proxy fetches the routing table @@ -58,6 +56,4 @@ async def patch(self): await self.proxy.check_routes(self.users, self.services) -default_handlers = [ - (r"/api/proxy", ProxyAPIHandler), -] +default_handlers = [(r"/api/proxy", ProxyAPIHandler)] diff --git a/jupyterhub/apihandlers/services.py b/jupyterhub/apihandlers/services.py --- a/jupyterhub/apihandlers/services.py +++ b/jupyterhub/apihandlers/services.py @@ -2,10 +2,8 @@ Currently GET-only, no actions can be taken to modify services. """ - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import json from tornado import web @@ -14,6 +12,7 @@ from ..utils import admin_only from .base import APIHandler + def service_model(service): """Produce the model for a service""" return { @@ -23,9 +22,10 @@ def service_model(service): 'prefix': service.server.base_url if service.server else '', 'command': service.command, 'pid': service.proc.pid if service.proc else 0, - 'info': service.info + 'info': service.info, } + class ServiceListAPIHandler(APIHandler): @admin_only def get(self): @@ -35,6 +35,7 @@ def get(self): def admin_or_self(method): """Decorator for restricting access to either the target service or admin""" + def decorated_method(self, name): current = self.current_user if current is None: @@ -49,10 +50,11 @@ def decorated_method(self, name): if name not in self.services: raise web.HTTPError(404) return method(self, name) + return decorated_method -class ServiceAPIHandler(APIHandler): +class ServiceAPIHandler(APIHandler): @admin_or_self def get(self, name): service = self.services[name] diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -1,20 +1,24 @@ """User handlers""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import asyncio -from datetime import datetime, timedelta, timezone import json +from datetime import datetime +from datetime import timedelta +from datetime import timezone from async_generator import aclosing from dateutil.parser import parse as parse_date -from tornado import web +from tornado import web from tornado.iostream import StreamClosedError from .. import orm from ..user import User -from ..utils import admin_only, isoformat, iterate_until, maybe_future, url_path_join +from ..utils import admin_only +from ..utils import isoformat +from ..utils import iterate_until +from ..utils import maybe_future +from ..utils import url_path_join from .base import APIHandler @@ -89,16 +93,19 @@ async def post(self): except Exception as e: self.log.error("Failed to create user: %s" % name, exc_info=True) self.users.delete(user) - raise web.HTTPError(400, "Failed to create user %s: %s" % (name, str(e))) + raise web.HTTPError( + 400, "Failed to create user %s: %s" % (name, str(e)) + ) else: created.append(user) - self.write(json.dumps([ self.user_model(u) for u in created ])) + self.write(json.dumps([self.user_model(u) for u in created])) self.set_status(201) def admin_or_self(method): """Decorator for restricting access to either the target user or admin""" + def m(self, name, *args, **kwargs): current = self.current_user if current is None: @@ -110,15 +117,17 @@ def m(self, name, *args, **kwargs): if not self.find_user(name): raise web.HTTPError(404) return method(self, name, *args, **kwargs) + return m class UserAPIHandler(APIHandler): - @admin_or_self async def get(self, name): user = self.find_user(name) - model = self.user_model(user, include_servers=True, include_state=self.current_user.admin) + model = self.user_model( + user, include_servers=True, include_state=self.current_user.admin + ) # auth state will only be shown if the requester is an admin # this means users can't see their own auth state unless they # are admins, Hub admins often are also marked as admins so they @@ -161,11 +170,16 @@ async def delete(self, name): if user.name == self.current_user.name: raise web.HTTPError(400, "Cannot delete yourself!") if user.spawner._stop_pending: - raise web.HTTPError(400, "%s's server is in the process of stopping, please wait." % name) + raise web.HTTPError( + 400, "%s's server is in the process of stopping, please wait." % name + ) if user.running: await self.stop_single_user(user) if user.spawner._stop_pending: - raise web.HTTPError(400, "%s's server is in the process of stopping, please wait." % name) + raise web.HTTPError( + 400, + "%s's server is in the process of stopping, please wait." % name, + ) await maybe_future(self.authenticator.delete_user(user)) # remove from registry @@ -183,7 +197,10 @@ async def patch(self, name): if 'name' in data and data['name'] != name: # check if the new name is already taken inside db if self.find_user(data['name']): - raise web.HTTPError(400, "User %s already exists, username must be unique" % data['name']) + raise web.HTTPError( + 400, + "User %s already exists, username must be unique" % data['name'], + ) for key, value in data.items(): if key == 'auth_state': await user.save_auth_state(value) @@ -197,6 +214,7 @@ async def patch(self, name): class UserTokenListAPIHandler(APIHandler): """API endpoint for listing/creating tokens""" + @admin_or_self def get(self, name): """Get tokens for a given user""" @@ -207,6 +225,7 @@ def get(self, name): now = datetime.utcnow() api_tokens = [] + def sort_key(token): return token.last_activity or token.created @@ -228,10 +247,7 @@ def sort_key(token): self.db.commit() continue oauth_tokens.append(self.token_model(token)) - self.write(json.dumps({ - 'api_tokens': api_tokens, - 'oauth_tokens': oauth_tokens, - })) + self.write(json.dumps({'api_tokens': api_tokens, 'oauth_tokens': oauth_tokens})) async def post(self, name): body = self.get_json_body() or {} @@ -253,8 +269,9 @@ async def post(self, name): except Exception as e: # suppress and log error here in case Authenticator # isn't prepared to handle auth via this data - self.log.error("Error authenticating request for %s: %s", - self.request.uri, e) + self.log.error( + "Error authenticating request for %s: %s", self.request.uri, e + ) raise web.HTTPError(403) requester = self.find_user(name) if requester is None: @@ -274,9 +291,16 @@ async def post(self, name): if requester is not user: note += " by %s %s" % (kind, requester.name) - api_token = user.new_api_token(note=note, expires_in=body.get('expires_in', None)) + api_token = user.new_api_token( + note=note, expires_in=body.get('expires_in', None) + ) if requester is not user: - self.log.info("%s %s requested API token for %s", kind.title(), requester.name, user.name) + self.log.info( + "%s %s requested API token for %s", + kind.title(), + requester.name, + user.name, + ) else: user_kind = 'user' if isinstance(user, User) else 'service' self.log.info("%s %s requested new API token", user_kind.title(), user.name) @@ -308,7 +332,7 @@ def find_token_by_id(self, user, token_id): except ValueError: raise web.HTTPError(404, not_found) - orm_token = self.db.query(Token).filter(Token.id==id).first() + orm_token = self.db.query(Token).filter(Token.id == id).first() if orm_token is None or orm_token.user is not user.orm_user: raise web.HTTPError(404, "Token not found %s", orm_token) return orm_token @@ -333,8 +357,7 @@ def delete(self, name, token_id): if isinstance(token, orm.OAuthAccessToken): client_id = token.client_id tokens = [ - token for token in user.oauth_tokens - if token.client_id == client_id + token for token in user.oauth_tokens if token.client_id == client_id ] else: tokens = [token] @@ -354,16 +377,19 @@ async def post(self, name, server_name=''): if server_name: if not self.allow_named_servers: raise web.HTTPError(400, "Named servers are not enabled.") - if self.named_server_limit_per_user > 0 and server_name not in user.orm_spawners: + if ( + self.named_server_limit_per_user > 0 + and server_name not in user.orm_spawners + ): named_spawners = list(user.all_spawners(include_default=False)) if self.named_server_limit_per_user <= len(named_spawners): raise web.HTTPError( 400, "User {} already has the maximum of {} named servers." " One must be deleted before a new server can be created".format( - name, - self.named_server_limit_per_user - )) + name, self.named_server_limit_per_user + ), + ) spawner = user.spawners[server_name] pending = spawner.pending if pending == 'spawn': @@ -396,7 +422,6 @@ async def delete(self, name, server_name=''): options = self.get_json_body() remove = (options or {}).get('remove', False) - def _remove_spawner(f=None): if f and f.exception(): return @@ -408,7 +433,9 @@ def _remove_spawner(f=None): if not self.allow_named_servers: raise web.HTTPError(400, "Named servers are not enabled.") if server_name not in user.orm_spawners: - raise web.HTTPError(404, "%s has no server named '%s'" % (name, server_name)) + raise web.HTTPError( + 404, "%s has no server named '%s'" % (name, server_name) + ) elif remove: raise web.HTTPError(400, "Cannot delete the default server") @@ -423,7 +450,8 @@ def _remove_spawner(f=None): if spawner.pending: raise web.HTTPError( - 400, "%s is pending %s, please wait" % (spawner._log_name, spawner.pending) + 400, + "%s is pending %s, please wait" % (spawner._log_name, spawner.pending), ) stop_future = None @@ -449,13 +477,16 @@ class UserAdminAccessAPIHandler(APIHandler): This handler sets the necessary cookie for an admin to login to a single-user server. """ + @admin_only def post(self, name): - self.log.warning("Deprecated in JupyterHub 0.8." - " Admin access API is not needed now that we use OAuth.") + self.log.warning( + "Deprecated in JupyterHub 0.8." + " Admin access API is not needed now that we use OAuth." + ) current = self.current_user - self.log.warning("Admin user %s has requested access to %s's server", - current.name, name, + self.log.warning( + "Admin user %s has requested access to %s's server", current.name, name ) if not self.settings.get('admin_access', False): raise web.HTTPError(403, "admin access to user servers disabled") @@ -501,10 +532,7 @@ async def keepalive(self): except (StreamClosedError, RuntimeError): return - await asyncio.wait( - [self._finish_future], - timeout=self.keepalive_interval, - ) + await asyncio.wait([self._finish_future], timeout=self.keepalive_interval) @admin_or_self async def get(self, username, server_name=''): @@ -535,11 +563,7 @@ async def get(self, username, server_name=''): 'html_message': 'Server ready at <a href="{0}">{0}</a>'.format(url), 'url': url, } - failed_event = { - 'progress': 100, - 'failed': True, - 'message': "Spawn failed", - } + failed_event = {'progress': 100, 'failed': True, 'message': "Spawn failed"} if spawner.ready: # spawner already ready. Trigger progress-completion immediately @@ -561,7 +585,9 @@ async def get(self, username, server_name=''): raise web.HTTPError(400, "%s is not starting...", spawner._log_name) # retrieve progress events from the Spawner - async with aclosing(iterate_until(spawn_future, spawner._generate_progress())) as events: + async with aclosing( + iterate_until(spawn_future, spawner._generate_progress()) + ) as events: async for event in events: # don't allow events to sneakily set the 'ready' flag if 'ready' in event: @@ -584,7 +610,9 @@ async def get(self, username, server_name=''): if f and f.done() and f.exception(): failed_event['message'] = "Spawn failed: %s" % f.exception() else: - self.log.warning("Server %s didn't start for unknown reason", spawner._log_name) + self.log.warning( + "Server %s didn't start for unknown reason", spawner._log_name + ) await self.send_event(failed_event) @@ -609,13 +637,12 @@ def _parse_timestamp(timestamp): 400, "Rejecting activity from more than an hour in the future: {}".format( isoformat(dt) - ) + ), ) return dt class ActivityAPIHandler(APIHandler): - def _validate_servers(self, user, servers): """Validate servers dict argument @@ -632,10 +659,7 @@ def _validate_servers(self, user, servers): if server_name not in spawners: raise web.HTTPError( 400, - "No such server '{}' for user {}".format( - server_name, - user.name, - ) + "No such server '{}' for user {}".format(server_name, user.name), ) # check that each per-server field is a dict if not isinstance(server_info, dict): @@ -645,7 +669,9 @@ def _validate_servers(self, user, servers): raise web.HTTPError(400, msg) # parse last_activity timestamps # _parse_timestamp above is responsible for raising errors - server_info['last_activity'] = _parse_timestamp(server_info['last_activity']) + server_info['last_activity'] = _parse_timestamp( + server_info['last_activity'] + ) return servers @admin_or_self @@ -663,8 +689,7 @@ def post(self, username): servers = body.get('servers') if not last_activity_timestamp and not servers: raise web.HTTPError( - 400, - "body must contain at least one of `last_activity` or `servers`" + 400, "body must contain at least one of `last_activity` or `servers`" ) if servers: @@ -677,13 +702,9 @@ def post(self, username): # update user.last_activity if specified if last_activity_timestamp: last_activity = _parse_timestamp(last_activity_timestamp) - if ( - (not user.last_activity) - or last_activity > user.last_activity - ): - self.log.debug("Activity for user %s: %s", - user.name, - isoformat(last_activity), + if (not user.last_activity) or last_activity > user.last_activity: + self.log.debug( + "Activity for user %s: %s", user.name, isoformat(last_activity) ) user.last_activity = last_activity else: @@ -699,11 +720,9 @@ def post(self, username): last_activity = server_info['last_activity'] spawner = user.orm_spawners[server_name] - if ( - (not spawner.last_activity) - or last_activity > spawner.last_activity - ): - self.log.debug("Activity on server %s/%s: %s", + if (not spawner.last_activity) or last_activity > spawner.last_activity: + self.log.debug( + "Activity on server %s/%s: %s", user.name, server_name, isoformat(last_activity), diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -1,25 +1,26 @@ #!/usr/bin/env python3 """The multi-user notebook application""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import asyncio import atexit import binascii -from concurrent.futures import ThreadPoolExecutor -from datetime import datetime, timezone -from functools import partial -from getpass import getuser import logging -from operator import itemgetter import os import re import signal import socket import sys +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime +from datetime import timezone +from functools import partial +from getpass import getuser +from operator import itemgetter from textwrap import dedent -from urllib.parse import unquote, urlparse, urlunparse +from urllib.parse import unquote +from urllib.parse import urlparse +from urllib.parse import urlunparse if sys.version_info[:2] < (3, 3): raise ValueError("Python < 3.3 not supported: %s" % sys.version) @@ -38,9 +39,21 @@ from tornado.platform.asyncio import AsyncIOMainLoop from traitlets import ( - Unicode, Integer, Dict, TraitError, List, Bool, Any, - Tuple, Type, Set, Instance, Bytes, Float, - observe, default, + Unicode, + Integer, + Dict, + TraitError, + List, + Bool, + Any, + Tuple, + Type, + Set, + Instance, + Bytes, + Float, + observe, + default, ) from traitlets.config import Application, Configurable, catch_config_error @@ -62,9 +75,11 @@ from .utils import ( maybe_future, url_path_join, - print_stacks, print_ps_info, + print_stacks, + print_ps_info, make_ssl_context, ) + # classes for config from .auth import Authenticator, PAMAuthenticator from .crypto import CryptKeeper @@ -99,36 +114,48 @@ aliases.update(common_aliases) flags = { - 'debug': ({'Application': {'log_level': logging.DEBUG}}, - "set log level to logging.DEBUG (maximize logging output)"), - 'generate-config': ({'JupyterHub': {'generate_config': True}}, - "generate default config file"), - 'generate-certs': ({'JupyterHub': {'generate_certs': True}}, - "generate certificates used for internal ssl"), - 'no-db': ({'JupyterHub': {'db_url': 'sqlite:///:memory:'}}, - "disable persisting state database to disk" + 'debug': ( + {'Application': {'log_level': logging.DEBUG}}, + "set log level to logging.DEBUG (maximize logging output)", + ), + 'generate-config': ( + {'JupyterHub': {'generate_config': True}}, + "generate default config file", ), - 'upgrade-db': ({'JupyterHub': {'upgrade_db': True}}, + 'generate-certs': ( + {'JupyterHub': {'generate_certs': True}}, + "generate certificates used for internal ssl", + ), + 'no-db': ( + {'JupyterHub': {'db_url': 'sqlite:///:memory:'}}, + "disable persisting state database to disk", + ), + 'upgrade-db': ( + {'JupyterHub': {'upgrade_db': True}}, """Automatically upgrade the database if needed on startup. Only safe if the database has been backed up. Only SQLite database files will be backed up automatically. - """ + """, ), - 'no-ssl': ({'JupyterHub': {'confirm_no_ssl': True}}, - "[DEPRECATED in 0.7: does nothing]" + 'no-ssl': ( + {'JupyterHub': {'confirm_no_ssl': True}}, + "[DEPRECATED in 0.7: does nothing]", ), } -COOKIE_SECRET_BYTES = 32 # the number of bytes to use when generating new cookie secrets +COOKIE_SECRET_BYTES = ( + 32 +) # the number of bytes to use when generating new cookie secrets HEX_RE = re.compile('^([a-f0-9]{2})+$', re.IGNORECASE) -_mswindows = (os.name == "nt") +_mswindows = os.name == "nt" class NewToken(Application): """Generate and print a new API token""" + name = 'jupyterhub-token' version = jupyterhub.__version__ description = """Generate and return new API token for a user. @@ -144,6 +171,7 @@ class NewToken(Application): """ name = Unicode() + @default('name') def _default_name(self): return getuser() @@ -164,9 +192,11 @@ def start(self): hub = JupyterHub(parent=self) hub.load_config_file(hub.config_file) hub.init_db() + def init_users(): loop = asyncio.new_event_loop() loop.run_until_complete(hub.init_users()) + ThreadPoolExecutor(1).submit(init_users).result() user = orm.User.find(hub.db, self.name) if user is None: @@ -199,6 +229,7 @@ def start(self): class JupyterHub(Application): """An Application for starting a Multi-User Jupyter Notebook server.""" + name = 'jupyterhub' version = jupyterhub.__version__ @@ -227,10 +258,14 @@ class JupyterHub(Application): subcommands = { 'token': (NewToken, "Generate an API token for a user"), - 'upgrade-db': (UpgradeDB, "Upgrade your JupyterHub state database to the current version."), + 'upgrade-db': ( + UpgradeDB, + "Upgrade your JupyterHub state database to the current version.", + ), } classes = List() + @default('classes') def _load_classes(self): classes = [Spawner, Authenticator, CryptKeeper] @@ -244,7 +279,8 @@ def _load_classes(self): classes.append(cls) return classes - load_groups = Dict(List(Unicode()), + load_groups = Dict( + List(Unicode()), help="""Dict of 'group': ['usernames'] to load at startup. This strictly *adds* groups and users to groups. @@ -252,100 +288,105 @@ def _load_classes(self): Loading one set of groups, then starting JupyterHub again with a different set will not remove users or groups from previous launches. That must be done through the API. - """ + """, ).tag(config=True) - config_file = Unicode('jupyterhub_config.py', - help="The config file to load", - ).tag(config=True) - generate_config = Bool(False, - help="Generate default config file", - ).tag(config=True) - generate_certs = Bool(False, - help="Generate certs used for internal ssl", - ).tag(config=True) - answer_yes = Bool(False, - help="Answer yes to any questions (e.g. confirm overwrite)" + config_file = Unicode('jupyterhub_config.py', help="The config file to load").tag( + config=True + ) + generate_config = Bool(False, help="Generate default config file").tag(config=True) + generate_certs = Bool(False, help="Generate certs used for internal ssl").tag( + config=True + ) + answer_yes = Bool( + False, help="Answer yes to any questions (e.g. confirm overwrite)" ).tag(config=True) - pid_file = Unicode('', + pid_file = Unicode( + '', help="""File to write PID Useful for daemonizing JupyterHub. - """ + """, ).tag(config=True) - cookie_max_age_days = Float(14, + cookie_max_age_days = Float( + 14, help="""Number of days for a login cookie to be valid. Default is two weeks. - """ + """, ).tag(config=True) - redirect_to_server = Bool(True, - help="Redirect user to server (if running), instead of control panel." + redirect_to_server = Bool( + True, help="Redirect user to server (if running), instead of control panel." ).tag(config=True) - last_activity_interval = Integer(300, - help="Interval (in seconds) at which to update last-activity timestamps." + last_activity_interval = Integer( + 300, help="Interval (in seconds) at which to update last-activity timestamps." ).tag(config=True) - proxy_check_interval = Integer(30, - help="Interval (in seconds) at which to check if the proxy is running." + proxy_check_interval = Integer( + 30, help="Interval (in seconds) at which to check if the proxy is running." ).tag(config=True) - service_check_interval = Integer(60, - help="Interval (in seconds) at which to check connectivity of services with web endpoints." + service_check_interval = Integer( + 60, + help="Interval (in seconds) at which to check connectivity of services with web endpoints.", ).tag(config=True) - active_user_window = Integer(30 * 60, - help="Duration (in seconds) to determine the number of active users." + active_user_window = Integer( + 30 * 60, help="Duration (in seconds) to determine the number of active users." ).tag(config=True) - data_files_path = Unicode(DATA_FILES_PATH, - help="The location of jupyterhub data files (e.g. /usr/local/share/jupyterhub)" + data_files_path = Unicode( + DATA_FILES_PATH, + help="The location of jupyterhub data files (e.g. /usr/local/share/jupyterhub)", ).tag(config=True) template_paths = List( - help="Paths to search for jinja templates, before using the default templates.", + help="Paths to search for jinja templates, before using the default templates." ).tag(config=True) @default('template_paths') def _template_paths_default(self): return [os.path.join(self.data_files_path, 'templates')] - template_vars = Dict( - help="Extra variables to be passed into jinja templates", - ).tag(config=True) + template_vars = Dict(help="Extra variables to be passed into jinja templates").tag( + config=True + ) - confirm_no_ssl = Bool(False, - help="""DEPRECATED: does nothing""" - ).tag(config=True) - ssl_key = Unicode('', + confirm_no_ssl = Bool(False, help="""DEPRECATED: does nothing""").tag(config=True) + ssl_key = Unicode( + '', help="""Path to SSL key file for the public facing interface of the proxy When setting this, you should also set ssl_cert - """ + """, ).tag(config=True) - ssl_cert = Unicode('', + ssl_cert = Unicode( + '', help="""Path to SSL certificate file for the public facing interface of the proxy When setting this, you should also set ssl_key - """ + """, ).tag(config=True) - internal_ssl = Bool(False, + internal_ssl = Bool( + False, help="""Enable SSL for all internal communication This enables end-to-end encryption between all JupyterHub components. JupyterHub will automatically create the necessary certificate authority and sign notebook certificates as they're created. - """ + """, ).tag(config=True) - internal_certs_location = Unicode('internal-ssl', + internal_certs_location = Unicode( + 'internal-ssl', help="""The location to store certificates automatically created by JupyterHub. Use with internal_ssl - """ + """, ).tag(config=True) - recreate_internal_certs = Bool(False, + recreate_internal_certs = Bool( + False, help="""Recreate all certificates used within JupyterHub on restart. Note: enabling this feature requires restarting all notebook servers. Use with internal_ssl - """ + """, ).tag(config=True) external_ssl_authorities = Dict( help="""Dict authority:dict(files). Specify the key, cert, and/or @@ -379,7 +420,7 @@ def _template_paths_default(self): for each authority. Use with internal_ssl - """ + """, ) internal_ssl_components_trust = Dict( help="""Dict component:list(components). This dict specifies the @@ -394,12 +435,8 @@ def _template_paths_default(self): Use with internal_ssl """ ) - internal_ssl_key = Unicode( - help="""The key to be used for internal ssl""" - ) - internal_ssl_cert = Unicode( - help="""The cert to be used for internal ssl""" - ) + internal_ssl_key = Unicode(help="""The key to be used for internal ssl""") + internal_ssl_cert = Unicode(help="""The cert to be used for internal ssl""") internal_ssl_ca = Unicode( help="""The certificate authority to be used for internal ssl""" ) @@ -408,7 +445,8 @@ def _template_paths_default(self): generated for both the proxy API and proxy client. """ ) - trusted_alt_names = List(Unicode(), + trusted_alt_names = List( + Unicode(), help="""Names to include in the subject alternative name. These names will be used for server name verification. This is useful @@ -416,10 +454,11 @@ def _template_paths_default(self): are on different hosts. Use with internal_ssl - """ + """, ).tag(config=True) - ip = Unicode('', + ip = Unicode( + '', help="""The public facing ip of the whole JupyterHub application (specifically referred to as the proxy). @@ -429,10 +468,11 @@ def _template_paths_default(self): .. deprecated: 0.9 Use JupyterHub.bind_url - """ + """, ).tag(config=True) - port = Integer(8000, + port = Integer( + 8000, help="""The public facing port of the proxy. This is the port on which the proxy will listen. @@ -441,10 +481,11 @@ def _template_paths_default(self): .. deprecated: 0.9 Use JupyterHub.bind_url - """ + """, ).tag(config=True) - base_url = URLPrefix('/', + base_url = URLPrefix( + '/', help="""The base URL of the entire application. Add this to the beginning of all JupyterHub URLs. @@ -452,7 +493,7 @@ def _template_paths_default(self): .. deprecated: 0.9 Use JupyterHub.bind_url - """ + """, ).tag(config=True) @default('base_url') @@ -476,10 +517,11 @@ def _url_part_changed(self, change): This is the address on which the proxy will bind. Sets protocol, ip, base_url - """ + """, ).tag(config=True) - subdomain_host = Unicode('', + subdomain_host = Unicode( + '', help="""Run single-user servers on subdomains of this host. This should be the full `https://hub.domain.tld[:port]`. @@ -491,7 +533,7 @@ def _url_part_changed(self, change): In general, this is most easily achieved with wildcard DNS. When using SSL (i.e. always) this also requires a wildcard SSL certificate. - """ + """, ).tag(config=True) def _subdomain_host_changed(self, name, old, new): @@ -500,9 +542,7 @@ def _subdomain_host_changed(self, name, old, new): # if not specified, assume https: You have to be really explicit about HTTP! self.subdomain_host = 'https://' + new - domain = Unicode( - help="domain name, e.g. 'example.com' (excludes protocol, port)" - ) + domain = Unicode(help="domain name, e.g. 'example.com' (excludes protocol, port)") @default('domain') def _domain_default(self): @@ -510,8 +550,9 @@ def _domain_default(self): return '' return urlparse(self.subdomain_host).hostname - logo_file = Unicode('', - help="Specify path to a logo image to override the Jupyter logo in the banner." + logo_file = Unicode( + '', + help="Specify path to a logo image to override the Jupyter logo in the banner.", ).tag(config=True) @default('logo_file') @@ -533,15 +574,17 @@ def _logo_file_default(self): .. versionchanged:: 1.0 proxies may be registered via entry points, e.g. `c.JupyterHub.proxy_class = 'traefik'` - """ + """, ).tag(config=True) - proxy_cmd = Command([], config=True, + proxy_cmd = Command( + [], + config=True, help="DEPRECATED since version 0.8. Use ConfigurableHTTPProxy.command", ).tag(config=True) - debug_proxy = Bool(False, - help="DEPRECATED since version 0.8: Use ConfigurableHTTPProxy.debug", + debug_proxy = Bool( + False, help="DEPRECATED since version 0.8: Use ConfigurableHTTPProxy.debug" ).tag(config=True) proxy_auth_token = Unicode( help="DEPRECATED since version 0.8: Use ConfigurableHTTPProxy.auth_token" @@ -552,10 +595,15 @@ def _logo_file_default(self): 'debug_proxy': 'debug', 'proxy_auth_token': 'auth_token', } + @observe(*_proxy_config_map) def _deprecated_proxy_config(self, change): dest = self._proxy_config_map[change.name] - self.log.warning("JupyterHub.%s is deprecated in JupyterHub 0.8, use ConfigurableHTTPProxy.%s", change.name, dest) + self.log.warning( + "JupyterHub.%s is deprecated in JupyterHub 0.8, use ConfigurableHTTPProxy.%s", + change.name, + dest, + ) self.config.ConfigurableHTTPProxy[dest] = change.new proxy_api_ip = Unicode( @@ -564,15 +612,19 @@ def _deprecated_proxy_config(self, change): proxy_api_port = Integer( help="DEPRECATED since version 0.8 : Use ConfigurableHTTPProxy.api_url" ).tag(config=True) + @observe('proxy_api_port', 'proxy_api_ip') def _deprecated_proxy_api(self, change): - self.log.warning("JupyterHub.%s is deprecated in JupyterHub 0.8, use ConfigurableHTTPProxy.api_url", change.name) + self.log.warning( + "JupyterHub.%s is deprecated in JupyterHub 0.8, use ConfigurableHTTPProxy.api_url", + change.name, + ) self.config.ConfigurableHTTPProxy.api_url = 'http://{}:{}'.format( - self.proxy_api_ip or '127.0.0.1', - self.proxy_api_port or self.port + 1, + self.proxy_api_ip or '127.0.0.1', self.proxy_api_port or self.port + 1 ) - hub_port = Integer(8081, + hub_port = Integer( + 8081, help="""The internal port for the Hub process. This is the internal port of the hub itself. It should never be accessed directly. @@ -580,10 +632,11 @@ def _deprecated_proxy_api(self, change): It is rare that this port should be set except in cases of port conflict. See also `hub_ip` for the ip and `hub_bind_url` for setting the full bind URL. - """ + """, ).tag(config=True) - hub_ip = Unicode('127.0.0.1', + hub_ip = Unicode( + '127.0.0.1', help="""The ip address for the Hub process to *bind* to. By default, the hub listens on localhost only. This address must be accessible from @@ -592,10 +645,11 @@ def _deprecated_proxy_api(self, change): See `hub_connect_ip` for cases where the bind and connect address should differ, or `hub_bind_url` for setting the full bind URL. - """ + """, ).tag(config=True) - hub_connect_ip = Unicode('', + hub_connect_ip = Unicode( + '', help="""The ip or hostname for proxies and spawners to use for connecting to the Hub. @@ -608,7 +662,7 @@ def _deprecated_proxy_api(self, change): spawner or proxy documentation to see if they have extra requirements. .. versionadded:: 0.8 - """ + """, ).tag(config=True) hub_connect_url = Unicode( @@ -626,7 +680,7 @@ def _deprecated_proxy_api(self, change): .. versionadded:: 0.9 """, - config=True + config=True, ) hub_bind_url = Unicode( @@ -644,7 +698,7 @@ def _deprecated_proxy_api(self, change): .. versionadded:: 0.9 """, config=True, - ) + ) hub_connect_port = Integer( 0, @@ -657,11 +711,11 @@ def _deprecated_proxy_api(self, change): .. deprecated:: 0.9 Use hub_connect_url - """ + """, ).tag(config=True) - hub_prefix = URLPrefix('/hub/', - help="The prefix for the hub server. Always /base_url/hub/" + hub_prefix = URLPrefix( + '/hub/', help="The prefix for the hub server. Always /base_url/hub/" ) @default('hub_prefix') @@ -673,7 +727,8 @@ def _update_hub_prefix(self, change): """add base URL to hub prefix""" self.hub_prefix = self._hub_prefix_default() - trust_user_provided_tokens = Bool(False, + trust_user_provided_tokens = Bool( + False, help="""Trust user-provided tokens (via JupyterHub.service_tokens) to have good entropy. @@ -692,7 +747,7 @@ def _update_hub_prefix(self, change): If your inserted tokens are generated by a good-quality mechanism, e.g. `openssl rand -hex 32`, then you can set this flag to True to reduce the cost of checking authentication tokens. - """ + """, ).tag(config=True) cookie_secret = Bytes( help="""The cookie secret to use to encrypt cookies. @@ -701,23 +756,24 @@ def _update_hub_prefix(self, change): Should be exactly 256 bits (32 bytes). """ - ).tag( - config=True, - env='JPY_COOKIE_SECRET', - ) + ).tag(config=True, env='JPY_COOKIE_SECRET') + @observe('cookie_secret') def _cookie_secret_check(self, change): secret = change.new if len(secret) > COOKIE_SECRET_BYTES: - self.log.warning("Cookie secret is %i bytes. It should be %i.", - len(secret), COOKIE_SECRET_BYTES, + self.log.warning( + "Cookie secret is %i bytes. It should be %i.", + len(secret), + COOKIE_SECRET_BYTES, ) - cookie_secret_file = Unicode('jupyterhub_cookie_secret', - help="""File in which to store the cookie secret.""" + cookie_secret_file = Unicode( + 'jupyterhub_cookie_secret', help="""File in which to store the cookie secret.""" ).tag(config=True) - api_tokens = Dict(Unicode(), + api_tokens = Dict( + Unicode(), help="""PENDING DEPRECATION: consider using service_tokens Dict of token:username to be loaded into the database. @@ -726,29 +782,33 @@ def _cookie_secret_check(self, change): which authenticate as JupyterHub users. Consider using service_tokens for general services that talk to the JupyterHub API. - """ + """, ).tag(config=True) - authenticate_prometheus = Bool(True, - help="Authentication for prometheus metrics").tag(config=True) + authenticate_prometheus = Bool( + True, help="Authentication for prometheus metrics" + ).tag(config=True) @observe('api_tokens') def _deprecate_api_tokens(self, change): - self.log.warning("JupyterHub.api_tokens is pending deprecation" + self.log.warning( + "JupyterHub.api_tokens is pending deprecation" " since JupyterHub version 0.8." " Consider using JupyterHub.service_tokens." " If you have a use case for services that identify as users," " let us know: https://github.com/jupyterhub/jupyterhub/issues" ) - service_tokens = Dict(Unicode(), + service_tokens = Dict( + Unicode(), help="""Dict of token:servicename to be loaded into the database. Allows ahead-of-time generation of API tokens for use by externally managed services. - """ + """, ).tag(config=True) - services = List(Dict(), + services = List( + Dict(), help="""List of service specification dictionaries. A service @@ -767,7 +827,7 @@ def _deprecate_api_tokens(self, change): 'environment': } ] - """ + """, ).tag(config=True) _service_map = Dict() @@ -790,7 +850,7 @@ def _deprecate_api_tokens(self, change): .. versionchanged:: 1.0 authenticators may be registered via entry points, e.g. `c.JupyterHub.authenticator_class = 'pam'` - """ + """, ).tag(config=True) authenticator = Instance(Authenticator) @@ -799,18 +859,19 @@ def _deprecate_api_tokens(self, change): def _authenticator_default(self): return self.authenticator_class(parent=self, db=self.db) - allow_named_servers = Bool(False, - help="Allow named single-user servers per user" + allow_named_servers = Bool( + False, help="Allow named single-user servers per user" ).tag(config=True) - named_server_limit_per_user = Integer(0, + named_server_limit_per_user = Integer( + 0, help=""" Maximum number of concurrent named servers that can be created by a user at a time. Setting this can limit the total resources a user can consume. If set to 0, no limit is enforced. - """ + """, ).tag(config=True) # class for spawning single-user servers @@ -825,7 +886,7 @@ def _authenticator_default(self): .. versionchanged:: 1.0 spawners may be registered via entry points, e.g. `c.JupyterHub.spawner_class = 'localprocess'` - """ + """, ).tag(config=True) concurrent_spawn_limit = Integer( @@ -847,7 +908,7 @@ def _authenticator_default(self): to finish starting before they can start their own. If set to 0, no limit is enforced. - """ + """, ).tag(config=True) spawn_throttle_retry_range = Tuple( @@ -864,7 +925,7 @@ def _authenticator_default(self): The lower bound should ideally be approximately the median spawn time for your deployment. - """ + """, ) active_server_limit = Integer( @@ -883,11 +944,12 @@ def _authenticator_default(self): Spawn requests will be rejected with a 429 error asking them to try again. If set to 0, no limit is enforced. - """ + """, ).tag(config=True) - db_url = Unicode('sqlite:///jupyterhub.sqlite', - help="url for the database. e.g. `sqlite:///jupyterhub.sqlite`" + db_url = Unicode( + 'sqlite:///jupyterhub.sqlite', + help="url for the database. e.g. `sqlite:///jupyterhub.sqlite`", ).tag(config=True) @observe('db_url') @@ -903,17 +965,17 @@ def _db_url_changed(self, change): """ ).tag(config=True) - upgrade_db = Bool(False, + upgrade_db = Bool( + False, help="""Upgrade the database automatically on start. Only safe if database is regularly backed up. Only SQLite databases will be backed up to a local file automatically. - """).tag(config=True) - reset_db = Bool(False, - help="Purge and reset the database." + """, ).tag(config=True) - debug_db = Bool(False, - help="log all database transactions. This has A LOT of output" + reset_db = Bool(False, help="Purge and reset the database.").tag(config=True) + debug_db = Bool( + False, help="log all database transactions. This has A LOT of output" ).tag(config=True) session_factory = Any() @@ -924,11 +986,12 @@ def _users_default(self): assert self.tornado_settings return UserDict(db_factory=lambda: self.db, settings=self.tornado_settings) - admin_access = Bool(False, + admin_access = Bool( + False, help="""Grant admin users permission to access single-user servers. Users should be properly informed if this is enabled. - """ + """, ).tag(config=True) admin_users = Set( help="""DEPRECATED since version 0.7.2, use Authenticator.admin_users instead.""" @@ -938,7 +1001,8 @@ def _users_default(self): help="Extra settings overrides to pass to the tornado application." ).tag(config=True) - cleanup_servers = Bool(True, + cleanup_servers = Bool( + True, help="""Whether to shutdown single-user servers when the Hub shuts down. Disable if you want to be able to teardown the Hub while leaving the single-user servers running. @@ -947,10 +1011,11 @@ def _users_default(self): only shutdown the Hub, leaving everything else running. The Hub should be able to resume from database state. - """ + """, ).tag(config=True) - cleanup_proxy = Bool(True, + cleanup_proxy = Bool( + True, help="""Whether to shutdown the proxy when the Hub shuts down. Disable if you want to be able to teardown the Hub while leaving the proxy running. @@ -961,7 +1026,7 @@ def _users_default(self): only shutdown the Hub, leaving everything else running. The Hub should be able to resume from database state. - """ + """, ).tag(config=True) statsd_host = Unicode( @@ -969,13 +1034,11 @@ def _users_default(self): ).tag(config=True) statsd_port = Integer( - 8125, - help="Port on which to send statsd metrics about the hub" + 8125, help="Port on which to send statsd metrics about the hub" ).tag(config=True) statsd_prefix = Unicode( - 'jupyterhub', - help="Prefix to use for all metrics sent by jupyterhub to statsd" + 'jupyterhub', help="Prefix to use for all metrics sent by jupyterhub to statsd" ).tag(config=True) handlers = List() @@ -1010,7 +1073,9 @@ def _log_format_default(self): @observe('extra_log_file') def _log_file_changed(self, change): if change.new: - self.log.warning(dedent(""" + self.log.warning( + dedent( + """ extra_log_file is DEPRECATED in jupyterhub-0.8.2. extra_log_file only redirects logs of the Hub itself, @@ -1021,28 +1086,32 @@ def _log_file_changed(self, change): output instead, e.g. jupyterhub &>> '{}' - """.format(change.new))) + """.format( + change.new + ) + ) + ) extra_log_handlers = List( - Instance(logging.Handler), - help="Extra log handlers to set on JupyterHub logger", + Instance(logging.Handler), help="Extra log handlers to set on JupyterHub logger" ).tag(config=True) - statsd = Any(allow_none=False, help="The statsd client, if any. A mock will be used if we aren't using statsd") + statsd = Any( + allow_none=False, + help="The statsd client, if any. A mock will be used if we aren't using statsd", + ) shutdown_on_logout = Bool( - False, - help="""Shuts down all user servers on logout""" + False, help="""Shuts down all user servers on logout""" ).tag(config=True) @default('statsd') def _statsd(self): if self.statsd_host: import statsd + client = statsd.StatsClient( - self.statsd_host, - self.statsd_port, - self.statsd_prefix + self.statsd_host, self.statsd_port, self.statsd_prefix ) return client else: @@ -1061,8 +1130,7 @@ def init_logging(self): ) _formatter = self._log_formatter_cls( - fmt=self.log_format, - datefmt=self.log_datefmt, + fmt=self.log_format, datefmt=self.log_datefmt ) for handler in self.extra_log_handlers: if handler.formatter is None: @@ -1070,7 +1138,9 @@ def init_logging(self): self.log.addHandler(handler) # disable curl debug, which is TOO MUCH - logging.getLogger('tornado.curl_httpclient').setLevel(max(self.log_level, logging.INFO)) + logging.getLogger('tornado.curl_httpclient').setLevel( + max(self.log_level, logging.INFO) + ) # hook up tornado 3's loggers to our app handlers for log in (app_log, access_log, gen_log): @@ -1097,7 +1167,7 @@ def add_url_prefix(prefix, handlers): Should be of the form ``("<regex>", Handler)`` The Hub prefix will be added, so `/my-page` will be served at `/hub/my-page`. - """, + """ ).tag(config=True) default_url = Unicode( @@ -1105,7 +1175,7 @@ def add_url_prefix(prefix, handlers): The default URL for users when they arrive (e.g. when user directs to "/") By default, redirects users to their own server. - """, + """ ).tag(config=True) def init_handlers(self): @@ -1124,12 +1194,17 @@ def init_handlers(self): self.handlers = self.add_url_prefix(self.hub_prefix, h) # some extra handlers, outside hub_prefix - self.handlers.extend([ - # add trailing / to ``/user|services/:name` - (r"%s(user|services)/([^/]+)" % self.base_url, handlers.AddSlashHandler), - (r"(?!%s).*" % self.hub_prefix, handlers.PrefixRedirectHandler), - (r'(.*)', handlers.Template404), - ]) + self.handlers.extend( + [ + # add trailing / to ``/user|services/:name` + ( + r"%s(user|services)/([^/]+)" % self.base_url, + handlers.AddSlashHandler, + ), + (r"(?!%s).*" % self.hub_prefix, handlers.PrefixRedirectHandler), + (r'(.*)', handlers.Template404), + ] + ) def _check_db_path(self, path): """More informative log messages for failed filesystem access""" @@ -1147,9 +1222,7 @@ def init_secrets(self): trait_name = 'cookie_secret' trait = self.traits()[trait_name] env_name = trait.metadata.get('env') - secret_file = os.path.abspath( - os.path.expanduser(self.cookie_secret_file) - ) + secret_file = os.path.abspath(os.path.expanduser(self.cookie_secret_file)) secret = self.cookie_secret secret_from = 'config' # load priority: 1. config, 2. env, 3. file @@ -1162,7 +1235,7 @@ def init_secrets(self): secret_from = 'file' self.log.info("Loading %s from %s", trait_name, secret_file) try: - if not _mswindows: # Windows permissions don't follow POSIX rules + if not _mswindows: # Windows permissions don't follow POSIX rules perm = os.stat(secret_file).st_mode if perm & 0o07: msg = "cookie_secret_file can be read or written by anybody" @@ -1175,7 +1248,9 @@ def init_secrets(self): else: # old b64 secret with a bunch of ignored bytes secret = binascii.a2b_base64(text_secret) - self.log.warning(dedent(""" + self.log.warning( + dedent( + """ Old base64 cookie-secret detected in {0}. JupyterHub >= 0.8 expects 32B hex-encoded cookie secret @@ -1184,12 +1259,16 @@ def init_secrets(self): To generate a new secret: openssl rand -hex 32 > "{0}" - """).format(secret_file)) + """ + ).format(secret_file) + ) except Exception as e: self.log.error( "Refusing to run JupyterHub with invalid cookie_secret_file. " "%s error was: %s", - secret_file, e) + secret_file, + e, + ) self.exit(1) if not secret: @@ -1204,7 +1283,7 @@ def init_secrets(self): with open(secret_file, 'w') as f: f.write(text_secret) f.write('\n') - if not _mswindows: # Windows permissions don't follow POSIX rules + if not _mswindows: # Windows permissions don't follow POSIX rules try: os.chmod(secret_file, 0o600) except OSError: @@ -1217,8 +1296,11 @@ def init_internal_ssl(self): if self.internal_ssl: from certipy import Certipy, CertNotFoundError - certipy = Certipy(store_dir=self.internal_certs_location, - remove_existing=self.recreate_internal_certs) + + certipy = Certipy( + store_dir=self.internal_certs_location, + remove_existing=self.recreate_internal_certs, + ) # Here we define how trust should be laid out per each component self.internal_ssl_components_trust = { @@ -1237,15 +1319,17 @@ def init_internal_ssl(self): for authority, files in self.internal_ssl_authorities.items(): if files: self.log.info("Adding CA for %s", authority) - certipy.store.add_record( - authority, is_ca=True, files=files) + certipy.store.add_record(authority, is_ca=True, files=files) self.internal_trust_bundles = certipy.trust_from_graph( - self.internal_ssl_components_trust) + self.internal_ssl_components_trust + ) default_alt_names = ["IP:127.0.0.1", "DNS:localhost"] if self.subdomain_host: - default_alt_names.append("DNS:%s" % urlparse(self.subdomain_host).hostname) + default_alt_names.append( + "DNS:%s" % urlparse(self.subdomain_host).hostname + ) # The signed certs used by hub-internal components try: internal_key_pair = certipy.store.get_record("hub-internal") @@ -1253,17 +1337,12 @@ def init_internal_ssl(self): alt_names = list(default_alt_names) # In the event the hub needs to be accessed externally, add # the fqdn and (optionally) rev_proxy to the set of alt_names. - alt_names += (["DNS:" + socket.getfqdn()] - + self.trusted_alt_names) + alt_names += ["DNS:" + socket.getfqdn()] + self.trusted_alt_names self.log.info( - "Adding CA for %s: %s", - "hub-internal", - ";".join(alt_names), + "Adding CA for %s: %s", "hub-internal", ";".join(alt_names) ) internal_key_pair = certipy.create_signed_pair( - "hub-internal", - hub_name, - alt_names=alt_names, + "hub-internal", hub_name, alt_names=alt_names ) else: self.log.info("Using existing hub-internal CA") @@ -1283,9 +1362,7 @@ def init_internal_ssl(self): ';'.join(alt_names), ) record = certipy.create_signed_pair( - component, - ca_name, - alt_names=alt_names, + component, ca_name, alt_names=alt_names ) else: self.log.info("Using existing %s CA", component) @@ -1307,9 +1384,7 @@ def init_internal_ssl(self): self.internal_ssl_cert, cafile=self.internal_ssl_ca, ) - AsyncHTTPClient.configure( - None, defaults={"ssl_options" : ssl_context} - ) + AsyncHTTPClient.configure(None, defaults={"ssl_options": ssl_context}) def init_db(self): """Create the database connection""" @@ -1320,10 +1395,7 @@ def init_db(self): try: self.session_factory = orm.new_session_factory( - self.db_url, - reset=self.reset_db, - echo=self.debug_db, - **self.db_kwargs + self.db_url, reset=self.reset_db, echo=self.debug_db, **self.db_kwargs ) self.db = self.session_factory() except OperationalError as e: @@ -1331,11 +1403,15 @@ def init_db(self): self.log.debug("Database error was:", exc_info=True) if self.db_url.startswith('sqlite:///'): self._check_db_path(self.db_url.split(':///', 1)[1]) - self.log.critical('\n'.join([ - "If you recently upgraded JupyterHub, try running", - " jupyterhub upgrade-db", - "to upgrade your JupyterHub database schema", - ])) + self.log.critical( + '\n'.join( + [ + "If you recently upgraded JupyterHub, try running", + " jupyterhub upgrade-db", + "to upgrade your JupyterHub database schema", + ] + ) + ) self.exit(1) except orm.DatabaseSchemaMismatch as e: self.exit(e) @@ -1352,8 +1428,7 @@ def init_hub(self): if self.hub_bind_url: # ensure hub_prefix is set on bind_url self.hub_bind_url = urlunparse( - urlparse(self.hub_bind_url) - ._replace(path=self.hub_prefix) + urlparse(self.hub_bind_url)._replace(path=self.hub_prefix) ) hub_args['bind_url'] = self.hub_bind_url else: @@ -1385,8 +1460,7 @@ def init_hub(self): if self.hub_connect_url: # ensure hub_prefix is on connect_url self.hub_connect_url = urlunparse( - urlparse(self.hub_connect_url) - ._replace(path=self.hub_prefix) + urlparse(self.hub_connect_url)._replace(path=self.hub_prefix) ) self.hub.connect_url = self.hub_connect_url if self.internal_ssl: @@ -1403,7 +1477,9 @@ async def init_users(self): try: ck.check_available() except Exception as e: - self.exit("auth_state is enabled, but encryption is not available: %s" % e) + self.exit( + "auth_state is enabled, but encryption is not available: %s" % e + ) if self.admin_users and not self.authenticator.admin_users: self.log.warning( @@ -1422,7 +1498,9 @@ async def init_users(self): if not admin_users: self.log.warning("No admin users, admin interface will be unavailable.") - self.log.warning("Add any administrative users to `c.Authenticator.admin_users` in config.") + self.log.warning( + "Add any administrative users to `c.Authenticator.admin_users` in config." + ) new_users = [] @@ -1449,7 +1527,9 @@ async def init_users(self): raise ValueError("username %r is not valid" % username) if not whitelist: - self.log.info("Not using whitelist. Any authenticated user will be allowed.") + self.log.info( + "Not using whitelist. Any authenticated user will be allowed." + ) # add whitelisted users to the db for name in whitelist: @@ -1472,17 +1552,23 @@ async def init_users(self): except Exception: self.log.exception("Error adding user %s already in db", user.name) if self.authenticator.delete_invalid_users: - self.log.warning("Deleting invalid user %s from the Hub database", user.name) + self.log.warning( + "Deleting invalid user %s from the Hub database", user.name + ) db.delete(user) else: - self.log.warning(dedent(""" + self.log.warning( + dedent( + """ You can set c.Authenticator.delete_invalid_users = True to automatically delete users from the Hub database that no longer pass Authenticator validation, such as when user accounts are deleted from the external system without notifying JupyterHub. - """)) + """ + ) + ) else: # handle database upgrades where user.created is undefined. # we don't want to allow user.created to be undefined, @@ -1505,7 +1591,11 @@ async def init_groups(self): db.add(group) for username in usernames: username = self.authenticator.normalize_username(username) - if not (await maybe_future(self.authenticator.check_whitelist(username, None))): + if not ( + await maybe_future( + self.authenticator.check_whitelist(username, None) + ) + ): raise ValueError("Username %r is not in whitelist" % username) user = orm.User.find(db, name=username) if user is None: @@ -1529,7 +1619,9 @@ async def _add_tokens(self, token_dict, kind): for token, name in token_dict.items(): if kind == 'user': name = self.authenticator.normalize_username(name) - if not (await maybe_future(self.authenticator.check_whitelist(name, None))): + if not ( + await maybe_future(self.authenticator.check_whitelist(name, None)) + ): raise ValueError("Token name %r is not in whitelist" % name) if not self.authenticator.validate_username(name): raise ValueError("Token name %r is not valid" % name) @@ -1547,7 +1639,11 @@ async def _add_tokens(self, token_dict, kind): try: # set generated=False to ensure that user-provided tokens # get extra hashing (don't trust entropy of user-provided tokens) - obj.new_api_token(token, note="from config", generated=self.trust_user_provided_tokens) + obj.new_api_token( + token, + note="from config", + generated=self.trust_user_provided_tokens, + ) except Exception: if created: # don't allow bad tokens to create users @@ -1571,8 +1667,7 @@ async def init_api_tokens(self): # we don't need to be prompt about this # because expired tokens cannot be used anyway pc = PeriodicCallback( - purge_expired_tokens, - 1e3 * self.purge_expired_tokens_interval, + purge_expired_tokens, 1e3 * self.purge_expired_tokens_interval ) pc.start() @@ -1597,11 +1692,14 @@ def init_services(self): self.db.add(orm_service) orm_service.admin = spec.get('admin', False) self.db.commit() - service = Service(parent=self, + service = Service( + parent=self, app=self, base_url=self.base_url, - db=self.db, orm=orm_service, - domain=domain, host=host, + db=self.db, + orm=orm_service, + domain=domain, + host=host, hub=self.hub, ) @@ -1615,7 +1713,9 @@ def init_services(self): if not service.api_token: # generate new token # TODO: revoke old tokens? - service.api_token = service.orm.new_api_token(note="generated at startup") + service.api_token = service.orm.new_api_token( + note="generated at startup" + ) else: # ensure provided token is registered self.service_tokens[service.api_token] = service.name @@ -1666,9 +1766,19 @@ async def check_services_health(self): try: await Server.from_orm(service.orm.server).wait_up(timeout=1) except TimeoutError: - self.log.warning("Cannot connect to %s service %s at %s", service.kind, name, service.url) + self.log.warning( + "Cannot connect to %s service %s at %s", + service.kind, + name, + service.url, + ) else: - self.log.debug("%s service %s running at %s", service.kind.title(), name, service.url) + self.log.debug( + "%s service %s running at %s", + service.kind.title(), + name, + service.url, + ) async def init_spawners(self): db = self.db @@ -1680,14 +1790,16 @@ def _user_summary(user): parts.append('admin') for name, spawner in sorted(user.orm_spawners.items(), key=itemgetter(0)): if spawner.server: - parts.append('%s:%s running at %s' % (user.name, name, spawner.server)) + parts.append( + '%s:%s running at %s' % (user.name, name, spawner.server) + ) return ' '.join(parts) async def user_stopped(user, server_name): spawner = user.spawners[server_name] status = await spawner.poll() - self.log.warning("User %s server stopped with exit code: %s", - user.name, status, + self.log.warning( + "User %s server stopped with exit code: %s", user.name, status ) await self.proxy.delete_user(user, server_name) await user.stop(server_name) @@ -1698,8 +1810,10 @@ async def check_spawner(user, name, spawner): try: status = await spawner.poll() except Exception: - self.log.exception("Failed to poll spawner for %s, assuming the spawner is not running.", - spawner._log_name) + self.log.exception( + "Failed to poll spawner for %s, assuming the spawner is not running.", + spawner._log_name, + ) status = -1 if status is None: @@ -1710,7 +1824,9 @@ async def check_spawner(user, name, spawner): if url != url_in_db: self.log.warning( "%s had invalid url %s. Updating to %s", - spawner._log_name, url_in_db, url, + spawner._log_name, + url_in_db, + url, ) urlinfo = urlparse(url) spawner.server.protocol = urlinfo.scheme @@ -1724,15 +1840,15 @@ async def check_spawner(user, name, spawner): self.db.commit() self.log.debug( - "Verifying that %s is running at %s", - spawner._log_name, url, + "Verifying that %s is running at %s", spawner._log_name, url ) try: await user._wait_up(spawner) except TimeoutError: self.log.error( "%s does not appear to be running at %s, shutting it down.", - spawner._log_name, url, + spawner._log_name, + url, ) status = -1 @@ -1745,7 +1861,10 @@ async def check_spawner(user, name, spawner): # but indicates the user's server died while the Hub wasn't running # if spawner.server is defined. if spawner.server: - self.log.warning("%s appears to have stopped while the Hub was down", spawner._log_name) + self.log.warning( + "%s appears to have stopped while the Hub was down", + spawner._log_name, + ) # remove server entry from db db.delete(spawner.orm_spawner.server) spawner.server = None @@ -1829,21 +1948,18 @@ def init_proxy(self): def init_tornado_settings(self): """Set up the tornado settings dict.""" base_url = self.hub.base_url - jinja_options = dict( - autoescape=True, - ) + jinja_options = dict(autoescape=True) jinja_options.update(self.jinja_environment_options) base_path = self._template_paths_default()[0] if base_path not in self.template_paths: self.template_paths.append(base_path) - loader = ChoiceLoader([ - PrefixLoader({'templates': FileSystemLoader([base_path])}, '/'), - FileSystemLoader(self.template_paths) - ]) - jinja_env = Environment( - loader=loader, - **jinja_options + loader = ChoiceLoader( + [ + PrefixLoader({'templates': FileSystemLoader([base_path])}, '/'), + FileSystemLoader(self.template_paths), + ] ) + jinja_env = Environment(loader=loader, **jinja_options) login_url = url_path_join(base_url, 'login') logout_url = self.authenticator.logout_url(base_url) @@ -1899,7 +2015,7 @@ def init_tornado_settings(self): internal_ssl_cert=self.internal_ssl_cert, internal_ssl_ca=self.internal_ssl_ca, trusted_alt_names=self.trusted_alt_names, - shutdown_on_logout=self.shutdown_on_logout + shutdown_on_logout=self.shutdown_on_logout, ) # allow configured settings to have priority settings.update(self.tornado_settings) @@ -1910,7 +2026,9 @@ def init_tornado_settings(self): def init_tornado_application(self): """Instantiate the tornado Application object""" - self.tornado_application = web.Application(self.handlers, **self.tornado_settings) + self.tornado_application = web.Application( + self.handlers, **self.tornado_settings + ) def init_pycurl(self): """Configure tornado to use pycurl by default, if available""" @@ -1918,7 +2036,10 @@ def init_pycurl(self): try: AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient") except ImportError as e: - self.log.debug("Could not load pycurl: %s\npycurl is recommended if you have a large number of users.", e) + self.log.debug( + "Could not load pycurl: %s\npycurl is recommended if you have a large number of users.", + e, + ) def write_pid_file(self): pid = os.getpid() @@ -1935,10 +2056,12 @@ async def initialize(self, *args, **kwargs): self.load_config_file(self.config_file) self.init_logging() if 'JupyterHubApp' in self.config: - self.log.warning("Use JupyterHub in config, not JupyterHubApp. Outdated config:\n%s", - '\n'.join('JupyterHubApp.{key} = {value!r}'.format(key=key, value=value) + self.log.warning( + "Use JupyterHub in config, not JupyterHubApp. Outdated config:\n%s", + '\n'.join( + 'JupyterHubApp.{key} = {value!r}'.format(key=key, value=value) for key, value in self.config.JupyterHubApp.items() - ) + ), ) cfg = self.config.copy() cfg.JupyterHub.merge(cfg.JupyterHubApp) @@ -1962,12 +2085,9 @@ def _log_cls(name, cls): else: version = '' self.log.info( - "Using %s: %s.%s%s", - name, - cls.__module__ or '', - cls.__name__, - version, + "Using %s: %s.%s%s", name, cls.__module__ or '', cls.__name__, version ) + _log_cls("Authenticator", self.authenticator_class) _log_cls("Spawner", self.spawner_class) @@ -1993,7 +2113,7 @@ async def cleanup(self): futures = [] - managed_services = [ s for s in self._service_map.values() if s.managed ] + managed_services = [s for s in self._service_map.values() if s.managed] if managed_services: self.log.info("Cleaning up %i services...", len(managed_services)) for service in managed_services: @@ -2039,9 +2159,11 @@ def write_config_file(self): """Write our default config to a .py config file""" config_file_dir = os.path.dirname(os.path.abspath(self.config_file)) if not os.path.isdir(config_file_dir): - self.exit("{} does not exist. The destination directory must exist before generating config file.".format( - config_file_dir, - )) + self.exit( + "{} does not exist. The destination directory must exist before generating config file.".format( + config_file_dir + ) + ) if os.path.exists(self.config_file) and not self.answer_yes: answer = '' @@ -2052,6 +2174,7 @@ def ask(): except KeyboardInterrupt: print('') # empty line return 'n' + answer = ask() while not answer.startswith(('y', 'n')): print("Please answer 'yes' or 'no'") @@ -2135,13 +2258,18 @@ async def start(self): if self.generate_certs: self.load_config_file(self.config_file) if not self.internal_ssl: - self.log.warn("You'll need to enable `internal_ssl` " - "in the `jupyterhub_config` file to use " - "these certs.") + self.log.warn( + "You'll need to enable `internal_ssl` " + "in the `jupyterhub_config` file to use " + "these certs." + ) self.internal_ssl = True self.init_internal_ssl() - self.log.info("Certificates written to directory `{}`".format( - self.internal_certs_location)) + self.log.info( + "Certificates written to directory `{}`".format( + self.internal_certs_location + ) + ) loop.stop() return @@ -2149,15 +2277,18 @@ async def start(self): self.internal_ssl_key, self.internal_ssl_cert, cafile=self.internal_ssl_ca, - check_hostname=False + check_hostname=False, ) # start the webserver - self.http_server = tornado.httpserver.HTTPServer(self.tornado_application, ssl_options=ssl_context, xheaders=True) + self.http_server = tornado.httpserver.HTTPServer( + self.tornado_application, ssl_options=ssl_context, xheaders=True + ) bind_url = urlparse(self.hub.bind_url) try: if bind_url.scheme.startswith('unix+'): from tornado.netutil import bind_unix_socket + socket = bind_unix_socket(unquote(bind_url.netloc)) self.http_server.add_socket(socket) else: @@ -2188,13 +2319,19 @@ async def start(self): # start the service(s) for service_name, service in self._service_map.items(): - msg = '%s at %s' % (service_name, service.url) if service.url else service_name + msg = ( + '%s at %s' % (service_name, service.url) + if service.url + else service_name + ) if service.managed: self.log.info("Starting managed service %s", msg) try: service.start() except Exception as e: - self.log.critical("Failed to start service %s", service_name, exc_info=True) + self.log.critical( + "Failed to start service %s", service_name, exc_info=True + ) self.exit(1) else: self.log.info("Adding external service %s", msg) @@ -2206,28 +2343,45 @@ async def start(self): ssl_context = make_ssl_context( self.internal_ssl_key, self.internal_ssl_cert, - cafile=self.internal_ssl_ca + cafile=self.internal_ssl_ca, + ) + await Server.from_orm(service.orm.server).wait_up( + http=True, timeout=1, ssl_context=ssl_context ) - await Server.from_orm(service.orm.server).wait_up(http=True, timeout=1, ssl_context=ssl_context) except TimeoutError: if service.managed: status = await service.spawner.poll() if status is not None: - self.log.error("Service %s exited with status %s", service_name, status) + self.log.error( + "Service %s exited with status %s", + service_name, + status, + ) break else: break else: - self.log.error("Cannot connect to %s service %s at %s. Is it running?", service.kind, service_name, service.url) + self.log.error( + "Cannot connect to %s service %s at %s. Is it running?", + service.kind, + service_name, + service.url, + ) await self.proxy.check_routes(self.users, self._service_map) - if self.service_check_interval and any(s.url for s in self._service_map.values()): - pc = PeriodicCallback(self.check_services_health, 1e3 * self.service_check_interval) + if self.service_check_interval and any( + s.url for s in self._service_map.values() + ): + pc = PeriodicCallback( + self.check_services_health, 1e3 * self.service_check_interval + ) pc.start() if self.last_activity_interval: - pc = PeriodicCallback(self.update_last_activity, 1e3 * self.last_activity_interval) + pc = PeriodicCallback( + self.update_last_activity, 1e3 * self.last_activity_interval + ) self.last_activity_callback = pc pc.start() diff --git a/jupyterhub/auth.py b/jupyterhub/auth.py --- a/jupyterhub/auth.py +++ b/jupyterhub/auth.py @@ -1,16 +1,16 @@ """Base Authenticator class and the default PAM Authenticator""" - # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. - -from concurrent.futures import ThreadPoolExecutor import inspect import pipes import re import sys -from shutil import which -from subprocess import Popen, PIPE, STDOUT import warnings +from concurrent.futures import ThreadPoolExecutor +from shutil import which +from subprocess import PIPE +from subprocess import Popen +from subprocess import STDOUT try: import pamela @@ -33,7 +33,9 @@ class Authenticator(LoggingConfigurable): db = Any() - enable_auth_state = Bool(False, config=True, + enable_auth_state = Bool( + False, + config=True, help="""Enable persisting auth_state (if available). auth_state will be encrypted and stored in the Hub's database. @@ -62,7 +64,7 @@ class Authenticator(LoggingConfigurable): See :meth:`.refresh_user` for what happens when user auth info is refreshed (nothing by default). - """ + """, ) refresh_pre_spawn = Bool( @@ -78,7 +80,7 @@ class Authenticator(LoggingConfigurable): If refresh_user cannot refresh the user auth data, launch will fail until the user logs in again. - """ + """, ) admin_users = Set( @@ -131,8 +133,11 @@ def _check_whitelist(self, change): sorted_names = sorted(short_names) single = ''.join(sorted_names) string_set_typo = "set('%s')" % single - self.log.warning("whitelist contains single-character names: %s; did you mean set([%r]) instead of %s?", - sorted_names[:8], single, string_set_typo, + self.log.warning( + "whitelist contains single-character names: %s; did you mean set([%r]) instead of %s?", + sorted_names[:8], + single, + string_set_typo, ) custom_html = Unicode( @@ -199,7 +204,8 @@ def validate_username(self, username): """ ).tag(config=True) - delete_invalid_users = Bool(False, + delete_invalid_users = Bool( + False, help="""Delete any users from the database that do not pass validation When JupyterHub starts, `.add_user` will be called @@ -213,10 +219,11 @@ def validate_username(self, username): If False (default), invalid users remain in the Hub's database and a warning will be issued. This is the default to avoid data loss due to config changes. - """ + """, ) - post_auth_hook = Any(config=True, + post_auth_hook = Any( + config=True, help=""" An optional hook function that you can implement to do some bootstrapping work during authentication. For example, loading user account @@ -248,12 +255,16 @@ def my_hook(authenticator, handler, authentication): c.Authenticator.post_auth_hook = my_hook - """ + """, ) def __init__(self, **kwargs): super().__init__(**kwargs) - for method_name in ('check_whitelist', 'check_blacklist', 'check_group_whitelist'): + for method_name in ( + 'check_whitelist', + 'check_blacklist', + 'check_group_whitelist', + ): original_method = getattr(self, method_name, None) if original_method is None: # no such method (check_group_whitelist is optional) @@ -273,14 +284,14 @@ def {1}(self, username, authentication=None): Adapting for compatibility. """.format( - self.__class__.__name__, - method_name, + self.__class__.__name__, method_name ), - DeprecationWarning + DeprecationWarning, ) def wrapped_method(username, authentication=None, **kwargs): return original_method(username, **kwargs) + setattr(self, method_name, wrapped_method) async def run_post_auth_hook(self, handler, authentication): @@ -299,11 +310,7 @@ async def run_post_auth_hook(self, handler, authentication): """ if self.post_auth_hook is not None: authentication = await maybe_future( - self.post_auth_hook( - self, - handler, - authentication, - ) + self.post_auth_hook(self, handler, authentication) ) return authentication @@ -380,21 +387,25 @@ async def get_authenticated_user(self, handler, data): if 'name' not in authenticated: raise ValueError("user missing a name: %r" % authenticated) else: - authenticated = { - 'name': authenticated, - } + authenticated = {'name': authenticated} authenticated.setdefault('auth_state', None) # Leave the default as None, but reevaluate later post-whitelist authenticated.setdefault('admin', None) # normalize the username - authenticated['name'] = username = self.normalize_username(authenticated['name']) + authenticated['name'] = username = self.normalize_username( + authenticated['name'] + ) if not self.validate_username(username): self.log.warning("Disallowing invalid username %r.", username) return - blacklist_pass = await maybe_future(self.check_blacklist(username, authenticated)) - whitelist_pass = await maybe_future(self.check_whitelist(username, authenticated)) + blacklist_pass = await maybe_future( + self.check_blacklist(username, authenticated) + ) + whitelist_pass = await maybe_future( + self.check_whitelist(username, authenticated) + ) if blacklist_pass: pass @@ -404,7 +415,9 @@ async def get_authenticated_user(self, handler, data): if whitelist_pass: if authenticated['admin'] is None: - authenticated['admin'] = await maybe_future(self.is_admin(handler, authenticated)) + authenticated['admin'] = await maybe_future( + self.is_admin(handler, authenticated) + ) authenticated = await self.run_post_auth_hook(handler, authenticated) @@ -534,7 +547,9 @@ def delete_user(self, user): """ self.whitelist.discard(user.name) - auto_login = Bool(False, config=True, + auto_login = Bool( + False, + config=True, help="""Automatically begin the login process rather than starting with a "Login with..." link at `/hub/login` @@ -544,7 +559,7 @@ def delete_user(self, user): registered with `.get_handlers()`. .. versionadded:: 0.8 - """ + """, ) def login_url(self, base_url): @@ -592,9 +607,7 @@ def get_handlers(self, app): list of ``('/url', Handler)`` tuples passed to tornado. The Hub prefix is added to any URLs. """ - return [ - ('/login', LoginHandler), - ] + return [('/login', LoginHandler)] class LocalAuthenticator(Authenticator): @@ -603,12 +616,13 @@ class LocalAuthenticator(Authenticator): Checks for local users, and can attempt to create them if they exist. """ - create_system_users = Bool(False, + create_system_users = Bool( + False, help=""" If set to True, will attempt to create local system users if they do not exist already. Supports Linux and BSD variants only. - """ + """, ).tag(config=True) add_user_cmd = Command( @@ -699,8 +713,9 @@ async def add_user(self, user): raise KeyError( "User {} does not exist on the system." " Set LocalAuthenticator.create_system_users=True" - " to automatically create system users from jupyterhub users." - .format(user.name) + " to automatically create system users from jupyterhub users.".format( + user.name + ) ) await maybe_future(super().add_user(user)) @@ -711,6 +726,7 @@ def _getgrnam(name): on Windows """ import grp + return grp.getgrnam(name) @staticmethod @@ -719,6 +735,7 @@ def _getpwnam(name): on Windows """ import pwd + return pwd.getpwnam(name) @staticmethod @@ -727,6 +744,7 @@ def _getgrouplist(name, group): on Windows """ import os + return os.getgrouplist(name, group) def system_user_exists(self, user): @@ -744,7 +762,7 @@ def add_system_user(self, user): Tested to work on FreeBSD and Linux, at least. """ name = user.name - cmd = [ arg.replace('USERNAME', name) for arg in self.add_user_cmd ] + [name] + cmd = [arg.replace('USERNAME', name) for arg in self.add_user_cmd] + [name] self.log.info("Creating user: %s", ' '.join(map(pipes.quote, cmd))) p = Popen(cmd, stdout=PIPE, stderr=STDOUT) p.wait() @@ -758,23 +776,27 @@ class PAMAuthenticator(LocalAuthenticator): # run PAM in a thread, since it can be slow executor = Any() + @default('executor') def _default_executor(self): return ThreadPoolExecutor(1) - encoding = Unicode('utf8', + encoding = Unicode( + 'utf8', help=""" The text encoding to use when communicating with PAM - """ + """, ).tag(config=True) - service = Unicode('login', + service = Unicode( + 'login', help=""" The name of the PAM service to use for authentication - """ + """, ).tag(config=True) - open_sessions = Bool(True, + open_sessions = Bool( + True, help=""" Whether to open a new PAM session when spawners are started. @@ -784,10 +806,11 @@ def _default_executor(self): If any errors are encountered when opening/closing PAM sessions, this is automatically set to False. - """ + """, ).tag(config=True) - check_account = Bool(True, + check_account = Bool( + True, help=""" Whether to check the user's account status via PAM during authentication. @@ -797,8 +820,8 @@ def _default_executor(self): Disabling this can be dangerous as authenticated but unauthorized users may be granted access and, therefore, arbitrary execution on the system. - """ - ).tag(config=True) + """, + ).tag(config=True) admin_groups = Set( help=""" @@ -809,15 +832,16 @@ def _default_executor(self): """ ).tag(config=True) - pam_normalize_username = Bool(False, + pam_normalize_username = Bool( + False, help=""" Round-trip the username via PAM lookups to make sure it is unique PAM can accept multiple usernames that map to the same user, for example DOMAIN\\username in some cases. To prevent this, convert username into uid, then back to uid to normalize. - """ - ).tag(config=True) + """, + ).tag(config=True) def __init__(self, **kwargs): if pamela is None: @@ -844,17 +868,24 @@ def is_admin(self, handler, authentication): # (returning None instead of just the username) as this indicates some sort of system failure admin_group_gids = {self._getgrnam(x).gr_gid for x in self.admin_groups} - user_group_gids = set(self._getgrouplist(username, self._getpwnam(username).pw_gid)) + user_group_gids = set( + self._getgrouplist(username, self._getpwnam(username).pw_gid) + ) admin_status = len(admin_group_gids & user_group_gids) != 0 except Exception as e: if handler is not None: - self.log.error("PAM Admin Group Check failed (%s@%s): %s", username, handler.request.remote_ip, e) + self.log.error( + "PAM Admin Group Check failed (%s@%s): %s", + username, + handler.request.remote_ip, + e, + ) else: self.log.error("PAM Admin Group Check failed: %s", e) # re-raise to return a 500 to the user and indicate a problem. We failed, not them. raise - + return admin_status @run_on_executor @@ -865,27 +896,40 @@ def authenticate(self, handler, data): """ username = data['username'] try: - pamela.authenticate(username, data['password'], service=self.service, encoding=self.encoding) + pamela.authenticate( + username, data['password'], service=self.service, encoding=self.encoding + ) except pamela.PAMError as e: if handler is not None: - self.log.warning("PAM Authentication failed (%s@%s): %s", username, handler.request.remote_ip, e) + self.log.warning( + "PAM Authentication failed (%s@%s): %s", + username, + handler.request.remote_ip, + e, + ) else: self.log.warning("PAM Authentication failed: %s", e) return None - + if self.check_account: try: - pamela.check_account(username, service=self.service, encoding=self.encoding) + pamela.check_account( + username, service=self.service, encoding=self.encoding + ) except pamela.PAMError as e: if handler is not None: - self.log.warning("PAM Account Check failed (%s@%s): %s", username, handler.request.remote_ip, e) + self.log.warning( + "PAM Account Check failed (%s@%s): %s", + username, + handler.request.remote_ip, + e, + ) else: self.log.warning("PAM Account Check failed: %s", e) return None return username - @run_on_executor def pre_spawn_start(self, user, spawner): """Open PAM session for user if so configured""" @@ -904,7 +948,9 @@ def post_spawn_stop(self, user, spawner): if not self.open_sessions: return try: - pamela.close_session(user.name, service=self.service, encoding=self.encoding) + pamela.close_session( + user.name, service=self.service, encoding=self.encoding + ) except pamela.PAMError as e: self.log.warning("Failed to close PAM session for %s: %s", user.name, e) self.log.warning("Disabling PAM sessions from now on.") @@ -916,12 +962,14 @@ def normalize_username(self, username): PAM can accept multiple usernames as the same user, normalize them.""" if self.pam_normalize_username: import pwd + uid = pwd.getpwnam(username).pw_uid username = pwd.getpwuid(uid).pw_name username = self.username_map.get(username, username) else: return super().normalize_username(username) + class DummyAuthenticator(Authenticator): """Dummy Authenticator for testing @@ -938,7 +986,7 @@ class DummyAuthenticator(Authenticator): Set a global password for all users wanting to log in. This allows users with any username to log in with the same static password. - """ + """, ) async def authenticate(self, handler, data): diff --git a/jupyterhub/crypto.py b/jupyterhub/crypto.py --- a/jupyterhub/crypto.py +++ b/jupyterhub/crypto.py @@ -1,35 +1,43 @@ - import base64 -from binascii import a2b_hex -from concurrent.futures import ThreadPoolExecutor import json import os +from binascii import a2b_hex +from concurrent.futures import ThreadPoolExecutor -from traitlets.config import SingletonConfigurable, Config -from traitlets import ( - Any, Dict, Integer, List, - default, observe, validate, -) +from traitlets import Any +from traitlets import default +from traitlets import Dict +from traitlets import Integer +from traitlets import List +from traitlets import observe +from traitlets import validate +from traitlets.config import Config +from traitlets.config import SingletonConfigurable try: import cryptography from cryptography.fernet import Fernet, MultiFernet, InvalidToken except ImportError: cryptography = None + class InvalidToken(Exception): pass + from .utils import maybe_future KEY_ENV = 'JUPYTERHUB_CRYPT_KEY' + class EncryptionUnavailable(Exception): pass + class CryptographyUnavailable(EncryptionUnavailable): def __str__(self): return "cryptography library is required for encryption" + class NoEncryptionKeys(EncryptionUnavailable): def __str__(self): return "Encryption keys must be specified in %s env" % KEY_ENV @@ -70,13 +78,16 @@ def _validate_key(key): return key + class CryptKeeper(SingletonConfigurable): """Encapsulate encryption configuration Use via the encryption_config singleton below. """ - n_threads = Integer(max(os.cpu_count(), 1), config=True, + n_threads = Integer( + max(os.cpu_count(), 1), + config=True, help="The number of threads to allocate for encryption", ) @@ -84,29 +95,35 @@ class CryptKeeper(SingletonConfigurable): def _config_default(self): # load application config by default from .app import JupyterHub + if JupyterHub.initialized(): return JupyterHub.instance().config else: return Config() executor = Any() + def _executor_default(self): return ThreadPoolExecutor(self.n_threads) keys = List(config=True) + def _keys_default(self): if KEY_ENV not in os.environ: return [] # key can be a ;-separated sequence for key rotation. # First item in the list is used for encryption. - return [ _validate_key(key) for key in os.environ[KEY_ENV].split(';') if key.strip() ] + return [ + _validate_key(key) for key in os.environ[KEY_ENV].split(';') if key.strip() + ] @validate('keys') def _ensure_bytes(self, proposal): # cast str to bytes - return [ _validate_key(key) for key in proposal.value ] + return [_validate_key(key) for key in proposal.value] fernet = Any() + def _fernet_default(self): if cryptography is None or not self.keys: return None @@ -153,6 +170,7 @@ def encrypt(data): """ return CryptKeeper.instance().encrypt(data) + def decrypt(data): """decrypt some data with the crypt keeper diff --git a/jupyterhub/dbutil.py b/jupyterhub/dbutil.py --- a/jupyterhub/dbutil.py +++ b/jupyterhub/dbutil.py @@ -1,15 +1,13 @@ """Database utilities for JupyterHub""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - # Based on pgcontents.utils.migrate, used under the Apache license. - -from contextlib import contextmanager -from datetime import datetime import os import shutil -from subprocess import check_call import sys +from contextlib import contextmanager +from datetime import datetime +from subprocess import check_call from tempfile import TemporaryDirectory from sqlalchemy import create_engine @@ -85,9 +83,7 @@ def upgrade(db_url, revision='head'): The alembic revision to upgrade to. """ with _temp_alembic_ini(db_url) as alembic_ini: - check_call( - ['alembic', '-c', alembic_ini, 'upgrade', revision] - ) + check_call(['alembic', '-c', alembic_ini, 'upgrade', revision]) def backup_db_file(db_file, log=None): @@ -133,30 +129,27 @@ def upgrade_if_needed(db_url, backup=True, log=None): def shell(args=None): """Start an IPython shell hooked up to the jupyerhub database""" from .app import JupyterHub + hub = JupyterHub() hub.load_config_file(hub.config_file) db_url = hub.db_url db = orm.new_session_factory(db_url, **hub.db_kwargs)() - ns = { - 'db': db, - 'db_url': db_url, - 'orm': orm, - } + ns = {'db': db, 'db_url': db_url, 'orm': orm} import IPython + IPython.start_ipython(args, user_ns=ns) def _alembic(args): """Run an alembic command with a temporary alembic.ini""" from .app import JupyterHub + hub = JupyterHub() hub.load_config_file(hub.config_file) db_url = hub.db_url with _temp_alembic_ini(db_url) as alembic_ini: - check_call( - ['alembic', '-c', alembic_ini] + args - ) + check_call(['alembic', '-c', alembic_ini] + args) def main(args=None): diff --git a/jupyterhub/handlers/__init__.py b/jupyterhub/handlers/__init__.py --- a/jupyterhub/handlers/__init__.py +++ b/jupyterhub/handlers/__init__.py @@ -1,8 +1,10 @@ +from . import base +from . import login +from . import metrics +from . import pages from .base import * from .login import * -from . import base, pages, login, metrics - default_handlers = [] for mod in (base, pages, login, metrics): default_handlers.extend(mod.default_handlers) diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -1,41 +1,49 @@ """HTTP Handlers for the hub server""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import asyncio import copy -from datetime import datetime, timedelta -from http.client import responses import json import math import random import re import time -from urllib.parse import urlparse, urlunparse, parse_qs, urlencode import uuid +from datetime import datetime +from datetime import timedelta +from http.client import responses +from urllib.parse import parse_qs +from urllib.parse import urlencode +from urllib.parse import urlparse +from urllib.parse import urlunparse from jinja2 import TemplateNotFound - from sqlalchemy.exc import SQLAlchemyError -from tornado.log import app_log -from tornado.httputil import url_concat, HTTPHeaders +from tornado import gen +from tornado import web +from tornado.httputil import HTTPHeaders +from tornado.httputil import url_concat from tornado.ioloop import IOLoop -from tornado.web import RequestHandler, MissingArgumentError -from tornado import gen, web +from tornado.log import app_log +from tornado.web import MissingArgumentError +from tornado.web import RequestHandler from .. import __version__ from .. import orm +from ..metrics import PROXY_ADD_DURATION_SECONDS +from ..metrics import ProxyAddStatus +from ..metrics import RUNNING_SERVERS +from ..metrics import SERVER_POLL_DURATION_SECONDS +from ..metrics import SERVER_SPAWN_DURATION_SECONDS +from ..metrics import SERVER_STOP_DURATION_SECONDS +from ..metrics import ServerPollStatus +from ..metrics import ServerSpawnStatus +from ..metrics import ServerStopStatus from ..objects import Server from ..spawner import LocalProcessSpawner from ..user import User -from ..utils import maybe_future, url_path_join -from ..metrics import ( - SERVER_SPAWN_DURATION_SECONDS, ServerSpawnStatus, - PROXY_ADD_DURATION_SECONDS, ProxyAddStatus, - SERVER_POLL_DURATION_SECONDS, ServerPollStatus, - RUNNING_SERVERS, SERVER_STOP_DURATION_SECONDS, ServerStopStatus -) +from ..utils import maybe_future +from ..utils import url_path_join # pattern for the authentication token header auth_header_pat = re.compile(r'^(?:token|bearer)\s+([^\s]+)$', flags=re.IGNORECASE) @@ -43,15 +51,16 @@ # mapping of reason: reason_message reasons = { 'timeout': "Failed to reach your server." - " Please try again later." - " Contact admin if the issue persists.", + " Please try again later." + " Contact admin if the issue persists.", 'error': "Failed to start your server on the last attempt. " - " Please contact admin if the issue persists.", + " Please contact admin if the issue persists.", } # constant, not configurable SESSION_COOKIE_NAME = 'jupyterhub-session-id' + class BaseHandler(RequestHandler): """Base Handler class with access to common methods and properties.""" @@ -151,14 +160,14 @@ def finish(self, *args, **kwargs): self.db.rollback() super().finish(*args, **kwargs) - #--------------------------------------------------------------- + # --------------------------------------------------------------- # Security policies - #--------------------------------------------------------------- + # --------------------------------------------------------------- @property def csp_report_uri(self): - return self.settings.get('csp_report_uri', - url_path_join(self.hub.base_url, 'security/csp-report') + return self.settings.get( + 'csp_report_uri', url_path_join(self.hub.base_url, 'security/csp-report') ) @property @@ -167,10 +176,9 @@ def content_security_policy(self): Can be overridden by defining Content-Security-Policy in settings['headers'] """ - return '; '.join([ - "frame-ancestors 'self'", - "report-uri " + self.csp_report_uri, - ]) + return '; '.join( + ["frame-ancestors 'self'", "report-uri " + self.csp_report_uri] + ) def get_content_type(self): return 'text/html' @@ -190,14 +198,16 @@ def set_default_headers(self): self.set_header(header_name, header_content) if 'Access-Control-Allow-Headers' not in headers: - self.set_header('Access-Control-Allow-Headers', 'accept, content-type, authorization') + self.set_header( + 'Access-Control-Allow-Headers', 'accept, content-type, authorization' + ) if 'Content-Security-Policy' not in headers: self.set_header('Content-Security-Policy', self.content_security_policy) self.set_header('Content-Type', self.get_content_type()) - #--------------------------------------------------------------- + # --------------------------------------------------------------- # Login and cookie-related - #--------------------------------------------------------------- + # --------------------------------------------------------------- @property def admin_users(self): @@ -236,8 +246,7 @@ def get_current_user_oauth_token(self): orm_token = orm.OAuthAccessToken.find(self.db, token) if orm_token is None: return None - orm_token.last_activity = \ - orm_token.user.last_activity = datetime.utcnow() + orm_token.last_activity = orm_token.user.last_activity = datetime.utcnow() self.db.commit() return self._user_from_orm(orm_token.user) @@ -259,7 +268,11 @@ async def refresh_auth(self, user, force=False): if not refresh_age: return user now = time.monotonic() - if not force and user._auth_refreshed and (now - user._auth_refreshed < refresh_age): + if ( + not force + and user._auth_refreshed + and (now - user._auth_refreshed < refresh_age) + ): # auth up-to-date return user @@ -276,8 +289,7 @@ async def refresh_auth(self, user, force=False): if not auth_info: self.log.warning( - "User %s has stale auth info. Login is required to refresh.", - user.name, + "User %s has stale auth info. Login is required to refresh.", user.name ) return @@ -325,10 +337,9 @@ def get_current_user_token(self): def _user_for_cookie(self, cookie_name, cookie_value=None): """Get the User for a given cookie, if there is one""" cookie_id = self.get_secure_cookie( - cookie_name, - cookie_value, - max_age_days=self.cookie_max_age_days, + cookie_name, cookie_value, max_age_days=self.cookie_max_age_days ) + def clear(): self.clear_cookie(cookie_name, path=self.hub.base_url) @@ -338,7 +349,7 @@ def clear(): clear() return cookie_id = cookie_id.decode('utf8', 'replace') - u = self.db.query(orm.User).filter(orm.User.cookie_id==cookie_id).first() + u = self.db.query(orm.User).filter(orm.User.cookie_id == cookie_id).first() user = self._user_from_orm(u) if user is None: self.log.warning("Invalid cookie token") @@ -422,8 +433,8 @@ def clear_login_cookie(self, name=None): count = 0 for access_token in ( self.db.query(orm.OAuthAccessToken) - .filter(orm.OAuthAccessToken.user_id==user.id) - .filter(orm.OAuthAccessToken.session_id==session_id) + .filter(orm.OAuthAccessToken.user_id == user.id) + .filter(orm.OAuthAccessToken.session_id == session_id) ): self.db.delete(access_token) count += 1 @@ -434,7 +445,11 @@ def clear_login_cookie(self, name=None): # clear hub cookie self.clear_cookie(self.hub.cookie_name, path=self.hub.base_url, **kwargs) # clear services cookie - self.clear_cookie('jupyterhub-services', path=url_path_join(self.base_url, 'services'), **kwargs) + self.clear_cookie( + 'jupyterhub-services', + path=url_path_join(self.base_url, 'services'), + **kwargs + ) def _set_cookie(self, key, value, encrypted=True, **overrides): """Setting any cookie should go through here @@ -444,10 +459,8 @@ def _set_cookie(self, key, value, encrypted=True, **overrides): """ # tornado <4.2 have a bug that consider secure==True as soon as # 'secure' kwarg is passed to set_secure_cookie - kwargs = { - 'httponly': True, - } - if self.request.protocol == 'https': + kwargs = {'httponly': True} + if self.request.protocol == 'https': kwargs['secure'] = True if self.subdomain_host: kwargs['domain'] = self.domain @@ -463,14 +476,10 @@ def _set_cookie(self, key, value, encrypted=True, **overrides): self.log.debug("Setting cookie %s: %s", key, kwargs) set_cookie(key, value, **kwargs) - def _set_user_cookie(self, user, server): self.log.debug("Setting cookie for %s: %s", user.name, server.cookie_name) self._set_cookie( - server.cookie_name, - user.cookie_id, - encrypted=True, - path=server.base_url, + server.cookie_name, user.cookie_id, encrypted=True, path=server.base_url ) def get_session_cookie(self): @@ -494,10 +503,13 @@ def set_session_cookie(self): def set_service_cookie(self, user): """set the login cookie for services""" - self._set_user_cookie(user, orm.Server( - cookie_name='jupyterhub-services', - base_url=url_path_join(self.base_url, 'services') - )) + self._set_user_cookie( + user, + orm.Server( + cookie_name='jupyterhub-services', + base_url=url_path_join(self.base_url, 'services'), + ), + ) def set_hub_cookie(self, user): """set the login cookie for the Hub""" @@ -508,7 +520,9 @@ def set_login_cookie(self, user): if self.subdomain_host and not self.request.host.startswith(self.domain): self.log.warning( "Possibly setting cookie on wrong domain: %s != %s", - self.request.host, self.domain) + self.request.host, + self.domain, + ) # set single cookie for services if self.db.query(orm.Service).filter(orm.Service.server != None).first(): @@ -553,10 +567,12 @@ def get_next_url(self, user=None): # add /hub/ prefix, to ensure we redirect to the right user's server. # The next request will be handled by SpawnHandler, # ultimately redirecting to the logged-in user's server. - without_prefix = next_url[len(self.base_url):] + without_prefix = next_url[len(self.base_url) :] next_url = url_path_join(self.hub.base_url, without_prefix) - self.log.warning("Redirecting %s to %s. For sharing public links, use /user-redirect/", - self.request.uri, next_url, + self.log.warning( + "Redirecting %s to %s. For sharing public links, use /user-redirect/", + self.request.uri, + next_url, ) if not next_url: @@ -627,12 +643,13 @@ async def login_user(self, data=None): else: self.statsd.incr('login.failure') self.statsd.timing('login.authenticate.failure', auth_timer.ms) - self.log.warning("Failed login for %s", (data or {}).get('username', 'unknown user')) - + self.log.warning( + "Failed login for %s", (data or {}).get('username', 'unknown user') + ) - #--------------------------------------------------------------- + # --------------------------------------------------------------- # spawning-related - #--------------------------------------------------------------- + # --------------------------------------------------------------- @property def slow_spawn_timeout(self): @@ -659,7 +676,9 @@ async def spawn_single_user(self, user, server_name='', options=None): if self.authenticator.refresh_pre_spawn: auth_user = await self.refresh_auth(user, force=True) if auth_user is None: - raise web.HTTPError(403, "auth has expired for %s, login again", user.name) + raise web.HTTPError( + 403, "auth has expired for %s, login again", user.name + ) spawn_start_time = time.perf_counter() self.extra_error_html = self.spawn_home_error @@ -681,7 +700,9 @@ async def spawn_single_user(self, user, server_name='', options=None): # but for 10k users this takes ~5ms # and saves us from bookkeeping errors active_counts = self.users.count_active_users() - spawn_pending_count = active_counts['spawn_pending'] + active_counts['proxy_pending'] + spawn_pending_count = ( + active_counts['spawn_pending'] + active_counts['proxy_pending'] + ) active_count = active_counts['active'] concurrent_spawn_limit = self.concurrent_spawn_limit @@ -700,18 +721,21 @@ async def spawn_single_user(self, user, server_name='', options=None): # round suggestion to nicer human value (nearest 10 seconds or minute) if retry_time <= 90: # round human seconds up to nearest 10 - human_retry_time = "%i0 seconds" % math.ceil(retry_time / 10.) + human_retry_time = "%i0 seconds" % math.ceil(retry_time / 10.0) else: # round number of minutes - human_retry_time = "%i minutes" % math.round(retry_time / 60.) + human_retry_time = "%i minutes" % math.round(retry_time / 60.0) self.log.warning( '%s pending spawns, throttling. Suggested retry in %s seconds.', - spawn_pending_count, retry_time, + spawn_pending_count, + retry_time, ) err = web.HTTPError( 429, - "Too many users trying to log in right now. Try again in {}.".format(human_retry_time) + "Too many users trying to log in right now. Try again in {}.".format( + human_retry_time + ), ) # can't call set_header directly here because it gets ignored # when errors are raised @@ -720,14 +744,13 @@ async def spawn_single_user(self, user, server_name='', options=None): raise err if active_server_limit and active_count >= active_server_limit: - self.log.info( - '%s servers active, no space available', - active_count, - ) + self.log.info('%s servers active, no space available', active_count) SERVER_SPAWN_DURATION_SECONDS.labels( status=ServerSpawnStatus.too_many_users ).observe(time.perf_counter() - spawn_start_time) - raise web.HTTPError(429, "Active user limit exceeded. Try again in a few minutes.") + raise web.HTTPError( + 429, "Active user limit exceeded. Try again in a few minutes." + ) tic = IOLoop.current().time() @@ -735,12 +758,16 @@ async def spawn_single_user(self, user, server_name='', options=None): spawn_future = user.spawn(server_name, options, handler=self) - self.log.debug("%i%s concurrent spawns", + self.log.debug( + "%i%s concurrent spawns", spawn_pending_count, - '/%i' % concurrent_spawn_limit if concurrent_spawn_limit else '') - self.log.debug("%i%s active servers", + '/%i' % concurrent_spawn_limit if concurrent_spawn_limit else '', + ) + self.log.debug( + "%i%s active servers", active_count, - '/%i' % active_server_limit if active_server_limit else '') + '/%i' % active_server_limit if active_server_limit else '', + ) spawner = user.spawners[server_name] # set spawn_pending now, so there's no gap where _spawn_pending is False @@ -756,7 +783,9 @@ async def finish_user_spawn(): # wait for spawn Future await spawn_future toc = IOLoop.current().time() - self.log.info("User %s took %.3f seconds to start", user_server_name, toc-tic) + self.log.info( + "User %s took %.3f seconds to start", user_server_name, toc - tic + ) self.statsd.timing('spawner.success', (toc - tic) * 1000) RUNNING_SERVERS.inc() SERVER_SPAWN_DURATION_SECONDS.labels( @@ -767,18 +796,16 @@ async def finish_user_spawn(): try: await self.proxy.add_user(user, server_name) - PROXY_ADD_DURATION_SECONDS.labels( - status='success' - ).observe( + PROXY_ADD_DURATION_SECONDS.labels(status='success').observe( time.perf_counter() - proxy_add_start_time ) except Exception: self.log.exception("Failed to add %s to proxy!", user_server_name) - self.log.error("Stopping %s to avoid inconsistent state", user_server_name) + self.log.error( + "Stopping %s to avoid inconsistent state", user_server_name + ) await user.stop() - PROXY_ADD_DURATION_SECONDS.labels( - status='failure' - ).observe( + PROXY_ADD_DURATION_SECONDS.labels(status='failure').observe( time.perf_counter() - proxy_add_start_time ) else: @@ -818,7 +845,8 @@ def _track_failure_count(f): self.log.warning( "%i consecutive spawns failed. " "Hub will exit if failure count reaches %i before succeeding", - failure_count, failure_limit, + failure_count, + failure_limit, ) if failure_limit and failure_count >= failure_limit: self.log.critical( @@ -828,6 +856,7 @@ def _track_failure_count(f): # mostly propagating errors for the current failures def abort(): raise SystemExit(1) + IOLoop.current().call_later(2, abort) finish_spawn_future.add_done_callback(_track_failure_count) @@ -842,8 +871,11 @@ def abort(): if spawner._spawn_pending and not spawner._waiting_for_response: # still in Spawner.start, which is taking a long time # we shouldn't poll while spawn is incomplete. - self.log.warning("User %s is slow to start (timeout=%s)", - user_server_name, self.slow_spawn_timeout) + self.log.warning( + "User %s is slow to start (timeout=%s)", + user_server_name, + self.slow_spawn_timeout, + ) return # start has finished, but the server hasn't come up @@ -861,22 +893,34 @@ def abort(): status=ServerSpawnStatus.failure ).observe(time.perf_counter() - spawn_start_time) - raise web.HTTPError(500, "Spawner failed to start [status=%s]. The logs for %s may contain details." % ( - status, spawner._log_name)) + raise web.HTTPError( + 500, + "Spawner failed to start [status=%s]. The logs for %s may contain details." + % (status, spawner._log_name), + ) if spawner._waiting_for_response: # hit timeout waiting for response, but server's running. # Hope that it'll show up soon enough, # though it's possible that it started at the wrong URL - self.log.warning("User %s is slow to become responsive (timeout=%s)", - user_server_name, self.slow_spawn_timeout) - self.log.debug("Expecting server for %s at: %s", - user_server_name, spawner.server.url) + self.log.warning( + "User %s is slow to become responsive (timeout=%s)", + user_server_name, + self.slow_spawn_timeout, + ) + self.log.debug( + "Expecting server for %s at: %s", + user_server_name, + spawner.server.url, + ) if spawner._proxy_pending: # User.spawn finished, but it hasn't been added to the proxy # Could be due to load or a slow proxy - self.log.warning("User %s is slow to be added to the proxy (timeout=%s)", - user_server_name, self.slow_spawn_timeout) + self.log.warning( + "User %s is slow to be added to the proxy (timeout=%s)", + user_server_name, + self.slow_spawn_timeout, + ) async def user_stopped(self, user, server_name): """Callback that fires when the spawner has stopped""" @@ -888,12 +932,11 @@ async def user_stopped(self, user, server_name): status=ServerPollStatus.from_status(status) ).observe(time.perf_counter() - poll_start_time) - if status is None: status = 'unknown' - self.log.warning("User %s server stopped, with exit code: %s", - user.name, status, + self.log.warning( + "User %s server stopped, with exit code: %s", user.name, status ) await self.proxy.delete_user(user, server_name) await user.stop(server_name) @@ -920,7 +963,9 @@ async def stop(): await self.proxy.delete_user(user, server_name) await user.stop(server_name) toc = time.perf_counter() - self.log.info("User %s server took %.3f seconds to stop", user.name, toc - tic) + self.log.info( + "User %s server took %.3f seconds to stop", user.name, toc - tic + ) self.statsd.timing('spawner.stop', (toc - tic) * 1000) RUNNING_SERVERS.dec() SERVER_STOP_DURATION_SECONDS.labels( @@ -934,21 +979,22 @@ async def stop(): spawner._stop_future = None spawner._stop_pending = False - future = spawner._stop_future = asyncio.ensure_future(stop()) try: await gen.with_timeout(timedelta(seconds=self.slow_stop_timeout), future) except gen.TimeoutError: # hit timeout, but stop is still pending - self.log.warning("User %s:%s server is slow to stop", user.name, server_name) + self.log.warning( + "User %s:%s server is slow to stop", user.name, server_name + ) # return handle on the future for hooking up callbacks return future - #--------------------------------------------------------------- + # --------------------------------------------------------------- # template rendering - #--------------------------------------------------------------- + # --------------------------------------------------------------- @property def spawn_home_error(self): @@ -1051,6 +1097,7 @@ def write_error(self, status_code, **kwargs): class Template404(BaseHandler): """Render our 404 template""" + async def prepare(self): await super().prepare() raise web.HTTPError(404) @@ -1061,6 +1108,7 @@ class PrefixRedirectHandler(BaseHandler): Redirects /foo to /prefix/foo, etc. """ + def get(self): uri = self.request.uri # Since self.base_url will end with trailing slash. @@ -1069,16 +1117,14 @@ def get(self): if not uri.endswith('/'): uri += '/' if uri.startswith(self.base_url): - path = self.request.uri[len(self.base_url):] + path = self.request.uri[len(self.base_url) :] else: path = self.request.path if not path: # default / -> /hub/ redirect # avoiding extra hop through /hub path = '/' - self.redirect(url_path_join( - self.hub.base_url, path, - ), permanent=False) + self.redirect(url_path_join(self.hub.base_url, path), permanent=False) class UserSpawnHandler(BaseHandler): @@ -1113,8 +1159,11 @@ async def get(self, user_name, user_path): if user is None: # no such user raise web.HTTPError(404, "No such user %s" % user_name) - self.log.info("Admin %s requesting spawn on behalf of %s", - current_user.name, user.name) + self.log.info( + "Admin %s requesting spawn on behalf of %s", + current_user.name, + user.name, + ) admin_spawn = True should_spawn = True else: @@ -1122,7 +1171,7 @@ async def get(self, user_name, user_path): admin_spawn = False # For non-admins, we should spawn if the user matches # otherwise redirect users to their own server - should_spawn = (current_user and current_user.name == user_name) + should_spawn = current_user and current_user.name == user_name if "api" in user_path.split("/") and user and not user.active: # API request for not-running server (e.g. notebook UI left open) @@ -1142,12 +1191,19 @@ async def get(self, user_name, user_path): port = host_info.port if not port: port = 443 if host_info.scheme == 'https' else 80 - if port != Server.from_url(self.proxy.public_url).connect_port and port == self.hub.connect_port: - self.log.warning(""" + if ( + port != Server.from_url(self.proxy.public_url).connect_port + and port == self.hub.connect_port + ): + self.log.warning( + """ Detected possible direct connection to Hub's private ip: %s, bypassing proxy. This will result in a redirect loop. Make sure to connect to the proxied public URL %s - """, self.request.full_url(), self.proxy.public_url) + """, + self.request.full_url(), + self.proxy.public_url, + ) # logged in as valid user, check for pending spawn if self.allow_named_servers: @@ -1167,19 +1223,31 @@ async def get(self, user_name, user_path): # Implicit spawn on /user/:name is not allowed if the user's last spawn failed. # We should point the user to Home if the most recent spawn failed. exc = spawner._spawn_future.exception() - self.log.error("Preventing implicit spawn for %s because last spawn failed: %s", - spawner._log_name, exc) + self.log.error( + "Preventing implicit spawn for %s because last spawn failed: %s", + spawner._log_name, + exc, + ) # raise a copy because each time an Exception object is re-raised, its traceback grows raise copy.copy(exc).with_traceback(exc.__traceback__) # check for pending spawn if spawner.pending == 'spawn' and spawner._spawn_future: # wait on the pending spawn - self.log.debug("Waiting for %s pending %s", spawner._log_name, spawner.pending) + self.log.debug( + "Waiting for %s pending %s", spawner._log_name, spawner.pending + ) try: - await gen.with_timeout(timedelta(seconds=self.slow_spawn_timeout), spawner._spawn_future) + await gen.with_timeout( + timedelta(seconds=self.slow_spawn_timeout), + spawner._spawn_future, + ) except gen.TimeoutError: - self.log.info("Pending spawn for %s didn't finish in %.1f seconds", spawner._log_name, self.slow_spawn_timeout) + self.log.info( + "Pending spawn for %s didn't finish in %.1f seconds", + spawner._log_name, + self.slow_spawn_timeout, + ) pass # we may have waited above, check pending again: @@ -1194,10 +1262,7 @@ async def get(self, user_name, user_path): else: page = "spawn_pending.html" html = self.render_template( - page, - user=user, - spawner=spawner, - progress_url=spawner._progress_url, + page, user=user, spawner=spawner, progress_url=spawner._progress_url ) self.finish(html) return @@ -1218,8 +1283,11 @@ async def get(self, user_name, user_path): if current_user.name != user.name: # spawning on behalf of another user url_parts.append(user.name) - self.redirect(url_concat(url_path_join(*url_parts), - {'next': self.request.uri})) + self.redirect( + url_concat( + url_path_join(*url_parts), {'next': self.request.uri} + ) + ) return else: await self.spawn_single_user(user, server_name) @@ -1230,9 +1298,7 @@ async def get(self, user_name, user_path): # spawn has started, but not finished self.statsd.incr('redirects.user_spawn_pending', 1) html = self.render_template( - "spawn_pending.html", - user=user, - progress_url=spawner._progress_url, + "spawn_pending.html", user=user, progress_url=spawner._progress_url ) self.finish(html) return @@ -1243,14 +1309,16 @@ async def get(self, user_name, user_path): try: redirects = int(self.get_argument('redirects', 0)) except ValueError: - self.log.warning("Invalid redirects argument %r", self.get_argument('redirects')) + self.log.warning( + "Invalid redirects argument %r", self.get_argument('redirects') + ) redirects = 0 # check redirect limit to prevent browser-enforced limits. # In case of version mismatch, raise on only two redirects. - if redirects >= self.settings.get( - 'user_redirect_limit', 4 - ) or (redirects >= 2 and spawner._jupyterhub_version != __version__): + if redirects >= self.settings.get('user_redirect_limit', 4) or ( + redirects >= 2 and spawner._jupyterhub_version != __version__ + ): # We stop if we've been redirected too many times. msg = "Redirect loop detected." if spawner._jupyterhub_version != __version__: @@ -1259,12 +1327,13 @@ async def get(self, user_name, user_path): " Try installing jupyterhub=={hub} in the user environment" " if you continue to have problems." ).format( - singleuser=spawner._jupyterhub_version or 'unknown (likely < 0.8)', + singleuser=spawner._jupyterhub_version + or 'unknown (likely < 0.8)', hub=__version__, ) raise web.HTTPError(500, msg) - without_prefix = self.request.uri[len(self.hub.base_url):] + without_prefix = self.request.uri[len(self.hub.base_url) :] target = url_path_join(self.base_url, without_prefix) if self.subdomain_host: target = user.host + target @@ -1297,10 +1366,9 @@ async def get(self, user_name, user_path): # not logged in, clear any cookies and reload self.statsd.incr('redirects.user_to_login', 1) self.clear_login_cookie() - self.redirect(url_concat( - self.settings['login_url'], - {'next': self.request.uri}, - )) + self.redirect( + url_concat(self.settings['login_url'], {'next': self.request.uri}) + ) class UserRedirectHandler(BaseHandler): @@ -1314,6 +1382,7 @@ class UserRedirectHandler(BaseHandler): .. versionadded:: 0.7 """ + @web.authenticated def get(self, path): user = self.current_user @@ -1326,12 +1395,13 @@ def get(self, path): class CSPReportHandler(BaseHandler): '''Accepts a content security policy violation report''' + @web.authenticated def post(self): '''Log a content security policy violation report''' self.log.warning( "Content security violation: %s", - self.request.body.decode('utf8', 'replace') + self.request.body.decode('utf8', 'replace'), ) # Report it to statsd as well self.statsd.incr('csp_report') @@ -1339,11 +1409,13 @@ def post(self): class AddSlashHandler(BaseHandler): """Handler for adding trailing slash to URLs that need them""" + def get(self, *args): src = urlparse(self.request.uri) dest = src._replace(path=src.path + '/') self.redirect(urlunparse(dest)) + default_handlers = [ (r'', AddSlashHandler), # add trailing / to `/hub` (r'/user/(?P<user_name>[^/]+)(?P<user_path>/.*)?', UserSpawnHandler), diff --git a/jupyterhub/handlers/login.py b/jupyterhub/handlers/login.py --- a/jupyterhub/handlers/login.py +++ b/jupyterhub/handlers/login.py @@ -1,16 +1,14 @@ """HTTP Handlers for the hub server""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import asyncio +from tornado import web from tornado.escape import url_escape from tornado.httputil import url_concat -from tornado import web -from .base import BaseHandler from ..utils import maybe_future +from .base import BaseHandler class LogoutHandler(BaseHandler): @@ -52,16 +50,17 @@ class LoginHandler(BaseHandler): """Render the login page.""" def _render(self, login_error=None, username=None): - return self.render_template('login.html', - next=url_escape(self.get_argument('next', default='')), - username=username, - login_error=login_error, - custom_html=self.authenticator.custom_html, - login_url=self.settings['login_url'], - authenticator_login_url=url_concat( - self.authenticator.login_url(self.hub.base_url), - {'next': self.get_argument('next', '')}, - ), + return self.render_template( + 'login.html', + next=url_escape(self.get_argument('next', default='')), + username=username, + login_error=login_error, + custom_html=self.authenticator.custom_html, + login_url=self.settings['login_url'], + authenticator_login_url=url_concat( + self.authenticator.login_url(self.hub.base_url), + {'next': self.get_argument('next', '')}, + ), ) async def get(self): @@ -87,7 +86,9 @@ async def get(self): self.redirect(self.get_next_url(user)) else: if self.get_argument('next', default=False): - auto_login_url = url_concat(auto_login_url, {'next': self.get_next_url()}) + auto_login_url = url_concat( + auto_login_url, {'next': self.get_next_url()} + ) self.redirect(auto_login_url) return username = self.get_argument('username', default='') @@ -109,8 +110,7 @@ async def post(self): self.redirect(self.get_next_url(user)) else: html = self._render( - login_error='Invalid username or password', - username=data['username'], + login_error='Invalid username or password', username=data['username'] ) self.finish(html) @@ -118,7 +118,4 @@ async def post(self): # /login renders the login page or the "Login with..." link, # so it should always be registered. # /logout clears cookies. -default_handlers = [ - (r"/login", LoginHandler), - (r"/logout", LogoutHandler), -] +default_handlers = [(r"/login", LoginHandler), (r"/logout", LogoutHandler)] diff --git a/jupyterhub/handlers/metrics.py b/jupyterhub/handlers/metrics.py --- a/jupyterhub/handlers/metrics.py +++ b/jupyterhub/handlers/metrics.py @@ -1,18 +1,21 @@ -from prometheus_client import REGISTRY, CONTENT_TYPE_LATEST, generate_latest +from prometheus_client import CONTENT_TYPE_LATEST +from prometheus_client import generate_latest +from prometheus_client import REGISTRY from tornado import gen -from .base import BaseHandler from ..utils import metrics_authentication +from .base import BaseHandler + class MetricsHandler(BaseHandler): """ Handler to serve Prometheus metrics """ + @metrics_authentication async def get(self): self.set_header('Content-Type', CONTENT_TYPE_LATEST) self.write(generate_latest(REGISTRY)) -default_handlers = [ - (r'/metrics$', MetricsHandler) -] + +default_handlers = [(r'/metrics$', MetricsHandler)] diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -1,18 +1,19 @@ """Basic html-rendering handlers.""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - from collections import defaultdict from datetime import datetime from http.client import responses from jinja2 import TemplateNotFound -from tornado import web, gen +from tornado import gen +from tornado import web from tornado.httputil import url_concat from .. import orm -from ..utils import admin_only, url_path_join, maybe_future +from ..utils import admin_only +from ..utils import maybe_future +from ..utils import url_path_join from .base import BaseHandler @@ -29,6 +30,7 @@ class RootHandler(BaseHandler): Otherwise, renders login page. """ + def get(self): user = self.current_user if self.default_url: @@ -53,16 +55,21 @@ async def get(self): # send the user to /spawn if they have no active servers, # to establish that this is an explicit spawn request rather # than an implicit one, which can be caused by any link to `/user/:name(/:server_name)` - url = url_path_join(self.hub.base_url, 'user', user.name) if user.active else url_path_join(self.hub.base_url, 'spawn') - html = self.render_template('home.html', + url = ( + url_path_join(self.hub.base_url, 'user', user.name) + if user.active + else url_path_join(self.hub.base_url, 'spawn') + ) + html = self.render_template( + 'home.html', user=user, url=url, allow_named_servers=self.allow_named_servers, named_server_limit_per_user=self.named_server_limit_per_user, url_path_join=url_path_join, # can't use user.spawners because the stop method of User pops named servers from user.spawners when they're stopped - spawners = user.orm_user._orm_spawners, - default_server = user.spawner, + spawners=user.orm_user._orm_spawners, + default_server=user.spawner, ) self.finish(html) @@ -74,13 +81,15 @@ class SpawnHandler(BaseHandler): Only enabled when Spawner.options_form is defined. """ + def _render_form(self, for_user, spawner_options_form, message=''): - return self.render_template('spawn.html', + return self.render_template( + 'spawn.html', for_user=for_user, spawner_options_form=spawner_options_form, error_message=message, url=self.request.uri, - spawner=for_user.spawner + spawner=for_user.spawner, ) @web.authenticated @@ -92,7 +101,9 @@ async def get(self, for_user=None): user = current_user = self.current_user if for_user is not None and for_user != user.name: if not user.admin: - raise web.HTTPError(403, "Only admins can spawn on behalf of other users") + raise web.HTTPError( + 403, "Only admins can spawn on behalf of other users" + ) user = self.find_user(for_user) if user is None: @@ -108,7 +119,9 @@ async def get(self, for_user=None): if spawner_options_form: # Add handler to spawner here so you can access query params in form rendering. user.spawner.handler = self - form = self._render_form(for_user=user, spawner_options_form=spawner_options_form) + form = self._render_form( + for_user=user, spawner_options_form=spawner_options_form + ) self.finish(form) else: # Explicit spawn request: clear _spawn_future @@ -129,7 +142,9 @@ async def post(self, for_user=None): user = current_user = self.current_user if for_user is not None and for_user != user.name: if not user.admin: - raise web.HTTPError(403, "Only admins can spawn on behalf of other users") + raise web.HTTPError( + 403, "Only admins can spawn on behalf of other users" + ) user = self.find_user(for_user) if user is None: raise web.HTTPError(404, "No such user: %s" % for_user) @@ -144,16 +159,20 @@ async def post(self, for_user=None): ) form_options = {} for key, byte_list in self.request.body_arguments.items(): - form_options[key] = [ bs.decode('utf8') for bs in byte_list ] + form_options[key] = [bs.decode('utf8') for bs in byte_list] for key, byte_list in self.request.files.items(): - form_options["%s_file"%key] = byte_list + form_options["%s_file" % key] = byte_list try: options = await maybe_future(user.spawner.options_from_form(form_options)) await self.spawn_single_user(user, options=options) except Exception as e: - self.log.error("Failed to spawn single-user server with form", exc_info=True) + self.log.error( + "Failed to spawn single-user server with form", exc_info=True + ) spawner_options_form = await user.spawner.get_options_form() - form = self._render_form(for_user=user, spawner_options_form=spawner_options_form, message=str(e)) + form = self._render_form( + for_user=user, spawner_options_form=spawner_options_form, message=str(e) + ) self.finish(form) return if current_user is user: @@ -176,9 +195,7 @@ class AdminHandler(BaseHandler): def get(self): available = {'name', 'admin', 'running', 'last_activity'} default_sort = ['admin', 'name'] - mapping = { - 'running': orm.Spawner.server_id, - } + mapping = {'running': orm.Spawner.server_id} for name in available: if name not in mapping: mapping[name] = getattr(orm.User, name) @@ -205,30 +222,32 @@ def get(self): if s not in sorts: sorts.append(s) if len(orders) < len(sorts): - for col in sorts[len(orders):]: + for col in sorts[len(orders) :]: orders.append(default_order[col]) else: - orders = orders[:len(sorts)] + orders = orders[: len(sorts)] # this could be one incomprehensible nested list comprehension # get User columns - cols = [ mapping[c] for c in sorts ] + cols = [mapping[c] for c in sorts] # get User.col.desc() order objects - ordered = [ getattr(c, o)() for c, o in zip(cols, orders) ] + ordered = [getattr(c, o)() for c, o in zip(cols, orders)] users = self.db.query(orm.User).outerjoin(orm.Spawner).order_by(*ordered) - users = [ self._user_from_orm(u) for u in users ] + users = [self._user_from_orm(u) for u in users] from itertools import chain + running = [] for u in users: running.extend(s for s in u.spawners.values() if s.active) - html = self.render_template('admin.html', + html = self.render_template( + 'admin.html', current_user=self.current_user, admin_access=self.settings.get('admin_access', False), users=users, running=running, - sort={s:o for s,o in zip(sorts, orders)}, + sort={s: o for s, o in zip(sorts, orders)}, allow_named_servers=self.allow_named_servers, named_server_limit_per_user=self.named_server_limit_per_user, ) @@ -243,11 +262,9 @@ def get(self): never = datetime(1900, 1, 1) user = self.current_user + def sort_key(token): - return ( - token.last_activity or never, - token.created or never, - ) + return (token.last_activity or never, token.created or never) now = datetime.utcnow() api_tokens = [] @@ -285,37 +302,33 @@ def sort_key(token): for token in tokens[1:]: if token.created < created: created = token.created - if ( - last_activity is None or - (token.last_activity and token.last_activity > last_activity) + if last_activity is None or ( + token.last_activity and token.last_activity > last_activity ): last_activity = token.last_activity token = tokens[0] - oauth_clients.append({ - 'client': token.client, - 'description': token.client.description or token.client.identifier, - 'created': created, - 'last_activity': last_activity, - 'tokens': tokens, - # only need one token id because - # revoking one oauth token revokes all oauth tokens for that client - 'token_id': tokens[0].api_id, - 'token_count': len(tokens), - }) + oauth_clients.append( + { + 'client': token.client, + 'description': token.client.description or token.client.identifier, + 'created': created, + 'last_activity': last_activity, + 'tokens': tokens, + # only need one token id because + # revoking one oauth token revokes all oauth tokens for that client + 'token_id': tokens[0].api_id, + 'token_count': len(tokens), + } + ) # sort oauth clients by last activity, created def sort_key(client): - return ( - client['last_activity'] or never, - client['created'] or never, - ) + return (client['last_activity'] or never, client['created'] or never) oauth_clients = sorted(oauth_clients, key=sort_key, reverse=True) html = self.render_template( - 'token.html', - api_tokens=api_tokens, - oauth_clients=oauth_clients, + 'token.html', api_tokens=api_tokens, oauth_clients=oauth_clients ) self.finish(html) @@ -331,10 +344,12 @@ def get(self, status_code_s): hub_home = url_path_join(self.hub.base_url, 'home') message_html = '' if status_code == 503: - message_html = ' '.join([ - "Your server appears to be down.", - "Try restarting it <a href='%s'>from the hub</a>" % hub_home - ]) + message_html = ' '.join( + [ + "Your server appears to be down.", + "Try restarting it <a href='%s'>from the hub</a>" % hub_home, + ] + ) ns = dict( status_code=status_code, status_message=status_message, @@ -355,6 +370,7 @@ def get(self, status_code_s): class HealthCheckHandler(BaseHandler): """Answer to health check""" + def get(self, *args): self.finish() diff --git a/jupyterhub/handlers/static.py b/jupyterhub/handlers/static.py --- a/jupyterhub/handlers/static.py +++ b/jupyterhub/handlers/static.py @@ -1,23 +1,27 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import os + from tornado.web import StaticFileHandler + class CacheControlStaticFilesHandler(StaticFileHandler): """StaticFileHandler subclass that sets Cache-Control: no-cache without `?v=` rather than relying on default browser cache behavior. """ + def compute_etag(self): return None - + def set_extra_headers(self, path): if "v" not in self.request.arguments: self.add_header("Cache-Control", "no-cache") + class LogoHandler(StaticFileHandler): """A singular handler for serving the logo.""" + def get(self): return super().get('') @@ -25,4 +29,3 @@ def get(self): def get_absolute_path(cls, root, path): """We only serve one file, ignore relative path""" return os.path.abspath(root) - diff --git a/jupyterhub/log.py b/jupyterhub/log.py --- a/jupyterhub/log.py +++ b/jupyterhub/log.py @@ -1,13 +1,15 @@ """logging utilities""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import json import traceback -from urllib.parse import urlparse, urlunparse +from urllib.parse import urlparse +from urllib.parse import urlunparse -from tornado.log import LogFormatter, access_log -from tornado.web import StaticFileHandler, HTTPError +from tornado.log import access_log +from tornado.log import LogFormatter +from tornado.web import HTTPError +from tornado.web import StaticFileHandler from .metrics import prometheus_log_method @@ -23,7 +25,11 @@ def coroutine_frames(all_frames): continue # start out conservative with filename + function matching # maybe just filename matching would be sufficient - elif frame[0].endswith('tornado/gen.py') and frame[2] in {'run', 'wrapper', '__init__'}: + elif frame[0].endswith('tornado/gen.py') and frame[2] in { + 'run', + 'wrapper', + '__init__', + }: continue elif frame[0].endswith('tornado/concurrent.py') and frame[2] == 'result': continue @@ -51,9 +57,11 @@ def coroutine_traceback(typ, value, tb): class CoroutineLogFormatter(LogFormatter): """Log formatter that scrubs coroutine frames""" + def formatException(self, exc_info): return ''.join(coroutine_traceback(*exc_info)) + # url params to be scrubbed if seen # any url param that *contains* one of these # will be scrubbed from logs @@ -96,6 +104,7 @@ def _scrub_headers(headers): # log_request adapted from IPython (BSD) + def log_request(handler): """log a bit more information about each request than tornado's default diff --git a/jupyterhub/metrics.py b/jupyterhub/metrics.py --- a/jupyterhub/metrics.py +++ b/jupyterhub/metrics.py @@ -17,13 +17,13 @@ """ from enum import Enum -from prometheus_client import Histogram from prometheus_client import Gauge +from prometheus_client import Histogram REQUEST_DURATION_SECONDS = Histogram( 'request_duration_seconds', 'request duration for all HTTP requests', - ['method', 'handler', 'code'] + ['method', 'handler', 'code'], ) SERVER_SPAWN_DURATION_SECONDS = Histogram( @@ -32,32 +32,29 @@ ['status'], # Use custom bucket sizes, since the default bucket ranges # are meant for quick running processes. Spawns can take a while! - buckets=[0.5, 1, 2.5, 5, 10, 15, 30, 60, 120, float("inf")] + buckets=[0.5, 1, 2.5, 5, 10, 15, 30, 60, 120, float("inf")], ) RUNNING_SERVERS = Gauge( - 'running_servers', - 'the number of user servers currently running' + 'running_servers', 'the number of user servers currently running' ) RUNNING_SERVERS.set(0) -TOTAL_USERS = Gauge( - 'total_users', - 'toal number of users' - ) +TOTAL_USERS = Gauge('total_users', 'toal number of users') -TOTAL_USERS.set(0) +TOTAL_USERS.set(0) CHECK_ROUTES_DURATION_SECONDS = Histogram( - 'check_routes_duration_seconds', - 'Time taken to validate all routes in proxy' + 'check_routes_duration_seconds', 'Time taken to validate all routes in proxy' ) + class ServerSpawnStatus(Enum): """ Possible values for 'status' label of SERVER_SPAWN_DURATION_SECONDS """ + success = 'success' failure = 'failure' already_pending = 'already-pending' @@ -67,27 +64,29 @@ class ServerSpawnStatus(Enum): def __str__(self): return self.value + for s in ServerSpawnStatus: # Create empty metrics with the given status SERVER_SPAWN_DURATION_SECONDS.labels(status=s) PROXY_ADD_DURATION_SECONDS = Histogram( - 'proxy_add_duration_seconds', - 'duration for adding user routes to proxy', - ['status'] + 'proxy_add_duration_seconds', 'duration for adding user routes to proxy', ['status'] ) + class ProxyAddStatus(Enum): """ Possible values for 'status' label of PROXY_ADD_DURATION_SECONDS """ + success = 'success' failure = 'failure' def __str__(self): return self.value + for s in ProxyAddStatus: PROXY_ADD_DURATION_SECONDS.labels(status=s) @@ -95,13 +94,15 @@ def __str__(self): SERVER_POLL_DURATION_SECONDS = Histogram( 'server_poll_duration_seconds', 'time taken to poll if server is running', - ['status'] + ['status'], ) + class ServerPollStatus(Enum): """ Possible values for 'status' label of SERVER_POLL_DURATION_SECONDS """ + running = 'running' stopped = 'stopped' @@ -112,27 +113,28 @@ def from_status(cls, status): return cls.running return cls.stopped + for s in ServerPollStatus: SERVER_POLL_DURATION_SECONDS.labels(status=s) - SERVER_STOP_DURATION_SECONDS = Histogram( - 'server_stop_seconds', - 'time taken for server stopping operation', - ['status'], + 'server_stop_seconds', 'time taken for server stopping operation', ['status'] ) + class ServerStopStatus(Enum): """ Possible values for 'status' label of SERVER_STOP_DURATION_SECONDS """ + success = 'success' failure = 'failure' def __str__(self): return self.value + for s in ServerStopStatus: SERVER_STOP_DURATION_SECONDS.labels(status=s) @@ -156,5 +158,5 @@ def prometheus_log_method(handler): REQUEST_DURATION_SECONDS.labels( method=handler.request.method, handler='{}.{}'.format(handler.__class__.__module__, type(handler).__name__), - code=handler.get_status() + code=handler.get_status(), ).observe(handler.request.request_time()) diff --git a/jupyterhub/oauth/provider.py b/jupyterhub/oauth/provider.py --- a/jupyterhub/oauth/provider.py +++ b/jupyterhub/oauth/provider.py @@ -2,30 +2,29 @@ implements https://oauthlib.readthedocs.io/en/latest/oauth2/server.html """ - from datetime import datetime from urllib.parse import urlparse -from oauthlib.oauth2 import RequestValidator, WebApplicationServer - +from oauthlib.oauth2 import RequestValidator +from oauthlib.oauth2 import WebApplicationServer +from oauthlib.oauth2.rfc6749.grant_types import authorization_code from sqlalchemy.orm import scoped_session +from tornado import web from tornado.escape import url_escape from tornado.log import app_log -from tornado import web from .. import orm -from ..utils import url_path_join, hash_token, compare_token - +from ..utils import compare_token +from ..utils import hash_token +from ..utils import url_path_join # patch absolute-uri check # because we want to allow relative uri oauth # for internal services -from oauthlib.oauth2.rfc6749.grant_types import authorization_code authorization_code.is_absolute_uri = lambda uri: True class JupyterHubRequestValidator(RequestValidator): - def __init__(self, db): self.db = db super().__init__() @@ -51,10 +50,7 @@ def authenticate_client(self, request, *args, **kwargs): client_id = request.client_id client_secret = request.client_secret oauth_client = ( - self.db - .query(orm.OAuthClient) - .filter_by(identifier=client_id) - .first() + self.db.query(orm.OAuthClient).filter_by(identifier=client_id).first() ) if oauth_client is None: return False @@ -78,10 +74,7 @@ def authenticate_client_id(self, client_id, request, *args, **kwargs): - Authorization Code Grant """ orm_client = ( - self.db - .query(orm.OAuthClient) - .filter_by(identifier=client_id) - .first() + self.db.query(orm.OAuthClient).filter_by(identifier=client_id).first() ) if orm_client is None: app_log.warning("No such oauth client %s", client_id) @@ -89,8 +82,9 @@ def authenticate_client_id(self, client_id, request, *args, **kwargs): request.client = orm_client return True - def confirm_redirect_uri(self, client_id, code, redirect_uri, client, - *args, **kwargs): + def confirm_redirect_uri( + self, client_id, code, redirect_uri, client, *args, **kwargs + ): """Ensure that the authorization process represented by this authorization code began with this 'redirect_uri'. If the client specifies a redirect_uri when obtaining code then that @@ -108,8 +102,10 @@ def confirm_redirect_uri(self, client_id, code, redirect_uri, client, """ # TODO: record redirect_uri used during oauth # if we ever support multiple destinations - app_log.debug("confirm_redirect_uri: client_id=%s, redirect_uri=%s", - client_id, redirect_uri, + app_log.debug( + "confirm_redirect_uri: client_id=%s, redirect_uri=%s", + client_id, + redirect_uri, ) if redirect_uri == client.redirect_uri: return True @@ -127,10 +123,7 @@ def get_default_redirect_uri(self, client_id, request, *args, **kwargs): - Implicit Grant """ orm_client = ( - self.db - .query(orm.OAuthClient) - .filter_by(identifier=client_id) - .first() + self.db.query(orm.OAuthClient).filter_by(identifier=client_id).first() ) if orm_client is None: raise KeyError(client_id) @@ -159,7 +152,9 @@ def get_original_scopes(self, refresh_token, request, *args, **kwargs): """ raise NotImplementedError() - def is_within_original_scope(self, request_scopes, refresh_token, request, *args, **kwargs): + def is_within_original_scope( + self, request_scopes, refresh_token, request, *args, **kwargs + ): """Check if requested scopes are within a scope of the refresh token. When access tokens are refreshed the scope of the new token needs to be within the scope of the original token. This is @@ -227,12 +222,15 @@ def save_authorization_code(self, client_id, code, request, *args, **kwargs): - Authorization Code Grant """ log_code = code.get('code', 'undefined')[:3] + '...' - app_log.debug("Saving authorization code %s, %s, %s, %s", client_id, log_code, args, kwargs) + app_log.debug( + "Saving authorization code %s, %s, %s, %s", + client_id, + log_code, + args, + kwargs, + ) orm_client = ( - self.db - .query(orm.OAuthClient) - .filter_by(identifier=client_id) - .first() + self.db.query(orm.OAuthClient).filter_by(identifier=client_id).first() ) if orm_client is None: raise ValueError("No such client: %s" % client_id) @@ -330,7 +328,11 @@ def save_bearer_token(self, token, request, *args, **kwargs): app_log.debug("Saving bearer token %s", log_token) if request.user is None: raise ValueError("No user for access token: %s" % request.user) - client = self.db.query(orm.OAuthClient).filter_by(identifier=request.client.client_id).first() + client = ( + self.db.query(orm.OAuthClient) + .filter_by(identifier=request.client.client_id) + .first() + ) orm_access_token = orm.OAuthAccessToken( client=client, grant_type=orm.GrantType.authorization_code, @@ -400,10 +402,7 @@ def validate_client_id(self, client_id, request, *args, **kwargs): """ app_log.debug("Validating client id %s", client_id) orm_client = ( - self.db - .query(orm.OAuthClient) - .filter_by(identifier=client_id) - .first() + self.db.query(orm.OAuthClient).filter_by(identifier=client_id).first() ) if orm_client is None: return False @@ -431,19 +430,13 @@ def validate_code(self, client_id, code, client, request, *args, **kwargs): Method is used by: - Authorization Code Grant """ - orm_code = ( - self.db - .query(orm.OAuthCode) - .filter_by(code=code) - .first() - ) + orm_code = self.db.query(orm.OAuthCode).filter_by(code=code).first() if orm_code is None: app_log.debug("No such code: %s", code) return False if orm_code.client_id != client_id: app_log.debug( - "OAuth code client id mismatch: %s != %s", - client_id, orm_code.client_id, + "OAuth code client id mismatch: %s != %s", client_id, orm_code.client_id ) return False request.user = orm_code.user @@ -453,7 +446,9 @@ def validate_code(self, client_id, code, client, request, *args, **kwargs): request.scopes = ['identify'] return True - def validate_grant_type(self, client_id, grant_type, client, request, *args, **kwargs): + def validate_grant_type( + self, client_id, grant_type, client, request, *args, **kwargs + ): """Ensure client is authorized to use the grant_type requested. :param client_id: Unicode client identifier :param grant_type: Unicode grant type, i.e. authorization_code, password. @@ -480,14 +475,13 @@ def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwarg - Authorization Code Grant - Implicit Grant """ - app_log.debug("validate_redirect_uri: client_id=%s, redirect_uri=%s", - client_id, redirect_uri, + app_log.debug( + "validate_redirect_uri: client_id=%s, redirect_uri=%s", + client_id, + redirect_uri, ) orm_client = ( - self.db - .query(orm.OAuthClient) - .filter_by(identifier=client_id) - .first() + self.db.query(orm.OAuthClient).filter_by(identifier=client_id).first() ) if orm_client is None: app_log.warning("No such oauth client %s", client_id) @@ -495,7 +489,9 @@ def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwarg if redirect_uri == orm_client.redirect_uri: return True else: - app_log.warning("Redirect uri %s != %s", redirect_uri, orm_client.redirect_uri) + app_log.warning( + "Redirect uri %s != %s", redirect_uri, orm_client.redirect_uri + ) return False def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs): @@ -514,7 +510,9 @@ def validate_refresh_token(self, refresh_token, client, request, *args, **kwargs return False raise NotImplementedError('Subclasses must implement this method.') - def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs): + def validate_response_type( + self, client_id, response_type, client, request, *args, **kwargs + ): """Ensure client is authorized to use the response_type requested. :param client_id: Unicode client identifier :param response_type: Unicode response type, i.e. code, token. @@ -555,10 +553,8 @@ def add_client(self, client_id, client_secret, redirect_uri, description=''): hash its client_secret before putting it in the database. """ # clear existing clients with same ID - for orm_client in ( - self.db - .query(orm.OAuthClient)\ - .filter_by(identifier=client_id) + for orm_client in self.db.query(orm.OAuthClient).filter_by( + identifier=client_id ): self.db.delete(orm_client) self.db.commit() @@ -574,12 +570,7 @@ def add_client(self, client_id, client_secret, redirect_uri, description=''): def fetch_by_client_id(self, client_id): """Find a client by its id""" - return ( - self.db - .query(orm.OAuthClient) - .filter_by(identifier=client_id) - .first() - ) + return self.db.query(orm.OAuthClient).filter_by(identifier=client_id).first() def make_provider(session_factory, url_prefix, login_url): @@ -588,4 +579,3 @@ def make_provider(session_factory, url_prefix, login_url): validator = JupyterHubRequestValidator(db) server = JupyterHubOAuthServer(db, validator) return server - diff --git a/jupyterhub/objects.py b/jupyterhub/objects.py --- a/jupyterhub/objects.py +++ b/jupyterhub/objects.py @@ -1,22 +1,28 @@ """Some general objects for use in JupyterHub""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import socket -from urllib.parse import urlparse, urlunparse import warnings +from urllib.parse import urlparse +from urllib.parse import urlunparse + +from traitlets import default +from traitlets import HasTraits +from traitlets import Instance +from traitlets import Integer +from traitlets import observe +from traitlets import Unicode +from traitlets import validate -from traitlets import ( - HasTraits, Instance, Integer, Unicode, - default, observe, validate, -) -from .traitlets import URLPrefix from . import orm -from .utils import ( - url_path_join, can_connect, wait_for_server, - wait_for_http_server, random_port, make_ssl_context, -) +from .traitlets import URLPrefix +from .utils import can_connect +from .utils import make_ssl_context +from .utils import random_port +from .utils import url_path_join +from .utils import wait_for_http_server +from .utils import wait_for_server + class Server(HasTraits): """An object representing an HTTP endpoint. @@ -24,6 +30,7 @@ class Server(HasTraits): *Some* of these reside in the database (user servers), but others (Hub, proxy) are in-memory only. """ + orm_server = Instance(orm.Server, allow_none=True) ip = Unicode() @@ -141,36 +148,31 @@ def _change(self, change): def host(self): if self.connect_url: parsed = urlparse(self.connect_url) - return "{proto}://{host}".format( - proto=parsed.scheme, - host=parsed.netloc, - ) + return "{proto}://{host}".format(proto=parsed.scheme, host=parsed.netloc) return "{proto}://{ip}:{port}".format( - proto=self.proto, - ip=self._connect_ip, - port=self._connect_port, + proto=self.proto, ip=self._connect_ip, port=self._connect_port ) @property def url(self): if self.connect_url: return self.connect_url - return "{host}{uri}".format( - host=self.host, - uri=self.base_url, - ) - + return "{host}{uri}".format(host=self.host, uri=self.base_url) def wait_up(self, timeout=10, http=False, ssl_context=None): """Wait for this server to come up""" if http: ssl_context = ssl_context or make_ssl_context( - self.keyfile, self.certfile, cafile=self.cafile) + self.keyfile, self.certfile, cafile=self.cafile + ) return wait_for_http_server( - self.url, timeout=timeout, ssl_context=ssl_context) + self.url, timeout=timeout, ssl_context=ssl_context + ) else: - return wait_for_server(self._connect_ip, self._connect_port, timeout=timeout) + return wait_for_server( + self._connect_ip, self._connect_port, timeout=timeout + ) def is_up(self): """Is the server accepting connections?""" @@ -190,11 +192,13 @@ class Hub(Server): @property def server(self): - warnings.warn("Hub.server is deprecated in JupyterHub 0.8. Access attributes on the Hub directly.", + warnings.warn( + "Hub.server is deprecated in JupyterHub 0.8. Access attributes on the Hub directly.", DeprecationWarning, stacklevel=2, ) return self + public_host = Unicode() routespec = Unicode() @@ -205,5 +209,7 @@ def api_url(self): def __repr__(self): return "<%s %s:%s>" % ( - self.__class__.__name__, self.server.ip, self.server.port, + self.__class__.__name__, + self.server.ip, + self.server.port, ) diff --git a/jupyterhub/orm.py b/jupyterhub/orm.py --- a/jupyterhub/orm.py +++ b/jupyterhub/orm.py @@ -1,36 +1,45 @@ """sqlalchemy ORM tools for the state of the constellation of processes""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - -from datetime import datetime, timedelta import enum import json +from datetime import datetime +from datetime import timedelta -import alembic.config import alembic.command +import alembic.config from alembic.script import ScriptDirectory -from tornado.log import app_log - -from sqlalchemy.types import TypeDecorator, Text, LargeBinary -from sqlalchemy import ( - create_engine, event, exc, inspect, or_, select, - Column, Integer, ForeignKey, Unicode, Boolean, - DateTime, Enum, Table, -) +from sqlalchemy import Boolean +from sqlalchemy import Column +from sqlalchemy import create_engine +from sqlalchemy import DateTime +from sqlalchemy import Enum +from sqlalchemy import event +from sqlalchemy import exc +from sqlalchemy import ForeignKey +from sqlalchemy import inspect +from sqlalchemy import Integer +from sqlalchemy import or_ +from sqlalchemy import select +from sqlalchemy import Table +from sqlalchemy import Unicode from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import ( - Session, - interfaces, object_session, relationship, sessionmaker, -) - +from sqlalchemy.orm import interfaces +from sqlalchemy.orm import object_session +from sqlalchemy.orm import relationship +from sqlalchemy.orm import Session +from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import StaticPool from sqlalchemy.sql.expression import bindparam +from sqlalchemy.types import LargeBinary +from sqlalchemy.types import Text +from sqlalchemy.types import TypeDecorator +from tornado.log import app_log -from .utils import ( - random_port, - new_token, hash_token, compare_token, -) +from .utils import compare_token +from .utils import hash_token +from .utils import new_token +from .utils import random_port # top-level variable for easier mocking in tests utcnow = datetime.utcnow @@ -68,6 +77,7 @@ class Server(Base): connection and cookie info """ + __tablename__ = 'servers' id = Column(Integer, primary_key=True) @@ -82,7 +92,9 @@ def __repr__(self): # user:group many:many mapping table -user_group_map = Table('user_group_map', Base.metadata, +user_group_map = Table( + 'user_group_map', + Base.metadata, Column('user_id', ForeignKey('users.id', ondelete='CASCADE'), primary_key=True), Column('group_id', ForeignKey('groups.id', ondelete='CASCADE'), primary_key=True), ) @@ -90,6 +102,7 @@ def __repr__(self): class Group(Base): """User Groups""" + __tablename__ = 'groups' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(Unicode(255), unique=True) @@ -97,7 +110,9 @@ class Group(Base): def __repr__(self): return "<%s %s (%i users)>" % ( - self.__class__.__name__, self.name, len(self.users) + self.__class__.__name__, + self.name, + len(self.users), ) @classmethod @@ -130,15 +145,15 @@ class User(Base): `servers` is a list that contains a reference for each of the user's single user notebook servers. The method `server` returns the first entry in the user's `servers` list. """ + __tablename__ = 'users' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(Unicode(255), unique=True) _orm_spawners = relationship( - "Spawner", - backref="user", - cascade="all, delete-orphan", + "Spawner", backref="user", cascade="all, delete-orphan" ) + @property def orm_spawners(self): return {s.name: s for s in self._orm_spawners} @@ -147,20 +162,12 @@ def orm_spawners(self): created = Column(DateTime, default=datetime.utcnow) last_activity = Column(DateTime, nullable=True) - api_tokens = relationship( - "APIToken", - backref="user", - cascade="all, delete-orphan", - ) + api_tokens = relationship("APIToken", backref="user", cascade="all, delete-orphan") oauth_tokens = relationship( - "OAuthAccessToken", - backref="user", - cascade="all, delete-orphan", + "OAuthAccessToken", backref="user", cascade="all, delete-orphan" ) oauth_codes = relationship( - "OAuthCode", - backref="user", - cascade="all, delete-orphan", + "OAuthCode", backref="user", cascade="all, delete-orphan" ) cookie_id = Column(Unicode(255), default=new_token, nullable=False, unique=True) # User.state is actually Spawner state @@ -192,8 +199,10 @@ def find(cls, db, name): """ return db.query(cls).filter(cls.name == name).first() + class Spawner(Base): """"State about a Spawner""" + __tablename__ = 'spawners' id = Column(Integer, primary_key=True, autoincrement=True) @@ -214,10 +223,12 @@ class Spawner(Base): # for which these should all be False active = running = ready = False pending = None + @property def orm_spawner(self): return self + class Service(Base): """A service run with JupyterHub @@ -235,6 +246,7 @@ class Service(Base): - pid: the process id (if managed) """ + __tablename__ = 'services' id = Column(Integer, primary_key=True, autoincrement=True) @@ -243,9 +255,7 @@ class Service(Base): admin = Column(Boolean, default=False) api_tokens = relationship( - "APIToken", - backref="service", - cascade="all, delete-orphan", + "APIToken", backref="service", cascade="all, delete-orphan" ) # service-specific interface @@ -270,6 +280,7 @@ def find(cls, db, name): class Hashed(object): """Mixin for tables with hashed tokens""" + prefix_length = 4 algorithm = "sha512" rounds = 16384 @@ -289,7 +300,7 @@ def token(self): @token.setter def token(self, token): """Store the hashed value and prefix for a token""" - self.prefix = token[:self.prefix_length] + self.prefix = token[: self.prefix_length] if self.generated: # Generated tokens are UUIDs, which have sufficient entropy on their own # and don't need salt & hash rounds. @@ -299,7 +310,9 @@ def token(self, token): else: rounds = self.rounds salt_bytes = self.salt_bytes - self.hashed = hash_token(token, rounds=rounds, salt=salt_bytes, algorithm=self.algorithm) + self.hashed = hash_token( + token, rounds=rounds, salt=salt_bytes, algorithm=self.algorithm + ) def match(self, token): """Is this my token?""" @@ -309,12 +322,13 @@ def match(self, token): def check_token(cls, db, token): """Check if a token is acceptable""" if len(token) < cls.min_length: - raise ValueError("Tokens must be at least %i characters, got %r" % ( - cls.min_length, token) + raise ValueError( + "Tokens must be at least %i characters, got %r" + % (cls.min_length, token) ) found = cls.find(db, token) if found: - raise ValueError("Collision on token: %s..." % token[:cls.prefix_length]) + raise ValueError("Collision on token: %s..." % token[: cls.prefix_length]) @classmethod def find_prefix(cls, db, token): @@ -322,7 +336,7 @@ def find_prefix(cls, db, token): Returns an SQLAlchemy query already filtered by prefix-matches. """ - prefix = token[:cls.prefix_length] + prefix = token[: cls.prefix_length] # since we can't filter on hashed values, filter on prefix # so we aren't comparing with all tokens return db.query(cls).filter(bindparam('prefix', prefix).startswith(cls.prefix)) @@ -344,10 +358,13 @@ def find(cls, db, token): class APIToken(Hashed, Base): """An API token""" + __tablename__ = 'api_tokens' user_id = Column(Integer, ForeignKey('users.id', ondelete="CASCADE"), nullable=True) - service_id = Column(Integer, ForeignKey('services.id', ondelete="CASCADE"), nullable=True) + service_id = Column( + Integer, ForeignKey('services.id', ondelete="CASCADE"), nullable=True + ) id = Column(Integer, primary_key=True) hashed = Column(Unicode(255), unique=True) @@ -375,10 +392,7 @@ def __repr__(self): kind = 'owner' name = 'unknown' return "<{cls}('{pre}...', {kind}='{name}')>".format( - cls=self.__class__.__name__, - pre=self.prefix, - kind=kind, - name=name, + cls=self.__class__.__name__, pre=self.prefix, kind=kind, name=name ) @classmethod @@ -387,9 +401,7 @@ def purge_expired(cls, db): now = utcnow() deleted = False for token in ( - db.query(cls) - .filter(cls.expires_at != None) - .filter(cls.expires_at < now) + db.query(cls).filter(cls.expires_at != None).filter(cls.expires_at < now) ): app_log.debug("Purging expired %s", token) deleted = True @@ -421,8 +433,15 @@ def find(cls, db, token, *, kind=None): return orm_token @classmethod - def new(cls, token=None, user=None, service=None, note='', generated=True, - expires_in=None): + def new( + cls, + token=None, + user=None, + service=None, + note='', + generated=True, + expires_in=None, + ): """Generate a new API token for a user or service""" assert user or service assert not (user and service) @@ -451,9 +470,9 @@ def new(cls, token=None, user=None, service=None, note='', generated=True, return token -#------------------------------------ +# ------------------------------------ # OAuth tables -#------------------------------------ +# ------------------------------------ class GrantType(enum.Enum): @@ -473,14 +492,16 @@ class OAuthAccessToken(Hashed, Base): def api_id(self): return 'o%i' % self.id - client_id = Column(Unicode(255), ForeignKey('oauth_clients.identifier', ondelete='CASCADE')) + client_id = Column( + Unicode(255), ForeignKey('oauth_clients.identifier', ondelete='CASCADE') + ) grant_type = Column(Enum(GrantType), nullable=False) expires_at = Column(Integer) refresh_token = Column(Unicode(255)) # TODO: drop refresh_expires_at. Refresh tokens shouldn't expire refresh_expires_at = Column(Integer) user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE')) - service = None # for API-equivalence with APIToken + service = None # for API-equivalence with APIToken # the browser session id associated with a given token session_id = Column(Unicode(255)) @@ -517,7 +538,9 @@ def find(cls, db, token): class OAuthCode(Base): __tablename__ = 'oauth_codes' id = Column(Integer, primary_key=True, autoincrement=True) - client_id = Column(Unicode(255), ForeignKey('oauth_clients.identifier', ondelete='CASCADE')) + client_id = Column( + Unicode(255), ForeignKey('oauth_clients.identifier', ondelete='CASCADE') + ) code = Column(Unicode(36)) expires_at = Column(Integer) redirect_uri = Column(Unicode(1023)) @@ -539,18 +562,14 @@ def client_id(self): return self.identifier access_tokens = relationship( - OAuthAccessToken, - backref='client', - cascade='all, delete-orphan', - ) - codes = relationship( - OAuthCode, - backref='client', - cascade='all, delete-orphan', + OAuthAccessToken, backref='client', cascade='all, delete-orphan' ) + codes = relationship(OAuthCode, backref='client', cascade='all, delete-orphan') + # General database utilities + class DatabaseSchemaMismatch(Exception): """Exception raised when the database schema version does not match @@ -560,6 +579,7 @@ class DatabaseSchemaMismatch(Exception): def register_foreign_keys(engine): """register PRAGMA foreign_keys=on on connection""" + @event.listens_for(engine, "connect") def connect(dbapi_con, con_record): cursor = dbapi_con.cursor() @@ -609,6 +629,7 @@ def register_ping_connection(engine): https://docs.sqlalchemy.org/en/rel_1_1/core/pooling.html#disconnect-handling-pessimistic """ + @event.listens_for(engine, "engine_connect") def ping_connection(connection, branch): if branch: @@ -633,7 +654,9 @@ def ping_connection(connection, branch): # condition, which is based on inspection of the original exception # by the dialect in use. if err.connection_invalidated: - app_log.error("Database connection error, attempting to reconnect: %s", err) + app_log.error( + "Database connection error, attempting to reconnect: %s", err + ) # run the same SELECT again - the connection will re-validate # itself and establish a new connection. The disconnect detection # here also causes the whole connection pool to be invalidated @@ -697,43 +720,50 @@ def check_db_revision(engine): # check database schema version # it should always be defined at this point - alembic_revision = engine.execute('SELECT version_num FROM alembic_version').first()[0] + alembic_revision = engine.execute( + 'SELECT version_num FROM alembic_version' + ).first()[0] if alembic_revision == head: app_log.debug("database schema version found: %s", alembic_revision) pass else: - raise DatabaseSchemaMismatch("Found database schema version {found} != {head}. " - "Backup your database and run `jupyterhub upgrade-db`" - " to upgrade to the latest schema.".format( - found=alembic_revision, - head=head, - )) + raise DatabaseSchemaMismatch( + "Found database schema version {found} != {head}. " + "Backup your database and run `jupyterhub upgrade-db`" + " to upgrade to the latest schema.".format( + found=alembic_revision, head=head + ) + ) def mysql_large_prefix_check(engine): """Check mysql has innodb_large_prefix set""" if not str(engine.url).startswith('mysql'): return False - variables = dict(engine.execute( - 'show variables where variable_name like ' - '"innodb_large_prefix" or ' - 'variable_name like "innodb_file_format";').fetchall()) - if (variables['innodb_file_format'] == 'Barracuda' and - variables['innodb_large_prefix'] == 'ON'): + variables = dict( + engine.execute( + 'show variables where variable_name like ' + '"innodb_large_prefix" or ' + 'variable_name like "innodb_file_format";' + ).fetchall() + ) + if ( + variables['innodb_file_format'] == 'Barracuda' + and variables['innodb_large_prefix'] == 'ON' + ): return True else: return False def add_row_format(base): - for t in base.metadata.tables.values(): + for t in base.metadata.tables.values(): t.dialect_kwargs['mysql_ROW_FORMAT'] = 'DYNAMIC' -def new_session_factory(url="sqlite:///:memory:", - reset=False, - expire_on_commit=False, - **kwargs): +def new_session_factory( + url="sqlite:///:memory:", reset=False, expire_on_commit=False, **kwargs +): """Create a new session at url""" if url.startswith('sqlite'): kwargs.setdefault('connect_args', {'check_same_thread': False}) @@ -757,7 +787,7 @@ def new_session_factory(url="sqlite:///:memory:", Base.metadata.drop_all(engine) if mysql_large_prefix_check(engine): # if mysql is allows large indexes - add_row_format(Base) # set format on the tables + add_row_format(Base) # set format on the tables # check the db revision (will raise, pointing to `upgrade-db` if version doesn't match) check_db_revision(engine) @@ -767,7 +797,5 @@ def new_session_factory(url="sqlite:///:memory:", # SQLAlchemy to expire objects after committing - we don't expect # concurrent runs of the hub talking to the same db. Turning # this off gives us a major performance boost - session_factory = sessionmaker(bind=engine, - expire_on_commit=expire_on_commit, - ) + session_factory = sessionmaker(bind=engine, expire_on_commit=expire_on_commit) return session_factory diff --git a/jupyterhub/proxy.py b/jupyterhub/proxy.py --- a/jupyterhub/proxy.py +++ b/jupyterhub/proxy.py @@ -14,36 +14,38 @@ 'host.tld/path/' for host-based routing or '/path/' for default routing. - Route paths should be normalized to always start and end with '/' """ - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import asyncio -from functools import wraps import json import os import signal -from subprocess import Popen import time -from urllib.parse import quote, urlparse +from functools import wraps +from subprocess import Popen +from urllib.parse import quote +from urllib.parse import urlparse from tornado import gen -from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPError +from tornado.httpclient import AsyncHTTPClient +from tornado.httpclient import HTTPError +from tornado.httpclient import HTTPRequest from tornado.ioloop import PeriodicCallback - - -from traitlets import ( - Any, Bool, Instance, Integer, Unicode, - default, observe, -) -from jupyterhub.traitlets import Command - +from traitlets import Any +from traitlets import Bool +from traitlets import default +from traitlets import Instance +from traitlets import Integer +from traitlets import observe +from traitlets import Unicode from traitlets.config import LoggingConfigurable +from . import utils from .metrics import CHECK_ROUTES_DURATION_SECONDS from .objects import Server -from . import utils -from .utils import url_path_join, make_ssl_context +from .utils import make_ssl_context +from .utils import url_path_join +from jupyterhub.traitlets import Command def _one_at_a_time(method): @@ -53,6 +55,7 @@ def _one_at_a_time(method): queue them instead of allowing them to be concurrently outstanding. """ method._lock = asyncio.Lock() + @wraps(method) async def locked_method(*args, **kwargs): async with method._lock: @@ -86,6 +89,7 @@ class Proxy(LoggingConfigurable): """ db_factory = Any() + @property def db(self): return self.db_factory() @@ -97,13 +101,16 @@ def db(self): ssl_cert = Unicode() host_routing = Bool() - should_start = Bool(True, config=True, - help="""Should the Hub start the proxy + should_start = Bool( + True, + config=True, + help="""Should the Hub start the proxy If True, the Hub will start the proxy and stop it. Set to False if the proxy is managed externally, such as by systemd, docker, or another service manager. - """) + """, + ) def start(self): """Start the proxy. @@ -136,9 +143,13 @@ def validate_routespec(self, routespec): # check host routing host_route = not routespec.startswith('/') if host_route and not self.host_routing: - raise ValueError("Cannot add host-based route %r, not using host-routing" % routespec) + raise ValueError( + "Cannot add host-based route %r, not using host-routing" % routespec + ) if self.host_routing and not host_route: - raise ValueError("Cannot add route without host %r, using host-routing" % routespec) + raise ValueError( + "Cannot add route without host %r, using host-routing" % routespec + ) # add trailing slash if not routespec.endswith('/'): return routespec + '/' @@ -220,16 +231,19 @@ async def add_service(self, service, client=None): """Add a service's server to the proxy table.""" if not service.server: raise RuntimeError( - "Service %s does not have an http endpoint to add to the proxy.", service.name) - - self.log.info("Adding service %s to proxy %s => %s", - service.name, service.proxy_spec, service.server.host, - ) + "Service %s does not have an http endpoint to add to the proxy.", + service.name, + ) - await self.add_route( + self.log.info( + "Adding service %s to proxy %s => %s", + service.name, service.proxy_spec, service.server.host, - {'service': service.name} + ) + + await self.add_route( + service.proxy_spec, service.server.host, {'service': service.name} ) async def delete_service(self, service, client=None): @@ -240,22 +254,23 @@ async def delete_service(self, service, client=None): async def add_user(self, user, server_name='', client=None): """Add a user's server to the proxy table.""" spawner = user.spawners[server_name] - self.log.info("Adding user %s to proxy %s => %s", - user.name, spawner.proxy_spec, spawner.server.host, - ) + self.log.info( + "Adding user %s to proxy %s => %s", + user.name, + spawner.proxy_spec, + spawner.server.host, + ) if spawner.pending and spawner.pending != 'spawn': raise RuntimeError( - "%s is pending %s, shouldn't be added to the proxy yet!" % (spawner._log_name, spawner.pending) + "%s is pending %s, shouldn't be added to the proxy yet!" + % (spawner._log_name, spawner.pending) ) await self.add_route( spawner.proxy_spec, spawner.server.host, - { - 'user': user.name, - 'server_name': server_name, - } + {'user': user.name, 'server_name': server_name}, ) async def delete_user(self, user, server_name=''): @@ -294,7 +309,7 @@ async def add_all_users(self, user_dict): @_one_at_a_time async def check_routes(self, user_dict, service_dict, routes=None): """Check that all users are properly routed on the proxy.""" - start = time.perf_counter() #timer starts here when user is created + start = time.perf_counter() # timer starts here when user is created if not routes: self.log.debug("Fetching routes to check") routes = await self.get_all_routes() @@ -314,7 +329,9 @@ async def check_routes(self, user_dict, service_dict, routes=None): else: route = routes[self.app.hub.routespec] if route['target'] != hub.host: - self.log.warning("Updating default route %s → %s", route['target'], hub.host) + self.log.warning( + "Updating default route %s → %s", route['target'], hub.host + ) futures.append(self.add_hub_route(hub)) for user in user_dict.values(): @@ -324,14 +341,17 @@ async def check_routes(self, user_dict, service_dict, routes=None): good_routes.add(spec) if spec not in user_routes: self.log.warning( - "Adding missing route for %s (%s)", spec, spawner.server) + "Adding missing route for %s (%s)", spec, spawner.server + ) futures.append(self.add_user(user, name)) else: route = routes[spec] if route['target'] != spawner.server.host: self.log.warning( "Updating route for %s (%s → %s)", - spec, route['target'], spawner.server, + spec, + route['target'], + spawner.server, ) futures.append(self.add_user(user, name)) elif spawner.pending: @@ -341,22 +361,26 @@ async def check_routes(self, user_dict, service_dict, routes=None): good_routes.add(spawner.proxy_spec) # check service routes - service_routes = {r['data']['service']: r - for r in routes.values() if 'service' in r['data']} + service_routes = { + r['data']['service']: r for r in routes.values() if 'service' in r['data'] + } for service in service_dict.values(): if service.server is None: continue good_routes.add(service.proxy_spec) if service.name not in service_routes: - self.log.warning("Adding missing route for %s (%s)", - service.name, service.server) + self.log.warning( + "Adding missing route for %s (%s)", service.name, service.server + ) futures.append(self.add_service(service)) else: route = service_routes[service.name] if route['target'] != service.server.host: self.log.warning( "Updating route for %s (%s → %s)", - route['routespec'], route['target'], service.server.host, + route['routespec'], + route['target'], + service.server.host, ) futures.append(self.add_service(service)) @@ -367,8 +391,8 @@ async def check_routes(self, user_dict, service_dict, routes=None): futures.append(self.delete_route(routespec)) await gen.multi(futures) - stop = time.perf_counter() #timer stops here when user is deleted - CHECK_ROUTES_DURATION_SECONDS.observe(stop - start) #histogram metric + stop = time.perf_counter() # timer stops here when user is deleted + CHECK_ROUTES_DURATION_SECONDS.observe(stop - start) # histogram metric def add_hub_route(self, hub): """Add the default route for the Hub""" @@ -408,7 +432,7 @@ class ConfigurableHTTPProxy(Proxy): Limiting this number avoids potential timeout errors by sending too many requests to update the proxy at once """, - ) + ) semaphore = Any() @default('semaphore') @@ -424,7 +448,7 @@ def _concurrency_changed(self, change): help="""The Proxy auth token Loaded from the CONFIGPROXY_AUTH_TOKEN env variable by default. - """, + """ ).tag(config=True) check_running_interval = Integer(5, config=True) @@ -437,25 +461,24 @@ def _auth_token_default(self): token = utils.new_token() return token - api_url = Unicode(config=True, - help="""The ip (or hostname) of the proxy's API endpoint""" - ) + api_url = Unicode( + config=True, help="""The ip (or hostname) of the proxy's API endpoint""" + ) @default('api_url') def _api_url_default(self): - url = '127.0.0.1:8001' - proto = 'http' - if self.app.internal_ssl: - proto = 'https' + url = '127.0.0.1:8001' + proto = 'http' + if self.app.internal_ssl: + proto = 'https' - return "{proto}://{url}".format( - proto=proto, - url=url, - ) + return "{proto}://{url}".format(proto=proto, url=url) - command = Command('configurable-http-proxy', config=True, - help="""The command to start the proxy""" - ) + command = Command( + 'configurable-http-proxy', + config=True, + help="""The command to start the proxy""", + ) pid_file = Unicode( "jupyterhub-proxy.pid", @@ -463,11 +486,14 @@ def _api_url_default(self): help="File in which to write the PID of the proxy process.", ) - _check_running_callback = Any(help="PeriodicCallback to check if the proxy is running") + _check_running_callback = Any( + help="PeriodicCallback to check if the proxy is running" + ) def _check_pid(self, pid): if os.name == 'nt': import psutil + if not psutil.pid_exists(pid): raise ProcessLookupError else: @@ -512,7 +538,7 @@ def _check_previous_process(self): if os.name == 'nt': self._terminate_win(pid) else: - os.kill(pid,sig_list[i]) + os.kill(pid, sig_list[i]) except ProcessLookupError: break time.sleep(1) @@ -558,11 +584,16 @@ async def start(self): env = os.environ.copy() env['CONFIGPROXY_AUTH_TOKEN'] = self.auth_token cmd = self.command + [ - '--ip', public_server.ip, - '--port', str(public_server.port), - '--api-ip', api_server.ip, - '--api-port', str(api_server.port), - '--error-target', url_path_join(self.hub.url, 'error'), + '--ip', + public_server.ip, + '--port', + str(public_server.port), + '--api-ip', + api_server.ip, + '--api-port', + str(api_server.port), + '--error-target', + url_path_join(self.hub.url, 'error'), ] if self.app.subdomain_host: cmd.append('--host-routing') @@ -595,28 +626,36 @@ async def start(self): cmd.extend(['--client-ssl-request-cert']) cmd.extend(['--client-ssl-reject-unauthorized']) if self.app.statsd_host: - cmd.extend([ - '--statsd-host', self.app.statsd_host, - '--statsd-port', str(self.app.statsd_port), - '--statsd-prefix', self.app.statsd_prefix + '.chp' - ]) + cmd.extend( + [ + '--statsd-host', + self.app.statsd_host, + '--statsd-port', + str(self.app.statsd_port), + '--statsd-prefix', + self.app.statsd_prefix + '.chp', + ] + ) # Warn if SSL is not used if ' --ssl' not in ' '.join(cmd): - self.log.warning("Running JupyterHub without SSL." - " I hope there is SSL termination happening somewhere else...") + self.log.warning( + "Running JupyterHub without SSL." + " I hope there is SSL termination happening somewhere else..." + ) self.log.info("Starting proxy @ %s", public_server.bind_url) self.log.debug("Proxy cmd: %s", cmd) shell = os.name == 'nt' try: - self.proxy_process = Popen(cmd, env=env, start_new_session=True, shell=shell) + self.proxy_process = Popen( + cmd, env=env, start_new_session=True, shell=shell + ) except FileNotFoundError as e: self.log.error( "Failed to find proxy %r\n" "The proxy can be installed with `npm install -g configurable-http-proxy`." "To install `npm`, install nodejs which includes `npm`." "If you see an `EACCES` error or permissions error, refer to the `npm` " - "documentation on How To Prevent Permissions Errors." - % self.command + "documentation on How To Prevent Permissions Errors." % self.command ) raise @@ -625,8 +664,7 @@ async def start(self): def _check_process(): status = self.proxy_process.poll() if status is not None: - e = RuntimeError( - "Proxy failed to start with exit code %i" % status) + e = RuntimeError("Proxy failed to start with exit code %i" % status) raise e from None for server in (public_server, api_server): @@ -678,9 +716,10 @@ async def check_running(self): """Check if the proxy is still running""" if self.proxy_process.poll() is None: return - self.log.error("Proxy stopped with exit code %r", - 'unknown' if self.proxy_process is None else self.proxy_process.poll() - ) + self.log.error( + "Proxy stopped with exit code %r", + 'unknown' if self.proxy_process is None else self.proxy_process.poll(), + ) self._remove_pid_file() await self.start() await self.restore_routes() @@ -724,12 +763,12 @@ async def api_request(self, path, method='GET', body=None, client=None): if isinstance(body, dict): body = json.dumps(body) self.log.debug("Proxy: Fetching %s %s", method, url) - req = HTTPRequest(url, - method=method, - headers={'Authorization': 'token {}'.format( - self.auth_token)}, - body=body, - ) + req = HTTPRequest( + url, + method=method, + headers={'Authorization': 'token {}'.format(self.auth_token)}, + body=body, + ) async with self.semaphore: result = await client.fetch(req) return result @@ -739,11 +778,7 @@ async def add_route(self, routespec, target, data): body['target'] = target body['jupyterhub'] = True path = self._routespec_to_chp_path(routespec) - await self.api_request( - path, - method='POST', - body=body, - ) + await self.api_request(path, method='POST', body=body) async def delete_route(self, routespec): path = self._routespec_to_chp_path(routespec) @@ -762,11 +797,7 @@ def _reformat_routespec(self, routespec, chp_data): """Reformat CHP data format to JupyterHub's proxy API.""" target = chp_data.pop('target') chp_data.pop('jupyterhub') - return { - 'routespec': routespec, - 'target': target, - 'data': chp_data, - } + return {'routespec': routespec, 'target': target, 'data': chp_data} async def get_all_routes(self, client=None): """Fetch the proxy's routes.""" @@ -779,6 +810,5 @@ async def get_all_routes(self, client=None): # exclude routes not associated with JupyterHub self.log.debug("Omitting non-jupyterhub route %r", routespec) continue - all_routes[routespec] = self._reformat_routespec( - routespec, chp_data) + all_routes[routespec] = self._reformat_routespec(routespec, chp_data) return all_routes diff --git a/jupyterhub/services/auth.py b/jupyterhub/services/auth.py --- a/jupyterhub/services/auth.py +++ b/jupyterhub/services/auth.py @@ -9,7 +9,6 @@ authenticate with the Hub. """ - import base64 import json import os @@ -18,22 +17,25 @@ import socket import string import time -from urllib.parse import quote, urlencode import uuid import warnings +from urllib.parse import quote +from urllib.parse import urlencode import requests - from tornado.gen import coroutine -from tornado.log import app_log from tornado.httputil import url_concat -from tornado.web import HTTPError, RequestHandler - +from tornado.log import app_log +from tornado.web import HTTPError +from tornado.web import RequestHandler +from traitlets import default +from traitlets import Dict +from traitlets import Instance +from traitlets import Integer +from traitlets import observe +from traitlets import Unicode +from traitlets import validate from traitlets.config import SingletonConfigurable -from traitlets import ( - Unicode, Integer, Instance, Dict, - default, observe, validate, -) from ..utils import url_path_join @@ -63,13 +65,14 @@ def __setitem__(self, key, value): def __repr__(self): """include values and timestamps in repr""" now = time.monotonic() - return repr({ - key: '{value} (age={age:.0f}s)'.format( - value=repr(value)[:16] + '...', - age=now-self.timestamps[key], - ) - for key, value in self.values.items() - }) + return repr( + { + key: '{value} (age={age:.0f}s)'.format( + value=repr(value)[:16] + '...', age=now - self.timestamps[key] + ) + for key, value in self.values.items() + } + ) def _check_age(self, key): """Check timestamp for a key""" @@ -131,24 +134,28 @@ class HubAuth(SingletonConfigurable): """ - hub_host = Unicode('', + hub_host = Unicode( + '', help="""The public host of JupyterHub Only used if JupyterHub is spreading servers across subdomains. - """ + """, ).tag(config=True) + @default('hub_host') def _default_hub_host(self): return os.getenv('JUPYTERHUB_HOST', '') - base_url = Unicode(os.getenv('JUPYTERHUB_SERVICE_PREFIX') or '/', + base_url = Unicode( + os.getenv('JUPYTERHUB_SERVICE_PREFIX') or '/', help="""The base URL prefix of this application e.g. /services/service-name/ or /user/name/ Default: get from JUPYTERHUB_SERVICE_PREFIX - """ + """, ).tag(config=True) + @validate('base_url') def _add_slash(self, proposal): """Ensure base_url starts and ends with /""" @@ -160,12 +167,14 @@ def _add_slash(self, proposal): return value # where is the hub - api_url = Unicode(os.getenv('JUPYTERHUB_API_URL') or 'http://127.0.0.1:8081/hub/api', + api_url = Unicode( + os.getenv('JUPYTERHUB_API_URL') or 'http://127.0.0.1:8081/hub/api', help="""The base API URL of the Hub. Typically `http://hub-ip:hub-port/hub/api` - """ + """, ).tag(config=True) + @default('api_url') def _api_url(self): env_url = os.getenv('JUPYTERHUB_API_URL') @@ -173,57 +182,65 @@ def _api_url(self): return env_url else: return 'http://127.0.0.1:8081' + url_path_join(self.hub_prefix, 'api') - - api_token = Unicode(os.getenv('JUPYTERHUB_API_TOKEN', ''), + + api_token = Unicode( + os.getenv('JUPYTERHUB_API_TOKEN', ''), help="""API key for accessing Hub API. Generate with `jupyterhub token [username]` or add to JupyterHub.services config. - """ + """, ).tag(config=True) - hub_prefix = Unicode('/hub/', + hub_prefix = Unicode( + '/hub/', help="""The URL prefix for the Hub itself. Typically /hub/ - """ + """, ).tag(config=True) + @default('hub_prefix') def _default_hub_prefix(self): return url_path_join(os.getenv('JUPYTERHUB_BASE_URL') or '/', 'hub') + '/' - login_url = Unicode('/hub/login', + login_url = Unicode( + '/hub/login', help="""The login URL to use Typically /hub/login - """ + """, ).tag(config=True) + @default('login_url') def _default_login_url(self): return self.hub_host + url_path_join(self.hub_prefix, 'login') - keyfile = Unicode('', + keyfile = Unicode( + '', help="""The ssl key to use for requests Use with certfile - """ + """, ).tag(config=True) - certfile = Unicode('', + certfile = Unicode( + '', help="""The ssl cert to use for requests Use with keyfile - """ + """, ).tag(config=True) - client_ca = Unicode('', + client_ca = Unicode( + '', help="""The ssl certificate authority to use to verify requests Use with keyfile and certfile - """ + """, ).tag(config=True) - cookie_name = Unicode('jupyterhub-services', - help="""The name of the cookie I should be looking for""" + cookie_name = Unicode( + 'jupyterhub-services', help="""The name of the cookie I should be looking for""" ).tag(config=True) cookie_options = Dict( @@ -245,21 +262,26 @@ def _default_cookie_options(self): return {} cookie_cache_max_age = Integer(help="DEPRECATED. Use cache_max_age") + @observe('cookie_cache_max_age') def _deprecated_cookie_cache(self, change): - warnings.warn("cookie_cache_max_age is deprecated in JupyterHub 0.8. Use cache_max_age instead.") + warnings.warn( + "cookie_cache_max_age is deprecated in JupyterHub 0.8. Use cache_max_age instead." + ) self.cache_max_age = change.new - cache_max_age = Integer(300, + cache_max_age = Integer( + 300, help="""The maximum time (in seconds) to cache the Hub's responses for authentication. A larger value reduces load on the Hub and occasional response lag. A smaller value reduces propagation time of changes on the Hub (rare). Default: 300 (five minutes) - """ + """, ).tag(config=True) cache = Instance(_ExpiringDict, allow_none=False) + @default('cache') def _default_cache(self): return _ExpiringDict(self.cache_max_age) @@ -311,25 +333,42 @@ def _api_request(self, method, url, **kwargs): except requests.ConnectionError as e: app_log.error("Error connecting to %s: %s", self.api_url, e) msg = "Failed to connect to Hub API at %r." % self.api_url - msg += " Is the Hub accessible at this URL (from host: %s)?" % socket.gethostname() + msg += ( + " Is the Hub accessible at this URL (from host: %s)?" + % socket.gethostname() + ) if '127.0.0.1' in self.api_url: - msg += " Make sure to set c.JupyterHub.hub_ip to an IP accessible to" + \ - " single-user servers if the servers are not on the same host as the Hub." + msg += ( + " Make sure to set c.JupyterHub.hub_ip to an IP accessible to" + + " single-user servers if the servers are not on the same host as the Hub." + ) raise HTTPError(500, msg) data = None if r.status_code == 404 and allow_404: pass elif r.status_code == 403: - app_log.error("I don't have permission to check authorization with JupyterHub, my auth token may have expired: [%i] %s", r.status_code, r.reason) + app_log.error( + "I don't have permission to check authorization with JupyterHub, my auth token may have expired: [%i] %s", + r.status_code, + r.reason, + ) app_log.error(r.text) - raise HTTPError(500, "Permission failure checking authorization, I may need a new token") + raise HTTPError( + 500, "Permission failure checking authorization, I may need a new token" + ) elif r.status_code >= 500: - app_log.error("Upstream failure verifying auth token: [%i] %s", r.status_code, r.reason) + app_log.error( + "Upstream failure verifying auth token: [%i] %s", + r.status_code, + r.reason, + ) app_log.error(r.text) raise HTTPError(502, "Failed to check authorization (upstream problem)") elif r.status_code >= 400: - app_log.warning("Failed to check authorization: [%i] %s", r.status_code, r.reason) + app_log.warning( + "Failed to check authorization: [%i] %s", r.status_code, r.reason + ) app_log.warning(r.text) msg = "Failed to check authorization" # pass on error_description from oauth failure @@ -358,10 +397,12 @@ def user_for_cookie(self, encrypted_cookie, use_cache=True, session_id=''): The 'name' field contains the user's name. """ return self._check_hub_authorization( - url=url_path_join(self.api_url, - "authorizations/cookie", - self.cookie_name, - quote(encrypted_cookie, safe='')), + url=url_path_join( + self.api_url, + "authorizations/cookie", + self.cookie_name, + quote(encrypted_cookie, safe=''), + ), cache_key='cookie:{}:{}'.format(session_id, encrypted_cookie), use_cache=use_cache, ) @@ -379,9 +420,9 @@ def user_for_token(self, token, use_cache=True, session_id=''): The 'name' field contains the user's name. """ return self._check_hub_authorization( - url=url_path_join(self.api_url, - "authorizations/token", - quote(token, safe='')), + url=url_path_join( + self.api_url, "authorizations/token", quote(token, safe='') + ), cache_key='token:{}:{}'.format(session_id, token), use_cache=use_cache, ) @@ -399,7 +440,9 @@ def get_token(self, handler): user_token = handler.get_argument('token', '') if not user_token: # get it from Authorization header - m = self.auth_header_pat.match(handler.request.headers.get(self.auth_header_name, '')) + m = self.auth_header_pat.match( + handler.request.headers.get(self.auth_header_name, '') + ) if m: user_token = m.group(1) return user_token @@ -469,11 +512,14 @@ class HubOAuth(HubAuth): @default('login_url') def _login_url(self): - return url_concat(self.oauth_authorization_url, { - 'client_id': self.oauth_client_id, - 'redirect_uri': self.oauth_redirect_uri, - 'response_type': 'code', - }) + return url_concat( + self.oauth_authorization_url, + { + 'client_id': self.oauth_client_id, + 'redirect_uri': self.oauth_redirect_uri, + 'response_type': 'code', + }, + ) @property def cookie_name(self): @@ -511,10 +557,11 @@ def _get_user_cookie(self, handler): Use JUPYTERHUB_CLIENT_ID by default. """ ).tag(config=True) + @default('oauth_client_id') def _client_id(self): return os.getenv('JUPYTERHUB_CLIENT_ID', '') - + @validate('oauth_client_id', 'api_token') def _ensure_not_empty(self, proposal): if not proposal.value: @@ -527,13 +574,18 @@ def _ensure_not_empty(self, proposal): Should generally be /base_url/oauth_callback """ ).tag(config=True) + @default('oauth_redirect_uri') def _default_redirect(self): - return os.getenv('JUPYTERHUB_OAUTH_CALLBACK_URL') or url_path_join(self.base_url, 'oauth_callback') + return os.getenv('JUPYTERHUB_OAUTH_CALLBACK_URL') or url_path_join( + self.base_url, 'oauth_callback' + ) - oauth_authorization_url = Unicode('/hub/api/oauth2/authorize', + oauth_authorization_url = Unicode( + '/hub/api/oauth2/authorize', help="The URL to redirect to when starting the OAuth process", ).tag(config=True) + @default('oauth_authorization_url') def _auth_url(self): return self.hub_host + url_path_join(self.hub_prefix, 'api/oauth2/authorize') @@ -541,6 +593,7 @@ def _auth_url(self): oauth_token_url = Unicode( help="""The URL for requesting an OAuth token from JupyterHub""" ).tag(config=True) + @default('oauth_token_url') def _token_url(self): return url_path_join(self.api_url, 'oauth2/token') @@ -565,11 +618,12 @@ def token_for_code(self, code): redirect_uri=self.oauth_redirect_uri, ) - token_reply = self._api_request('POST', self.oauth_token_url, + token_reply = self._api_request( + 'POST', + self.oauth_token_url, data=urlencode(params).encode('utf8'), - headers={ - 'Content-Type': 'application/x-www-form-urlencoded' - }) + headers={'Content-Type': 'application/x-www-form-urlencoded'}, + ) return token_reply['access_token'] @@ -577,9 +631,11 @@ def _encode_state(self, state): """Encode a state dict as url-safe base64""" # trim trailing `=` because = is itself not url-safe! json_state = json.dumps(state) - return base64.urlsafe_b64encode( - json_state.encode('utf8') - ).decode('ascii').rstrip('=') + return ( + base64.urlsafe_b64encode(json_state.encode('utf8')) + .decode('ascii') + .rstrip('=') + ) def _decode_state(self, b64_state): """Decode a base64 state @@ -621,7 +677,9 @@ def set_state_cookie(self, handler, next_url=None): # use a randomized cookie suffix to avoid collisions # in case of concurrent logins app_log.warning("Detected unused OAuth state cookies") - cookie_suffix = ''.join(random.choice(string.ascii_letters) for i in range(8)) + cookie_suffix = ''.join( + random.choice(string.ascii_letters) for i in range(8) + ) cookie_name = '{}-{}'.format(self.state_cookie_name, cookie_suffix) extra_state['cookie_name'] = cookie_name else: @@ -640,11 +698,7 @@ def set_state_cookie(self, handler, next_url=None): kwargs['secure'] = True # load user cookie overrides kwargs.update(self.cookie_options) - handler.set_secure_cookie( - cookie_name, - b64_state, - **kwargs - ) + handler.set_secure_cookie(cookie_name, b64_state, **kwargs) return b64_state def generate_state(self, next_url=None, **extra_state): @@ -658,10 +712,7 @@ def generate_state(self, next_url=None, **extra_state): ------- state (str): The base64-encoded state string. """ - state = { - 'uuid': uuid.uuid4().hex, - 'next_url': next_url, - } + state = {'uuid': uuid.uuid4().hex, 'next_url': next_url} state.update(extra_state) return self._encode_state(state) @@ -681,21 +732,19 @@ def get_state_cookie_name(self, b64_state=''): def set_cookie(self, handler, access_token): """Set a cookie recording OAuth result""" - kwargs = { - 'path': self.base_url, - 'httponly': True, - } + kwargs = {'path': self.base_url, 'httponly': True} if handler.request.protocol == 'https': kwargs['secure'] = True # load user cookie overrides kwargs.update(self.cookie_options) - app_log.debug("Setting oauth cookie for %s: %s, %s", - handler.request.remote_ip, self.cookie_name, kwargs) - handler.set_secure_cookie( + app_log.debug( + "Setting oauth cookie for %s: %s, %s", + handler.request.remote_ip, self.cookie_name, - access_token, - **kwargs + kwargs, ) + handler.set_secure_cookie(self.cookie_name, access_token, **kwargs) + def clear_cookie(self, handler): """Clear the OAuth cookie""" handler.clear_cookie(self.cookie_name, path=self.base_url) @@ -703,6 +752,7 @@ def clear_cookie(self, handler): class UserNotAllowed(Exception): """Exception raised when a user is identified and not allowed""" + def __init__(self, model): self.model = model @@ -738,19 +788,22 @@ def get(self): ... """ - hub_services = None # set of allowed services - hub_users = None # set of allowed users - hub_groups = None # set of allowed groups - allow_admin = False # allow any admin user access - + + hub_services = None # set of allowed services + hub_users = None # set of allowed users + hub_groups = None # set of allowed groups + allow_admin = False # allow any admin user access + @property def allow_all(self): """Property indicating that all successfully identified user or service should be allowed. """ - return (self.hub_services is None + return ( + self.hub_services is None and self.hub_users is None - and self.hub_groups is None) + and self.hub_groups is None + ) # self.hub_auth must be a HubAuth instance. # If nothing specified, use default config, @@ -758,6 +811,7 @@ def allow_all(self): # based on JupyterHub environment variables for services. _hub_auth = None hub_auth_class = HubAuth + @property def hub_auth(self): if self._hub_auth is None: @@ -794,7 +848,9 @@ def check_hub_user(self, model): name = model['name'] kind = model.setdefault('kind', 'user') if self.allow_all: - app_log.debug("Allowing Hub %s %s (all Hub users and services allowed)", kind, name) + app_log.debug( + "Allowing Hub %s %s (all Hub users and services allowed)", kind, name + ) return model if self.allow_admin and model.get('admin', False): @@ -816,7 +872,11 @@ def check_hub_user(self, model): return model elif self.hub_groups and set(model['groups']).intersection(self.hub_groups): allowed_groups = set(model['groups']).intersection(self.hub_groups) - app_log.debug("Allowing Hub user %s in group(s) %s", name, ','.join(sorted(allowed_groups))) + app_log.debug( + "Allowing Hub user %s in group(s) %s", + name, + ','.join(sorted(allowed_groups)), + ) # group in whitelist return model else: @@ -845,7 +905,10 @@ def get_current_user(self): # This is not the best, but avoids problems that can be caused # when get_current_user is allowed to raise. def raise_on_redirect(*args, **kwargs): - raise HTTPError(403, "{kind} {name} is not allowed.".format(**user_model)) + raise HTTPError( + 403, "{kind} {name} is not allowed.".format(**user_model) + ) + self.redirect = raise_on_redirect return except Exception: @@ -869,6 +932,7 @@ def raise_on_redirect(*args, **kwargs): class HubOAuthenticated(HubAuthenticated): """Simple subclass of HubAuthenticated using OAuth instead of old shared cookies""" + hub_auth_class = HubOAuth @@ -881,7 +945,7 @@ class HubOAuthCallbackHandler(HubOAuthenticated, RequestHandler): .. versionadded: 0.8 """ - + @coroutine def get(self): error = self.get_argument("error", False) @@ -917,5 +981,3 @@ def get(self): app_log.info("Logged-in user %s", user_model) self.hub_auth.set_cookie(self, token) self.redirect(next_url or self.hub_auth.base_url) - - diff --git a/jupyterhub/services/service.py b/jupyterhub/services/service.py --- a/jupyterhub/services/service.py +++ b/jupyterhub/services/service.py @@ -38,24 +38,26 @@ } """ - import copy +import os import pipes import shutil -import os from subprocess import Popen -from traitlets import ( - HasTraits, - Any, Bool, Dict, Unicode, Instance, - default, -) +from traitlets import Any +from traitlets import Bool +from traitlets import default +from traitlets import Dict +from traitlets import HasTraits +from traitlets import Instance +from traitlets import Unicode from traitlets.config import LoggingConfigurable from .. import orm from ..objects import Server +from ..spawner import LocalProcessSpawner +from ..spawner import set_user_setuid from ..traitlets import Command -from ..spawner import LocalProcessSpawner, set_user_setuid from ..utils import url_path_join @@ -81,14 +83,17 @@ def base_url(self): return '' return self.server.base_url + # We probably shouldn't use a Spawner here, # but there are too many concepts to share. + class _ServiceSpawner(LocalProcessSpawner): """Subclass of LocalProcessSpawner Removes notebook-specific-ness from LocalProcessSpawner. """ + cwd = Unicode() cmd = Command(minlen=0) @@ -115,16 +120,20 @@ def start(self): self.log.info("Spawning %s", ' '.join(pipes.quote(s) for s in cmd)) try: - self.proc = Popen(self.cmd, env=env, + self.proc = Popen( + self.cmd, + env=env, preexec_fn=self.make_preexec_fn(self.user.name), - start_new_session=True, # don't forward signals + start_new_session=True, # don't forward signals cwd=self.cwd or None, ) except PermissionError: # use which to get abspath script = shutil.which(cmd[0]) or cmd[0] - self.log.error("Permission denied trying to run %r. Does %s have access to this file?", - script, self.user.name, + self.log.error( + "Permission denied trying to run %r. Does %s have access to this file?", + script, + self.user.name, ) raise @@ -165,9 +174,9 @@ class Service(LoggingConfigurable): If the service has an http endpoint, it """ ).tag(input=True) - admin = Bool(False, - help="Does the service need admin-access to the Hub API?" - ).tag(input=True) + admin = Bool(False, help="Does the service need admin-access to the Hub API?").tag( + input=True + ) url = Unicode( help="""URL of the service. @@ -205,22 +214,23 @@ def kind(self): """ return 'managed' if self.managed else 'external' - command = Command(minlen=0, - help="Command to spawn this service, if managed." - ).tag(input=True) - cwd = Unicode( - help="""The working directory in which to run the service.""" - ).tag(input=True) + command = Command(minlen=0, help="Command to spawn this service, if managed.").tag( + input=True + ) + cwd = Unicode(help="""The working directory in which to run the service.""").tag( + input=True + ) environment = Dict( help="""Environment variables to pass to the service. Only used if the Hub is spawning the service. """ ).tag(input=True) - user = Unicode("", + user = Unicode( + "", help="""The user to become when launching the service. If unspecified, run the service as the same user as the Hub. - """ + """, ).tag(input=True) domain = Unicode() @@ -245,6 +255,7 @@ def kind(self): Default: `service-<name>` """ ).tag(input=True) + @default('oauth_client_id') def _default_client_id(self): return 'service-%s' % self.name @@ -256,6 +267,7 @@ def _default_client_id(self): Default: `/services/:name/oauth_callback` """ ).tag(input=True) + @default('oauth_redirect_uri') def _default_redirect_uri(self): if self.server is None: @@ -328,10 +340,7 @@ def start(self): cwd=self.cwd, hub=self.hub, user=_MockUser( - name=self.user, - service=self, - server=self.orm.server, - host=self.host, + name=self.user, service=self, server=self.orm.server, host=self.host ), internal_ssl=self.app.internal_ssl, internal_certs_location=self.app.internal_certs_location, @@ -344,7 +353,9 @@ def start(self): def _proc_stopped(self): """Called when the service process unexpectedly exits""" - self.log.error("Service %s exited with status %i", self.name, self.proc.returncode) + self.log.error( + "Service %s exited with status %i", self.name, self.proc.returncode + ) self.start() async def stop(self): @@ -357,4 +368,4 @@ async def stop(self): self.db.delete(self.orm.server) self.db.commit() self.spawner.stop_polling() - return (await self.spawner.stop()) + return await self.spawner.stop() diff --git a/jupyterhub/singleuser.py b/jupyterhub/singleuser.py --- a/jupyterhub/singleuser.py +++ b/jupyterhub/singleuser.py @@ -1,23 +1,24 @@ #!/usr/bin/env python """Extend regular notebook server to be aware of multiuser things.""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import asyncio -from datetime import datetime, timezone import json import os import random +from datetime import datetime +from datetime import timezone from textwrap import dedent from urllib.parse import urlparse -from jinja2 import ChoiceLoader, FunctionLoader - -from tornado.httpclient import AsyncHTTPClient, HTTPRequest +from jinja2 import ChoiceLoader +from jinja2 import FunctionLoader from tornado import gen from tornado import ioloop -from tornado.web import HTTPError, RequestHandler +from tornado.httpclient import AsyncHTTPClient +from tornado.httpclient import HTTPRequest +from tornado.web import HTTPError +from tornado.web import RequestHandler try: import notebook @@ -60,7 +61,9 @@ class HubAuthenticatedHandler(HubOAuthenticated): @property def allow_admin(self): - return self.settings.get('admin_access', os.getenv('JUPYTERHUB_ADMIN_ACCESS') or False) + return self.settings.get( + 'admin_access', os.getenv('JUPYTERHUB_ADMIN_ACCESS') or False + ) @property def hub_auth(self): @@ -68,17 +71,18 @@ def hub_auth(self): @property def hub_users(self): - return { self.settings['user'] } + return {self.settings['user']} @property def hub_groups(self): if self.settings['group']: - return { self.settings['group'] } + return {self.settings['group']} return set() class JupyterHubLoginHandler(LoginHandler): """LoginHandler that hooks up Hub authentication""" + @staticmethod def login_available(settings): return True @@ -113,12 +117,14 @@ class JupyterHubLogoutHandler(LogoutHandler): def get(self): self.settings['hub_auth'].clear_cookie(self) self.redirect( - self.settings['hub_host'] + - url_path_join(self.settings['hub_prefix'], 'logout')) + self.settings['hub_host'] + + url_path_join(self.settings['hub_prefix'], 'logout') + ) class OAuthCallbackHandler(HubOAuthCallbackHandler, IPythonHandler): """Mixin IPythonHandler to get the right error pages, etc.""" + @property def hub_auth(self): return self.settings['hub_auth'] @@ -126,23 +132,26 @@ def hub_auth(self): # register new hub related command-line aliases aliases = dict(notebook_aliases) -aliases.update({ - 'user': 'SingleUserNotebookApp.user', - 'group': 'SingleUserNotebookApp.group', - 'cookie-name': 'HubAuth.cookie_name', - 'hub-prefix': 'SingleUserNotebookApp.hub_prefix', - 'hub-host': 'SingleUserNotebookApp.hub_host', - 'hub-api-url': 'SingleUserNotebookApp.hub_api_url', - 'base-url': 'SingleUserNotebookApp.base_url', -}) +aliases.update( + { + 'user': 'SingleUserNotebookApp.user', + 'group': 'SingleUserNotebookApp.group', + 'cookie-name': 'HubAuth.cookie_name', + 'hub-prefix': 'SingleUserNotebookApp.hub_prefix', + 'hub-host': 'SingleUserNotebookApp.hub_host', + 'hub-api-url': 'SingleUserNotebookApp.hub_api_url', + 'base-url': 'SingleUserNotebookApp.base_url', + } +) flags = dict(notebook_flags) -flags.update({ - 'disable-user-config': ({ - 'SingleUserNotebookApp': { - 'disable_user_config': True - } - }, "Disable user-controlled configuration of the notebook server.") -}) +flags.update( + { + 'disable-user-config': ( + {'SingleUserNotebookApp': {'disable_user_config': True}}, + "Disable user-controlled configuration of the notebook server.", + ) + } +) page_template = """ {% extends "templates/page.html" %} @@ -209,11 +218,14 @@ def _exclude_home(path_list): class SingleUserNotebookApp(NotebookApp): """A Subclass of the regular NotebookApp that is aware of the parent multiuser context.""" - description = dedent(""" + + description = dedent( + """ Single-user server for JupyterHub. Extends the Jupyter Notebook server. Meant to be invoked by JupyterHub Spawners, and not directly. - """) + """ + ) examples = "" subcommands = {} @@ -229,6 +241,7 @@ class SingleUserNotebookApp(NotebookApp): # ensures that each spawn clears any cookies from previous session, # triggering OAuth again cookie_secret = Bytes() + def _cookie_secret_default(self): return os.urandom(32) @@ -279,7 +292,7 @@ def _hub_api_url_default(self): def _base_url_default(self): return os.environ.get('JUPYTERHUB_SERVICE_PREFIX') or '/' - #Note: this may be removed if notebook module is >= 5.0.0b1 + # Note: this may be removed if notebook module is >= 5.0.0b1 @validate('base_url') def _validate_base_url(self, proposal): """ensure base_url starts and ends with /""" @@ -320,14 +333,17 @@ def _ip_default(self): trust_xheaders = True login_handler_class = JupyterHubLoginHandler logout_handler_class = JupyterHubLogoutHandler - port_retries = 0 # disable port-retries, since the Spawner will tell us what port to use + port_retries = ( + 0 + ) # disable port-retries, since the Spawner will tell us what port to use - disable_user_config = Bool(False, + disable_user_config = Bool( + False, help="""Disable user configuration of single-user server. Prevents user-writable files that normally configure the single-user server from being loaded, ensuring admins have full control of configuration. - """ + """, ).tag(config=True) @validate('notebook_dir') @@ -394,22 +410,15 @@ def _validate_static_custom_path(self, proposal): # create dynamic default http client, # configured with any relevant ssl config hub_http_client = Any() + @default('hub_http_client') def _default_client(self): ssl_context = make_ssl_context( - self.keyfile, - self.certfile, - cafile=self.client_ca, - ) - AsyncHTTPClient.configure( - None, - defaults={ - "ssl_options": ssl_context, - }, + self.keyfile, self.certfile, cafile=self.client_ca ) + AsyncHTTPClient.configure(None, defaults={"ssl_options": ssl_context}) return AsyncHTTPClient() - async def check_hub_version(self): """Test a connection to my Hub @@ -418,13 +427,17 @@ async def check_hub_version(self): """ client = self.hub_http_client RETRIES = 5 - for i in range(1, RETRIES+1): + for i in range(1, RETRIES + 1): try: resp = await client.fetch(self.hub_api_url) except Exception: - self.log.exception("Failed to connect to my Hub at %s (attempt %i/%i). Is it running?", - self.hub_api_url, i, RETRIES) - await gen.sleep(min(2**i, 16)) + self.log.exception( + "Failed to connect to my Hub at %s (attempt %i/%i). Is it running?", + self.hub_api_url, + i, + RETRIES, + ) + await gen.sleep(min(2 ** i, 16)) else: break else: @@ -434,14 +447,15 @@ async def check_hub_version(self): _check_version(hub_version, __version__, self.log) server_name = Unicode() + @default('server_name') def _server_name_default(self): return os.environ.get('JUPYTERHUB_SERVER_NAME', '') hub_activity_url = Unicode( - config=True, - help="URL for sending JupyterHub activity updates", + config=True, help="URL for sending JupyterHub activity updates" ) + @default('hub_activity_url') def _default_activity_url(self): return os.environ.get('JUPYTERHUB_ACTIVITY_URL', '') @@ -452,8 +466,9 @@ def _default_activity_url(self): help=""" Interval (in seconds) on which to update the Hub with our latest activity. - """ + """, ) + @default('hub_activity_interval') def _default_activity_interval(self): env_value = os.environ.get('JUPYTERHUB_ACTIVITY_INTERVAL') @@ -478,10 +493,7 @@ async def notify_activity(self): self.log.warning("last activity is using naïve timestamps") last_activity = last_activity.replace(tzinfo=timezone.utc) - if ( - self._last_activity_sent - and last_activity < self._last_activity_sent - ): + if self._last_activity_sent and last_activity < self._last_activity_sent: self.log.debug("No activity since %s", self._last_activity_sent) return @@ -496,14 +508,14 @@ async def notify(): "Authorization": "token {}".format(self.hub_auth.api_token), "Content-Type": "application/json", }, - body=json.dumps({ - 'servers': { - self.server_name: { - 'last_activity': last_activity_timestamp, + body=json.dumps( + { + 'servers': { + self.server_name: {'last_activity': last_activity_timestamp} }, - }, - 'last_activity': last_activity_timestamp, - }) + 'last_activity': last_activity_timestamp, + } + ), ) try: await client.fetch(req) @@ -526,8 +538,8 @@ async def keep_activity_updated(self): if not self.hub_activity_url or not self.hub_activity_interval: self.log.warning("Activity events disabled") return - self.log.info("Updating Hub with activity every %s seconds", - self.hub_activity_interval + self.log.info( + "Updating Hub with activity every %s seconds", self.hub_activity_interval ) while True: try: @@ -561,7 +573,9 @@ def init_hub_auth(self): api_token = os.environ['JUPYTERHUB_API_TOKEN'] if not api_token: - self.exit("JUPYTERHUB_API_TOKEN env is required to run jupyterhub-singleuser. Did you launch it manually?") + self.exit( + "JUPYTERHUB_API_TOKEN env is required to run jupyterhub-singleuser. Did you launch it manually?" + ) self.hub_auth = HubOAuth( parent=self, api_token=api_token, @@ -586,30 +600,33 @@ def init_webapp(self): s['hub_prefix'] = self.hub_prefix s['hub_host'] = self.hub_host s['hub_auth'] = self.hub_auth - csp_report_uri = s['csp_report_uri'] = self.hub_host + url_path_join(self.hub_prefix, 'security/csp-report') + csp_report_uri = s['csp_report_uri'] = self.hub_host + url_path_join( + self.hub_prefix, 'security/csp-report' + ) headers = s.setdefault('headers', {}) headers['X-JupyterHub-Version'] = __version__ # set CSP header directly to workaround bugs in jupyter/notebook 5.0 - headers.setdefault('Content-Security-Policy', ';'.join([ - "frame-ancestors 'self'", - "report-uri " + csp_report_uri, - ])) + headers.setdefault( + 'Content-Security-Policy', + ';'.join(["frame-ancestors 'self'", "report-uri " + csp_report_uri]), + ) super(SingleUserNotebookApp, self).init_webapp() # add OAuth callback - self.web_app.add_handlers(r".*$", [( - urlparse(self.hub_auth.oauth_redirect_uri).path, - OAuthCallbackHandler - )]) - + self.web_app.add_handlers( + r".*$", + [(urlparse(self.hub_auth.oauth_redirect_uri).path, OAuthCallbackHandler)], + ) + # apply X-JupyterHub-Version to *all* request handlers (even redirects) self.patch_default_headers() self.patch_templates() - + def patch_default_headers(self): if hasattr(RequestHandler, '_orig_set_default_headers'): return RequestHandler._orig_set_default_headers = RequestHandler.set_default_headers + def set_jupyterhub_header(self): self._orig_set_default_headers() self.set_header('X-JupyterHub-Version', __version__) @@ -619,13 +636,16 @@ def set_jupyterhub_header(self): def patch_templates(self): """Patch page templates to add Hub-related buttons""" - self.jinja_template_vars['logo_url'] = self.hub_host + url_path_join(self.hub_prefix, 'logo') + self.jinja_template_vars['logo_url'] = self.hub_host + url_path_join( + self.hub_prefix, 'logo' + ) self.jinja_template_vars['hub_host'] = self.hub_host self.jinja_template_vars['hub_prefix'] = self.hub_prefix env = self.web_app.settings['jinja2_env'] - env.globals['hub_control_panel_url'] = \ - self.hub_host + url_path_join(self.hub_prefix, 'home') + env.globals['hub_control_panel_url'] = self.hub_host + url_path_join( + self.hub_prefix, 'home' + ) # patch jinja env loading to modify page template def get_page(name): @@ -633,10 +653,7 @@ def get_page(name): return page_template orig_loader = env.loader - env.loader = ChoiceLoader([ - FunctionLoader(get_page), - orig_loader, - ]) + env.loader = ChoiceLoader([FunctionLoader(get_page), orig_loader]) def main(argv=None): diff --git a/jupyterhub/spawner.py b/jupyterhub/spawner.py --- a/jupyterhub/spawner.py +++ b/jupyterhub/spawner.py @@ -1,10 +1,8 @@ """ Contains base Spawner class & default implementation """ - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import ast import asyncio import errno @@ -18,22 +16,35 @@ from subprocess import Popen from tempfile import mkdtemp -# FIXME: remove when we drop Python 3.5 support -from async_generator import async_generator, yield_ - +from async_generator import async_generator +from async_generator import yield_ from sqlalchemy import inspect - from tornado.ioloop import PeriodicCallback - +from traitlets import Any +from traitlets import Bool +from traitlets import default +from traitlets import Dict +from traitlets import Float +from traitlets import Instance +from traitlets import Integer +from traitlets import List +from traitlets import observe +from traitlets import Unicode +from traitlets import Union +from traitlets import validate from traitlets.config import LoggingConfigurable -from traitlets import ( - Any, Bool, Dict, Instance, Integer, Float, List, Unicode, Union, - default, observe, validate, -) from .objects import Server -from .traitlets import Command, ByteSpecification, Callable -from .utils import iterate_until, maybe_future, random_port, url_path_join, exponential_backoff +from .traitlets import ByteSpecification +from .traitlets import Callable +from .traitlets import Command +from .utils import exponential_backoff +from .utils import iterate_until +from .utils import maybe_future +from .utils import random_port +from .utils import url_path_join + +# FIXME: remove when we drop Python 3.5 support def _quote_safe(s): @@ -53,6 +64,7 @@ def _quote_safe(s): # to avoid getting interpreted by traitlets return repr(s) + class Spawner(LoggingConfigurable): """Base class for spawning single-user notebook servers. @@ -141,13 +153,17 @@ def __init_subclass__(cls, **kwargs): super().__init_subclass__() missing = [] - for attr in ('start','stop', 'poll'): + for attr in ('start', 'stop', 'poll'): if getattr(Spawner, attr) is getattr(cls, attr): missing.append(attr) if missing: - raise NotImplementedError("class `{}` needs to redefine the `start`," - "`stop` and `poll` methods. `{}` not redefined.".format(cls.__name__, '`, `'.join(missing))) + raise NotImplementedError( + "class `{}` needs to redefine the `start`," + "`stop` and `poll` methods. `{}` not redefined.".format( + cls.__name__, '`, `'.join(missing) + ) + ) proxy_spec = Unicode() @@ -180,6 +196,7 @@ def name(self): if self.orm_spawner: return self.orm_spawner.name return '' + hub = Any() authenticator = Any() internal_ssl = Bool(False) @@ -191,7 +208,8 @@ def name(self): oauth_client_id = Unicode() handler = Any() - will_resume = Bool(False, + will_resume = Bool( + False, help="""Whether the Spawner will resume on next start @@ -199,18 +217,20 @@ def name(self): If True, an existing Spawner will resume instead of starting anew (e.g. resuming a Docker container), and API tokens in use when the Spawner stops will not be deleted. - """ + """, ) - ip = Unicode('', + ip = Unicode( + '', help=""" The IP address (or hostname) the single-user server should listen on. The JupyterHub proxy implementation should be able to send packets to this interface. - """ + """, ).tag(config=True) - port = Integer(0, + port = Integer( + 0, help=""" The port for single-user servers to listen on. @@ -221,7 +241,7 @@ def name(self): e.g. in containers. New in version 0.7. - """ + """, ).tag(config=True) consecutive_failure_limit = Integer( @@ -237,47 +257,48 @@ def name(self): """, ).tag(config=True) - start_timeout = Integer(60, + start_timeout = Integer( + 60, help=""" Timeout (in seconds) before giving up on starting of single-user server. This is the timeout for start to return, not the timeout for the server to respond. Callers of spawner.start will assume that startup has failed if it takes longer than this. start should return when the server process is started and its location is known. - """ + """, ).tag(config=True) - http_timeout = Integer(30, + http_timeout = Integer( + 30, help=""" Timeout (in seconds) before giving up on a spawned HTTP server Once a server has successfully been spawned, this is the amount of time we wait before assuming that the server is unable to accept connections. - """ + """, ).tag(config=True) - poll_interval = Integer(30, + poll_interval = Integer( + 30, help=""" Interval (in seconds) on which to poll the spawner for single-user server's status. At every poll interval, each spawner's `.poll` method is called, which checks if the single-user server is still running. If it isn't running, then JupyterHub modifies its own state accordingly and removes appropriate routes from the configurable proxy. - """ + """, ).tag(config=True) _callbacks = List() _poll_callback = Any() - debug = Bool(False, - help="Enable debug-logging of the single-user server" - ).tag(config=True) + debug = Bool(False, help="Enable debug-logging of the single-user server").tag( + config=True + ) - options_form = Union([ - Unicode(), - Callable() - ], + options_form = Union( + [Unicode(), Callable()], help=""" An HTML form for options a user can specify on launching their server. @@ -303,7 +324,8 @@ def name(self): be called asynchronously if it returns a future, rather than a str. Note that the interface of the spawner class is not deemed stable across versions, so using this functionality might cause your JupyterHub upgrades to break. - """).tag(config=True) + """, + ).tag(config=True) async def get_options_form(self): """Get the options form @@ -341,30 +363,34 @@ def options_from_form(self, form_data): These user options are usually provided by the `options_form` displayed to the user when they start their server. - """) - - env_keep = List([ - 'PATH', - 'PYTHONPATH', - 'CONDA_ROOT', - 'CONDA_DEFAULT_ENV', - 'VIRTUAL_ENV', - 'LANG', - 'LC_ALL', - ], + """ + ) + + env_keep = List( + [ + 'PATH', + 'PYTHONPATH', + 'CONDA_ROOT', + 'CONDA_DEFAULT_ENV', + 'VIRTUAL_ENV', + 'LANG', + 'LC_ALL', + ], help=""" Whitelist of environment variables for the single-user server to inherit from the JupyterHub process. This whitelist is used to ensure that sensitive information in the JupyterHub process's environment (such as `CONFIGPROXY_AUTH_TOKEN`) is not passed to the single-user server's process. - """ + """, ).tag(config=True) - env = Dict(help="""Deprecated: use Spawner.get_env or Spawner.environment + env = Dict( + help="""Deprecated: use Spawner.get_env or Spawner.environment - extend Spawner.get_env for adding required env in Spawner subclasses - Spawner.environment for config-specified env - """) + """ + ) environment = Dict( help=""" @@ -386,7 +412,8 @@ def options_from_form(self, form_data): """ ).tag(config=True) - cmd = Command(['jupyterhub-singleuser'], + cmd = Command( + ['jupyterhub-singleuser'], allow_none=True, help=""" The command used for starting the single-user server. @@ -399,16 +426,17 @@ def options_from_form(self, form_data): Some spawners allow shell-style expansion here, allowing you to use environment variables. Most, including the default, do not. Consult the documentation for your spawner to verify! - """ + """, ).tag(config=True) - args = List(Unicode(), + args = List( + Unicode(), help=""" Extra arguments to be passed to the single-user server. Some spawners allow shell-style expansion here, allowing you to use environment variables here. Most, including the default, do not. Consult the documentation for your spawner to verify! - """ + """, ).tag(config=True) notebook_dir = Unicode( @@ -446,14 +474,16 @@ def options_from_form(self, form_data): def _deprecate_percent_u(self, proposal): v = proposal['value'] if '%U' in v: - self.log.warning("%%U for username in %s is deprecated in JupyterHub 0.7, use {username}", + self.log.warning( + "%%U for username in %s is deprecated in JupyterHub 0.7, use {username}", proposal['trait'].name, ) v = v.replace('%U', '{username}') self.log.warning("Converting %r to %r", proposal['value'], v) return v - disable_user_config = Bool(False, + disable_user_config = Bool( + False, help=""" Disable per-user configuration of single-user servers. @@ -462,10 +492,11 @@ def _deprecate_percent_u(self, proposal): Note: a user could circumvent this if the user modifies their Python environment, such as when they have their own conda environments / virtualenvs / containers. - """ + """, ).tag(config=True) - mem_limit = ByteSpecification(None, + mem_limit = ByteSpecification( + None, help=""" Maximum number of bytes a single-user notebook server is allowed to use. @@ -484,10 +515,11 @@ def _deprecate_percent_u(self, proposal): for the limit to work.** The default spawner, `LocalProcessSpawner`, does **not** implement this support. A custom spawner **must** add support for this setting for it to be enforced. - """ + """, ).tag(config=True) - cpu_limit = Float(None, + cpu_limit = Float( + None, allow_none=True, help=""" Maximum number of cpu-cores a single-user notebook server is allowed to use. @@ -503,10 +535,11 @@ def _deprecate_percent_u(self, proposal): for the limit to work.** The default spawner, `LocalProcessSpawner`, does **not** implement this support. A custom spawner **must** add support for this setting for it to be enforced. - """ + """, ).tag(config=True) - mem_guarantee = ByteSpecification(None, + mem_guarantee = ByteSpecification( + None, help=""" Minimum number of bytes a single-user notebook server is guaranteed to have available. @@ -520,10 +553,11 @@ def _deprecate_percent_u(self, proposal): for the limit to work.** The default spawner, `LocalProcessSpawner`, does **not** implement this support. A custom spawner **must** add support for this setting for it to be enforced. - """ + """, ).tag(config=True) - cpu_guarantee = Float(None, + cpu_guarantee = Float( + None, allow_none=True, help=""" Minimum number of cpu-cores a single-user notebook server is guaranteed to have available. @@ -535,7 +569,7 @@ def _deprecate_percent_u(self, proposal): for the limit to work.** The default spawner, `LocalProcessSpawner`, does **not** implement this support. A custom spawner **must** add support for this setting for it to be enforced. - """ + """, ).tag(config=True) pre_spawn_hook = Any( @@ -621,7 +655,9 @@ def get_env(self): """ env = {} if self.env: - warnings.warn("Spawner.env is deprecated, found %s" % self.env, DeprecationWarning) + warnings.warn( + "Spawner.env is deprecated, found %s" % self.env, DeprecationWarning + ) env.update(self.env) for key in self.env_keep: @@ -648,8 +684,9 @@ def get_env(self): if self.cookie_options: env['JUPYTERHUB_COOKIE_OPTIONS'] = json.dumps(self.cookie_options) env['JUPYTERHUB_HOST'] = self.hub.public_host - env['JUPYTERHUB_OAUTH_CALLBACK_URL'] = \ - url_path_join(self.user.url, self.name, 'oauth_callback') + env['JUPYTERHUB_OAUTH_CALLBACK_URL'] = url_path_join( + self.user.url, self.name, 'oauth_callback' + ) # Info previously passed on args env['JUPYTERHUB_USER'] = self.user.name @@ -749,7 +786,7 @@ def format_string(self, s): May be set in config if all spawners should have the same value(s), or set at runtime by Spawner that know their names. - """ + """, ) @default('ssl_alt_names') @@ -793,6 +830,7 @@ async def create_certs(self): to the host by either IP or DNS name (note the `default_names` below). """ from certipy import Certipy + default_names = ["DNS:localhost", "IP:127.0.0.1"] alt_names = [] alt_names.extend(self.ssl_alt_names) @@ -800,10 +838,7 @@ async def create_certs(self): if self.ssl_alt_names_include_local: alt_names = default_names + alt_names - self.log.info("Creating certs for %s: %s", - self._log_name, - ';'.join(alt_names), - ) + self.log.info("Creating certs for %s: %s", self._log_name, ';'.join(alt_names)) common_name = self.user.name or 'service' certipy = Certipy(store_dir=self.internal_certs_location) @@ -812,7 +847,7 @@ async def create_certs(self): 'user-' + common_name, notebook_component, alt_names=alt_names, - overwrite=True + overwrite=True, ) paths = { "keyfile": notebook_key_pair['files']['key'], @@ -862,7 +897,9 @@ def get_args(self): if self.port: args.append('--port=%i' % self.port) elif self.server and self.server.port: - self.log.warning("Setting port from user.server is deprecated as of JupyterHub 0.7.") + self.log.warning( + "Setting port from user.server is deprecated as of JupyterHub 0.7." + ) args.append('--port=%i' % self.server.port) if self.notebook_dir: @@ -903,13 +940,12 @@ async def _generate_progress(self): This method is always an async generator and will always yield at least one event. """ if not self._spawn_pending: - self.log.warning("Spawn not pending, can't generate progress for %s", self._log_name) + self.log.warning( + "Spawn not pending, can't generate progress for %s", self._log_name + ) return - await yield_({ - "progress": 0, - "message": "Server requested", - }) + await yield_({"progress": 0, "message": "Server requested"}) from async_generator import aclosing async with aclosing(self.progress()) as progress: @@ -940,10 +976,7 @@ async def progress(self): .. versionadded:: 0.9 """ - await yield_({ - "progress": 50, - "message": "Spawning server...", - }) + await yield_({"progress": 50, "message": "Spawning server..."}) async def start(self): """Start the single-user server @@ -954,7 +987,9 @@ async def start(self): .. versionchanged:: 0.7 Return ip, port instead of setting on self.user.server directly. """ - raise NotImplementedError("Override in subclass. Must be a Tornado gen.coroutine.") + raise NotImplementedError( + "Override in subclass. Must be a Tornado gen.coroutine." + ) async def stop(self, now=False): """Stop the single-user server @@ -967,7 +1002,9 @@ async def stop(self, now=False): Must be a coroutine. """ - raise NotImplementedError("Override in subclass. Must be a Tornado gen.coroutine.") + raise NotImplementedError( + "Override in subclass. Must be a Tornado gen.coroutine." + ) async def poll(self): """Check if the single-user process is running @@ -993,7 +1030,9 @@ async def poll(self): process has not yet completed. """ - raise NotImplementedError("Override in subclass. Must be a Tornado gen.coroutine.") + raise NotImplementedError( + "Override in subclass. Must be a Tornado gen.coroutine." + ) def add_poll_callback(self, callback, *args, **kwargs): """Add a callback to fire when the single-user server stops""" @@ -1023,8 +1062,7 @@ def start_polling(self): self.stop_polling() self._poll_callback = PeriodicCallback( - self.poll_and_notify, - 1e3 * self.poll_interval + self.poll_and_notify, 1e3 * self.poll_interval ) self._poll_callback.start() @@ -1048,8 +1086,10 @@ async def poll_and_notify(self): return status death_interval = Float(0.1) + async def wait_for_death(self, timeout=10): """Wait for the single-user server to die, up to timeout seconds""" + async def _wait_for_death(): status = await self.poll() return status is not None @@ -1093,11 +1133,12 @@ def set_user_setuid(username, chdir=True): """ import grp import pwd + user = pwd.getpwnam(username) uid = user.pw_uid gid = user.pw_gid home = user.pw_dir - gids = [ g.gr_gid for g in grp.getgrall() if username in g.gr_mem ] + gids = [g.gr_gid for g in grp.getgrall() if username in g.gr_mem] def preexec(): """Set uid/gid of current process @@ -1132,29 +1173,32 @@ class LocalProcessSpawner(Spawner): Note: This spawner does not implement CPU / memory guarantees and limits. """ - interrupt_timeout = Integer(10, + interrupt_timeout = Integer( + 10, help=""" Seconds to wait for single-user server process to halt after SIGINT. If the process has not exited cleanly after this many seconds, a SIGTERM is sent. - """ + """, ).tag(config=True) - term_timeout = Integer(5, + term_timeout = Integer( + 5, help=""" Seconds to wait for single-user server process to halt after SIGTERM. If the process does not exit cleanly after this many seconds of SIGTERM, a SIGKILL is sent. - """ + """, ).tag(config=True) - kill_timeout = Integer(5, + kill_timeout = Integer( + 5, help=""" Seconds to wait for process to halt after SIGKILL before giving up. If the process does not exit cleanly after this many seconds of SIGKILL, it becomes a zombie process. The hub process will log a warning and then give up. - """ + """, ).tag(config=True) popen_kwargs = Dict( @@ -1168,7 +1212,8 @@ class LocalProcessSpawner(Spawner): """ ).tag(config=True) - shell_cmd = Command(minlen=0, + shell_cmd = Command( + minlen=0, help="""Specify a shell command to launch. The single-user command will be appended to this list, @@ -1185,20 +1230,23 @@ class LocalProcessSpawner(Spawner): Using shell_cmd gives users control over PATH, etc., which could change what the jupyterhub-singleuser launch command does. Only use this for trusted users. - """ + """, ).tag(config=True) - proc = Instance(Popen, + proc = Instance( + Popen, allow_none=True, help=""" The process representing the single-user server process spawned for current user. Is None if no process has been spawned yet. - """) - pid = Integer(0, + """, + ) + pid = Integer( + 0, help=""" The process id (pid) of the single-user server process spawned for current user. - """ + """, ) def make_preexec_fn(self, name): @@ -1236,6 +1284,7 @@ def clear_state(self): def user_env(self, env): """Augment environment of spawned process with user specific env variables.""" import pwd + env['USER'] = self.user.name home = pwd.getpwnam(self.user.name).pw_dir shell = pwd.getpwnam(self.user.name).pw_shell @@ -1267,6 +1316,7 @@ async def move_certs(self, paths): and make them readable by the user. """ import pwd + key = paths['keyfile'] cert = paths['certfile'] ca = paths['cafile'] @@ -1324,8 +1374,10 @@ async def start(self): except PermissionError: # use which to get abspath script = shutil.which(cmd[0]) or cmd[0] - self.log.error("Permission denied trying to run %r. Does %s have access to this file?", - script, self.user.name, + self.log.error( + "Permission denied trying to run %r. Does %s have access to this file?", + script, + self.user.name, ) raise @@ -1445,24 +1497,25 @@ class SimpleLocalProcessSpawner(LocalProcessSpawner): help=""" Template to expand to set the user home. {username} is expanded to the jupyterhub username. - """ + """, ) home_dir = Unicode(help="The home directory for the user") + @default('home_dir') def _default_home_dir(self): - return self.home_dir_template.format( - username=self.user.name, - ) + return self.home_dir_template.format(username=self.user.name) def make_preexec_fn(self, name): home = self.home_dir + def preexec(): try: os.makedirs(home, 0o755, exist_ok=True) os.chdir(home) except Exception as e: self.log.exception("Error in preexec for %s", name) + return preexec def user_env(self, env): @@ -1474,4 +1527,3 @@ def user_env(self, env): def move_certs(self, paths): """No-op for installing certs""" return paths - diff --git a/jupyterhub/traitlets.py b/jupyterhub/traitlets.py --- a/jupyterhub/traitlets.py +++ b/jupyterhub/traitlets.py @@ -3,9 +3,13 @@ """ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import entrypoints -from traitlets import List, Unicode, Integer, Type, TraitType, TraitError +from traitlets import Integer +from traitlets import List +from traitlets import TraitError +from traitlets import TraitType +from traitlets import Type +from traitlets import Unicode class URLPrefix(Unicode): @@ -22,6 +26,7 @@ class Command(List): """Traitlet for a command that should be a list of strings, but allows it to be specified as a single string. """ + def __init__(self, default_value=None, **kwargs): kwargs.setdefault('minlen', 1) if isinstance(default_value, str): @@ -69,10 +74,18 @@ def validate(self, obj, value): try: num = float(value[:-1]) except ValueError: - raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value)) + raise TraitError( + '{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format( + val=value + ) + ) suffix = value[-1] if suffix not in self.UNIT_SUFFIXES: - raise TraitError('{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format(val=value)) + raise TraitError( + '{val} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'.format( + val=value + ) + ) else: return int(float(num) * self.UNIT_SUFFIXES[suffix]) @@ -89,7 +102,7 @@ class Callable(TraitType): def validate(self, obj, value): if callable(value): - return value + return value else: self.error(obj, value) @@ -113,7 +126,11 @@ def help(self): chunks = [self._original_help] chunks.append("Currently installed: ") for key, entry_point in self.load_entry_points().items(): - chunks.append(" - {}: {}.{}".format(key, entry_point.module_name, entry_point.object_name)) + chunks.append( + " - {}: {}.{}".format( + key, entry_point.module_name, entry_point.object_name + ) + ) return '\n'.join(chunks) @help.setter diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -1,31 +1,40 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - -from collections import defaultdict -from datetime import datetime, timedelta -from urllib.parse import quote, urlparse import warnings +from collections import defaultdict +from datetime import datetime +from datetime import timedelta +from urllib.parse import quote +from urllib.parse import urlparse from sqlalchemy import inspect from tornado import gen +from tornado import web from tornado.httputil import urlencode from tornado.log import app_log -from tornado import web - -from .utils import maybe_future, url_path_join, make_ssl_context from . import orm -from ._version import _check_version, __version__ +from ._version import __version__ +from ._version import _check_version +from .crypto import CryptKeeper +from .crypto import decrypt +from .crypto import encrypt +from .crypto import EncryptionUnavailable +from .crypto import InvalidToken +from .metrics import TOTAL_USERS from .objects import Server from .spawner import LocalProcessSpawner -from .crypto import encrypt, decrypt, CryptKeeper, EncryptionUnavailable, InvalidToken -from .metrics import TOTAL_USERS +from .utils import make_ssl_context +from .utils import maybe_future +from .utils import url_path_join + class UserDict(dict): """Like defaultdict, but for users Getting by a user id OR an orm.User instance returns a User wrapper around the orm user. """ + def __init__(self, db_factory, settings): self.db_factory = db_factory self.settings = settings @@ -105,7 +114,7 @@ def count_active_users(self): Returns dict with counts of active/pending/ready servers """ - counts = defaultdict(lambda : 0) + counts = defaultdict(lambda: 0) for user in self.values(): for spawner in user.spawners.values(): pending = spawner.pending @@ -145,11 +154,12 @@ def __init__(self, orm_user, settings=None, db=None): self.settings = settings or {} self.orm_user = orm_user - self.allow_named_servers = self.settings.get('allow_named_servers', False) - self.base_url = self.prefix = url_path_join( - self.settings.get('base_url', '/'), 'user', self.escaped_name) + '/' + self.base_url = self.prefix = ( + url_path_join(self.settings.get('base_url', '/'), 'user', self.escaped_name) + + '/' + ) self.spawners = _SpawnerDict(self._new_spawner) @@ -177,8 +187,10 @@ async def get_auth_state(self): try: auth_state = await decrypt(encrypted) except (ValueError, InvalidToken, EncryptionUnavailable) as e: - self.log.warning("Failed to retrieve encrypted auth_state for %s because %s", - self.name, e, + self.log.warning( + "Failed to retrieve encrypted auth_state for %s because %s", + self.name, + e, ) return # loading auth_state @@ -188,7 +200,6 @@ async def get_auth_state(self): await self.save_auth_state(auth_state) return auth_state - def all_spawners(self, include_default=True): """Generator yielding all my spawners @@ -247,17 +258,15 @@ def _new_spawner(self, server_name, spawner_class=None, **kwargs): proxy_spec=url_path_join(self.proxy_spec, server_name, '/'), db=self.db, oauth_client_id=client_id, - cookie_options = self.settings.get('cookie_options', {}), + cookie_options=self.settings.get('cookie_options', {}), trusted_alt_names=trusted_alt_names, ) if self.settings.get('internal_ssl'): ssl_kwargs = dict( internal_ssl=self.settings.get('internal_ssl'), - internal_trust_bundles=self.settings.get( - 'internal_trust_bundles'), - internal_certs_location=self.settings.get( - 'internal_certs_location'), + internal_trust_bundles=self.settings.get('internal_trust_bundles'), + internal_certs_location=self.settings.get('internal_certs_location'), ) spawn_kwargs.update(ssl_kwargs) @@ -308,14 +317,16 @@ def active(self): @property def spawn_pending(self): - warnings.warn("User.spawn_pending is deprecated in JupyterHub 0.8. Use Spawner.pending", + warnings.warn( + "User.spawn_pending is deprecated in JupyterHub 0.8. Use Spawner.pending", DeprecationWarning, ) return self.spawner.pending == 'spawn' @property def stop_pending(self): - warnings.warn("User.stop_pending is deprecated in JupyterHub 0.8. Use Spawner.pending", + warnings.warn( + "User.stop_pending is deprecated in JupyterHub 0.8. Use Spawner.pending", DeprecationWarning, ) return self.spawner.pending == 'stop' @@ -341,7 +352,9 @@ def proxy_spec(self): def domain(self): """Get the domain for my server.""" # use underscore as escape char for domains - return quote(self.name).replace('%', '_').lower() + '.' + self.settings['domain'] + return ( + quote(self.name).replace('%', '_').lower() + '.' + self.settings['domain'] + ) @property def host(self): @@ -360,10 +373,7 @@ def url(self): Full name.domain/path if using subdomains, otherwise just my /base/url """ if self.settings.get('subdomain_host'): - return '{host}{path}'.format( - host=self.host, - path=self.base_url, - ) + return '{host}{path}'.format(host=self.host, path=self.base_url) else: return self.base_url @@ -417,8 +427,7 @@ async def refresh_auth(self, handler): # if we got to here, auth is expired and couldn't be refreshed self.log.error( - "Auth expired for %s; cannot spawn until they login again", - self.name, + "Auth expired for %s; cannot spawn until they login again", self.name ) # auth expired, cannot spawn without a fresh login # it's the current user *and* spawn via GET, trigger login redirect @@ -433,8 +442,9 @@ async def refresh_auth(self, handler): else: # spawn via POST or on behalf of another user. # nothing we can do here but fail - raise web.HTTPError(400, "{}'s authentication has expired".format(self.name)) - + raise web.HTTPError( + 400, "{}'s authentication has expired".format(self.name) + ) async def spawn(self, server_name='', options=None, handler=None): """Start the user's spawner @@ -456,15 +466,12 @@ async def spawn(self, server_name='', options=None, handler=None): base_url = url_path_join(self.base_url, server_name) + '/' - orm_server = orm.Server( - base_url=base_url, - ) + orm_server = orm.Server(base_url=base_url) db.add(orm_server) note = "Server at %s" % base_url api_token = self.new_api_token(note=note) db.commit() - spawner = self.spawners[server_name] spawner.server = server = Server(orm_server=orm_server) assert spawner.orm_spawner.server is orm_server @@ -487,9 +494,11 @@ async def spawn(self, server_name='', options=None, handler=None): # create a new OAuth client + secret on every launch # containers that resume will be updated below oauth_provider.add_client( - client_id, api_token, + client_id, + api_token, url_path_join(self.url, server_name, 'oauth_callback'), - description="Server at %s" % (url_path_join(self.base_url, server_name) + '/'), + description="Server at %s" + % (url_path_join(self.base_url, server_name) + '/'), ) db.commit() @@ -500,9 +509,9 @@ async def spawn(self, server_name='', options=None, handler=None): spawner._start_pending = True # update spawner start time, and activity for both spawner and user - self.last_activity = \ - spawner.orm_spawner.started = \ - spawner.orm_spawner.last_activity = datetime.utcnow() + self.last_activity = ( + spawner.orm_spawner.started + ) = spawner.orm_spawner.last_activity = datetime.utcnow() db.commit() # wait for spawner.start to return try: @@ -540,7 +549,9 @@ async def spawn(self, server_name='', options=None, handler=None): else: # prior to 0.7, spawners had to store this info in user.server themselves. # Handle < 0.7 behavior with a warning, assuming info was stored in db by the Spawner. - self.log.warning("DEPRECATION: Spawner.start should return a url or (ip, port) tuple in JupyterHub >= 0.9") + self.log.warning( + "DEPRECATION: Spawner.start should return a url or (ip, port) tuple in JupyterHub >= 0.9" + ) if spawner.api_token and spawner.api_token != api_token: # Spawner re-used an API token, discard the unused api_token orm_token = orm.APIToken.find(self.db, api_token) @@ -551,50 +562,63 @@ async def spawn(self, server_name='', options=None, handler=None): found = orm.APIToken.find(self.db, spawner.api_token) if found: if found.user is not self.orm_user: - self.log.error("%s's server is using %s's token! Revoking this token.", - self.name, (found.user or found.service).name) + self.log.error( + "%s's server is using %s's token! Revoking this token.", + self.name, + (found.user or found.service).name, + ) self.db.delete(found) self.db.commit() raise ValueError("Invalid token for %s!" % self.name) else: # Spawner.api_token has changed, but isn't in the db. # What happened? Maybe something unclean in a resumed container. - self.log.warning("%s's server specified its own API token that's not in the database", - self.name + self.log.warning( + "%s's server specified its own API token that's not in the database", + self.name, ) # use generated=False because we don't trust this token # to have been generated properly - self.new_api_token(spawner.api_token, + self.new_api_token( + spawner.api_token, generated=False, note="retrieved from spawner %s" % server_name, ) # update OAuth client secret with updated API token if oauth_provider: oauth_provider.add_client( - client_id, spawner.api_token, + client_id, + spawner.api_token, url_path_join(self.url, server_name, 'oauth_callback'), ) db.commit() except Exception as e: if isinstance(e, gen.TimeoutError): - self.log.warning("{user}'s server failed to start in {s} seconds, giving up".format( - user=self.name, s=spawner.start_timeout, - )) + self.log.warning( + "{user}'s server failed to start in {s} seconds, giving up".format( + user=self.name, s=spawner.start_timeout + ) + ) e.reason = 'timeout' self.settings['statsd'].incr('spawner.failure.timeout') else: - self.log.error("Unhandled error starting {user}'s server: {error}".format( - user=self.name, error=e, - )) + self.log.error( + "Unhandled error starting {user}'s server: {error}".format( + user=self.name, error=e + ) + ) self.settings['statsd'].incr('spawner.failure.error') e.reason = 'error' try: await self.stop(spawner.name) except Exception: - self.log.error("Failed to cleanup {user}'s server that failed to start".format( - user=self.name, - ), exc_info=True) + self.log.error( + "Failed to cleanup {user}'s server that failed to start".format( + user=self.name + ), + exc_info=True, + ) # raise original exception spawner._start_pending = False raise e @@ -624,9 +648,8 @@ async def _wait_up(self, spawner): ssl_context = make_ssl_context(key, cert, cafile=ca) try: resp = await server.wait_up( - http=True, - timeout=spawner.http_timeout, - ssl_context=ssl_context) + http=True, timeout=spawner.http_timeout, ssl_context=ssl_context + ) except Exception as e: if isinstance(e, TimeoutError): self.log.warning( @@ -641,16 +664,21 @@ async def _wait_up(self, spawner): self.settings['statsd'].incr('spawner.failure.http_timeout') else: e.reason = 'error' - self.log.error("Unhandled error waiting for {user}'s server to show up at {url}: {error}".format( - user=self.name, url=server.url, error=e, - )) + self.log.error( + "Unhandled error waiting for {user}'s server to show up at {url}: {error}".format( + user=self.name, url=server.url, error=e + ) + ) self.settings['statsd'].incr('spawner.failure.http_error') try: await self.stop(spawner.name) except Exception: - self.log.error("Failed to cleanup {user}'s server that failed to start".format( - user=self.name, - ), exc_info=True) + self.log.error( + "Failed to cleanup {user}'s server that failed to start".format( + user=self.name + ), + exc_info=True, + ) # raise original TimeoutError raise e else: @@ -700,10 +728,8 @@ async def stop(self, server_name=''): spawner.oauth_client_id, spawner.oauth_client_id.split('-', 1)[1], ) - for oauth_client in ( - self.db - .query(orm.OAuthClient) - .filter(orm.OAuthClient.identifier.in_(client_ids)) + for oauth_client in self.db.query(orm.OAuthClient).filter( + orm.OAuthClient.identifier.in_(client_ids) ): self.log.debug("Deleting oauth client %s", oauth_client.identifier) self.db.delete(oauth_client) @@ -718,15 +744,18 @@ async def stop(self, server_name=''): auth = spawner.authenticator try: if auth: - await maybe_future( - auth.post_spawn_stop(self, spawner) - ) + await maybe_future(auth.post_spawn_stop(self, spawner)) except Exception: - self.log.exception("Error in Authenticator.post_spawn_stop for %s", self) + self.log.exception( + "Error in Authenticator.post_spawn_stop for %s", self + ) spawner._stop_pending = False if not ( - spawner._spawn_future and - (not spawner._spawn_future.done() or spawner._spawn_future.exception()) + spawner._spawn_future + and ( + not spawner._spawn_future.done() + or spawner._spawn_future.exception() + ) ): # pop Spawner *unless* it's stopping due to an error # because some pages serve latest-spawn error messages diff --git a/jupyterhub/utils.py b/jupyterhub/utils.py --- a/jupyterhub/utils.py +++ b/jupyterhub/utils.py @@ -1,30 +1,35 @@ """Miscellaneous utilities""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import asyncio -from binascii import b2a_hex import concurrent.futures -from datetime import datetime, timezone -import random import errno import hashlib -from hmac import compare_digest import inspect import os +import random import socket +import ssl import sys import threading -import ssl import uuid import warnings +from binascii import b2a_hex +from datetime import datetime +from datetime import timezone +from hmac import compare_digest -from async_generator import aclosing, asynccontextmanager, async_generator, yield_ -from tornado import gen, ioloop, web -from tornado.platform.asyncio import to_asyncio_future -from tornado.httpclient import AsyncHTTPClient, HTTPError +from async_generator import aclosing +from async_generator import async_generator +from async_generator import asynccontextmanager +from async_generator import yield_ +from tornado import gen +from tornado import ioloop +from tornado import web +from tornado.httpclient import AsyncHTTPClient +from tornado.httpclient import HTTPError from tornado.log import app_log +from tornado.platform.asyncio import to_asyncio_future def random_port(): @@ -72,9 +77,7 @@ def can_connect(ip, port): return True -def make_ssl_context( - keyfile, certfile, cafile=None, - verify=True, check_hostname=True): +def make_ssl_context(keyfile, certfile, cafile=None, verify=True, check_hostname=True): """Setup context for starting an https server or making requests over ssl. """ if not keyfile or not certfile: @@ -87,14 +90,16 @@ def make_ssl_context( async def exponential_backoff( - pass_func, - fail_message, - start_wait=0.2, - scale_factor=2, - max_wait=5, - timeout=10, - timeout_tolerance=0.1, - *args, **kwargs): + pass_func, + fail_message, + start_wait=0.2, + scale_factor=2, + max_wait=5, + timeout=10, + timeout_tolerance=0.1, + *args, + **kwargs +): """ Exponentially backoff until `pass_func` is true. @@ -177,8 +182,10 @@ async def wait_for_server(ip, port, timeout=10): ip = '127.0.0.1' await exponential_backoff( lambda: can_connect(ip, port), - "Server at {ip}:{port} didn't respond in {timeout} seconds".format(ip=ip, port=port, timeout=timeout), - timeout=timeout + "Server at {ip}:{port} didn't respond in {timeout} seconds".format( + ip=ip, port=port, timeout=timeout + ), + timeout=timeout, ) @@ -192,6 +199,7 @@ async def wait_for_http_server(url, timeout=10, ssl_context=None): client = AsyncHTTPClient() if ssl_context: client.ssl_options = ssl_context + async def is_reachable(): try: r = await client.fetch(url, follow_redirects=False) @@ -203,18 +211,26 @@ async def is_reachable(): # we expect 599 for no connection, # but 502 or other proxy error is conceivable app_log.warning( - "Server at %s responded with error: %s", url, e.code) + "Server at %s responded with error: %s", url, e.code + ) else: app_log.debug("Server at %s responded with %s", url, e.code) return e.response except (OSError, socket.error) as e: - if e.errno not in {errno.ECONNABORTED, errno.ECONNREFUSED, errno.ECONNRESET}: + if e.errno not in { + errno.ECONNABORTED, + errno.ECONNREFUSED, + errno.ECONNRESET, + }: app_log.warning("Failed to connect to %s (%s)", url, e) return False + re = await exponential_backoff( is_reachable, - "Server at {url} didn't respond in {timeout} seconds".format(url=url, timeout=timeout), - timeout=timeout + "Server at {url} didn't respond in {timeout} seconds".format( + url=url, timeout=timeout + ), + timeout=timeout, ) return re @@ -226,10 +242,12 @@ def auth_decorator(check_auth): I heard you like decorators, so I put a decorator in your decorator, so you can decorate while you decorate. """ + def decorator(method): def decorated(self, *args, **kwargs): check_auth(self) return method(self, *args, **kwargs) + decorated.__name__ = method.__name__ decorated.__doc__ = method.__doc__ return decorated @@ -267,6 +285,7 @@ def admin_only(self): if user is None or not user.admin: raise web.HTTPError(403) + @auth_decorator def metrics_authentication(self): """Decorator for restricting access to metrics""" @@ -277,6 +296,7 @@ def metrics_authentication(self): # Token utilities + def new_token(*args, **kwargs): """Generator for new random tokens @@ -313,7 +333,9 @@ def compare_token(compare, token): Uses the same algorithm and salt of the hashed token for comparison. """ algorithm, srounds, salt, _ = compare.split(':') - hashed = hash_token(token, salt=salt, rounds=int(srounds), algorithm=algorithm).encode('utf8') + hashed = hash_token( + token, salt=salt, rounds=int(srounds), algorithm=algorithm + ).encode('utf8') compare = compare.encode('utf8') if compare_digest(compare, hashed): return True @@ -330,7 +352,7 @@ def url_path_join(*pieces): """ initial = pieces[0].startswith('/') final = pieces[-1].endswith('/') - stripped = [ s.strip('/') for s in pieces ] + stripped = [s.strip('/') for s in pieces] result = '/'.join(s for s in stripped if s) if initial: @@ -354,7 +376,7 @@ def print_ps_info(file=sys.stderr): # nothing to print warnings.warn( "psutil unavailable. Install psutil to get CPU and memory stats", - stacklevel=2 + stacklevel=2, ) return p = psutil.Process() @@ -368,13 +390,13 @@ def print_ps_info(file=sys.stderr): # format memory (only resident set) rss = p.memory_info().rss if rss >= 1e9: - mem_s = '%.1fG' % (rss/1e9) + mem_s = '%.1fG' % (rss / 1e9) elif rss >= 1e7: - mem_s = '%.0fM' % (rss/1e6) + mem_s = '%.0fM' % (rss / 1e6) elif rss >= 1e6: - mem_s = '%.1fM' % (rss/1e6) + mem_s = '%.1fM' % (rss / 1e6) else: - mem_s = '%.0fk' % (rss/1e3) + mem_s = '%.0fk' % (rss / 1e3) # left-justify and shrink-to-fit columns cpulen = max(len(cpu_s), 4) @@ -383,19 +405,22 @@ def print_ps_info(file=sys.stderr): fdlen = max(len(fd_s), 3) threadlen = len('threads') - print("%s %s %s %s" % ( - '%CPU'.ljust(cpulen), - 'MEM'.ljust(memlen), - 'FDs'.ljust(fdlen), - 'threads', - ), file=file) + print( + "%s %s %s %s" + % ('%CPU'.ljust(cpulen), 'MEM'.ljust(memlen), 'FDs'.ljust(fdlen), 'threads'), + file=file, + ) - print("%s %s %s %s" % ( - cpu_s.ljust(cpulen), - mem_s.ljust(memlen), - fd_s.ljust(fdlen), - str(p.num_threads()).ljust(7), - ), file=file) + print( + "%s %s %s %s" + % ( + cpu_s.ljust(cpulen), + mem_s.ljust(memlen), + fd_s.ljust(fdlen), + str(p.num_threads()).ljust(7), + ), + file=file, + ) # trailing blank line print('', file=file) @@ -522,8 +547,8 @@ async def iterate_until(deadline_future, generator): while True: item_future = asyncio.ensure_future(aiter.__anext__()) await asyncio.wait( - [item_future, deadline_future], - return_when=asyncio.FIRST_COMPLETED) + [item_future, deadline_future], return_when=asyncio.FIRST_COMPLETED + ) if item_future.done(): try: await yield_(item_future.result()) @@ -549,4 +574,3 @@ async def iterate_until(deadline_future, generator): def utcnow(): """Return timezone-aware utcnow""" return datetime.now(timezone.utc) - diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -1,18 +1,21 @@ #!/usr/bin/env python3 # coding: utf-8 - # Copyright (c) Juptyer Development Team. # Distributed under the terms of the Modified BSD License. - -#----------------------------------------------------------------------------- +# ----------------------------------------------------------------------------- # Minimal Python version sanity check (from IPython) -#----------------------------------------------------------------------------- - +# ----------------------------------------------------------------------------- from __future__ import print_function import os import shutil import sys +from glob import glob +from subprocess import check_call + +from setuptools import setup +from setuptools.command.bdist_egg import bdist_egg + v = sys.version_info if v[:2] < (3, 5): @@ -26,14 +29,6 @@ warning = "WARNING: Windows is not officially supported" print(warning, file=sys.stderr) -# At least we're on the python version we need, move on. - -import os -from glob import glob -from subprocess import check_call - -from setuptools import setup -from setuptools.command.bdist_egg import bdist_egg pjoin = os.path.join @@ -43,9 +38,10 @@ is_repo = os.path.exists(pjoin(here, '.git')) -#--------------------------------------------------------------------------- +# --------------------------------------------------------------------------- # Build basic package data, etc. -#--------------------------------------------------------------------------- +# --------------------------------------------------------------------------- + def get_data_files(): """Get data files in share/jupyter""" @@ -54,25 +50,20 @@ def get_data_files(): ntrim = len(here + os.path.sep) for (d, dirs, filenames) in os.walk(share_jupyterhub): - data_files.append(( - d[ntrim:], - [ pjoin(d, f) for f in filenames ] - )) + data_files.append((d[ntrim:], [pjoin(d, f) for f in filenames])) return data_files + def get_package_data(): """Get package data (mostly alembic config) """ package_data = {} - package_data['jupyterhub'] = [ - 'alembic.ini', - 'alembic/*', - 'alembic/versions/*', - ] + package_data['jupyterhub'] = ['alembic.ini', 'alembic/*', 'alembic/versions/*'] return package_data + ns = {} with open(pjoin(here, 'jupyterhub', '_version.py')) as f: exec(f.read(), {}, ns) @@ -88,24 +79,24 @@ def get_package_data(): setup_args = dict( - name = 'jupyterhub', - packages = packages, - # dummy, so that install_data doesn't get skipped - # this will be overridden when bower is run anyway - data_files = get_data_files() or ['dummy'], - package_data = get_package_data(), - version = ns['__version__'], - description = "JupyterHub: A multi-user server for Jupyter notebooks", - long_description = readme, - long_description_content_type = 'text/markdown', - author = "Jupyter Development Team", - author_email = "[email protected]", - url = "https://jupyter.org", - license = "BSD", - platforms = "Linux, Mac OS X", - keywords = ['Interactive', 'Interpreter', 'Shell', 'Web'], - python_requires = ">=3.5", - entry_points = { + name='jupyterhub', + packages=packages, + # dummy, so that install_data doesn't get skipped + # this will be overridden when bower is run anyway + data_files=get_data_files() or ['dummy'], + package_data=get_package_data(), + version=ns['__version__'], + description="JupyterHub: A multi-user server for Jupyter notebooks", + long_description=readme, + long_description_content_type='text/markdown', + author="Jupyter Development Team", + author_email="[email protected]", + url="https://jupyter.org", + license="BSD", + platforms="Linux, Mac OS X", + keywords=['Interactive', 'Interpreter', 'Shell', 'Web'], + python_requires=">=3.5", + entry_points={ 'jupyterhub.authenticators': [ 'default = jupyterhub.auth:PAMAuthenticator', 'pam = jupyterhub.auth:PAMAuthenticator', @@ -123,9 +114,9 @@ def get_package_data(): 'console_scripts': [ 'jupyterhub = jupyterhub.app:main', 'jupyterhub-singleuser = jupyterhub.singleuser:main', - ] + ], }, - classifiers = [ + classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Intended Audience :: Science/Research', @@ -133,7 +124,7 @@ def get_package_data(): 'Programming Language :: Python', 'Programming Language :: Python :: 3', ], - project_urls = { + project_urls={ 'Documentation': 'https://jupyterhub.readthedocs.io', 'Funding': 'https://jupyter.org/about', 'Source': 'https://github.com/jupyterhub/jupyterhub/', @@ -141,9 +132,9 @@ def get_package_data(): }, ) -#--------------------------------------------------------------------------- +# --------------------------------------------------------------------------- # custom distutils commands -#--------------------------------------------------------------------------- +# --------------------------------------------------------------------------- # imports here, so they are after setuptools import if there was one from distutils.cmd import Command @@ -158,6 +149,7 @@ def mtime(path): class BaseCommand(Command): """Dumb empty command because Command needs subclasses to override too much""" + user_options = [] def initialize_options(self): @@ -198,7 +190,11 @@ def run(self): return print("installing js dependencies with npm") - check_call(['npm', 'install', '--progress=false', '--unsafe-perm'], cwd=here, shell=shell) + check_call( + ['npm', 'install', '--progress=false', '--unsafe-perm'], + cwd=here, + shell=shell, + ) os.utime(self.node_modules) os.utime(self.bower_dir) @@ -245,11 +241,16 @@ def run(self): sourcemap = style_css + '.map' args = [ - 'npm', 'run', 'lessc', '--', '--clean-css', + 'npm', + 'run', + 'lessc', + '--', + '--clean-css', '--source-map-basepath={}'.format(static), '--source-map={}'.format(sourcemap), '--source-map-rootpath=../', - style_less, style_css, + style_less, + style_css, ] try: check_call(args, cwd=here, shell=shell) @@ -273,6 +274,7 @@ def run(self): else: pass return super().run() + return Command @@ -282,8 +284,11 @@ class bdist_egg_disabled(bdist_egg): Prevents setup.py install from performing setuptools' default easy_install, which it should never ever do. """ + def run(self): - sys.exit("Aborting implicit building of eggs. Use `pip install .` to install from source.") + sys.exit( + "Aborting implicit building of eggs. Use `pip install .` to install from source." + ) setup_args['cmdclass'] = { @@ -299,12 +304,16 @@ def run(self): setup_args['zip_safe'] = False from setuptools.command.develop import develop + + class develop_js_css(develop): def run(self): if not self.uninstall: self.distribution.run_command('js') self.distribution.run_command('css') develop.run(self) + + setup_args['cmdclass']['develop'] = develop_js_css setup_args['install_requires'] = install_requires = [] @@ -315,12 +324,14 @@ def run(self): continue install_requires.append(req) -#--------------------------------------------------------------------------- +# --------------------------------------------------------------------------- # setup -#--------------------------------------------------------------------------- +# --------------------------------------------------------------------------- + def main(): setup(**setup_args) + if __name__ == '__main__': main() diff --git a/setupegg.py b/setupegg.py --- a/setupegg.py +++ b/setupegg.py @@ -1,7 +1,7 @@ #!/usr/bin/env python """Wrapper to run setup.py using setuptools.""" - # Import setuptools and call the actual setup import setuptools + with open('setup.py', 'rb') as f: exec(compile(f.read(), 'setup.py', 'exec')) diff --git a/tools/tasks.py b/tools/tasks.py --- a/tools/tasks.py +++ b/tools/tasks.py @@ -19,19 +19,17 @@ """ # derived from PyZMQ release/tasks.py (used under BSD) - # Copyright (c) Jupyter Developers # Distributed under the terms of the Modified BSD License. - import glob import os import pipes import shutil - from contextlib import contextmanager from distutils.version import LooseVersion as V -from invoke import task, run as invoke_run +from invoke import run as invoke_run +from invoke import task pjoin = os.path.join here = os.path.dirname(__file__) @@ -98,7 +96,7 @@ def patch_version(vs, path=pjoin(here, '..')): break for line in f: post_lines.append(line) - + # write new version.py with open(version_py, 'w') as f: for line in pre_lines: @@ -107,7 +105,7 @@ def patch_version(vs, path=pjoin(here, '..')): f.write(' %r,\n' % part) for line in post_lines: f.write(line) - + # verify result ns = {} with open(version_py) as f: @@ -149,15 +147,16 @@ def make_env(*packages): """ if not os.path.exists(env_root): os.makedirs(env_root) - + env = os.path.join(env_root, os.path.basename(py_exe)) py = pjoin(env, 'bin', 'python') # new env if not os.path.exists(py): - run('python -m virtualenv {} -p {}'.format( - pipes.quote(env), - pipes.quote(py_exe), - )) + run( + 'python -m virtualenv {} -p {}'.format( + pipes.quote(env), pipes.quote(py_exe) + ) + ) py = pjoin(env, 'bin', 'python') run([py, '-V']) install(py, 'pip', 'setuptools') @@ -174,7 +173,7 @@ def build_sdist(py): with cd(repo_root): cmd = [py, 'setup.py', 'sdist', '--formats=gztar'] run(cmd) - + return glob.glob(pjoin(repo_root, 'dist', '*.tar.gz'))[0] @@ -188,7 +187,7 @@ def sdist(vs, upload=False): with cd(repo_root): install(py, 'twine') run([py, '-m', 'twine', 'upload', 'dist/*']) - + untag(vs, push=upload) return untar(tarball) @@ -214,7 +213,7 @@ def untar(tarball): os.makedirs(sdist_root) with cd(sdist_root): run(['tar', '-xzf', tarball]) - + return glob.glob(pjoin(sdist_root, '*'))[0] @@ -231,7 +230,7 @@ def release(vs, upload=False): clone_repo(reset=True) if os.path.exists(env_root): shutil.rmtree(env_root) - + path = sdist(vs, upload=upload) print("Working in %r" % path) with cd(path): @@ -239,4 +238,3 @@ def release(vs, upload=False): if upload: py = make_env('twine') run([py, '-m', 'twine', 'upload', 'dist/*']) -
diff --git a/docs/source/contributing/tests.rst b/docs/source/contributing/tests.rst --- a/docs/source/contributing/tests.rst +++ b/docs/source/contributing/tests.rst @@ -75,4 +75,4 @@ the asynchronous test timeout to a higher value than the default of 5s, since some of our tests take longer than 5s to execute. If the tests are still timing out, try increasing that value even more. You can also set an environment variable ``ASYNC_TEST_TIMEOUT`` instead of -passing ``--async-test-timeout`` to each invocation of pytest. \ No newline at end of file +passing ``--async-test-timeout`` to each invocation of pytest. diff --git a/jupyterhub/tests/conftest.py b/jupyterhub/tests/conftest.py --- a/jupyterhub/tests/conftest.py +++ b/jupyterhub/tests/conftest.py @@ -23,34 +23,33 @@ - `slow_bad_spawn` """ - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import asyncio -from getpass import getuser import inspect import logging import os import sys +from getpass import getuser from subprocess import TimeoutExpired from unittest import mock -from pytest import fixture, raises -from tornado import ioloop, gen +from pytest import fixture +from pytest import raises +from tornado import gen +from tornado import ioloop from tornado.httpclient import HTTPError from tornado.platform.asyncio import AsyncIOMainLoop -from .. import orm +import jupyterhub.services.service +from . import mocking from .. import crypto +from .. import orm from ..utils import random_port - -from . import mocking from .mocking import MockHub -from .utils import ssl_setup, add_user from .test_services import mockservice_cmd - -import jupyterhub.services.service +from .utils import add_user +from .utils import ssl_setup # global db session object _db = None @@ -78,12 +77,7 @@ def app(request, io_loop, ssl_tmpdir): ssl_enabled = getattr(request.module, "ssl_enabled", False) kwargs = dict() if ssl_enabled: - kwargs.update( - dict( - internal_ssl=True, - internal_certs_location=str(ssl_tmpdir), - ) - ) + kwargs.update(dict(internal_ssl=True, internal_certs_location=str(ssl_tmpdir))) mocked_app = MockHub.instance(**kwargs) @@ -107,9 +101,7 @@ def fin(): @fixture def auth_state_enabled(app): - app.authenticator.auth_state = { - 'who': 'cares', - } + app.authenticator.auth_state = {'who': 'cares'} app.authenticator.enable_auth_state = True ck = crypto.CryptKeeper.instance() before_keys = ck.keys @@ -128,9 +120,7 @@ def db(): global _db if _db is None: _db = orm.new_session_factory('sqlite:///:memory:')() - user = orm.User( - name=getuser(), - ) + user = orm.User(name=getuser()) _db.add(user) _db.commit() return _db @@ -221,12 +211,12 @@ def admin_user(app, username): yield user - class MockServiceSpawner(jupyterhub.services.service._ServiceSpawner): """mock services for testing. Shorter intervals, etc. """ + poll_interval = 1 @@ -237,11 +227,7 @@ def _mockservice(request, app, url=False): global _mock_service_counter _mock_service_counter += 1 name = 'mock-service-%i' % _mock_service_counter - spec = { - 'name': name, - 'command': mockservice_cmd, - 'admin': True, - } + spec = {'name': name, 'command': mockservice_cmd, 'admin': True} if url: if app.internal_ssl: spec['url'] = 'https://127.0.0.1:%i' % random_port() @@ -250,22 +236,29 @@ def _mockservice(request, app, url=False): io_loop = app.io_loop - with mock.patch.object(jupyterhub.services.service, '_ServiceSpawner', MockServiceSpawner): + with mock.patch.object( + jupyterhub.services.service, '_ServiceSpawner', MockServiceSpawner + ): app.services = [spec] app.init_services() assert name in app._service_map service = app._service_map[name] + @gen.coroutine def start(): # wait for proxy to be updated before starting the service yield app.proxy.add_all_services(app._service_map) service.start() + io_loop.run_sync(start) + def cleanup(): import asyncio + asyncio.get_event_loop().run_until_complete(service.stop()) app.services[:] = [] app._service_map.clear() + request.addfinalizer(cleanup) # ensure process finishes starting with raises(TimeoutExpired): @@ -290,47 +283,44 @@ def mockservice_url(request, app): @fixture def admin_access(app): """Grant admin-access with this fixture""" - with mock.patch.dict(app.tornado_settings, - {'admin_access': True}): + with mock.patch.dict(app.tornado_settings, {'admin_access': True}): yield @fixture def no_patience(app): """Set slow-spawning timeouts to zero""" - with mock.patch.dict(app.tornado_settings, - {'slow_spawn_timeout': 0.1, - 'slow_stop_timeout': 0.1}): + with mock.patch.dict( + app.tornado_settings, {'slow_spawn_timeout': 0.1, 'slow_stop_timeout': 0.1} + ): yield @fixture def slow_spawn(app): """Fixture enabling SlowSpawner""" - with mock.patch.dict(app.tornado_settings, - {'spawner_class': mocking.SlowSpawner}): + with mock.patch.dict(app.tornado_settings, {'spawner_class': mocking.SlowSpawner}): yield @fixture def never_spawn(app): """Fixture enabling NeverSpawner""" - with mock.patch.dict(app.tornado_settings, - {'spawner_class': mocking.NeverSpawner}): + with mock.patch.dict(app.tornado_settings, {'spawner_class': mocking.NeverSpawner}): yield @fixture def bad_spawn(app): """Fixture enabling BadSpawner""" - with mock.patch.dict(app.tornado_settings, - {'spawner_class': mocking.BadSpawner}): + with mock.patch.dict(app.tornado_settings, {'spawner_class': mocking.BadSpawner}): yield @fixture def slow_bad_spawn(app): """Fixture enabling SlowBadSpawner""" - with mock.patch.dict(app.tornado_settings, - {'spawner_class': mocking.SlowBadSpawner}): + with mock.patch.dict( + app.tornado_settings, {'spawner_class': mocking.SlowBadSpawner} + ): yield diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -26,32 +26,36 @@ - public_url """ - import asyncio -from concurrent.futures import ThreadPoolExecutor import os import sys -from tempfile import NamedTemporaryFile import threading +from concurrent.futures import ThreadPoolExecutor +from tempfile import NamedTemporaryFile from unittest import mock from urllib.parse import urlparse +from pamela import PAMError from tornado import gen from tornado.concurrent import Future from tornado.ioloop import IOLoop +from traitlets import Bool +from traitlets import default +from traitlets import Dict -from traitlets import Bool, Dict, default - +from .. import orm from ..app import JupyterHub from ..auth import PAMAuthenticator -from .. import orm from ..objects import Server -from ..spawner import LocalProcessSpawner, SimpleLocalProcessSpawner from ..singleuser import SingleUserNotebookApp -from ..utils import random_port, url_path_join -from .utils import async_requests, ssl_setup, public_host, public_url - -from pamela import PAMError +from ..spawner import LocalProcessSpawner +from ..spawner import SimpleLocalProcessSpawner +from ..utils import random_port +from ..utils import url_path_join +from .utils import async_requests +from .utils import public_host +from .utils import public_url +from .utils import ssl_setup def mock_authenticate(username, password, service, encoding): @@ -79,6 +83,7 @@ class MockSpawner(SimpleLocalProcessSpawner): - disables user-switching that we need root permissions to do - spawns `jupyterhub.tests.mocksu` instead of a full single-user server """ + def user_env(self, env): env = super().user_env(env) if self.handler: @@ -90,6 +95,7 @@ def _cmd_default(self): return [sys.executable, '-m', 'jupyterhub.tests.mocksu'] use_this_api_token = None + def start(self): if self.use_this_api_token: self.api_token = self.use_this_api_token @@ -103,6 +109,7 @@ class SlowSpawner(MockSpawner): delay = 2 _start_future = None + @gen.coroutine def start(self): (ip, port) = yield super().start() @@ -140,6 +147,7 @@ def poll(self): class BadSpawner(MockSpawner): """Spawner that fails immediately""" + def start(self): raise RuntimeError("I don't work!") @@ -154,8 +162,9 @@ async def start(self): class FormSpawner(MockSpawner): """A spawner that has an options form defined""" + options_form = "IMAFORM" - + def options_from_form(self, form_data): options = {} options['notspecified'] = 5 @@ -167,6 +176,7 @@ def options_from_form(self, form_data): options['hello'] = form_data['hello_file'][0] return options + class FalsyCallableFormSpawner(FormSpawner): """A spawner that has a callable options form defined returning a falsy value""" @@ -181,6 +191,7 @@ def __init__(self, name, members, gid=1111): self.gr_mem = members self.gr_gid = gid + class MockStructPasswd: """Mock pwd.struct_passwd""" @@ -193,30 +204,31 @@ class MockPAMAuthenticator(PAMAuthenticator): auth_state = None # If true, return admin users marked as admin. return_admin = False + @default('admin_users') def _admin_users_default(self): return {'admin'} - + def system_user_exists(self, user): # skip the add-system-user bit return not user.name.startswith('dne') - + @gen.coroutine def authenticate(self, *args, **kwargs): - with mock.patch.multiple('pamela', - authenticate=mock_authenticate, - open_session=mock_open_session, - close_session=mock_open_session, - check_account=mock_check_account, + with mock.patch.multiple( + 'pamela', + authenticate=mock_authenticate, + open_session=mock_open_session, + close_session=mock_open_session, + check_account=mock_check_account, ): - username = yield super(MockPAMAuthenticator, self).authenticate(*args, **kwargs) + username = yield super(MockPAMAuthenticator, self).authenticate( + *args, **kwargs + ) if username is None: return elif self.auth_state: - return { - 'name': username, - 'auth_state': self.auth_state, - } + return {'name': username, 'auth_state': self.auth_state} else: return username @@ -339,7 +351,7 @@ def cleanup(): pool.shutdown() # ignore the call that will fire in atexit - self.cleanup = lambda : None + self.cleanup = lambda: None self.db_file.close() @gen.coroutine @@ -349,11 +361,9 @@ def login_user(self, name): external_ca = None if self.internal_ssl: external_ca = self.external_certs['files']['ca'] - r = yield async_requests.post(base_url + 'hub/login', - data={ - 'username': name, - 'password': name, - }, + r = yield async_requests.post( + base_url + 'hub/login', + data={'username': name, 'password': name}, allow_redirects=False, verify=external_ca, ) @@ -364,6 +374,7 @@ def login_user(self, name): # single-user-server mocking: + class MockSingleUserServer(SingleUserNotebookApp): """Mock-out problematic parts of single-user server when run in a thread @@ -378,7 +389,9 @@ def init_signal(self): class StubSingleUserSpawner(MockSpawner): """Spawner that starts a MockSingleUserServer in a thread.""" + _thread = None + @gen.coroutine def start(self): ip = self.ip = '127.0.0.1' @@ -387,11 +400,12 @@ def start(self): args = self.get_args() evt = threading.Event() print(args, env) + def _run(): asyncio.set_event_loop(asyncio.new_event_loop()) io_loop = IOLoop() io_loop.make_current() - io_loop.add_callback(lambda : evt.set()) + io_loop.add_callback(lambda: evt.set()) with mock.patch.dict(os.environ, env): app = self._app = MockSingleUserServer() @@ -420,4 +434,3 @@ def poll(self): return None else: return 0 - diff --git a/jupyterhub/tests/mockservice.py b/jupyterhub/tests/mockservice.py --- a/jupyterhub/tests/mockservice.py +++ b/jupyterhub/tests/mockservice.py @@ -12,28 +12,33 @@ - WhoAmIHandler: returns name of user making a request (deprecated cookie login) - OWhoAmIHandler: returns name of user making a request (OAuth login) """ - import json -import pprint import os +import pprint import sys from urllib.parse import urlparse import requests -from tornado import web, httpserver, ioloop +from tornado import httpserver +from tornado import ioloop +from tornado import web -from jupyterhub.services.auth import HubAuthenticated, HubOAuthenticated, HubOAuthCallbackHandler +from jupyterhub.services.auth import HubAuthenticated +from jupyterhub.services.auth import HubOAuthCallbackHandler +from jupyterhub.services.auth import HubOAuthenticated from jupyterhub.utils import make_ssl_context class EchoHandler(web.RequestHandler): """Reply to an HTTP request with the path of the request.""" + def get(self): self.write(self.request.path) class EnvHandler(web.RequestHandler): """Reply to an HTTP request with the service's environment as JSON.""" + def get(self): self.set_header('Content-Type', 'application/json') self.write(json.dumps(dict(os.environ))) @@ -41,11 +46,12 @@ def get(self): class APIHandler(web.RequestHandler): """Relay API requests to the Hub's API using the service's API token.""" + def get(self, path): api_token = os.environ['JUPYTERHUB_API_TOKEN'] api_url = os.environ['JUPYTERHUB_API_URL'] - r = requests.get(api_url + path, - headers={'Authorization': 'token %s' % api_token}, + r = requests.get( + api_url + path, headers={'Authorization': 'token %s' % api_token} ) r.raise_for_status() self.set_header('Content-Type', 'application/json') @@ -57,6 +63,7 @@ class WhoAmIHandler(HubAuthenticated, web.RequestHandler): Uses "deprecated" cookie login """ + @web.authenticated def get(self): self.write(self.get_current_user()) @@ -67,6 +74,7 @@ class OWhoAmIHandler(HubOAuthenticated, web.RequestHandler): Uses OAuth login flow """ + @web.authenticated def get(self): self.write(self.get_current_user()) @@ -77,14 +85,17 @@ def main(): if os.getenv('JUPYTERHUB_SERVICE_URL'): url = urlparse(os.environ['JUPYTERHUB_SERVICE_URL']) - app = web.Application([ - (r'.*/env', EnvHandler), - (r'.*/api/(.*)', APIHandler), - (r'.*/whoami/?', WhoAmIHandler), - (r'.*/owhoami/?', OWhoAmIHandler), - (r'.*/oauth_callback', HubOAuthCallbackHandler), - (r'.*', EchoHandler), - ], cookie_secret=os.urandom(32)) + app = web.Application( + [ + (r'.*/env', EnvHandler), + (r'.*/api/(.*)', APIHandler), + (r'.*/whoami/?', WhoAmIHandler), + (r'.*/owhoami/?', OWhoAmIHandler), + (r'.*/oauth_callback', HubOAuthCallbackHandler), + (r'.*', EchoHandler), + ], + cookie_secret=os.urandom(32), + ) ssl_context = None key = os.environ.get('JUPYTERHUB_SSL_KEYFILE') or '' @@ -92,11 +103,7 @@ def main(): ca = os.environ.get('JUPYTERHUB_SSL_CLIENT_CA') or '' if key and cert and ca: - ssl_context = make_ssl_context( - key, - cert, - cafile = ca, - check_hostname = False) + ssl_context = make_ssl_context(key, cert, cafile=ca, check_hostname=False) server = httpserver.HTTPServer(app, ssl_options=ssl_context) server.listen(url.port, url.hostname) @@ -108,5 +115,6 @@ def main(): if __name__ == '__main__': from tornado.options import parse_command_line + parse_command_line() main() diff --git a/jupyterhub/tests/mocksu.py b/jupyterhub/tests/mocksu.py --- a/jupyterhub/tests/mocksu.py +++ b/jupyterhub/tests/mocksu.py @@ -13,41 +13,40 @@ """ import argparse import json -import sys import os +import sys + +from tornado import httpserver +from tornado import ioloop +from tornado import web -from tornado import web, httpserver, ioloop -from .mockservice import EnvHandler from ..utils import make_ssl_context +from .mockservice import EnvHandler + class EchoHandler(web.RequestHandler): def get(self): self.write(self.request.path) + class ArgsHandler(web.RequestHandler): def get(self): self.write(json.dumps(sys.argv)) + def main(args): - app = web.Application([ - (r'.*/args', ArgsHandler), - (r'.*/env', EnvHandler), - (r'.*', EchoHandler), - ]) - + app = web.Application( + [(r'.*/args', ArgsHandler), (r'.*/env', EnvHandler), (r'.*', EchoHandler)] + ) + ssl_context = None key = os.environ.get('JUPYTERHUB_SSL_KEYFILE') or '' cert = os.environ.get('JUPYTERHUB_SSL_CERTFILE') or '' ca = os.environ.get('JUPYTERHUB_SSL_CLIENT_CA') or '' if key and cert and ca: - ssl_context = make_ssl_context( - key, - cert, - cafile = ca, - check_hostname = False - ) + ssl_context = make_ssl_context(key, cert, cafile=ca, check_hostname=False) server = httpserver.HTTPServer(app, ssl_options=ssl_context) server.listen(args.port) @@ -56,6 +55,7 @@ def main(args): except KeyboardInterrupt: print('\nInterrupted') + if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--port', type=int) diff --git a/jupyterhub/tests/populate_db.py b/jupyterhub/tests/populate_db.py --- a/jupyterhub/tests/populate_db.py +++ b/jupyterhub/tests/populate_db.py @@ -4,9 +4,8 @@ used in test_db.py """ - -from datetime import datetime import os +from datetime import datetime import jupyterhub from jupyterhub import orm @@ -90,6 +89,7 @@ def populate_db(url): if __name__ == '__main__': import sys + if len(sys.argv) > 1: url = sys.argv[1] else: diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -1,30 +1,32 @@ """Tests for the REST API.""" - import asyncio -from datetime import datetime, timedelta -from concurrent.futures import Future import json import re import sys -from unittest import mock -from urllib.parse import urlparse, quote import uuid -from async_generator import async_generator, yield_ +from concurrent.futures import Future +from datetime import datetime +from datetime import timedelta +from unittest import mock +from urllib.parse import quote +from urllib.parse import urlparse +from async_generator import async_generator +from async_generator import yield_ from pytest import mark from tornado import gen import jupyterhub from .. import orm -from ..utils import url_path_join as ujoin, utcnow -from .mocking import public_host, public_url -from .utils import ( - add_user, - api_request, - async_requests, - auth_header, - find_user, -) +from ..utils import url_path_join as ujoin +from ..utils import utcnow +from .mocking import public_host +from .mocking import public_url +from .utils import add_user +from .utils import api_request +from .utils import async_requests +from .utils import auth_header +from .utils import find_user # -------------------- @@ -48,12 +50,15 @@ async def test_auth_api(app): assert reply['name'] == user.name # check fail - r = await api_request(app, 'authorizations/token', api_token, - headers={'Authorization': 'no sir'}, + r = await api_request( + app, 'authorizations/token', api_token, headers={'Authorization': 'no sir'} ) assert r.status_code == 403 - r = await api_request(app, 'authorizations/token', api_token, + r = await api_request( + app, + 'authorizations/token', + api_token, headers={'Authorization': 'token: %s' % user.cookie_id}, ) assert r.status_code == 403 @@ -67,37 +72,39 @@ async def test_referer_check(app): user = add_user(app.db, name='admin', admin=True) cookies = await app.login_user('admin') - r = await api_request(app, 'users', - headers={ - 'Authorization': '', - 'Referer': 'null', - }, cookies=cookies, + r = await api_request( + app, 'users', headers={'Authorization': '', 'Referer': 'null'}, cookies=cookies ) assert r.status_code == 403 - r = await api_request(app, 'users', + r = await api_request( + app, + 'users', headers={ 'Authorization': '', 'Referer': 'http://attack.com/csrf/vulnerability', - }, cookies=cookies, + }, + cookies=cookies, ) assert r.status_code == 403 - r = await api_request(app, 'users', - headers={ - 'Authorization': '', - 'Referer': url, - 'Host': host, - }, cookies=cookies, + r = await api_request( + app, + 'users', + headers={'Authorization': '', 'Referer': url, 'Host': host}, + cookies=cookies, ) assert r.status_code == 200 - r = await api_request(app, 'users', + r = await api_request( + app, + 'users', headers={ 'Authorization': '', 'Referer': ujoin(url, 'foo/bar/baz/bat'), 'Host': host, - }, cookies=cookies, + }, + cookies=cookies, ) assert r.status_code == 200 @@ -106,6 +113,7 @@ async def test_referer_check(app): # User API tests # -------------- + def normalize_timestamp(ts): """Normalize a timestamp @@ -128,12 +136,16 @@ def normalize_user(user): for server in user['servers'].values(): for key in ('started', 'last_activity'): server[key] = normalize_timestamp(server[key]) - server['progress_url'] = re.sub(r'.*/hub/api', 'PREFIX/hub/api', server['progress_url']) - if (isinstance(server['state'], dict) - and isinstance(server['state'].get('pid', None), int)): + server['progress_url'] = re.sub( + r'.*/hub/api', 'PREFIX/hub/api', server['progress_url'] + ) + if isinstance(server['state'], dict) and isinstance( + server['state'].get('pid', None), int + ): server['state']['pid'] = 0 return user + def fill_user(model): """Fill a default user model @@ -153,6 +165,7 @@ def fill_user(model): TIMESTAMP = normalize_timestamp(datetime.now().isoformat() + 'Z') + @mark.user async def test_get_users(app): db = app.db @@ -160,22 +173,13 @@ async def test_get_users(app): assert r.status_code == 200 users = sorted(r.json(), key=lambda d: d['name']) - users = [ normalize_user(u) for u in users ] + users = [normalize_user(u) for u in users] assert users == [ - fill_user({ - 'name': 'admin', - 'admin': True, - }), - fill_user({ - 'name': 'user', - 'admin': False, - 'last_activity': None, - }), + fill_user({'name': 'admin', 'admin': True}), + fill_user({'name': 'user', 'admin': False, 'last_activity': None}), ] - r = await api_request(app, 'users', - headers=auth_header(db, 'user'), - ) + r = await api_request(app, 'users', headers=auth_header(db, 'user')) assert r.status_code == 403 @@ -202,17 +206,13 @@ async def test_get_self(app): ) db.add(oauth_token) db.commit() - r = await api_request(app, 'user', headers={ - 'Authorization': 'token ' + token, - }) + r = await api_request(app, 'user', headers={'Authorization': 'token ' + token}) r.raise_for_status() model = r.json() assert model['name'] == u.name # invalid auth gets 403 - r = await api_request(app, 'user', headers={ - 'Authorization': 'token notvalid', - }) + r = await api_request(app, 'user', headers={'Authorization': 'token notvalid'}) assert r.status_code == 403 @@ -251,8 +251,11 @@ async def test_add_multi_user_bad(app): @mark.user async def test_add_multi_user_invalid(app): app.authenticator.username_pattern = r'w.*' - r = await api_request(app, 'users', method='post', - data=json.dumps({'usernames': ['Willow', 'Andrew', 'Tara']}) + r = await api_request( + app, + 'users', + method='post', + data=json.dumps({'usernames': ['Willow', 'Andrew', 'Tara']}), ) app.authenticator.username_pattern = '' assert r.status_code == 400 @@ -263,12 +266,12 @@ async def test_add_multi_user_invalid(app): async def test_add_multi_user(app): db = app.db names = ['a', 'b'] - r = await api_request(app, 'users', method='post', - data=json.dumps({'usernames': names}), + r = await api_request( + app, 'users', method='post', data=json.dumps({'usernames': names}) ) assert r.status_code == 201 reply = r.json() - r_names = [ user['name'] for user in reply ] + r_names = [user['name'] for user in reply] assert names == r_names for name in names: @@ -278,20 +281,20 @@ async def test_add_multi_user(app): assert not user.admin # try to create the same users again - r = await api_request(app, 'users', method='post', - data=json.dumps({'usernames': names}), + r = await api_request( + app, 'users', method='post', data=json.dumps({'usernames': names}) ) assert r.status_code == 409 names = ['a', 'b', 'ab'] # try to create the same users again - r = await api_request(app, 'users', method='post', - data=json.dumps({'usernames': names}), + r = await api_request( + app, 'users', method='post', data=json.dumps({'usernames': names}) ) assert r.status_code == 201 reply = r.json() - r_names = [ user['name'] for user in reply ] + r_names = [user['name'] for user in reply] assert r_names == ['ab'] @@ -299,12 +302,15 @@ async def test_add_multi_user(app): async def test_add_multi_user_admin(app): db = app.db names = ['c', 'd'] - r = await api_request(app, 'users', method='post', + r = await api_request( + app, + 'users', + method='post', data=json.dumps({'usernames': names, 'admin': True}), ) assert r.status_code == 201 reply = r.json() - r_names = [ user['name'] for user in reply ] + r_names = [user['name'] for user in reply] assert names == r_names for name in names: @@ -340,8 +346,8 @@ async def test_add_user_duplicate(app): async def test_add_admin(app): db = app.db name = 'newadmin' - r = await api_request(app, 'users', name, method='post', - data=json.dumps({'admin': True}), + r = await api_request( + app, 'users', name, method='post', data=json.dumps({'admin': True}) ) assert r.status_code == 201 user = find_user(db, name) @@ -369,8 +375,8 @@ async def test_make_admin(app): assert user.name == name assert not user.admin - r = await api_request(app, 'users', name, method='patch', - data=json.dumps({'admin': True}) + r = await api_request( + app, 'users', name, method='patch', data=json.dumps({'admin': True}) ) assert r.status_code == 200 user = find_user(db, name) @@ -388,8 +394,8 @@ async def test_set_auth_state(app, auth_state_enabled): assert user is not None assert user.name == name - r = await api_request(app, 'users', name, method='patch', - data=json.dumps({'auth_state': auth_state}) + r = await api_request( + app, 'users', name, method='patch', data=json.dumps({'auth_state': auth_state}) ) assert r.status_code == 200 @@ -409,7 +415,10 @@ async def test_user_set_auth_state(app, auth_state_enabled): assert user_auth_state is None r = await api_request( - app, 'users', name, method='patch', + app, + 'users', + name, + method='patch', data=json.dumps({'auth_state': auth_state}), headers=auth_header(app.db, name), ) @@ -446,8 +455,7 @@ async def test_user_get_auth_state(app, auth_state_enabled): assert user.name == name await user.save_auth_state(auth_state) - r = await api_request(app, 'users', name, - headers=auth_header(app.db, name)) + r = await api_request(app, 'users', name, headers=auth_header(app.db, name)) assert r.status_code == 200 assert 'auth_state' not in r.json() @@ -457,13 +465,10 @@ async def test_spawn(app): db = app.db name = 'wash' user = add_user(db, app=app, name=name) - options = { - 's': ['value'], - 'i': 5, - } + options = {'s': ['value'], 'i': 5} before_servers = sorted(db.query(orm.Server), key=lambda s: s.url) - r = await api_request(app, 'users', name, 'server', method='post', - data=json.dumps(options), + r = await api_request( + app, 'users', name, 'server', method='post', data=json.dumps(options) ) assert r.status_code == 201 assert 'pid' in user.orm_spawners[''].state @@ -520,7 +525,9 @@ async def test_spawn_handler(app): app_user = app.users[name] # spawn via API with ?foo=bar - r = await api_request(app, 'users', name, 'server', method='post', params={'foo': 'bar'}) + r = await api_request( + app, 'users', name, 'server', method='post', params={'foo': 'bar'} + ) r.raise_for_status() # verify that request params got passed down @@ -640,6 +647,7 @@ def next_event(it): if line.startswith('data:'): return json.loads(line.split(':', 1)[1]) + @mark.slow async def test_progress(request, app, no_patience, slow_spawn): db = app.db @@ -655,15 +663,9 @@ async def test_progress(request, app, no_patience, slow_spawn): ex = async_requests.executor line_iter = iter(r.iter_lines(decode_unicode=True)) evt = await ex.submit(next_event, line_iter) - assert evt == { - 'progress': 0, - 'message': 'Server requested', - } + assert evt == {'progress': 0, 'message': 'Server requested'} evt = await ex.submit(next_event, line_iter) - assert evt == { - 'progress': 50, - 'message': 'Spawning server...', - } + assert evt == {'progress': 50, 'message': 'Spawning server...'} evt = await ex.submit(next_event, line_iter) url = app_user.url assert evt == { @@ -769,10 +771,7 @@ async def test_progress_bad_slow(request, app, no_patience, slow_bad_spawn): async def progress_forever(): """progress function that yields messages forever""" for i in range(1, 10): - await yield_({ - 'progress': i, - 'message': 'Stage %s' % i, - }) + await yield_({'progress': i, 'message': 'Stage %s' % i}) # wait a long time before the next event await gen.sleep(10) @@ -781,7 +780,8 @@ async def progress_forever(): # additional progress_forever defined as native # async generator # to test for issues with async_generator wrappers - exec(""" + exec( + """ async def progress_forever_native(): for i in range(1, 10): yield { @@ -790,7 +790,9 @@ async def progress_forever_native(): } # wait a long time before the next event await gen.sleep(10) -""", globals()) +""", + globals(), + ) async def test_spawn_progress_cutoff(request, app, no_patience, slow_spawn): @@ -818,24 +820,20 @@ async def test_spawn_progress_cutoff(request, app, no_patience, slow_spawn): evt = await ex.submit(next_event, line_iter) assert evt['progress'] == 0 evt = await ex.submit(next_event, line_iter) - assert evt == { - 'progress': 1, - 'message': 'Stage 1', - } + assert evt == {'progress': 1, 'message': 'Stage 1'} evt = await ex.submit(next_event, line_iter) assert evt['progress'] == 100 async def test_spawn_limit(app, no_patience, slow_spawn, request): db = app.db - p = mock.patch.dict(app.tornado_settings, - {'concurrent_spawn_limit': 2}) + p = mock.patch.dict(app.tornado_settings, {'concurrent_spawn_limit': 2}) p.start() request.addfinalizer(p.stop) # start two pending spawns names = ['ykka', 'hjarka'] - users = [ add_user(db, app=app, name=name) for name in names ] + users = [add_user(db, app=app, name=name) for name in names] users[0].spawner._start_future = Future() users[1].spawner._start_future = Future() for name in names: @@ -875,17 +873,17 @@ async def test_spawn_limit(app, no_patience, slow_spawn, request): while any(u.spawner.active for u in users): await gen.sleep(0.1) + @mark.slow async def test_active_server_limit(app, request): db = app.db - p = mock.patch.dict(app.tornado_settings, - {'active_server_limit': 2}) + p = mock.patch.dict(app.tornado_settings, {'active_server_limit': 2}) p.start() request.addfinalizer(p.stop) # start two pending spawns names = ['ykka', 'hjarka'] - users = [ add_user(db, app=app, name=name) for name in names ] + users = [add_user(db, app=app, name=name) for name in names] for name in names: r = await api_request(app, 'users', name, 'server', method='post') r.raise_for_status() @@ -932,6 +930,7 @@ async def test_active_server_limit(app, request): assert counts['ready'] == 0 assert counts['pending'] == 0 + @mark.slow async def test_start_stop_race(app, no_patience, slow_spawn): user = add_user(app.db, app, name='panda') @@ -996,22 +995,18 @@ async def test_cookie(app): cookie_name = app.hub.cookie_name # cookie jar gives '"cookie-value"', we want 'cookie-value' cookie = cookies[cookie_name][1:-1] - r = await api_request(app, 'authorizations/cookie', - cookie_name, "nothintoseehere", - ) + r = await api_request(app, 'authorizations/cookie', cookie_name, "nothintoseehere") assert r.status_code == 404 - r = await api_request(app, 'authorizations/cookie', - cookie_name, quote(cookie, safe=''), + r = await api_request( + app, 'authorizations/cookie', cookie_name, quote(cookie, safe='') ) r.raise_for_status() reply = r.json() assert reply['name'] == name # deprecated cookie in body: - r = await api_request(app, 'authorizations/cookie', - cookie_name, data=cookie, - ) + r = await api_request(app, 'authorizations/cookie', cookie_name, data=cookie) r.raise_for_status() reply = r.json() assert reply['name'] == name @@ -1035,15 +1030,11 @@ async def test_check_token(app): assert r.status_code == 404 [email protected]("headers, status", [ - ({}, 200), - ({'Authorization': 'token bad'}, 403), -]) [email protected]("headers, status", [({}, 200), ({'Authorization': 'token bad'}, 403)]) async def test_get_new_token_deprecated(app, headers, status): # request a new token - r = await api_request(app, 'authorizations', 'token', - method='post', - headers=headers, + r = await api_request( + app, 'authorizations', 'token', method='post', headers=headers ) assert r.status_code == status if status != 200: @@ -1058,11 +1049,11 @@ async def test_get_new_token_deprecated(app, headers, status): async def test_token_formdata_deprecated(app): """Create a token for a user with formdata and no auth header""" - data = { - 'username': 'fake', - 'password': 'fake', - } - r = await api_request(app, 'authorizations', 'token', + data = {'username': 'fake', 'password': 'fake'} + r = await api_request( + app, + 'authorizations', + 'token', method='post', data=json.dumps(data) if data else None, noauth=True, @@ -1076,22 +1067,26 @@ async def test_token_formdata_deprecated(app): assert reply['name'] == data['username'] [email protected]("as_user, for_user, status", [ - ('admin', 'other', 200), - ('admin', 'missing', 400), - ('user', 'other', 403), - ('user', 'user', 200), -]) [email protected]( + "as_user, for_user, status", + [ + ('admin', 'other', 200), + ('admin', 'missing', 400), + ('user', 'other', 403), + ('user', 'user', 200), + ], +) async def test_token_as_user_deprecated(app, as_user, for_user, status): # ensure both users exist u = add_user(app.db, app, name=as_user) if for_user != 'missing': add_user(app.db, app, name=for_user) data = {'username': for_user} - headers = { - 'Authorization': 'token %s' % u.new_api_token(), - } - r = await api_request(app, 'authorizations', 'token', + headers = {'Authorization': 'token %s' % u.new_api_token()} + r = await api_request( + app, + 'authorizations', + 'token', method='post', data=json.dumps(data), headers=headers, @@ -1107,11 +1102,14 @@ async def test_token_as_user_deprecated(app, as_user, for_user, status): assert reply['name'] == data['username'] [email protected]("headers, status, note, expires_in", [ - ({}, 200, 'test note', None), - ({}, 200, '', 100), - ({'Authorization': 'token bad'}, 403, '', None), -]) [email protected]( + "headers, status, note, expires_in", + [ + ({}, 200, 'test note', None), + ({}, 200, '', 100), + ({'Authorization': 'token bad'}, 403, '', None), + ], +) async def test_get_new_token(app, headers, status, note, expires_in): options = {} if note: @@ -1123,10 +1121,8 @@ async def test_get_new_token(app, headers, status, note, expires_in): else: body = '' # request a new token - r = await api_request(app, 'users/admin/tokens', - method='post', - headers=headers, - data=body, + r = await api_request( + app, 'users/admin/tokens', method='post', headers=headers, data=body ) assert r.status_code == status if status != 200: @@ -1157,30 +1153,34 @@ async def test_get_new_token(app, headers, status, note, expires_in): assert normalize_token(reply) == initial # delete the token - r = await api_request(app, 'users/admin/tokens', token_id, - method='delete') + r = await api_request(app, 'users/admin/tokens', token_id, method='delete') assert r.status_code == 204 # verify deletion r = await api_request(app, 'users/admin/tokens', token_id) assert r.status_code == 404 [email protected]("as_user, for_user, status", [ - ('admin', 'other', 200), - ('admin', 'missing', 404), - ('user', 'other', 403), - ('user', 'user', 200), -]) [email protected]( + "as_user, for_user, status", + [ + ('admin', 'other', 200), + ('admin', 'missing', 404), + ('user', 'other', 403), + ('user', 'user', 200), + ], +) async def test_token_for_user(app, as_user, for_user, status): # ensure both users exist u = add_user(app.db, app, name=as_user) if for_user != 'missing': add_user(app.db, app, name=for_user) data = {'username': for_user} - headers = { - 'Authorization': 'token %s' % u.new_api_token(), - } - r = await api_request(app, 'users', for_user, 'tokens', + headers = {'Authorization': 'token %s' % u.new_api_token()} + r = await api_request( + app, + 'users', + for_user, + 'tokens', method='post', data=json.dumps(data), headers=headers, @@ -1191,9 +1191,7 @@ async def test_token_for_user(app, as_user, for_user, status): return assert 'token' in reply token_id = reply['id'] - r = await api_request(app, 'users', for_user, 'tokens', token_id, - headers=headers, - ) + r = await api_request(app, 'users', for_user, 'tokens', token_id, headers=headers) r.raise_for_status() reply = r.json() assert reply['user'] == for_user @@ -1203,30 +1201,25 @@ async def test_token_for_user(app, as_user, for_user, status): note = 'Requested via api by user %s' % as_user assert reply['note'] == note - # delete the token - r = await api_request(app, 'users', for_user, 'tokens', token_id, - method='delete', - headers=headers, + r = await api_request( + app, 'users', for_user, 'tokens', token_id, method='delete', headers=headers ) assert r.status_code == 204 - r = await api_request(app, 'users', for_user, 'tokens', token_id, - headers=headers, - ) + r = await api_request(app, 'users', for_user, 'tokens', token_id, headers=headers) assert r.status_code == 404 async def test_token_authenticator_noauth(app): """Create a token for a user relying on Authenticator.authenticate and no auth header""" name = 'user' - data = { - 'auth': { - 'username': name, - 'password': name, - }, - } - r = await api_request(app, 'users', name, 'tokens', + data = {'auth': {'username': name, 'password': name}} + r = await api_request( + app, + 'users', + name, + 'tokens', method='post', data=json.dumps(data) if data else None, noauth=True, @@ -1242,17 +1235,14 @@ async def test_token_authenticator_noauth(app): async def test_token_authenticator_dict_noauth(app): """Create a token for a user relying on Authenticator.authenticate and no auth header""" - app.authenticator.auth_state = { - 'who': 'cares', - } + app.authenticator.auth_state = {'who': 'cares'} name = 'user' - data = { - 'auth': { - 'username': name, - 'password': name, - }, - } - r = await api_request(app, 'users', name, 'tokens', + data = {'auth': {'username': name, 'password': name}} + r = await api_request( + app, + 'users', + name, + 'tokens', method='post', data=json.dumps(data) if data else None, noauth=True, @@ -1266,22 +1256,21 @@ async def test_token_authenticator_dict_noauth(app): assert reply['name'] == name [email protected]("as_user, for_user, status", [ - ('admin', 'other', 200), - ('admin', 'missing', 404), - ('user', 'other', 403), - ('user', 'user', 200), -]) [email protected]( + "as_user, for_user, status", + [ + ('admin', 'other', 200), + ('admin', 'missing', 404), + ('user', 'other', 403), + ('user', 'user', 200), + ], +) async def test_token_list(app, as_user, for_user, status): u = add_user(app.db, app, name=as_user) if for_user != 'missing': for_user_obj = add_user(app.db, app, name=for_user) - headers = { - 'Authorization': 'token %s' % u.new_api_token(), - } - r = await api_request(app, 'users', for_user, 'tokens', - headers=headers, - ) + headers = {'Authorization': 'token %s' % u.new_api_token()} + r = await api_request(app, 'users', for_user, 'tokens', headers=headers) assert r.status_code == status if status != 200: return @@ -1292,8 +1281,8 @@ async def test_token_list(app, as_user, for_user, status): assert all(token['user'] == for_user for token in reply['oauth_tokens']) # validate individual token ids for token in reply['api_tokens'] + reply['oauth_tokens']: - r = await api_request(app, 'users', for_user, 'tokens', token['id'], - headers=headers, + r = await api_request( + app, 'users', for_user, 'tokens', token['id'], headers=headers ) r.raise_for_status() reply = r.json() @@ -1320,29 +1309,25 @@ async def test_groups_list(app): r = await api_request(app, 'groups') r.raise_for_status() reply = r.json() - assert reply == [{ - 'kind': 'group', - 'name': 'alphaflight', - 'users': [] - }] + assert reply == [{'kind': 'group', 'name': 'alphaflight', 'users': []}] @mark.group async def test_add_multi_group(app): db = app.db names = ['group1', 'group2'] - r = await api_request(app, 'groups', method='post', - data=json.dumps({'groups': names}), - ) + r = await api_request( + app, 'groups', method='post', data=json.dumps({'groups': names}) + ) assert r.status_code == 201 reply = r.json() r_names = [group['name'] for group in reply] assert names == r_names # try to create the same groups again - r = await api_request(app, 'groups', method='post', - data=json.dumps({'groups': names}), - ) + r = await api_request( + app, 'groups', method='post', data=json.dumps({'groups': names}) + ) assert r.status_code == 409 @@ -1359,11 +1344,7 @@ async def test_group_get(app): r = await api_request(app, 'groups/alphaflight') r.raise_for_status() reply = r.json() - assert reply == { - 'kind': 'group', - 'name': 'alphaflight', - 'users': ['sasquatch'] - } + assert reply == {'kind': 'group', 'name': 'alphaflight', 'users': ['sasquatch']} @mark.group @@ -1372,13 +1353,16 @@ async def test_group_create_delete(app): r = await api_request(app, 'groups/runaways', method='delete') assert r.status_code == 404 - r = await api_request(app, 'groups/new', method='post', - data=json.dumps({'users': ['doesntexist']}), + r = await api_request( + app, 'groups/new', method='post', data=json.dumps({'users': ['doesntexist']}) ) assert r.status_code == 400 assert orm.Group.find(db, name='new') is None - r = await api_request(app, 'groups/omegaflight', method='post', + r = await api_request( + app, + 'groups/omegaflight', + method='post', data=json.dumps({'users': ['sasquatch']}), ) r.raise_for_status() @@ -1410,18 +1394,23 @@ async def test_group_add_users(app): assert r.status_code == 400 names = ['aurora', 'guardian', 'northstar', 'sasquatch', 'shaman', 'snowbird'] - users = [ find_user(db, name=name) or add_user(db, app=app, name=name) for name in names ] - r = await api_request(app, 'groups/alphaflight/users', method='post', data=json.dumps({ - 'users': names, - })) + users = [ + find_user(db, name=name) or add_user(db, app=app, name=name) for name in names + ] + r = await api_request( + app, + 'groups/alphaflight/users', + method='post', + data=json.dumps({'users': names}), + ) r.raise_for_status() for user in users: print(user.name) - assert [ g.name for g in user.groups ] == ['alphaflight'] + assert [g.name for g in user.groups] == ['alphaflight'] group = orm.Group.find(db, name='alphaflight') - assert sorted([ u.name for u in group.users ]) == sorted(names) + assert sorted([u.name for u in group.users]) == sorted(names) @mark.group @@ -1432,19 +1421,22 @@ async def test_group_delete_users(app): assert r.status_code == 400 names = ['aurora', 'guardian', 'northstar', 'sasquatch', 'shaman', 'snowbird'] - users = [ find_user(db, name=name) for name in names ] - r = await api_request(app, 'groups/alphaflight/users', method='delete', data=json.dumps({ - 'users': names[:2], - })) + users = [find_user(db, name=name) for name in names] + r = await api_request( + app, + 'groups/alphaflight/users', + method='delete', + data=json.dumps({'users': names[:2]}), + ) r.raise_for_status() for user in users[:2]: assert user.groups == [] for user in users[2:]: - assert [ g.name for g in user.groups ] == ['alphaflight'] + assert [g.name for g in user.groups] == ['alphaflight'] group = orm.Group.find(db, name='alphaflight') - assert sorted([ u.name for u in group.users ]) == sorted(names[2:]) + assert sorted([u.name for u in group.users]) == sorted(names[2:]) # ----------------- @@ -1473,9 +1465,7 @@ async def test_get_services(app, mockservice_url): } } - r = await api_request(app, 'services', - headers=auth_header(db, 'user'), - ) + r = await api_request(app, 'services', headers=auth_header(db, 'user')) assert r.status_code == 403 @@ -1498,14 +1488,14 @@ async def test_get_service(app, mockservice_url): 'info': {}, } - r = await api_request(app, 'services/%s' % mockservice.name, - headers={ - 'Authorization': 'token %s' % mockservice.api_token - } + r = await api_request( + app, + 'services/%s' % mockservice.name, + headers={'Authorization': 'token %s' % mockservice.api_token}, ) r.raise_for_status() - r = await api_request(app, 'services/%s' % mockservice.name, - headers=auth_header(db, 'user'), + r = await api_request( + app, 'services/%s' % mockservice.name, headers=auth_header(db, 'user') ) assert r.status_code == 403 @@ -1519,9 +1509,7 @@ async def test_root_api(app): kwargs["verify"] = app.internal_ssl_ca r = await async_requests.get(url, **kwargs) r.raise_for_status() - expected = { - 'version': jupyterhub.__version__ - } + expected = {'version': jupyterhub.__version__} assert r.json() == expected @@ -1662,15 +1650,20 @@ def test_shutdown(app): # which makes gen_test unhappy. So we run the loop ourselves. async def shutdown(): - r = await api_request(app, 'shutdown', method='post', - data=json.dumps({'servers': True, 'proxy': True,}), + r = await api_request( + app, + 'shutdown', + method='post', + data=json.dumps({'servers': True, 'proxy': True}), ) return r real_stop = loop.stop + def stop(): stop.called = True loop.call_later(1, real_stop) + with mock.patch.object(loop, 'stop', stop): r = loop.run_sync(shutdown, timeout=5) r.raise_for_status() diff --git a/jupyterhub/tests/test_app.py b/jupyterhub/tests/test_app.py --- a/jupyterhub/tests/test_app.py +++ b/jupyterhub/tests/test_app.py @@ -1,25 +1,30 @@ """Test the JupyterHub entry point""" - import binascii import os import re import sys -from subprocess import check_output, Popen, PIPE -from tempfile import NamedTemporaryFile, TemporaryDirectory +from subprocess import check_output +from subprocess import PIPE +from subprocess import Popen +from tempfile import NamedTemporaryFile +from tempfile import TemporaryDirectory from unittest.mock import patch import pytest from tornado import gen from traitlets.config import Config +from .. import orm +from ..app import COOKIE_SECRET_BYTES +from ..app import JupyterHub from .mocking import MockHub from .test_api import add_user -from .. import orm -from ..app import COOKIE_SECRET_BYTES, JupyterHub def test_help_all(): - out = check_output([sys.executable, '-m', 'jupyterhub', '--help-all']).decode('utf8', 'replace') + out = check_output([sys.executable, '-m', 'jupyterhub', '--help-all']).decode( + 'utf8', 'replace' + ) assert '--ip' in out assert '--JupyterHub.ip' in out @@ -39,9 +44,11 @@ def test_generate_config(): cfg_file = tf.name with open(cfg_file, 'w') as f: f.write("c.A = 5") - p = Popen([sys.executable, '-m', 'jupyterhub', - '--generate-config', '-f', cfg_file], - stdout=PIPE, stdin=PIPE) + p = Popen( + [sys.executable, '-m', 'jupyterhub', '--generate-config', '-f', cfg_file], + stdout=PIPE, + stdin=PIPE, + ) out, _ = p.communicate(b'n') out = out.decode('utf8', 'replace') assert os.path.exists(cfg_file) @@ -49,9 +56,11 @@ def test_generate_config(): cfg_text = f.read() assert cfg_text == 'c.A = 5' - p = Popen([sys.executable, '-m', 'jupyterhub', - '--generate-config', '-f', cfg_file], - stdout=PIPE, stdin=PIPE) + p = Popen( + [sys.executable, '-m', 'jupyterhub', '--generate-config', '-f', cfg_file], + stdout=PIPE, + stdin=PIPE, + ) out, _ = p.communicate(b'x\ny') out = out.decode('utf8', 'replace') assert os.path.exists(cfg_file) @@ -184,17 +193,21 @@ async def test_load_groups(tmpdir, request): db = hub.db blue = orm.Group.find(db, name='blue') assert blue is not None - assert sorted([ u.name for u in blue.users ]) == sorted(to_load['blue']) + assert sorted([u.name for u in blue.users]) == sorted(to_load['blue']) gold = orm.Group.find(db, name='gold') assert gold is not None - assert sorted([ u.name for u in gold.users ]) == sorted(to_load['gold']) + assert sorted([u.name for u in gold.users]) == sorted(to_load['gold']) async def test_resume_spawners(tmpdir, request): if not os.getenv('JUPYTERHUB_TEST_DB_URL'): - p = patch.dict(os.environ, { - 'JUPYTERHUB_TEST_DB_URL': 'sqlite:///%s' % tmpdir.join('jupyterhub.sqlite'), - }) + p = patch.dict( + os.environ, + { + 'JUPYTERHUB_TEST_DB_URL': 'sqlite:///%s' + % tmpdir.join('jupyterhub.sqlite') + }, + ) p.start() request.addfinalizer(p.stop) @@ -253,32 +266,18 @@ async def new_hub(): @pytest.mark.parametrize( 'hub_config, expected', [ - ( - {'ip': '0.0.0.0'}, - {'bind_url': 'http://0.0.0.0:8000/'}, - ), + ({'ip': '0.0.0.0'}, {'bind_url': 'http://0.0.0.0:8000/'}), ( {'port': 123, 'base_url': '/prefix'}, - { - 'bind_url': 'http://:123/prefix/', - 'base_url': '/prefix/', - }, - ), - ( - {'bind_url': 'http://0.0.0.0:12345/sub'}, - {'base_url': '/sub/'}, + {'bind_url': 'http://:123/prefix/', 'base_url': '/prefix/'}, ), + ({'bind_url': 'http://0.0.0.0:12345/sub'}, {'base_url': '/sub/'}), ( # no config, test defaults {}, - { - 'base_url': '/', - 'bind_url': 'http://:8000', - 'ip': '', - 'port': 8000, - }, + {'base_url': '/', 'bind_url': 'http://:8000', 'ip': '', 'port': 8000}, ), - ] + ], ) def test_url_config(hub_config, expected): # construct the config object diff --git a/jupyterhub/tests/test_auth.py b/jupyterhub/tests/test_auth.py --- a/jupyterhub/tests/test_auth.py +++ b/jupyterhub/tests/test_auth.py @@ -1,59 +1,59 @@ """Tests for PAM authentication""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import os from unittest import mock import pytest from requests import HTTPError -from jupyterhub import auth, crypto, orm - -from .mocking import MockPAMAuthenticator, MockStructGroup, MockStructPasswd +from .mocking import MockPAMAuthenticator +from .mocking import MockStructGroup +from .mocking import MockStructPasswd from .utils import add_user +from jupyterhub import auth +from jupyterhub import crypto +from jupyterhub import orm async def test_pam_auth(): authenticator = MockPAMAuthenticator() - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'match', - 'password': 'match', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'match', 'password': 'match'} + ) assert authorized['name'] == 'match' - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'match', - 'password': 'nomatch', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'match', 'password': 'nomatch'} + ) assert authorized is None # Account check is on by default for increased security - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'notallowedmatch', - 'password': 'notallowedmatch', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'notallowedmatch', 'password': 'notallowedmatch'} + ) assert authorized is None async def test_pam_auth_account_check_disabled(): authenticator = MockPAMAuthenticator(check_account=False) - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'allowedmatch', - 'password': 'allowedmatch', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'allowedmatch', 'password': 'allowedmatch'} + ) assert authorized['name'] == 'allowedmatch' - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'notallowedmatch', - 'password': 'notallowedmatch', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'notallowedmatch', 'password': 'notallowedmatch'} + ) assert authorized['name'] == 'notallowedmatch' async def test_pam_auth_admin_groups(): - jh_users = MockStructGroup('jh_users', ['group_admin', 'also_group_admin', 'override_admin', 'non_admin'], 1234) + jh_users = MockStructGroup( + 'jh_users', + ['group_admin', 'also_group_admin', 'override_admin', 'non_admin'], + 1234, + ) jh_admins = MockStructGroup('jh_admins', ['group_admin'], 5678) wheel = MockStructGroup('wheel', ['also_group_admin'], 9999) system_groups = [jh_users, jh_admins, wheel] @@ -68,7 +68,7 @@ async def test_pam_auth_admin_groups(): 'group_admin': [jh_users.gr_gid, jh_admins.gr_gid], 'also_group_admin': [jh_users.gr_gid, wheel.gr_gid], 'override_admin': [jh_users.gr_gid], - 'non_admin': [jh_users.gr_gid] + 'non_admin': [jh_users.gr_gid], } def getgrnam(name): @@ -76,80 +76,82 @@ def getgrnam(name): def getpwnam(name): return [x for x in system_users if x.pw_name == name][0] - + def getgrouplist(name, group): return user_group_map[name] - authenticator = MockPAMAuthenticator(admin_groups={'jh_admins', 'wheel'}, - admin_users={'override_admin'}) + authenticator = MockPAMAuthenticator( + admin_groups={'jh_admins', 'wheel'}, admin_users={'override_admin'} + ) # Check admin_group applies as expected - with mock.patch.multiple(authenticator, - _getgrnam=getgrnam, - _getpwnam=getpwnam, - _getgrouplist=getgrouplist): - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'group_admin', - 'password': 'group_admin' - }) + with mock.patch.multiple( + authenticator, + _getgrnam=getgrnam, + _getpwnam=getpwnam, + _getgrouplist=getgrouplist, + ): + authorized = await authenticator.get_authenticated_user( + None, {'username': 'group_admin', 'password': 'group_admin'} + ) assert authorized['name'] == 'group_admin' assert authorized['admin'] is True # Check multiple groups work, just in case. - with mock.patch.multiple(authenticator, - _getgrnam=getgrnam, - _getpwnam=getpwnam, - _getgrouplist=getgrouplist): - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'also_group_admin', - 'password': 'also_group_admin' - }) + with mock.patch.multiple( + authenticator, + _getgrnam=getgrnam, + _getpwnam=getpwnam, + _getgrouplist=getgrouplist, + ): + authorized = await authenticator.get_authenticated_user( + None, {'username': 'also_group_admin', 'password': 'also_group_admin'} + ) assert authorized['name'] == 'also_group_admin' assert authorized['admin'] is True # Check admin_users still applies correctly - with mock.patch.multiple(authenticator, - _getgrnam=getgrnam, - _getpwnam=getpwnam, - _getgrouplist=getgrouplist): - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'override_admin', - 'password': 'override_admin' - }) + with mock.patch.multiple( + authenticator, + _getgrnam=getgrnam, + _getpwnam=getpwnam, + _getgrouplist=getgrouplist, + ): + authorized = await authenticator.get_authenticated_user( + None, {'username': 'override_admin', 'password': 'override_admin'} + ) assert authorized['name'] == 'override_admin' assert authorized['admin'] is True # Check it doesn't admin everyone - with mock.patch.multiple(authenticator, - _getgrnam=getgrnam, - _getpwnam=getpwnam, - _getgrouplist=getgrouplist): - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'non_admin', - 'password': 'non_admin' - }) + with mock.patch.multiple( + authenticator, + _getgrnam=getgrnam, + _getpwnam=getpwnam, + _getgrouplist=getgrouplist, + ): + authorized = await authenticator.get_authenticated_user( + None, {'username': 'non_admin', 'password': 'non_admin'} + ) assert authorized['name'] == 'non_admin' assert authorized['admin'] is False async def test_pam_auth_whitelist(): authenticator = MockPAMAuthenticator(whitelist={'wash', 'kaylee'}) - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'kaylee', - 'password': 'kaylee', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'kaylee', 'password': 'kaylee'} + ) assert authorized['name'] == 'kaylee' - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'wash', - 'password': 'nomatch', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'wash', 'password': 'nomatch'} + ) assert authorized is None - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'mal', - 'password': 'mal', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'mal', 'password': 'mal'} + ) assert authorized is None @@ -160,80 +162,78 @@ def getgrnam(name): authenticator = MockPAMAuthenticator(group_whitelist={'group'}) with mock.patch.object(authenticator, '_getgrnam', getgrnam): - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'kaylee', - 'password': 'kaylee', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'kaylee', 'password': 'kaylee'} + ) assert authorized['name'] == 'kaylee' with mock.patch.object(authenticator, '_getgrnam', getgrnam): - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'mal', - 'password': 'mal', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'mal', 'password': 'mal'} + ) assert authorized is None async def test_pam_auth_blacklist(): # Null case compared to next case authenticator = MockPAMAuthenticator() - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'wash', - 'password': 'wash', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'wash', 'password': 'wash'} + ) assert authorized['name'] == 'wash' # Blacklist basics authenticator = MockPAMAuthenticator(blacklist={'wash'}) - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'wash', - 'password': 'wash', - }) - assert authorized is None + authorized = await authenticator.get_authenticated_user( + None, {'username': 'wash', 'password': 'wash'} + ) + assert authorized is None # User in both white and blacklists: default deny. Make error someday? - authenticator = MockPAMAuthenticator(blacklist={'wash'}, whitelist={'wash', 'kaylee'}) - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'wash', - 'password': 'wash', - }) + authenticator = MockPAMAuthenticator( + blacklist={'wash'}, whitelist={'wash', 'kaylee'} + ) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'wash', 'password': 'wash'} + ) assert authorized is None # User not in blacklist can log in - authenticator = MockPAMAuthenticator(blacklist={'wash'}, whitelist={'wash', 'kaylee'}) - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'kaylee', - 'password': 'kaylee', - }) + authenticator = MockPAMAuthenticator( + blacklist={'wash'}, whitelist={'wash', 'kaylee'} + ) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'kaylee', 'password': 'kaylee'} + ) assert authorized['name'] == 'kaylee' # User in whitelist, blacklist irrelevent - authenticator = MockPAMAuthenticator(blacklist={'mal'}, whitelist={'wash', 'kaylee'}) - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'wash', - 'password': 'wash', - }) + authenticator = MockPAMAuthenticator( + blacklist={'mal'}, whitelist={'wash', 'kaylee'} + ) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'wash', 'password': 'wash'} + ) assert authorized['name'] == 'wash' # User in neither list - authenticator = MockPAMAuthenticator(blacklist={'mal'}, whitelist={'wash', 'kaylee'}) - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'simon', - 'password': 'simon', - }) + authenticator = MockPAMAuthenticator( + blacklist={'mal'}, whitelist={'wash', 'kaylee'} + ) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'simon', 'password': 'simon'} + ) assert authorized is None # blacklist == {} authenticator = MockPAMAuthenticator(blacklist=set(), whitelist={'wash', 'kaylee'}) - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'kaylee', - 'password': 'kaylee', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'kaylee', 'password': 'kaylee'} + ) assert authorized['name'] == 'kaylee' async def test_deprecated_signatures(): - def deprecated_xlist(self, username): return True @@ -244,20 +244,18 @@ def deprecated_xlist(self, username): check_blacklist=deprecated_xlist, ): deprecated_authenticator = MockPAMAuthenticator() - authorized = await deprecated_authenticator.get_authenticated_user(None, { - 'username': 'test', - 'password': 'test' - }) + authorized = await deprecated_authenticator.get_authenticated_user( + None, {'username': 'test', 'password': 'test'} + ) assert authorized is not None async def test_pam_auth_no_such_group(): authenticator = MockPAMAuthenticator(group_whitelist={'nosuchcrazygroup'}) - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'kaylee', - 'password': 'kaylee', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'kaylee', 'password': 'kaylee'} + ) assert authorized is None @@ -302,6 +300,7 @@ async def test_add_system_user(): authenticator.add_user_cmd = ['echo', '/home/USERNAME'] record = {} + class DummyPopen: def __init__(self, cmd, *args, **kwargs): record['cmd'] = cmd @@ -402,44 +401,38 @@ async def test_auth_state_disabled(app, auth_state_unavailable): async def test_normalize_names(): a = MockPAMAuthenticator() - authorized = await a.get_authenticated_user(None, { - 'username': 'ZOE', - 'password': 'ZOE', - }) + authorized = await a.get_authenticated_user( + None, {'username': 'ZOE', 'password': 'ZOE'} + ) assert authorized['name'] == 'zoe' - authorized = await a.get_authenticated_user(None, { - 'username': 'Glenn', - 'password': 'Glenn', - }) + authorized = await a.get_authenticated_user( + None, {'username': 'Glenn', 'password': 'Glenn'} + ) assert authorized['name'] == 'glenn' - authorized = await a.get_authenticated_user(None, { - 'username': 'hExi', - 'password': 'hExi', - }) + authorized = await a.get_authenticated_user( + None, {'username': 'hExi', 'password': 'hExi'} + ) assert authorized['name'] == 'hexi' - authorized = await a.get_authenticated_user(None, { - 'username': 'Test', - 'password': 'Test', - }) + authorized = await a.get_authenticated_user( + None, {'username': 'Test', 'password': 'Test'} + ) assert authorized['name'] == 'test' async def test_username_map(): a = MockPAMAuthenticator(username_map={'wash': 'alpha'}) - authorized = await a.get_authenticated_user(None, { - 'username': 'WASH', - 'password': 'WASH', - }) + authorized = await a.get_authenticated_user( + None, {'username': 'WASH', 'password': 'WASH'} + ) assert authorized['name'] == 'alpha' - authorized = await a.get_authenticated_user(None, { - 'username': 'Inara', - 'password': 'Inara', - }) + authorized = await a.get_authenticated_user( + None, {'username': 'Inara', 'password': 'Inara'} + ) assert authorized['name'] == 'inara' @@ -463,9 +456,8 @@ def test_auth_hook(authenticator, handler, authentication): a = MockPAMAuthenticator(post_auth_hook=test_auth_hook) - authorized = yield a.get_authenticated_user(None, { - 'username': 'test_user', - 'password': 'test_user' - }) + authorized = yield a.get_authenticated_user( + None, {'username': 'test_user', 'password': 'test_user'} + ) assert authorized['testkey'] == 'testvalue' diff --git a/jupyterhub/tests/test_auth_expiry.py b/jupyterhub/tests/test_auth_expiry.py --- a/jupyterhub/tests/test_auth_expiry.py +++ b/jupyterhub/tests/test_auth_expiry.py @@ -7,15 +7,16 @@ - doesn't need refresh - needs refresh and cannot be refreshed without new login """ - import asyncio from contextlib import contextmanager from unittest import mock -from urllib.parse import parse_qs, urlparse +from urllib.parse import parse_qs +from urllib.parse import urlparse import pytest -from .utils import api_request, get_page +from .utils import api_request +from .utils import get_page async def refresh_expired(authenticator, user): diff --git a/jupyterhub/tests/test_crypto.py b/jupyterhub/tests/test_crypto.py --- a/jupyterhub/tests/test_crypto.py +++ b/jupyterhub/tests/test_crypto.py @@ -1,24 +1,29 @@ -from binascii import b2a_hex, b2a_base64 import os +from binascii import b2a_base64 +from binascii import b2a_hex +from unittest.mock import patch import pytest -from unittest.mock import patch from .. import crypto -from ..crypto import encrypt, decrypt +from ..crypto import decrypt +from ..crypto import encrypt keys = [('%i' % i).encode('ascii') * 32 for i in range(3)] -hex_keys = [ b2a_hex(key).decode('ascii') for key in keys ] -b64_keys = [ b2a_base64(key).decode('ascii').strip() for key in keys ] - - [email protected]("key_env, keys", [ - (hex_keys[0], [keys[0]]), - (';'.join([b64_keys[0], hex_keys[1]]), keys[:2]), - (';'.join([hex_keys[0], b64_keys[1], '']), keys[:2]), - ('', []), - (';', []), -]) +hex_keys = [b2a_hex(key).decode('ascii') for key in keys] +b64_keys = [b2a_base64(key).decode('ascii').strip() for key in keys] + + [email protected]( + "key_env, keys", + [ + (hex_keys[0], [keys[0]]), + (';'.join([b64_keys[0], hex_keys[1]]), keys[:2]), + (';'.join([hex_keys[0], b64_keys[1], '']), keys[:2]), + ('', []), + (';', []), + ], +) def test_env_constructor(key_env, keys): with patch.dict(os.environ, {crypto.KEY_ENV: key_env}): ck = crypto.CryptKeeper() @@ -29,12 +34,15 @@ def test_env_constructor(key_env, keys): assert ck.fernet is None [email protected]("key", [ - 'a' * 44, # base64, not 32 bytes - ('%44s' % 'notbase64'), # not base64 - b'x' * 64, # not hex - b'short', # not 32 bytes -]) [email protected]( + "key", + [ + 'a' * 44, # base64, not 32 bytes + ('%44s' % 'notbase64'), # not base64 + b'x' * 64, # not hex + b'short', # not 32 bytes + ], +) def test_bad_keys(key): ck = crypto.CryptKeeper() with pytest.raises(ValueError): @@ -76,4 +84,3 @@ async def test_missing_keys(crypt_keeper): with pytest.raises(crypto.NoEncryptionKeys): await decrypt(b'whatever') - diff --git a/jupyterhub/tests/test_db.py b/jupyterhub/tests/test_db.py --- a/jupyterhub/tests/test_db.py +++ b/jupyterhub/tests/test_db.py @@ -1,14 +1,16 @@ -from glob import glob import os -from subprocess import check_call import sys import tempfile +from glob import glob +from subprocess import check_call import pytest from pytest import raises from traitlets.config import Config -from ..app import NewToken, UpgradeDB, JupyterHub +from ..app import JupyterHub +from ..app import NewToken +from ..app import UpgradeDB here = os.path.abspath(os.path.dirname(__file__)) @@ -33,13 +35,7 @@ def generate_old_db(env_dir, hub_version, db_url): check_call([env_py, populate_db, db_url]) [email protected]( - 'hub_version', - [ - '0.7.2', - '0.8.1', - ], -) [email protected]('hub_version', ['0.7.2', '0.8.1']) async def test_upgrade(tmpdir, hub_version): db_url = os.getenv('JUPYTERHUB_TEST_DB_URL') if db_url: diff --git a/jupyterhub/tests/test_dummyauth.py b/jupyterhub/tests/test_dummyauth.py --- a/jupyterhub/tests/test_dummyauth.py +++ b/jupyterhub/tests/test_dummyauth.py @@ -1,52 +1,47 @@ """Tests for dummy authentication""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import pytest from jupyterhub.auth import DummyAuthenticator + async def test_dummy_auth_without_global_password(): authenticator = DummyAuthenticator() - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'test_user', - 'password': 'test_pass', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'test_user', 'password': 'test_pass'} + ) assert authorized['name'] == 'test_user' - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'test_user', - 'password': '', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'test_user', 'password': ''} + ) assert authorized['name'] == 'test_user' + async def test_dummy_auth_without_username(): authenticator = DummyAuthenticator() - authorized = await authenticator.get_authenticated_user(None, { - 'username': '', - 'password': 'test_pass', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': '', 'password': 'test_pass'} + ) assert authorized is None + async def test_dummy_auth_with_global_password(): authenticator = DummyAuthenticator() authenticator.password = "test_password" - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'test_user', - 'password': 'test_password', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'test_user', 'password': 'test_password'} + ) assert authorized['name'] == 'test_user' - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'test_user', - 'password': 'qwerty', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'test_user', 'password': 'qwerty'} + ) assert authorized is None - authorized = await authenticator.get_authenticated_user(None, { - 'username': 'some_other_user', - 'password': 'test_password', - }) + authorized = await authenticator.get_authenticated_user( + None, {'username': 'some_other_user', 'password': 'test_password'} + ) assert authorized['name'] == 'some_other_user' diff --git a/jupyterhub/tests/test_internal_ssl_api.py b/jupyterhub/tests/test_internal_ssl_api.py --- a/jupyterhub/tests/test_internal_ssl_api.py +++ b/jupyterhub/tests/test_internal_ssl_api.py @@ -1,7 +1,6 @@ """Tests for the SSL enabled REST API.""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - from jupyterhub.tests.test_api import * + ssl_enabled = True diff --git a/jupyterhub/tests/test_internal_ssl_app.py b/jupyterhub/tests/test_internal_ssl_app.py --- a/jupyterhub/tests/test_internal_ssl_app.py +++ b/jupyterhub/tests/test_internal_ssl_app.py @@ -1,10 +1,9 @@ """Test the JupyterHub entry point with internal ssl""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import sys -import jupyterhub.tests.mocking +import jupyterhub.tests.mocking from jupyterhub.tests.test_app import * + ssl_enabled = True diff --git a/jupyterhub/tests/test_internal_ssl_connections.py b/jupyterhub/tests/test_internal_ssl_connections.py --- a/jupyterhub/tests/test_internal_ssl_connections.py +++ b/jupyterhub/tests/test_internal_ssl_connections.py @@ -1,19 +1,17 @@ """Tests for jupyterhub internal_ssl connections""" - +import sys import time from subprocess import check_output -import sys +from unittest import mock from urllib.parse import urlparse import pytest - -import jupyterhub -from tornado import gen -from unittest import mock from requests.exceptions import SSLError +from tornado import gen -from .utils import async_requests +import jupyterhub from .test_api import add_user +from .utils import async_requests ssl_enabled = True @@ -25,8 +23,10 @@ def wait_for_spawner(spawner, timeout=10): polling at shorter intervals for early termination """ deadline = time.monotonic() + timeout + def wait(): return spawner.server.wait_up(timeout=1, http=True) + while time.monotonic() < deadline: status = yield spawner.poll() assert status is None @@ -58,9 +58,9 @@ async def test_connection_proxy_api_wrong_certs(app): async def test_connection_notebook_wrong_certs(app): """Connecting to a notebook fails without correct certs""" with mock.patch.dict( - app.config.LocalProcessSpawner, - {'cmd': [sys.executable, '-m', 'jupyterhub.tests.mocksu']} - ): + app.config.LocalProcessSpawner, + {'cmd': [sys.executable, '-m', 'jupyterhub.tests.mocksu']}, + ): user = add_user(app.db, app, name='foo') await user.spawn() await wait_for_spawner(user.spawner) diff --git a/jupyterhub/tests/test_internal_ssl_spawner.py b/jupyterhub/tests/test_internal_ssl_spawner.py --- a/jupyterhub/tests/test_internal_ssl_spawner.py +++ b/jupyterhub/tests/test_internal_ssl_spawner.py @@ -1,7 +1,6 @@ """Tests for process spawning with internal_ssl""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - from jupyterhub.tests.test_spawner import * + ssl_enabled = True diff --git a/jupyterhub/tests/test_named_servers.py b/jupyterhub/tests/test_named_servers.py --- a/jupyterhub/tests/test_named_servers.py +++ b/jupyterhub/tests/test_named_servers.py @@ -5,15 +5,21 @@ import pytest from ..utils import url_path_join - -from .test_api import api_request, add_user, fill_user, normalize_user, TIMESTAMP from .mocking import public_url +from .test_api import add_user +from .test_api import api_request +from .test_api import fill_user +from .test_api import normalize_user +from .test_api import TIMESTAMP from .utils import async_requests + @pytest.fixture def named_servers(app): - with mock.patch.dict(app.tornado_settings, - {'allow_named_servers': True, 'named_server_limit_per_user': 2}): + with mock.patch.dict( + app.tornado_settings, + {'allow_named_servers': True, 'named_server_limit_per_user': 2}, + ): yield @@ -30,24 +36,27 @@ async def test_default_server(app, named_servers): user_model = normalize_user(r.json()) print(user_model) - assert user_model == fill_user({ - 'name': username, - 'auth_state': None, - 'server': user.url, - 'servers': { - '': { - 'name': '', - 'started': TIMESTAMP, - 'last_activity': TIMESTAMP, - 'url': user.url, - 'pending': None, - 'ready': True, - 'progress_url': 'PREFIX/hub/api/users/{}/server/progress'.format(username), - 'state': {'pid': 0}, + assert user_model == fill_user( + { + 'name': username, + 'auth_state': None, + 'server': user.url, + 'servers': { + '': { + 'name': '', + 'started': TIMESTAMP, + 'last_activity': TIMESTAMP, + 'url': user.url, + 'pending': None, + 'ready': True, + 'progress_url': 'PREFIX/hub/api/users/{}/server/progress'.format( + username + ), + 'state': {'pid': 0}, + } }, - }, - }) - + } + ) # now stop the server r = await api_request(app, 'users', username, 'server', method='delete') @@ -58,11 +67,9 @@ async def test_default_server(app, named_servers): r.raise_for_status() user_model = normalize_user(r.json()) - assert user_model == fill_user({ - 'name': username, - 'servers': {}, - 'auth_state': None, - }) + assert user_model == fill_user( + {'name': username, 'servers': {}, 'auth_state': None} + ) async def test_create_named_server(app, named_servers): @@ -89,24 +96,27 @@ async def test_create_named_server(app, named_servers): r.raise_for_status() user_model = normalize_user(r.json()) - assert user_model == fill_user({ - 'name': username, - 'auth_state': None, - 'servers': { - servername: { - 'name': name, - 'started': TIMESTAMP, - 'last_activity': TIMESTAMP, - 'url': url_path_join(user.url, name, '/'), - 'pending': None, - 'ready': True, - 'progress_url': 'PREFIX/hub/api/users/{}/servers/{}/progress'.format( - username, servername), - 'state': {'pid': 0}, - } - for name in [servername] - }, - }) + assert user_model == fill_user( + { + 'name': username, + 'auth_state': None, + 'servers': { + servername: { + 'name': name, + 'started': TIMESTAMP, + 'last_activity': TIMESTAMP, + 'url': url_path_join(user.url, name, '/'), + 'pending': None, + 'ready': True, + 'progress_url': 'PREFIX/hub/api/users/{}/servers/{}/progress'.format( + username, servername + ), + 'state': {'pid': 0}, + } + for name in [servername] + }, + } + ) async def test_delete_named_server(app, named_servers): @@ -119,7 +129,9 @@ async def test_delete_named_server(app, named_servers): r.raise_for_status() assert r.status_code == 201 - r = await api_request(app, 'users', username, 'servers', servername, method='delete') + r = await api_request( + app, 'users', username, 'servers', servername, method='delete' + ) r.raise_for_status() assert r.status_code == 204 @@ -127,18 +139,20 @@ async def test_delete_named_server(app, named_servers): r.raise_for_status() user_model = normalize_user(r.json()) - assert user_model == fill_user({ - 'name': username, - 'auth_state': None, - 'servers': {}, - }) + assert user_model == fill_user( + {'name': username, 'auth_state': None, 'servers': {}} + ) # wrapper Spawner is gone assert servername not in user.spawners # low-level record still exists assert servername in user.orm_spawners r = await api_request( - app, 'users', username, 'servers', servername, + app, + 'users', + username, + 'servers', + servername, method='delete', data=json.dumps({'remove': True}), ) @@ -153,7 +167,9 @@ async def test_named_server_disabled(app): servername = 'okay' r = await api_request(app, 'users', username, 'servers', servername, method='post') assert r.status_code == 400 - r = await api_request(app, 'users', username, 'servers', servername, method='delete') + r = await api_request( + app, 'users', username, 'servers', servername, method='delete' + ) assert r.status_code == 400 @@ -180,7 +196,10 @@ async def test_named_server_limit(app, named_servers): servername3 = 'bar-3' r = await api_request(app, 'users', username, 'servers', servername3, method='post') assert r.status_code == 400 - assert r.json() == {"status": 400, "message": "User foo already has the maximum of 2 named servers. One must be deleted before a new server can be created"} + assert r.json() == { + "status": 400, + "message": "User foo already has the maximum of 2 named servers. One must be deleted before a new server can be created", + } # Create default server r = await api_request(app, 'users', username, 'server', method='post') @@ -189,7 +208,11 @@ async def test_named_server_limit(app, named_servers): # Delete 1st named server r = await api_request( - app, 'users', username, 'servers', servername1, + app, + 'users', + username, + 'servers', + servername1, method='delete', data=json.dumps({'remove': True}), ) diff --git a/jupyterhub/tests/test_objects.py b/jupyterhub/tests/test_objects.py --- a/jupyterhub/tests/test_objects.py +++ b/jupyterhub/tests/test_objects.py @@ -1,6 +1,6 @@ """Tests for basic object-wrappers""" - import socket + import pytest from jupyterhub.objects import Server @@ -16,7 +16,7 @@ 'port': 123, 'host': 'http://abc:123', 'url': 'http://abc:123/x/', - } + }, ), ( 'https://abc', @@ -26,9 +26,9 @@ 'proto': 'https', 'host': 'https://abc:443', 'url': 'https://abc:443/x/', - } + }, ), - ] + ], ) def test_bind_url(bind_url, attrs): s = Server(bind_url=bind_url, base_url='/x/') @@ -43,26 +43,28 @@ def test_bind_url(bind_url, attrs): 'ip, port, attrs', [ ( - '', 123, + '', + 123, { 'ip': '', 'port': 123, 'host': 'http://{}:123'.format(_hostname), 'url': 'http://{}:123/x/'.format(_hostname), 'bind_url': 'http://*:123/x/', - } + }, ), ( - '127.0.0.1', 999, + '127.0.0.1', + 999, { 'ip': '127.0.0.1', 'port': 999, 'host': 'http://127.0.0.1:999', 'url': 'http://127.0.0.1:999/x/', 'bind_url': 'http://127.0.0.1:999/x/', - } + }, ), - ] + ], ) def test_ip_port(ip, port, attrs): s = Server(ip=ip, port=port, base_url='/x/') diff --git a/jupyterhub/tests/test_orm.py b/jupyterhub/tests/test_orm.py --- a/jupyterhub/tests/test_orm.py +++ b/jupyterhub/tests/test_orm.py @@ -1,27 +1,26 @@ """Tests for the ORM bits""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - -from datetime import datetime, timedelta import os import socket +from datetime import datetime +from datetime import timedelta from unittest import mock import pytest from tornado import gen -from .. import orm -from .. import objects from .. import crypto +from .. import objects +from .. import orm +from ..emptyclass import EmptyClass from ..user import User from .mocking import MockSpawner -from ..emptyclass import EmptyClass def assert_not_found(db, ORMType, id): """Assert that an item with a given id is not found""" - assert db.query(ORMType).filter(ORMType.id==id).first() is None + assert db.query(ORMType).filter(ORMType.id == id).first() is None def test_server(db): @@ -124,7 +123,9 @@ def test_token_expiry(db): # approximate range assert orm_token.expires_at > now + timedelta(seconds=50) assert orm_token.expires_at < now + timedelta(seconds=70) - the_future = mock.patch('jupyterhub.orm.utcnow', lambda : now + timedelta(seconds=70)) + the_future = mock.patch( + 'jupyterhub.orm.utcnow', lambda: now + timedelta(seconds=70) + ) with the_future: found = orm.APIToken.find(db, token=token) assert found is None @@ -215,11 +216,9 @@ class BadSpawner(MockSpawner): def start(self): raise RuntimeError("Split the party") - user = User(orm_user, { - 'spawner_class': BadSpawner, - 'config': None, - 'statsd': EmptyClass(), - }) + user = User( + orm_user, {'spawner_class': BadSpawner, 'config': None, 'statsd': EmptyClass()} + ) with pytest.raises(RuntimeError) as exc: await user.spawn() @@ -346,9 +345,7 @@ def test_user_delete_cascade(db): oauth_code = orm.OAuthCode(client=oauth_client, user=user) db.add(oauth_code) oauth_token = orm.OAuthAccessToken( - client=oauth_client, - user=user, - grant_type=orm.GrantType.authorization_code, + client=oauth_client, user=user, grant_type=orm.GrantType.authorization_code ) db.add(oauth_token) db.commit() @@ -384,9 +381,7 @@ def test_oauth_client_delete_cascade(db): oauth_code = orm.OAuthCode(client=oauth_client, user=user) db.add(oauth_code) oauth_token = orm.OAuthAccessToken( - client=oauth_client, - user=user, - grant_type=orm.GrantType.authorization_code, + client=oauth_client, user=user, grant_type=orm.GrantType.authorization_code ) db.add(oauth_token) db.commit() @@ -477,6 +472,3 @@ def test_group_delete_cascade(db): db.delete(user1) db.commit() assert user1 not in group1.users - - - diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -1,30 +1,27 @@ """Tests for HTML pages""" - import asyncio import sys from unittest import mock -from urllib.parse import urlencode, urlparse +from urllib.parse import urlencode +from urllib.parse import urlparse +import pytest from bs4 import BeautifulSoup from tornado import gen from tornado.httputil import url_concat -from ..handlers import BaseHandler -from ..utils import url_path_join as ujoin from .. import orm from ..auth import Authenticator - -import pytest - -from .mocking import FormSpawner, FalsyCallableFormSpawner -from .utils import ( - async_requests, - api_request, - add_user, - get_page, - public_url, - public_host, -) +from ..handlers import BaseHandler +from ..utils import url_path_join as ujoin +from .mocking import FalsyCallableFormSpawner +from .mocking import FormSpawner +from .utils import add_user +from .utils import api_request +from .utils import async_requests +from .utils import get_page +from .utils import public_host +from .utils import public_url async def test_root_no_auth(app): @@ -53,8 +50,7 @@ async def test_root_redirect(app): async def test_root_default_url_noauth(app): - with mock.patch.dict(app.tornado_settings, - {'default_url': '/foo/bar'}): + with mock.patch.dict(app.tornado_settings, {'default_url': '/foo/bar'}): r = await get_page('/', app, allow_redirects=False) r.raise_for_status() url = r.headers.get('Location', '') @@ -65,8 +61,7 @@ async def test_root_default_url_noauth(app): async def test_root_default_url_auth(app): name = 'wash' cookies = await app.login_user(name) - with mock.patch.dict(app.tornado_settings, - {'default_url': '/foo/bar'}): + with mock.patch.dict(app.tornado_settings, {'default_url': '/foo/bar'}): r = await get_page('/', app, cookies=cookies, allow_redirects=False) r.raise_for_status() url = r.headers.get('Location', '') @@ -106,12 +101,7 @@ async def test_admin(app): assert r.url.endswith('/admin') [email protected]('sort', [ - 'running', - 'last_activity', - 'admin', - 'name', -]) [email protected]('sort', ['running', 'last_activity', 'admin', 'name']) async def test_admin_sort(app, sort): cookies = await app.login_user('admin') r = await get_page('admin?sort=%s' % sort, app, cookies=cookies) @@ -146,7 +136,9 @@ async def test_spawn_redirect(app): assert path == ujoin(app.base_url, '/user/%s/' % name) # stop server to ensure /user/name is handled by the Hub - r = await api_request(app, 'users', name, 'server', method='delete', cookies=cookies) + r = await api_request( + app, 'users', name, 'server', method='delete', cookies=cookies + ) r.raise_for_status() # test handing of trailing slash on `/user/name` @@ -208,7 +200,9 @@ async def test_spawn_page(app): async def test_spawn_page_falsy_callable(app): - with mock.patch.dict(app.users.settings, {'spawner_class': FalsyCallableFormSpawner}): + with mock.patch.dict( + app.users.settings, {'spawner_class': FalsyCallableFormSpawner} + ): cookies = await app.login_user('erik') r = await get_page('spawn', app, cookies=cookies) assert 'user/erik' in r.url @@ -276,22 +270,22 @@ async def test_spawn_form_with_file(app): u = app.users[orm_u] await u.stop() - r = await async_requests.post(ujoin(base_url, 'spawn'), - cookies=cookies, - data={ - 'bounds': ['-1', '1'], - 'energy': '511keV', - }, - files={'hello': ('hello.txt', b'hello world\n')} - ) + r = await async_requests.post( + ujoin(base_url, 'spawn'), + cookies=cookies, + data={'bounds': ['-1', '1'], 'energy': '511keV'}, + files={'hello': ('hello.txt', b'hello world\n')}, + ) r.raise_for_status() assert u.spawner.user_options == { 'energy': '511keV', 'bounds': [-1, 1], 'notspecified': 5, - 'hello': {'filename': 'hello.txt', - 'body': b'hello world\n', - 'content_type': 'application/unknown'}, + 'hello': { + 'filename': 'hello.txt', + 'body': b'hello world\n', + 'content_type': 'application/unknown', + }, } @@ -305,9 +299,9 @@ async def test_user_redirect(app): path = urlparse(r.url).path assert path == ujoin(app.base_url, '/hub/login') query = urlparse(r.url).query - assert query == urlencode({ - 'next': ujoin(app.hub.base_url, '/user-redirect/tree/top/') - }) + assert query == urlencode( + {'next': ujoin(app.hub.base_url, '/user-redirect/tree/top/')} + ) r = await get_page('/user-redirect/notebooks/test.ipynb', app, cookies=cookies) r.raise_for_status() @@ -339,19 +333,17 @@ async def test_user_redirect_deprecated(app): path = urlparse(r.url).path assert path == ujoin(app.base_url, '/hub/login') query = urlparse(r.url).query - assert query == urlencode({ - 'next': ujoin(app.base_url, '/hub/user/baduser/test.ipynb') - }) + assert query == urlencode( + {'next': ujoin(app.base_url, '/hub/user/baduser/test.ipynb')} + ) async def test_login_fail(app): name = 'wash' base_url = public_url(app) - r = await async_requests.post(base_url + 'hub/login', - data={ - 'username': name, - 'password': 'wrong', - }, + r = await async_requests.post( + base_url + 'hub/login', + data={'username': name, 'password': 'wrong'}, allow_redirects=False, ) assert not r.cookies @@ -359,20 +351,17 @@ async def test_login_fail(app): async def test_login_strip(app): """Test that login form doesn't strip whitespace from passwords""" - form_data = { - 'username': 'spiff', - 'password': ' space man ', - } + form_data = {'username': 'spiff', 'password': ' space man '} base_url = public_url(app) called_with = [] + @gen.coroutine def mock_authenticate(handler, data): called_with.append(data) with mock.patch.object(app.authenticator, 'authenticate', mock_authenticate): - await async_requests.post(base_url + 'hub/login', - data=form_data, - allow_redirects=False, + await async_requests.post( + base_url + 'hub/login', data=form_data, allow_redirects=False ) assert called_with == [form_data] @@ -389,12 +378,11 @@ def mock_authenticate(handler, data): (False, '/user/other', '/hub/user/other'), (False, '/absolute', '/absolute'), (False, '/has?query#andhash', '/has?query#andhash'), - # next_url outside is not allowed (False, 'https://other.domain', ''), (False, 'ftp://other.domain', ''), (False, '//other.domain', ''), - ] + ], ) async def test_login_redirect(app, running, next_url, location): cookies = await app.login_user('river') @@ -427,10 +415,11 @@ async def test_auto_login(app, request): class DummyLoginHandler(BaseHandler): def get(self): self.write('ok!') + base_url = public_url(app) + '/' - app.tornado_application.add_handlers(".*$", [ - (ujoin(app.hub.base_url, 'dummy'), DummyLoginHandler), - ]) + app.tornado_application.add_handlers( + ".*$", [(ujoin(app.hub.base_url, 'dummy'), DummyLoginHandler)] + ) # no auto_login: end up at /hub/login r = await async_requests.get(base_url) assert r.url == public_url(app, path='hub/login') @@ -438,9 +427,7 @@ def get(self): authenticator = Authenticator(auto_login=True) authenticator.login_url = lambda base_url: ujoin(base_url, 'dummy') - with mock.patch.dict(app.tornado_settings, { - 'authenticator': authenticator, - }): + with mock.patch.dict(app.tornado_settings, {'authenticator': authenticator}): r = await async_requests.get(base_url) assert r.url == public_url(app, path='hub/dummy') @@ -449,10 +436,12 @@ async def test_auto_login_logout(app): name = 'burnham' cookies = await app.login_user(name) - with mock.patch.dict(app.tornado_settings, { - 'authenticator': Authenticator(auto_login=True), - }): - r = await async_requests.get(public_host(app) + app.tornado_settings['logout_url'], cookies=cookies) + with mock.patch.dict( + app.tornado_settings, {'authenticator': Authenticator(auto_login=True)} + ): + r = await async_requests.get( + public_host(app) + app.tornado_settings['logout_url'], cookies=cookies + ) r.raise_for_status() logout_url = public_host(app) + app.tornado_settings['logout_url'] assert r.url == logout_url @@ -462,7 +451,9 @@ async def test_auto_login_logout(app): async def test_logout(app): name = 'wash' cookies = await app.login_user(name) - r = await async_requests.get(public_host(app) + app.tornado_settings['logout_url'], cookies=cookies) + r = await async_requests.get( + public_host(app) + app.tornado_settings['logout_url'], cookies=cookies + ) r.raise_for_status() login_url = public_host(app) + app.tornado_settings['login_url'] assert r.url == login_url @@ -489,12 +480,11 @@ async def test_shutdown_on_logout(app, shutdown_on_logout): assert spawner.active # logout - with mock.patch.dict(app.tornado_settings, { - 'shutdown_on_logout': shutdown_on_logout, - }): + with mock.patch.dict( + app.tornado_settings, {'shutdown_on_logout': shutdown_on_logout} + ): r = await async_requests.get( - public_host(app) + app.tornado_settings['logout_url'], - cookies=cookies, + public_host(app) + app.tornado_settings['logout_url'], cookies=cookies ) r.raise_for_status() @@ -549,7 +539,9 @@ async def test_oauth_token_page(app): user = app.users[orm.User.find(app.db, name)] client = orm.OAuthClient(identifier='token') app.db.add(client) - oauth_token = orm.OAuthAccessToken(client=client, user=user, grant_type=orm.GrantType.authorization_code) + oauth_token = orm.OAuthAccessToken( + client=client, user=user, grant_type=orm.GrantType.authorization_code + ) app.db.add(oauth_token) app.db.commit() r = await get_page('token', app, cookies=cookies) @@ -557,23 +549,14 @@ async def test_oauth_token_page(app): assert r.status_code == 200 [email protected]("error_status", [ - 503, - 404, -]) [email protected]("error_status", [503, 404]) async def test_proxy_error(app, error_status): r = await get_page('/error/%i' % error_status, app) assert r.status_code == 200 @pytest.mark.parametrize( - "announcements", - [ - "", - "spawn", - "spawn,home,login", - "login,logout", - ] + "announcements", ["", "spawn", "spawn,home,login", "login,logout"] ) async def test_announcements(app, announcements): """Test announcements on various pages""" @@ -618,16 +601,13 @@ def assert_announcement(name, text): @pytest.mark.parametrize( - "params", - [ - "", - "redirect_uri=/noexist", - "redirect_uri=ok&client_id=nosuchthing", - ] + "params", ["", "redirect_uri=/noexist", "redirect_uri=ok&client_id=nosuchthing"] ) async def test_bad_oauth_get(app, params): cookies = await app.login_user("authorizer") - r = await get_page("hub/api/oauth2/authorize?" + params, app, hub=False, cookies=cookies) + r = await get_page( + "hub/api/oauth2/authorize?" + params, app, hub=False, cookies=cookies + ) assert r.status_code == 400 @@ -637,11 +617,14 @@ async def test_token_page(app): r = await get_page("token", app, cookies=cookies) r.raise_for_status() assert urlparse(r.url).path.endswith('/hub/token') + def extract_body(r): soup = BeautifulSoup(r.text, "html5lib") import re + # trim empty lines return re.sub(r"(\n\s*)+", "\n", soup.body.find(class_="container").text) + body = extract_body(r) assert "Request new API token" in body, body # no tokens yet, no lists diff --git a/jupyterhub/tests/test_proxy.py b/jupyterhub/tests/test_proxy.py --- a/jupyterhub/tests/test_proxy.py +++ b/jupyterhub/tests/test_proxy.py @@ -1,20 +1,21 @@ """Test a proxy being started before the Hub""" - -from contextlib import contextmanager import json import os +from contextlib import contextmanager from queue import Queue from subprocess import Popen -from urllib.parse import urlparse, quote - -from traitlets.config import Config +from urllib.parse import quote +from urllib.parse import urlparse import pytest +from traitlets.config import Config from .. import orm +from ..utils import url_path_join as ujoin +from ..utils import wait_for_http_server from .mocking import MockHub -from .test_api import api_request, add_user -from ..utils import wait_for_http_server, url_path_join as ujoin +from .test_api import add_user +from .test_api import api_request @pytest.fixture @@ -52,25 +53,30 @@ def fin(): env['CONFIGPROXY_AUTH_TOKEN'] = auth_token cmd = [ 'configurable-http-proxy', - '--ip', app.ip, - '--port', str(app.port), - '--api-ip', proxy_ip, - '--api-port', str(proxy_port), + '--ip', + app.ip, + '--port', + str(app.port), + '--api-ip', + proxy_ip, + '--api-port', + str(proxy_port), '--log-level=debug', ] if app.subdomain_host: cmd.append('--host-routing') proxy = Popen(cmd, env=env) - def _cleanup_proxy(): if proxy.poll() is None: proxy.terminate() proxy.wait(timeout=10) + request.addfinalizer(_cleanup_proxy) def wait_for_proxy(): return wait_for_http_server('http://%s:%i' % (proxy_ip, proxy_port)) + await wait_for_proxy() await app.initialize([]) @@ -84,8 +90,9 @@ def wait_for_proxy(): # add user to the db and start a single user server name = 'river' add_user(app.db, app, name=name) - r = await api_request(app, 'users', name, 'server', method='post', - bypass_proxy=True) + r = await api_request( + app, 'users', name, 'server', method='post', bypass_proxy=True + ) r.raise_for_status() routes = await app.proxy.get_all_routes() @@ -122,12 +129,18 @@ def wait_for_proxy(): new_auth_token = 'different!' env['CONFIGPROXY_AUTH_TOKEN'] = new_auth_token proxy_port = 55432 - cmd = ['configurable-http-proxy', - '--ip', app.ip, - '--port', str(app.port), - '--api-ip', proxy_ip, - '--api-port', str(proxy_port), - '--default-target', 'http://%s:%i' % (app.hub_ip, app.hub_port), + cmd = [ + 'configurable-http-proxy', + '--ip', + app.ip, + '--port', + str(app.port), + '--api-ip', + proxy_ip, + '--api-port', + str(proxy_port), + '--default-target', + 'http://%s:%i' % (app.hub_ip, app.hub_port), ] if app.subdomain_host: cmd.append('--host-routing') @@ -140,10 +153,7 @@ def wait_for_proxy(): app, 'proxy', method='patch', - data=json.dumps({ - 'api_url': new_api_url, - 'auth_token': new_auth_token, - }), + data=json.dumps({'api_url': new_api_url, 'auth_token': new_auth_token}), bypass_proxy=True, ) r.raise_for_status() @@ -156,14 +166,8 @@ def wait_for_proxy(): assert sorted(routes.keys()) == [app.hub.routespec, user_spec] [email protected]("username", [ - 'zoe', - '50fia', - '秀樹', - '~TestJH', - 'has@', -]) -async def test_check_routes(app, username, disable_check_routes): [email protected]("username", ['zoe', '50fia', '秀樹', '~TestJH', 'has@']) +async def test_check_routes(app, username, disable_check_routes): proxy = app.proxy test_user = add_user(app.db, app, name=username) r = await api_request(app, 'users/%s/server' % username, method='post') @@ -191,14 +195,17 @@ async def test_check_routes(app, username, disable_check_routes): assert before == after [email protected]("routespec", [ - '/has%20space/foo/', - '/missing-trailing/slash', - '/has/@/', - '/has/' + quote('üñîçø∂é'), - 'host.name/path/', - 'other.host/path/no/slash', -]) [email protected]( + "routespec", + [ + '/has%20space/foo/', + '/missing-trailing/slash', + '/has/@/', + '/has/' + quote('üñîçø∂é'), + 'host.name/path/', + 'other.host/path/no/slash', + ], +) async def test_add_get_delete(app, routespec, disable_check_routes): arg = routespec if not routespec.endswith('/'): @@ -207,6 +214,7 @@ async def test_add_get_delete(app, routespec, disable_check_routes): # host-routes when not host-routing raises an error # and vice versa expect_value_error = bool(app.subdomain_host) ^ (not routespec.startswith('/')) + @contextmanager def context(): if expect_value_error: diff --git a/jupyterhub/tests/test_services.py b/jupyterhub/tests/test_services.py --- a/jupyterhub/tests/test_services.py +++ b/jupyterhub/tests/test_services.py @@ -1,22 +1,26 @@ """Tests for services""" - import asyncio +import os +import sys +import time from binascii import hexlify from contextlib import contextmanager -import os from subprocess import Popen -import sys from threading import Event -import time -from async_generator import asynccontextmanager, async_generator, yield_ import pytest import requests +from async_generator import async_generator +from async_generator import asynccontextmanager +from async_generator import yield_ from tornado import gen from tornado.ioloop import IOLoop +from ..utils import maybe_future +from ..utils import random_port +from ..utils import url_path_join +from ..utils import wait_for_http_server from .mocking import public_url -from ..utils import url_path_join, wait_for_http_server, random_port, maybe_future from .utils import async_requests mockservice_path = os.path.dirname(os.path.abspath(__file__)) @@ -80,12 +84,14 @@ async def test_proxy_service(app, mockservice_url): async def test_external_service(app): name = 'external' async with external_service(app, name=name) as env: - app.services = [{ - 'name': name, - 'admin': True, - 'url': env['JUPYTERHUB_SERVICE_URL'], - 'api_token': env['JUPYTERHUB_API_TOKEN'], - }] + app.services = [ + { + 'name': name, + 'admin': True, + 'url': env['JUPYTERHUB_SERVICE_URL'], + 'api_token': env['JUPYTERHUB_API_TOKEN'], + } + ] await maybe_future(app.init_services()) await app.init_api_tokens() await app.proxy.add_all_services(app._service_map) diff --git a/jupyterhub/tests/test_services_auth.py b/jupyterhub/tests/test_services_auth.py --- a/jupyterhub/tests/test_services_auth.py +++ b/jupyterhub/tests/test_services_auth.py @@ -1,35 +1,42 @@ """Tests for service authentication""" import asyncio -from binascii import hexlify import copy -from functools import partial import json import os -from queue import Queue import sys +from binascii import hexlify +from functools import partial +from queue import Queue from threading import Thread from unittest import mock from urllib.parse import urlparse import pytest -from pytest import raises import requests import requests_mock - -from tornado.ioloop import IOLoop +from pytest import raises from tornado.httpserver import HTTPServer -from tornado.web import RequestHandler, Application, authenticated, HTTPError from tornado.httputil import url_concat +from tornado.ioloop import IOLoop +from tornado.web import Application +from tornado.web import authenticated +from tornado.web import HTTPError +from tornado.web import RequestHandler from .. import orm -from ..services.auth import _ExpiringDict, HubAuth, HubAuthenticated +from ..services.auth import _ExpiringDict +from ..services.auth import HubAuth +from ..services.auth import HubAuthenticated from ..utils import url_path_join -from .mocking import public_url, public_host +from .mocking import public_host +from .mocking import public_url from .test_api import add_user -from .utils import async_requests, AsyncSession +from .utils import async_requests +from .utils import AsyncSession # mock for sending monotonic counter way into the future -monotonic_future = mock.patch('time.monotonic', lambda : sys.maxsize) +monotonic_future = mock.patch('time.monotonic', lambda: sys.maxsize) + def test_expiring_dict(): cache = _ExpiringDict(max_age=30) @@ -69,9 +76,7 @@ def test_expiring_dict(): def test_hub_auth(): auth = HubAuth(cookie_name='foo') - mock_model = { - 'name': 'onyxia' - } + mock_model = {'name': 'onyxia'} url = url_path_join(auth.api_url, "authorizations/cookie/foo/bar") with requests_mock.Mocker() as m: m.get(url, text=json.dumps(mock_model)) @@ -87,9 +92,7 @@ def test_hub_auth(): assert user_model is None # invalidate cache with timer - mock_model = { - 'name': 'willow' - } + mock_model = {'name': 'willow'} with monotonic_future, requests_mock.Mocker() as m: m.get(url, text=json.dumps(mock_model)) user_model = auth.user_for_cookie('bar') @@ -110,16 +113,14 @@ def test_hub_auth(): def test_hub_authenticated(request): auth = HubAuth(cookie_name='jubal') - mock_model = { - 'name': 'jubalearly', - 'groups': ['lions'], - } + mock_model = {'name': 'jubalearly', 'groups': ['lions']} cookie_url = url_path_join(auth.api_url, "authorizations/cookie", auth.cookie_name) good_url = url_path_join(cookie_url, "early") bad_url = url_path_join(cookie_url, "late") class TestHandler(HubAuthenticated, RequestHandler): hub_auth = auth + @authenticated def get(self): self.finish(self.get_current_user()) @@ -127,16 +128,15 @@ def get(self): # start hub-authenticated service in a thread: port = 50505 q = Queue() + def run(): asyncio.set_event_loop(asyncio.new_event_loop()) - app = Application([ - ('/*', TestHandler), - ], login_url=auth.login_url) + app = Application([('/*', TestHandler)], login_url=auth.login_url) http_server = HTTPServer(app) http_server.listen(port) loop = IOLoop.current() - loop.add_callback(lambda : q.put(loop)) + loop.add_callback(lambda: q.put(loop)) loop.start() t = Thread(target=run) @@ -146,6 +146,7 @@ def finish_thread(): loop.add_callback(loop.stop) t.join(timeout=30) assert not t.is_alive() + request.addfinalizer(finish_thread) # wait for thread to start @@ -153,16 +154,15 @@ def finish_thread(): with requests_mock.Mocker(real_http=True) as m: # no cookie - r = requests.get('http://127.0.0.1:%i' % port, - allow_redirects=False, - ) + r = requests.get('http://127.0.0.1:%i' % port, allow_redirects=False) r.raise_for_status() assert r.status_code == 302 assert auth.login_url in r.headers['Location'] # wrong cookie m.get(bad_url, status_code=404) - r = requests.get('http://127.0.0.1:%i' % port, + r = requests.get( + 'http://127.0.0.1:%i' % port, cookies={'jubal': 'late'}, allow_redirects=False, ) @@ -176,7 +176,8 @@ def finish_thread(): # upstream 403 m.get(bad_url, status_code=403) - r = requests.get('http://127.0.0.1:%i' % port, + r = requests.get( + 'http://127.0.0.1:%i' % port, cookies={'jubal': 'late'}, allow_redirects=False, ) @@ -185,7 +186,8 @@ def finish_thread(): m.get(good_url, text=json.dumps(mock_model)) # no whitelist - r = requests.get('http://127.0.0.1:%i' % port, + r = requests.get( + 'http://127.0.0.1:%i' % port, cookies={'jubal': 'early'}, allow_redirects=False, ) @@ -194,7 +196,8 @@ def finish_thread(): # pass whitelist TestHandler.hub_users = {'jubalearly'} - r = requests.get('http://127.0.0.1:%i' % port, + r = requests.get( + 'http://127.0.0.1:%i' % port, cookies={'jubal': 'early'}, allow_redirects=False, ) @@ -203,7 +206,8 @@ def finish_thread(): # no pass whitelist TestHandler.hub_users = {'kaylee'} - r = requests.get('http://127.0.0.1:%i' % port, + r = requests.get( + 'http://127.0.0.1:%i' % port, cookies={'jubal': 'early'}, allow_redirects=False, ) @@ -211,7 +215,8 @@ def finish_thread(): # pass group whitelist TestHandler.hub_groups = {'lions'} - r = requests.get('http://127.0.0.1:%i' % port, + r = requests.get( + 'http://127.0.0.1:%i' % port, cookies={'jubal': 'early'}, allow_redirects=False, ) @@ -220,7 +225,8 @@ def finish_thread(): # no pass group whitelist TestHandler.hub_groups = {'tigers'} - r = requests.get('http://127.0.0.1:%i' % port, + r = requests.get( + 'http://127.0.0.1:%i' % port, cookies={'jubal': 'early'}, allow_redirects=False, ) @@ -230,15 +236,14 @@ def finish_thread(): async def test_hubauth_cookie(app, mockservice_url): """Test HubAuthenticated service with user cookies""" cookies = await app.login_user('badger') - r = await async_requests.get(public_url(app, mockservice_url) + '/whoami/', cookies=cookies) + r = await async_requests.get( + public_url(app, mockservice_url) + '/whoami/', cookies=cookies + ) r.raise_for_status() print(r.text) reply = r.json() - sub_reply = { key: reply.get(key, 'missing') for key in ['name', 'admin']} - assert sub_reply == { - 'name': 'badger', - 'admin': False, - } + sub_reply = {key: reply.get(key, 'missing') for key in ['name', 'admin']} + assert sub_reply == {'name': 'badger', 'admin': False} async def test_hubauth_token(app, mockservice_url): @@ -248,28 +253,25 @@ async def test_hubauth_token(app, mockservice_url): app.db.commit() # token in Authorization header - r = await async_requests.get(public_url(app, mockservice_url) + '/whoami/', - headers={ - 'Authorization': 'token %s' % token, - }) + r = await async_requests.get( + public_url(app, mockservice_url) + '/whoami/', + headers={'Authorization': 'token %s' % token}, + ) reply = r.json() - sub_reply = { key: reply.get(key, 'missing') for key in ['name', 'admin']} - assert sub_reply == { - 'name': 'river', - 'admin': False, - } + sub_reply = {key: reply.get(key, 'missing') for key in ['name', 'admin']} + assert sub_reply == {'name': 'river', 'admin': False} # token in ?token parameter - r = await async_requests.get(public_url(app, mockservice_url) + '/whoami/?token=%s' % token) + r = await async_requests.get( + public_url(app, mockservice_url) + '/whoami/?token=%s' % token + ) r.raise_for_status() reply = r.json() - sub_reply = { key: reply.get(key, 'missing') for key in ['name', 'admin']} - assert sub_reply == { - 'name': 'river', - 'admin': False, - } + sub_reply = {key: reply.get(key, 'missing') for key in ['name', 'admin']} + assert sub_reply == {'name': 'river', 'admin': False} - r = await async_requests.get(public_url(app, mockservice_url) + '/whoami/?token=no-such-token', + r = await async_requests.get( + public_url(app, mockservice_url) + '/whoami/?token=no-such-token', allow_redirects=False, ) assert r.status_code == 302 @@ -288,30 +290,25 @@ async def test_hubauth_service_token(app, mockservice_url): await app.init_api_tokens() # token in Authorization header - r = await async_requests.get(public_url(app, mockservice_url) + '/whoami/', - headers={ - 'Authorization': 'token %s' % token, - }) + r = await async_requests.get( + public_url(app, mockservice_url) + '/whoami/', + headers={'Authorization': 'token %s' % token}, + ) r.raise_for_status() reply = r.json() - assert reply == { - 'kind': 'service', - 'name': name, - 'admin': False, - } + assert reply == {'kind': 'service', 'name': name, 'admin': False} assert not r.cookies # token in ?token parameter - r = await async_requests.get(public_url(app, mockservice_url) + '/whoami/?token=%s' % token) + r = await async_requests.get( + public_url(app, mockservice_url) + '/whoami/?token=%s' % token + ) r.raise_for_status() reply = r.json() - assert reply == { - 'kind': 'service', - 'name': name, - 'admin': False, - } + assert reply == {'kind': 'service', 'name': name, 'admin': False} - r = await async_requests.get(public_url(app, mockservice_url) + '/whoami/?token=no-such-token', + r = await async_requests.get( + public_url(app, mockservice_url) + '/whoami/?token=no-such-token', allow_redirects=False, ) assert r.status_code == 302 @@ -350,11 +347,8 @@ async def test_oauth_service(app, mockservice_url): r.raise_for_status() assert r.status_code == 200 reply = r.json() - sub_reply = { key:reply.get(key, 'missing') for key in ('kind', 'name') } - assert sub_reply == { - 'name': 'link', - 'kind': 'user', - } + sub_reply = {key: reply.get(key, 'missing') for key in ('kind', 'name')} + assert sub_reply == {'name': 'link', 'kind': 'user'} # token-authenticated request to HubOAuth token = app.users[name].new_api_token() @@ -367,11 +361,7 @@ async def test_oauth_service(app, mockservice_url): # verify that ?token= requests set a cookie assert len(r.cookies) != 0 # ensure cookie works in future requests - r = await async_requests.get( - url, - cookies=r.cookies, - allow_redirects=False, - ) + r = await async_requests.get(url, cookies=r.cookies, allow_redirects=False) r.raise_for_status() assert r.url == url reply = r.json() @@ -391,14 +381,14 @@ async def test_oauth_cookie_collision(app, mockservice_url): print(oauth_1.headers) print(oauth_1.cookies, oauth_1.url, url) assert state_cookie_name in s.cookies - state_cookies = [ c for c in s.cookies.keys() if c.startswith(state_cookie_name) ] + state_cookies = [c for c in s.cookies.keys() if c.startswith(state_cookie_name)] # only one state cookie assert state_cookies == [state_cookie_name] state_1 = s.cookies[state_cookie_name] # start second oauth login before finishing the first oauth_2 = await s.get(url) - state_cookies = [ c for c in s.cookies.keys() if c.startswith(state_cookie_name) ] + state_cookies = [c for c in s.cookies.keys() if c.startswith(state_cookie_name)] assert len(state_cookies) == 2 # get the random-suffix cookie name state_cookie_2 = sorted(state_cookies)[-1] @@ -408,9 +398,7 @@ async def test_oauth_cookie_collision(app, mockservice_url): # finish oauth 2 # submit the oauth form to complete authorization r = await s.post( - oauth_2.url, - data={'scopes': ['identify']}, - headers={'Referer': oauth_2.url}, + oauth_2.url, data={'scopes': ['identify']}, headers={'Referer': oauth_2.url} ) r.raise_for_status() assert r.url == url @@ -422,9 +410,7 @@ async def test_oauth_cookie_collision(app, mockservice_url): # finish oauth 1 r = await s.post( - oauth_1.url, - data={'scopes': ['identify']}, - headers={'Referer': oauth_1.url}, + oauth_1.url, data={'scopes': ['identify']}, headers={'Referer': oauth_1.url} ) r.raise_for_status() assert r.url == url @@ -436,7 +422,7 @@ async def test_oauth_cookie_collision(app, mockservice_url): assert s.cookies[service_cookie_name] != service_cookie_2 # after completing both OAuth logins, no OAuth state cookies remain - state_cookies = [ s for s in s.cookies.keys() if s.startswith(state_cookie_name) ] + state_cookies = [s for s in s.cookies.keys() if s.startswith(state_cookie_name)] assert state_cookies == [] @@ -455,11 +441,13 @@ async def test_oauth_logout(app, mockservice_url): s = AsyncSession() name = 'propha' app_user = add_user(app.db, app=app, name=name) + def auth_tokens(): """Return list of OAuth access tokens for the user""" return list( app.db.query(orm.OAuthAccessToken).filter( - orm.OAuthAccessToken.user_id == app_user.id) + orm.OAuthAccessToken.user_id == app_user.id + ) ) # ensure we start empty @@ -480,14 +468,8 @@ def auth_tokens(): r.raise_for_status() assert r.status_code == 200 reply = r.json() - sub_reply = { - key: reply.get(key, 'missing') - for key in ('kind', 'name') - } - assert sub_reply == { - 'name': name, - 'kind': 'user', - } + sub_reply = {key: reply.get(key, 'missing') for key in ('kind', 'name')} + assert sub_reply == {'name': name, 'kind': 'user'} # save cookies to verify cache saved_cookies = copy.deepcopy(s.cookies) session_id = s.cookies['jupyterhub-session-id'] @@ -522,11 +504,5 @@ def auth_tokens(): r.raise_for_status() assert r.status_code == 200 reply = r.json() - sub_reply = { - key: reply.get(key, 'missing') - for key in ('kind', 'name') - } - assert sub_reply == { - 'name': name, - 'kind': 'user', - } + sub_reply = {key: reply.get(key, 'missing') for key in ('kind', 'name')} + assert sub_reply == {'name': name, 'kind': 'user'} diff --git a/jupyterhub/tests/test_singleuser.py b/jupyterhub/tests/test_singleuser.py --- a/jupyterhub/tests/test_singleuser.py +++ b/jupyterhub/tests/test_singleuser.py @@ -1,16 +1,16 @@ """Tests for jupyterhub.singleuser""" - -from subprocess import check_output import sys +from subprocess import check_output from urllib.parse import urlparse import pytest import jupyterhub -from .mocking import StubSingleUserSpawner, public_url from ..utils import url_path_join - -from .utils import async_requests, AsyncSession +from .mocking import public_url +from .mocking import StubSingleUserSpawner +from .utils import async_requests +from .utils import AsyncSession async def test_singleuser_auth(app): @@ -47,11 +47,7 @@ async def test_singleuser_auth(app): r = await s.get(url) assert urlparse(r.url).path.endswith('/oauth2/authorize') # submit the oauth form to complete authorization - r = await s.post( - r.url, - data={'scopes': ['identify']}, - headers={'Referer': r.url}, - ) + r = await s.post(r.url, data={'scopes': ['identify']}, headers={'Referer': r.url}) assert urlparse(r.url).path.rstrip('/').endswith('/user/nandy/tree') # user isn't authorized, should raise 403 assert r.status_code == 403 @@ -85,11 +81,14 @@ async def test_disable_user_config(app): def test_help_output(): - out = check_output([sys.executable, '-m', 'jupyterhub.singleuser', '--help-all']).decode('utf8', 'replace') + out = check_output( + [sys.executable, '-m', 'jupyterhub.singleuser', '--help-all'] + ).decode('utf8', 'replace') assert 'JupyterHub' in out def test_version(): - out = check_output([sys.executable, '-m', 'jupyterhub.singleuser', '--version']).decode('utf8', 'replace') + out = check_output( + [sys.executable, '-m', 'jupyterhub.singleuser', '--version'] + ).decode('utf8', 'replace') assert jupyterhub.__version__ in out - diff --git a/jupyterhub/tests/test_spawner.py b/jupyterhub/tests/test_spawner.py --- a/jupyterhub/tests/test_spawner.py +++ b/jupyterhub/tests/test_spawner.py @@ -1,27 +1,28 @@ """Tests for process spawning""" - # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - import logging import os import signal -from subprocess import Popen import sys import tempfile import time +from subprocess import Popen from unittest import mock from urllib.parse import urlparse import pytest from tornado import gen -from ..objects import Hub, Server from .. import orm from .. import spawner as spawnermod -from ..spawner import LocalProcessSpawner, Spawner +from ..objects import Hub +from ..objects import Server +from ..spawner import LocalProcessSpawner +from ..spawner import Spawner from ..user import User -from ..utils import new_token, url_path_join +from ..utils import new_token +from ..utils import url_path_join from .mocking import public_url from .test_api import add_user from .utils import async_requests @@ -84,8 +85,10 @@ async def wait_for_spawner(spawner, timeout=10): polling at shorter intervals for early termination """ deadline = time.monotonic() + timeout + def wait(): return spawner.server.wait_up(timeout=1, http=True) + while time.monotonic() < deadline: status = await spawner.poll() assert status is None @@ -187,11 +190,13 @@ def test_setcwd(): os.chdir(cwd) chdir = os.chdir temp_root = os.path.realpath(os.path.abspath(tempfile.gettempdir())) + def raiser(path): path = os.path.realpath(os.path.abspath(path)) if not path.startswith(temp_root): raise OSError(path) chdir(path) + with mock.patch('os.chdir', raiser): spawnermod._try_setcwd(cwd) assert os.getcwd().startswith(temp_root) @@ -209,6 +214,7 @@ def test_string_formatting(db): async def test_popen_kwargs(db): mock_proc = mock.Mock(spec=Popen) + def mock_popen(*args, **kwargs): mock_proc.args = args mock_proc.kwargs = kwargs @@ -226,7 +232,8 @@ def mock_popen(*args, **kwargs): async def test_shell_cmd(db, tmpdir, request): f = tmpdir.join('bashrc') f.write('export TESTVAR=foo\n') - s = new_spawner(db, + s = new_spawner( + db, cmd=[sys.executable, '-m', 'jupyterhub.tests.mocksu'], shell_cmd=['bash', '--rcfile', str(f), '-i', '-c'], ) @@ -251,8 +258,9 @@ async def test_shell_cmd(db, tmpdir, request): def test_inherit_overwrite(): """On 3.6+ we check things are overwritten at import time """ - if sys.version_info >= (3,6): + if sys.version_info >= (3, 6): with pytest.raises(NotImplementedError): + class S(Spawner): pass @@ -372,19 +380,14 @@ async def test_spawner_delete_server(app): assert spawner.server is None [email protected]( - "name", - [ - "has@x", - "has~x", - "has%x", - "has%40x", - ] -) [email protected]("name", ["has@x", "has~x", "has%x", "has%40x"]) async def test_spawner_routing(app, name): """Test routing of names with special characters""" db = app.db - with mock.patch.dict(app.config.LocalProcessSpawner, {'cmd': [sys.executable, '-m', 'jupyterhub.tests.mocksu']}): + with mock.patch.dict( + app.config.LocalProcessSpawner, + {'cmd': [sys.executable, '-m', 'jupyterhub.tests.mocksu']}, + ): user = add_user(app.db, app, name=name) await user.spawn() await wait_for_spawner(user.spawner) diff --git a/jupyterhub/tests/test_traitlets.py b/jupyterhub/tests/test_traitlets.py --- a/jupyterhub/tests/test_traitlets.py +++ b/jupyterhub/tests/test_traitlets.py @@ -1,12 +1,16 @@ import pytest -from traitlets import HasTraits, TraitError +from traitlets import HasTraits +from traitlets import TraitError -from jupyterhub.traitlets import URLPrefix, Command, ByteSpecification +from jupyterhub.traitlets import ByteSpecification +from jupyterhub.traitlets import Command +from jupyterhub.traitlets import URLPrefix def test_url_prefix(): class C(HasTraits): url = URLPrefix() + c = C() c.url = '/a/b/c/' assert c.url == '/a/b/c/' @@ -20,6 +24,7 @@ def test_command(): class C(HasTraits): cmd = Command('default command') cmd2 = Command(['default_cmd']) + c = C() assert c.cmd == ['default command'] assert c.cmd2 == ['default_cmd'] diff --git a/jupyterhub/tests/test_utils.py b/jupyterhub/tests/test_utils.py --- a/jupyterhub/tests/test_utils.py +++ b/jupyterhub/tests/test_utils.py @@ -1,9 +1,11 @@ """Tests for utilities""" - import asyncio + import pytest +from async_generator import aclosing +from async_generator import async_generator +from async_generator import yield_ -from async_generator import aclosing, async_generator, yield_ from ..utils import iterate_until @@ -26,12 +28,15 @@ def schedule_future(io_loop, *, delay, result=None): return f [email protected]("deadline, n, delay, expected", [ - (0, 3, 1, []), - (0, 3, 0, [0, 1, 2]), - (5, 3, 0.01, [0, 1, 2]), - (0.5, 10, 0.2, [0, 1]), -]) [email protected]( + "deadline, n, delay, expected", + [ + (0, 3, 1, []), + (0, 3, 0, [0, 1, 2]), + (5, 3, 0.01, [0, 1, 2]), + (0.5, 10, 0.2, [0, 1]), + ], +) async def test_iterate_until(io_loop, deadline, n, delay, expected): f = schedule_future(io_loop, delay=deadline) diff --git a/jupyterhub/tests/test_version.py b/jupyterhub/tests/test_version.py --- a/jupyterhub/tests/test_version.py +++ b/jupyterhub/tests/test_version.py @@ -6,14 +6,17 @@ from .._version import _check_version [email protected]('hub_version, singleuser_version, log_level, msg', [ - ('0.8.0', '0.8.0', logging.DEBUG, 'both on version'), - ('0.8.0', '0.8.1', logging.DEBUG, ''), - ('0.8.0', '0.8.0.dev', logging.DEBUG, ''), - ('0.8.0', '0.9.0', logging.WARNING, 'This could cause failure to authenticate'), - ('', '0.8.0', logging.WARNING, 'Hub has no version header'), - ('0.8.0', '', logging.WARNING, 'Single-user server has no version header'), -]) [email protected]( + 'hub_version, singleuser_version, log_level, msg', + [ + ('0.8.0', '0.8.0', logging.DEBUG, 'both on version'), + ('0.8.0', '0.8.1', logging.DEBUG, ''), + ('0.8.0', '0.8.0.dev', logging.DEBUG, ''), + ('0.8.0', '0.9.0', logging.WARNING, 'This could cause failure to authenticate'), + ('', '0.8.0', logging.WARNING, 'Hub has no version header'), + ('0.8.0', '', logging.WARNING, 'Single-user server has no version header'), + ], +) def test_check_version(hub_version, singleuser_version, log_level, msg, caplog): log = logging.getLogger() caplog.set_level(logging.DEBUG) diff --git a/jupyterhub/tests/utils.py b/jupyterhub/tests/utils.py --- a/jupyterhub/tests/utils.py +++ b/jupyterhub/tests/utils.py @@ -1,8 +1,8 @@ import asyncio from concurrent.futures import ThreadPoolExecutor -from certipy import Certipy import requests +from certipy import Certipy from jupyterhub import orm from jupyterhub.objects import Server @@ -68,6 +68,7 @@ def check_db_locks(func): def api_request(app, *api_path, **kwargs): """ + def new_func(app, *args, **kwargs): retval = func(app, *args, **kwargs) @@ -116,9 +117,9 @@ def auth_header(db, name): @check_db_locks -async def api_request(app, *api_path, method='get', - noauth=False, bypass_proxy=False, - **kwargs): +async def api_request( + app, *api_path, method='get', noauth=False, bypass_proxy=False, **kwargs +): """Make an API request""" if bypass_proxy: # make a direct request to the hub, @@ -128,11 +129,7 @@ async def api_request(app, *api_path, method='get', base_url = public_url(app, path='hub') headers = kwargs.setdefault('headers', {}) - if ( - 'Authorization' not in headers - and not noauth - and 'cookies' not in kwargs - ): + if 'Authorization' not in headers and not noauth and 'cookies' not in kwargs: # make a copy to avoid modifying arg in-place kwargs['headers'] = h = {} h.update(headers) @@ -151,7 +148,10 @@ async def api_request(app, *api_path, method='get', kwargs["verify"] = app.internal_ssl_ca resp = await f(url, **kwargs) assert "frame-ancestors 'self'" in resp.headers['Content-Security-Policy'] - assert ujoin(app.hub.base_url, "security/csp-report") in resp.headers['Content-Security-Policy'] + assert ( + ujoin(app.hub.base_url, "security/csp-report") + in resp.headers['Content-Security-Policy'] + ) assert 'http' not in resp.headers['Content-Security-Policy'] if not kwargs.get('stream', False) and resp.content: assert resp.headers.get('content-type') == 'application/json' @@ -190,4 +190,3 @@ def public_url(app, user_or_service=None, path=''): return host + ujoin(prefix, path) else: return host + prefix - diff --git a/testing/jupyterhub_config.py b/testing/jupyterhub_config.py --- a/testing/jupyterhub_config.py +++ b/testing/jupyterhub_config.py @@ -4,13 +4,15 @@ to enable testing without administrative privileges. """ -c = get_config() # noqa +c = get_config() # noqa from jupyterhub.auth import DummyAuthenticator + c.JupyterHub.authenticator_class = DummyAuthenticator # Optionally set a global password that all users must use # c.DummyAuthenticator.password = "your_password" from jupyterhub.spawners import SimpleSpawner + c.JupyterHub.spawner_class = SimpleSpawner
Autoformat with black? I'm not a fan of style-checking in CI that requires human intervention, but auto-formatters like [black](https://pypi.org/project/black/) allow us to eliminate code style as a review point, even if the auto-formatter doesn't always make the best decisions. I think projects with style-enforcement are generally contributor-hostile, but projects with auto-formatting can eliminate contributor stress about "does my style match?" The biggest problem with adopting an auto-formatter in an existing project is that it'll make one huge PR that's not meaningful, which is a bit of a mess for version control history and understanding the code base. If we adopt black, I would aim to enable the skip-string-normalization feature, since that would cause the biggest churn (and I frankly happen to disagree with the design of black there). What do folks think? If there's interest, I can investigate picking up https://pre-commit.com which offers some pretty handy hooks for quick fixes. /cc @willingc
2019-02-15T10:56:51Z
[]
[]
jupyterhub/jupyterhub
2,510
jupyterhub__jupyterhub-2510
[ "2507" ]
5cb8ccf8b2a1ae009a5a919e38783520362e37f5
diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -427,6 +427,7 @@ def _remove_spawner(f=None): return self.log.info("Deleting spawner %s", spawner._log_name) self.db.delete(spawner.orm_spawner) + user.spawners.pop(server_name, None) self.db.commit() if server_name:
diff --git a/jupyterhub/tests/test_named_servers.py b/jupyterhub/tests/test_named_servers.py --- a/jupyterhub/tests/test_named_servers.py +++ b/jupyterhub/tests/test_named_servers.py @@ -162,8 +162,10 @@ async def test_delete_named_server(app, named_servers): ) r.raise_for_status() assert r.status_code == 204 - # low-level record is now removes + # low-level record is now removed assert servername not in user.orm_spawners + # and it's still not in the high-level wrapper dict + assert servername not in user.spawners async def test_named_server_disabled(app):
Deleting and recreating a named server results in lost name in GUI <!-- Welcome to Zero to JupyterHub! Before filing an issue, please search through the issues to see if your question has been discussed before. If you need more information after searching, feel free to message us on the gitter channel. Many JupyterHub community members watch the gitter channel so you will have the benefit of other users' experience as well as the JupyterHub team. If you still wish to file an issue, please submit as much detail about your issue as possible. If you think it would be helpful, include a scrubbed version of your `config.yaml` file. We've put a place below where you can paste this in. *** WARNING *** Make sure you remove all sensitive information that's in your `config.yaml` file, as GitHub is a public space. Please remove at *least* the following fields: * any special keys under auth * proxy.secretToken * hub.cookieSecret If you post any sensitive information we reserve the right to edit your comment in order to remove it. --> ## Description I've been working on a POC for my place of work to examine the feasibility of using JupyterHub to serve Jupyter Notebook/Lab servers with custom images containing a Python SDK we're working on. Recently, I've been working on testing out named servers. In that process, I've discovered that if you delete a named server from the browser GUI, then recreate it in (in any fashion, whether by the REST API or through the GUI), that server will no longer appear listed. ## To reproduce 1. Create a named server: ![image](https://user-images.githubusercontent.com/11052254/55366470-c26c8000-549d-11e9-9fff-f5ff4e7ac5b4.png) 2. Delete it: ![image](https://user-images.githubusercontent.com/11052254/55366831-4b37eb80-549f-11e9-9fec-20d4298e55ab.png) 3. Create it again: `curl -X POST -H "Authorization: token a_very_secret_token" "http://my.host.domain/hub/api/users/pmende/servers/serverA"` Now the user's Hub Control Panel/Home still no longer lists the server (i.e., it is identical to the image after 2, above), but there is definitely a running pod with the server name: ``` $ kubectl get pods -n jhub NAME READY STATUS RESTARTS AGE hub-949c864ff-v7dx2 1/1 Running 0 18m jupyter-pmende-2dserver-41 1/1 Running 0 3m44s proxy-c88fd6f59-s8k82 1/1 Running 0 18m ``` ## Hub creation `helm upgrade --install jhub jupyterhub/jupyterhub --namespace jhub --version=0.9-8ed2f81 --values config.yaml` ## Contents of `config.yaml` ``` ######################### # Networking Config # ######################### proxy: secretToken: "mysupersecrettoken" service: type: NodePort nodePorts: http: 31212 chp: resources: requests: memory: 0 cpu: 0 ingress: enabled: true hosts: - my.host.domain rules: http: - paths: /hub/api backend: serviceName: hub servicePort: 8081 ######################### # Hardware/Image Config # ######################### singleuser: image: name: jupyter/scipy-notebook tag: 59b402ce701d cpu: guarantee: 0.25 limit: 0.5 memory: guarantee: "256M" limit: "320M" profileList: - display_name: "Default" description: "0.25 CPU; 256M Ram" default: True - display_name: "BIG" description: "0.5 Whole CPUs, 512M Ram" kubespawner_override: cpu_guarantee: 0.5 cpu_limit: 0.75 mem_guarantee: "512M" mem_limit: "640M" ######################### # Hub Config # ######################### hub: allowNamedServers: true extraConfig: | c.JupyterHub.admin_access = True c.JupyterHub.api_tokens = { "a_very_secret_token": "pmende" } ```
I think this may be very valuable feedback for the JupyterHub repository, but I fail to transfer the issue there. Ping: @minrk Yes, this is likely a result of the underlying JupyterHub implementation details, and not specific to JupyterHub on Kubernetes. Happy to have it transferred. Migrated issue to jupyterhub. Will need to do some testing. There appear to be two things wrong: 1. when deleting the server, the pod should have been deleted. This *may* be a kubespawner bug, but I'm suspecting it's not. Delete is two actions: stop the server and then delete the entry. It looks like stop may have been skipped. Stop is what deletes the pod. 2. removal from the UI is a different, should be unrelated bug. I'm not sure how that would happen, but thanks for the test case.
2019-04-05T14:51:22Z
[]
[]
jupyterhub/jupyterhub
2,824
jupyterhub__jupyterhub-2824
[ "2819" ]
703af1dd1eddb266e5fd80774e3baa413728be0c
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -57,6 +57,7 @@ Float, observe, default, + validate, ) from traitlets.config import Application, Configurable, catch_config_error @@ -310,6 +311,19 @@ def _load_classes(self): config_file = Unicode('jupyterhub_config.py', help="The config file to load").tag( config=True ) + + @validate("config_file") + def _validate_config_file(self, proposal): + if not os.path.isfile(proposal.value): + print( + "ERROR: Failed to find specified config file: {}".format( + proposal.value + ), + file=sys.stderr, + ) + sys.exit(1) + return proposal.value + generate_config = Bool(False, help="Generate default config file").tag(config=True) generate_certs = Bool(False, help="Generate certs used for internal ssl").tag( config=True
diff --git a/jupyterhub/tests/test_app.py b/jupyterhub/tests/test_app.py --- a/jupyterhub/tests/test_app.py +++ b/jupyterhub/tests/test_app.py @@ -3,9 +3,11 @@ import os import re import sys +import time from subprocess import check_output from subprocess import PIPE from subprocess import Popen +from subprocess import run from tempfile import NamedTemporaryFile from tempfile import TemporaryDirectory from unittest.mock import patch @@ -39,6 +41,24 @@ def test_token_app(): assert re.match(r'^[a-z0-9]+$', out) +def test_raise_error_on_missing_specified_config(): + """ + Using the -f or --config flag when starting JupyterHub should require the + file to be found and exit if it isn't. + """ + process = Popen( + [sys.executable, '-m', 'jupyterhub', '--config', 'not-available.py'] + ) + # wait inpatiently for the process to exit + for i in range(100): + time.sleep(0.1) + returncode = process.poll() + if returncode is not None: + break + process.kill() + assert returncode == 1 + + def test_generate_config(): with NamedTemporaryFile(prefix='jupyterhub_config', suffix='.py') as tf: cfg_file = tf.name
Using --config with a missing config should raise an error ```shell # this cause no error jupyterhub --config /asdfasdf ``` I want the above to cause an error! If it doesn't, it cause various delayed errors. As an example in https://github.com/jupyterhub/zero-to-jupyterhub-k8s/issues/1463, a failure to find the passed --config led to a harder to debug error. In this case, the `jupyterhub/k8s-hub` image that doesn't ship with configurable-http-proxy, but it doesn't need it either assuming the config file is passed and found. --- I inspected the current setup, and conclude that there is a default value on a `config_file` Traitlet set to `"jupyterhub_config.py"`, so it may not be obvious if it has been set explicitly or not which is required information for us. One idea is to try to spot if it has been explicitly set or if we rely on the default value using traitlets know-how, and then run a check very early to see if it exists or not, and error out early if it doesn't. No matter what, we should catch a provided configuration file that doesn't exist somehow! ## Relevant parts of the code base Where I think --config translates to the JupyterHub class traitlet config_file: https://github.com/jupyterhub/jupyterhub/blob/703af1dd1eddb266e5fd80774e3baa413728be0c/jupyterhub/app.py#L100-L105 Where the config_file traitlet is defined along with a default value: https://github.com/jupyterhub/jupyterhub/blob/703af1dd1eddb266e5fd80774e3baa413728be0c/jupyterhub/app.py#L310-L312 Where the config_file is first used: https://github.com/jupyterhub/jupyterhub/blob/703af1dd1eddb266e5fd80774e3baa413728be0c/jupyterhub/app.py#L2207-L2213
@minrk I could benefit from a nudge on how to fix this. Got any general advice or ideas about this? Is it enough to catch this issue in the `initialize` function? Do you know if I can detect if a traitlet has been explicitly set somehow? In initialize should be fine. > Do you know if I can detect if a traitlet has been explicitly set somehow? Yes, `@validate` handlers are called whenever a trait is set (this is called prior to completing the attribute assignment, to allow validation, errors, or coercion). This would be the most traitlet-approved way to validate a trait. Additionally, `@observe` handlers are called *after* setting, and are usually used for linking one trait to another. Errors could be raised here, but it wouldn't prevent the assignment in the first place. That wouldn't really matter if we're calling `self.exit(1)` to exit the process, for instance.
2019-11-17T13:15:23Z
[]
[]
jupyterhub/jupyterhub
2,936
jupyterhub__jupyterhub-2936
[ "2928" ]
bc7bb5076ff2deabc7702c75dce208166d14568e
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -1670,9 +1670,12 @@ async def init_users(self): # This lets whitelist be used to set up initial list, # but changes to the whitelist can occur in the database, # and persist across sessions. + total_users = 0 for user in db.query(orm.User): try: - await maybe_future(self.authenticator.add_user(user)) + f = self.authenticator.add_user(user) + if f: + await maybe_future(f) except Exception: self.log.exception("Error adding user %s already in db", user.name) if self.authenticator.delete_invalid_users: @@ -1694,6 +1697,7 @@ async def init_users(self): ) ) else: + total_users += 1 # handle database upgrades where user.created is undefined. # we don't want to allow user.created to be undefined, # so initialize it to last_activity (if defined) or now. @@ -1705,6 +1709,8 @@ async def init_users(self): # From this point on, any user changes should be done simultaneously # to the whitelist set and user db, unless the whitelist is empty (all users allowed). + TOTAL_USERS.set(total_users) + async def init_groups(self): """Load predefined groups into the database""" db = self.db @@ -2005,21 +2011,23 @@ async def check_spawner(user, name, spawner): spawner._check_pending = False # parallelize checks for running Spawners + # run query on extant Server objects + # so this is O(running servers) not O(total users) check_futures = [] - for orm_user in db.query(orm.User): - user = self.users[orm_user] - self.log.debug("Loading state for %s from db", user.name) - for name, orm_spawner in user.orm_spawners.items(): - if orm_spawner.server is not None: - # spawner should be running - # instantiate Spawner wrapper and check if it's still alive - spawner = user.spawners[name] - # signal that check is pending to avoid race conditions - spawner._check_pending = True - f = asyncio.ensure_future(check_spawner(user, name, spawner)) - check_futures.append(f) - - TOTAL_USERS.set(len(self.users)) + for orm_server in db.query(orm.Server): + orm_spawners = orm_server.spawner + if not orm_spawners: + continue + orm_spawner = orm_spawners[0] + # instantiate Spawner wrapper and check if it's still alive + # spawner should be running + user = self.users[orm_spawner.user] + spawner = user.spawners[orm_spawner.name] + self.log.debug("Loading state for %s from db", spawner._log_name) + # signal that check is pending to avoid race conditions + spawner._check_pending = True + f = asyncio.ensure_future(check_spawner(user, spawner.name, spawner)) + check_futures.append(f) # it's important that we get here before the first await # so that we know all spawners are instantiated and in the check-pending state diff --git a/jupyterhub/orm.py b/jupyterhub/orm.py --- a/jupyterhub/orm.py +++ b/jupyterhub/orm.py @@ -230,7 +230,7 @@ class Spawner(Base): user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE')) server_id = Column(Integer, ForeignKey('servers.id', ondelete='SET NULL')) - server = relationship(Server, cascade="all") + server = relationship(Server, backref='spawner', cascade="all") state = Column(JSONDict) name = Column(Unicode(255)) @@ -282,7 +282,7 @@ class Service(Base): # service-specific interface _server_id = Column(Integer, ForeignKey('servers.id', ondelete='SET NULL')) - server = relationship(Server, cascade='all') + server = relationship(Server, backref='service', cascade='all') pid = Column(Integer) def new_api_token(self, token=None, **kwargs):
diff --git a/jupyterhub/tests/test_spawner.py b/jupyterhub/tests/test_spawner.py --- a/jupyterhub/tests/test_spawner.py +++ b/jupyterhub/tests/test_spawner.py @@ -103,7 +103,8 @@ def wait(): async def test_single_user_spawner(app, request): - user = next(iter(app.users.values()), None) + orm_user = app.db.query(orm.User).first() + user = app.users[orm_user] spawner = user.spawner spawner.cmd = ['jupyterhub-singleuser'] await user.spawn()
Extremely slow hub start up with large numbers of users **Describe the bug** We have an instance of JupyterHub with over 50,000 users in it, connected to a custom authenticator. When starting the hub pod it takes over 15 minutes to get to the ready state, where it is accepting requests. During this period of time the Hub is effectively offline for users and they can not start notebooks. This appears to be linear related to users based on the delays we were seeing at 30,000. **To Reproduce** 1. Create 50k+ users 2. Boot hub, see how long until pod goes to ready state **Expected behavior** Ideally this would take a lot less time. **Compute Information** - Kubernetes 1.15 - JupyterHub Version - jupyterhub/k8s-hub:0.9.0-beta.3
After some investigation in the code, I'm curious if this block is the culprit: https://github.com/jupyterhub/jupyterhub/blob/bc7bb5076ff2deabc7702c75dce208166d14568e/jupyterhub/app.py#L1668-L1702 Iterating through all 50k + users on boot definitely has a cost, even if only a few ms per user, that adds up. Would it be possible to make this scan skippable? Or moved out of the boot critical path. I can confirm it also happens when running JupyterHub via `jupyterhub` command and not only via Kubernetes #2525 may be relevant. I don't think it's really related to #2525. In adding some debug code there are 2 big iteration loops over every user (which grows linearly over time). The first one is adding every user to the authenticator, linked above. This seems like it's something that ideally the authenticator would have an interface to say whether or not this was needed, so an authenticator could skip that step. The second one is the init_spawners. This one is more confusing to me, because the code seems to specify an init_spawners timeout, after which point it will do this async in the background. However, testing locally that doesn't work. I set it to 2 seconds, and it still has to process every row in the db, the timeout is never triggered. I wonder if because the db loop is not async friendly that this timeout is not working as expected. With a local checkout can basically drop our startup time from 15 minutes to a couple of seconds by doing an early return in init_users and not runnning the full add_user loop, and always doing the init_spawners in async mode. Proposed solution (which I can iterate on if people are interested) 1. Either make the authenticator have an interface for whether add_user is useful for it (for external auth it is not), or make a config value to skip it. 2. Add an init_spawners_async config value to only do init_spawners in the async mode. Default to False for current behavior, but True would skip it. Thanks for the debugging and suggestions. @minrk has done a lot of work and thinking on the fast/slow startup and I think implemented most of the init spawners timeout (or at least he was involved). This means it would be good to get his input, especially on historical parts. Profiling startup is important, that's where we've found big wins in the past, and probably where we should start here as well, now that we seem to have recurring issues. Iterating over 50k entries in Python doesn't generally take a huge amount of time unless there's a nontrivial action taken on each. The default add_user is a call adding a string to a set, so we're talking less than a millisecond per user (a quick test on my laptop has this stage taking about one second with 50k users with GitHubOAuthenticator, or 20 microseconds per user). So skipping `add_user` isn't likely to save a lot of time, and would introduce a new problem by requiring a new solution for what the base add_user does, reconciling whitelists. A quick profile of startup with several thousand users suggests that the time is still ~all in `init_spawners`, even with no spawners running. There's probably something unnecessary going on here, and the Authenticator is unlikely to be a big help. The main task of Hub startup is to ensure consistency of the database state. It's hard to do this in anything less than O(N) time, but it shouldn't have to be a big number times N, at least for the typically large majority of users who aren't running. Importantly, almost nothing of what is done with idle users is async, so the async init_spawners is unlikely to help. That only helps the slow startup for lots of *running* users, whereas for very large user counts, it's likely ~all blocking database calls. I see this taking 45 seconds with 30k users on my laptop, which is too long! What database are you using in profiling this? We're using postgresql in production. The concern isn't actually the add_user call per say. I suspect there is enough overhead of the ORM reflection creation (this is also based on previous experience on this overhead in OpenStack). For out 50,000 user case to get to 15 minutes, it only means we need to be spending 9ms per user in each of these loops. Running with --log-level=DEBUG definitely shows these 2 iteration loops as being where we're loosing most of the time when talking to a postgresql database. Having diagnosed the main issue of instantiating the higher-level User wrapper (O(N users) queries for Spawners, then O(N spawners > N users) queries for running servers), I now have a draft where startup for 30k users with only 10 running is down from 45 seconds to 1.2 seconds. I just have to check if that breaks anything! Great! Would love to give that a shot and test with our data. Let me know when a branch exists with it. I'm profiling with sqlite, but the database implementation shouldn't be relevant to the calls to add_user, which makes no database calls. If indeed it were 9 milliseconds, but the add_user loop is closer to microseconds in my measurements, so you'd need more like a million users for that to happen. Unfortunately, you do have to be careful with debug-level logging for performance, since there are extra queries to produce the debug logs see all of what's going on. Sure, that's fair, let me do timing blocks without using the debug calls.
2020-02-18T16:13:42Z
[]
[]
jupyterhub/jupyterhub
2,971
jupyterhub__jupyterhub-2971
[ "2970" ]
1bdc66c75b786c11fb24c13eb281a0dd61fa0a92
diff --git a/jupyterhub/_version.py b/jupyterhub/_version.py --- a/jupyterhub/_version.py +++ b/jupyterhub/_version.py @@ -18,6 +18,15 @@ __version__ = ".".join(map(str, version_info[:3])) + ".".join(version_info[3:]) +# Singleton flag to only log the major/minor mismatch warning once per mismatch combo. +_version_mismatch_warning_logged = {} + + +def reset_globals(): + """Used to reset globals between test cases.""" + global _version_mismatch_warning_logged + _version_mismatch_warning_logged = {} + def _check_version(hub_version, singleuser_version, log): """Compare Hub and single-user server versions""" @@ -42,19 +51,27 @@ def _check_version(hub_version, singleuser_version, log): hub_major_minor = V(hub_version).version[:2] singleuser_major_minor = V(singleuser_version).version[:2] extra = "" + do_log = True if singleuser_major_minor == hub_major_minor: # patch-level mismatch or lower, log difference at debug-level # because this should be fine log_method = log.debug else: # log warning-level for more significant mismatch, such as 0.8 vs 0.9, etc. - log_method = log.warning - extra = " This could cause failure to authenticate and result in redirect loops!" - log_method( - "jupyterhub version %s != jupyterhub-singleuser version %s." + extra, - hub_version, - singleuser_version, - ) + key = '%s-%s' % (hub_version, singleuser_version) + global _version_mismatch_warning_logged + if _version_mismatch_warning_logged.get(key): + do_log = False # We already logged this warning so don't log it again. + else: + log_method = log.warning + extra = " This could cause failure to authenticate and result in redirect loops!" + _version_mismatch_warning_logged[key] = True + if do_log: + log_method( + "jupyterhub version %s != jupyterhub-singleuser version %s." + extra, + hub_version, + singleuser_version, + ) else: log.debug( "jupyterhub and jupyterhub-singleuser both on version %s" % hub_version
diff --git a/jupyterhub/tests/test_version.py b/jupyterhub/tests/test_version.py --- a/jupyterhub/tests/test_version.py +++ b/jupyterhub/tests/test_version.py @@ -4,6 +4,11 @@ import pytest from .._version import _check_version +from .._version import reset_globals + + +def setup_function(function): + reset_globals() @pytest.mark.parametrize( @@ -25,3 +30,27 @@ def test_check_version(hub_version, singleuser_version, log_level, msg, caplog): record = caplog.records[0] assert record.levelno == log_level assert msg in record.getMessage() + + +def test_check_version_singleton(caplog): + """Tests that minor version difference logging is only logged once.""" + # Run test_check_version twice which will assert that the warning is only logged + # once. + for x in range(2): + test_check_version( + '1.2.0', + '1.1.0', + logging.WARNING, + 'This could cause failure to authenticate', + caplog, + ) + # Run it again with a different singleuser_version to make sure that is logged as + # a warning. + caplog.clear() + test_check_version( + '1.2.0', + '1.1.1', + logging.WARNING, + 'This could cause failure to authenticate', + caplog, + )
singleuser server version check spams the logs **Describe the bug** We have ~277 active single user servers in our deployment right now and on restart of the hub service we see this for each one: > Mar 4 09:20:45 hub-7bccd48cd5-mp4fk hub [W 2020-03-04 15:20:45.996 JupyterHub _version:56] jupyterhub version 1.2.0dev != jupyterhub-singleuser version 1.1.0. This could cause failure to authenticate and result in redirect loops! My only complaint is that logging that per server is redundant and spams the logs. Can we just log that once per restart of the hub? **To Reproduce** Have the jupyterhub and jupyterhub-singleuser services at different minor versions. **Expected behavior** Just log the warning once since there is no user/server specific context in the message. **Compute Information** - 1.2.0dev - we're running with a custom build based on b4391d0f796864a5b01167701d95eafce3ad987e so that we can pick up the performance fix for issue #2928.
2020-03-04T16:42:46Z
[]
[]
jupyterhub/jupyterhub
3,089
jupyterhub__jupyterhub-3089
[ "3061" ]
252015f50d8c9ed2927fc540ea11f0f1a9c000f9
diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -654,8 +654,42 @@ def get_next_url(self, user=None, default=None): next_url = url_path_join(self.hub.base_url, 'spawn') else: next_url = url_path_join(self.hub.base_url, 'home') + + next_url = self.append_query_parameters(next_url, exclude=['next']) return next_url + def append_query_parameters(self, url, exclude=None): + """Append the current request's query parameters to the given URL. + + Supports an extra optional parameter ``exclude`` that when provided must + contain a list of parameters to be ignored, i.e. these parameters will + not be added to the URL. + + This is important to avoid infinite loops with the next parameter being + added over and over, for instance. + + The default value for ``exclude`` is an array with "next". This is useful + as most use cases in JupyterHub (all?) won't want to include the next + parameter twice (the next parameter is added elsewhere to the query + parameters). + + :param str url: a URL + :param list exclude: optional list of parameters to be ignored, defaults to + a list with "next" (to avoid redirect-loops) + :rtype (str) + """ + if exclude is None: + exclude = ['next'] + if self.request.query: + query_string = [ + param + for param in parse_qsl(self.request.query) + if param[0] not in exclude + ] + if query_string: + url = url_concat(url, query_string) + return url + async def auth_to_user(self, authenticated, user=None): """Persist data from .authenticate() or .refresh_user() to the User database diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -285,6 +285,8 @@ def _get_pending_url(self, user, server_name): self.hub.base_url, "spawn-pending", user.escaped_name, server_name ) + pending_url = self.append_query_parameters(pending_url, exclude=['next']) + if self.get_argument('next', None): # preserve `?next=...` through spawn-pending pending_url = url_concat(pending_url, {'next': self.get_argument('next')})
diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -9,6 +9,7 @@ import pytest from bs4 import BeautifulSoup from tornado import gen +from tornado.escape import url_escape from tornado.httputil import url_concat from .. import orm @@ -516,6 +517,58 @@ async def test_user_redirect_deprecated(app, username): ) [email protected]( + 'url, params, redirected_url, form_action', + [ + ( + # spawn?param=value + # will encode given parameters for an unauthenticated URL in the next url + # the next parameter will contain the app base URL (replaces BASE_URL in tests) + 'spawn', + [('param', 'value')], + '/hub/login?next={{BASE_URL}}hub%2Fspawn%3Fparam%3Dvalue', + '/hub/login?next={{BASE_URL}}hub%2Fspawn%3Fparam%3Dvalue', + ), + ( + # login?param=fromlogin&next=encoded(/hub/spawn?param=value) + # will drop parameters given to the login page, passing only the next url + 'login', + [('param', 'fromlogin'), ('next', '/hub/spawn?param=value')], + '/hub/login?param=fromlogin&next=%2Fhub%2Fspawn%3Fparam%3Dvalue', + '/hub/login?next=%2Fhub%2Fspawn%3Fparam%3Dvalue', + ), + ( + # login?param=value&anotherparam=anothervalue + # will drop parameters given to the login page, and use an empty next url + 'login', + [('param', 'value'), ('anotherparam', 'anothervalue')], + '/hub/login?param=value&anotherparam=anothervalue', + '/hub/login?next=', + ), + ( + # login + # simplest case, accessing the login URL, gives an empty next url + 'login', + [], + '/hub/login', + '/hub/login?next=', + ), + ], +) +async def test_login_page(app, url, params, redirected_url, form_action): + url = url_concat(url, params) + r = await get_page(url, app) + redirected_url = redirected_url.replace('{{BASE_URL}}', url_escape(app.base_url)) + assert r.url.endswith(redirected_url) + # now the login.html rendered template must include the given parameters in the form + # action URL, including the next URL + page = BeautifulSoup(r.text, "html.parser") + form = page.find("form", method="post") + action = form.attrs['action'] + form_action = form_action.replace('{{BASE_URL}}', url_escape(app.base_url)) + assert action.endswith(form_action) + + async def test_login_fail(app): name = 'wash' base_url = public_url(app) @@ -546,26 +599,29 @@ def mock_authenticate(handler, data): @pytest.mark.parametrize( - 'running, next_url, location', + 'running, next_url, location, params', [ # default URL if next not specified, for both running and not - (True, '', ''), - (False, '', ''), + (True, '', '', None), + (False, '', '', None), # next_url is respected - (False, '/hub/admin', '/hub/admin'), - (False, '/user/other', '/hub/user/other'), - (False, '/absolute', '/absolute'), - (False, '/has?query#andhash', '/has?query#andhash'), + (False, '/hub/admin', '/hub/admin', None), + (False, '/user/other', '/hub/user/other', None), + (False, '/absolute', '/absolute', None), + (False, '/has?query#andhash', '/has?query#andhash', None), # next_url outside is not allowed - (False, 'relative/path', ''), - (False, 'https://other.domain', ''), - (False, 'ftp://other.domain', ''), - (False, '//other.domain', ''), - (False, '///other.domain/triple', ''), - (False, '\\\\other.domain/backslashes', ''), + (False, 'relative/path', '', None), + (False, 'https://other.domain', '', None), + (False, 'ftp://other.domain', '', None), + (False, '//other.domain', '', None), + (False, '///other.domain/triple', '', None), + (False, '\\\\other.domain/backslashes', '', None), + # params are handled correctly + (True, '/hub/admin', 'hub/admin?left=1&right=2', [('left', 1), ('right', 2)]), + (False, '/hub/admin', 'hub/admin?left=1&right=2', [('left', 1), ('right', 2)]), ], ) -async def test_login_redirect(app, running, next_url, location): +async def test_login_redirect(app, running, next_url, location, params): cookies = await app.login_user('river') user = app.users['river'] if location: @@ -577,6 +633,8 @@ async def test_login_redirect(app, running, next_url, location): location = ujoin(app.base_url, 'hub/spawn') url = 'login' + if params: + url = url_concat(url, params) if next_url: if '//' not in next_url and next_url.startswith('/'): next_url = ujoin(app.base_url, next_url, '')
query parameters dropped when redirecting from hub to login page <!-- Thank you for contributing. These HTML commments will not render in the issue, but you can delete them once you've read them if you prefer! --> ### Bug description query parameters are dropped when redirecting from hub to login page. Documentation which I list below says query parameters should be preserved. From hub log you can see the parameters are dropped on redirect: [I 2020-05-29 05:55:28.094 JupyterHub log:174] 302 GET /hub/?frog=water -> /hub/login (@10.0.1.5) 1.01ms [I 2020-05-29 05:55:28.147 JupyterHub log:174] 302 GET /hub/login -> /hub/oauth_login (@10.0.1.5) 0.91ms Documentation states: https://jupyterhub.readthedocs.io/en/stable/reference/urls.html All authenticated handlers redirect to /hub/login to login users prior to being redirected back to the originating page. The returned request should preserve all query parameters. #### Expected behaviour query parameters would be preserved on redirects #### Actual behaviour query parameters are dropped ### How to reproduce <!-- Use this section to describe the steps that a user would take to experience this bug. --> 1. Go to /hub?x=y 2. It will redirect to /login and your url parameters will be gone ### Your personal set up <!-- Tell us a little about the system you're using. --> - OS: linux - Version: JupyterHub version 1.1.0 - Configuration: <!-- Be careful not to share any sensitive information. --->
2020-06-15T10:12:34Z
[]
[]
jupyterhub/jupyterhub
3,208
jupyterhub__jupyterhub-3208
[ "3191" ]
284e379341ba25bb8a1e36838252ce0617472335
diff --git a/jupyterhub/traitlets.py b/jupyterhub/traitlets.py --- a/jupyterhub/traitlets.py +++ b/jupyterhub/traitlets.py @@ -9,6 +9,7 @@ from traitlets import TraitError from traitlets import TraitType from traitlets import Type +from traitlets import Undefined from traitlets import Unicode @@ -27,11 +28,15 @@ class Command(List): but allows it to be specified as a single string. """ - def __init__(self, default_value=None, **kwargs): + def __init__(self, default_value=Undefined, **kwargs): kwargs.setdefault('minlen', 1) if isinstance(default_value, str): default_value = [default_value] - super().__init__(Unicode(), default_value, **kwargs) + if default_value is not Undefined and ( + not (default_value is None and not kwargs.get("allow_none", False)) + ): + kwargs["default_value"] = default_value + super().__init__(Unicode(), **kwargs) def validate(self, obj, value): if isinstance(value, str):
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -403,7 +403,7 @@ def _default_url(self): - authenticated, so we are testing auth - always available (i.e. in base ServerApp and NotebookApp """ - return "/api/spec.yaml" + return "/api/status" _thread = None
CI: jupyter-server build fails since late september The `test_singleuser_auth` step fails with the following error ([example failure](https://travis-ci.org/github/jupyterhub/jupyterhub/jobs/729518444)) ``` 404 Client Error: Not Found for url: http://127.0.0.1:59471/@/space%20word/user/nandy/api/spec.yaml?redirects=2 ``` Has something change with regards to `@` symbols or spaces in words like `space word`? Yes it has, in `jupyter-server` it seems, because there have been releases in this time span. ![image](https://user-images.githubusercontent.com/3837114/94790428-9275a400-03d6-11eb-807f-1a174e1b3721.png) ## References - [jupyter-server changelog](https://github.com/jupyter/jupyter_server/blob/master/CHANGELOG.md) - [The only PR that I saw in the changelog with clear potential to cause our CI error](https://github.com/jupyter/jupyter_server/pull/304) - [A seemingly related PR by, @minrk](https://github.com/jupyterhub/jupyterhub/pull/3168) - [Another seemingly related PR, by @danlester](https://github.com/jupyterhub/jupyterhub/pull/3167)
I've narrowed it down a bit Passes: ``` pip install jupyter_server==1.0.0rc16 JUPYTERHUB_SINGLEUSER_APP=jupyterhub.tests.mockserverapp.MockServerApp pytest jupyterhub/tests/test_singleuser.py ``` Hangs: ``` pip install jupyter_server==1.0.0 JUPYTERHUB_SINGLEUSER_APP=jupyterhub.tests.mockserverapp.MockServerApp pytest jupyterhub/tests/test_singleuser.py ``` Fails: ``` pip install jupyter_server==1.0.1 JUPYTERHUB_SINGLEUSER_APP=jupyterhub.tests.mockserverapp.MockServerApp pytest jupyterhub/tests/test_singleuser.py ``` `1.0.0rc16` - `1.0.0`: https://github.com/jupyter/jupyter_server/compare/1.0.0rc16...1.0.0 `1.0.0` - `1.0.1`: https://github.com/jupyter/jupyter_server/compare/1.0.0...1.0.1 Enabling verbose output: `JUPYTERHUB_SINGLEUSER_APP=jupyterhub.tests.mockserverapp.MockServerApp pytest jupyterhub/tests/test_singleuser.py -k test_singleuser_auth -vs` I suspect the URL encoding is a red herring, and the [addition of some missing templates](https://github.com/jupyter/jupyter_server/commit/49a16a7a362af1543a737011e703537a739976da) has changed the behaviour. Note the line `Using contents: services/contents` and onwards in `1.0.1` that's missing from `1.0.0rc16`: `1.0.1`: ``` ... [I 2020-10-01 21:11:14.043 MockSingleUserServer auth:985] Logged-in user {'kind': 'user', 'name': 'nandy', 'admin': False, 'groups': [], 'server': '/@/space%20word/user/nandy/', 'pending': None, 'created': '2020-10-01T20:11:11.731209Z', 'last_activity': '2020-10-01T20:11:14.039860Z', 'servers': None} [I 2020-10-01 21:11:14.044 MockSingleUserServer log:181] 302 GET /@/space%20word/user/nandy/oauth_callback?code=[secret]&state=[secret] -> /@/space%20word/user/nandy/api/spec.yaml?redirects=2 (@127.0.0.1) 31.25ms [W 11:14.049 MockHub handlers:23] Serving api spec (experimental, incomplete) [D 11:14.049 MockHub handlers:241] Using contents: services/contents [D 11:14.056 MockHub handlers:750] Path favicon.ico served from /home/USER/miniconda3/envs/jupyter-dev/lib/python3.8/site-packages/jupyter_server/static/favicon.ico [W 2020-10-01 21:11:14.057 MockSingleUserServer log:181] 404 GET /@/space%20word/user/nandy/api/spec.yaml?redirects=2 ([email protected]) 8.59ms ['--ip=127.0.0.1', '--port=55511', '--SingleUserNotebookApp.default_url=/api/spec.yaml'] {'PATH': '/home/USER/.local/bin:/home/USER/bin:/home/USER/.local/bin:/home/USER/bin:/home/USER/miniconda3/envs/jupyter-dev/bin:/home/USER/miniconda3/condabin:/home/USER/.local/bin:/home/USER/bin:/usr/share/Modules/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin', 'CONDA_DEFAULT_ENV': 'jupyter-dev', 'LANG': 'en_GB.UTF-8', 'JUPYTERHUB_SINGLEUSER_APP': 'jupyterhub.tests.mockserverapp.MockServerApp', 'JUPYTERHUB_API_TOKEN': '0d56cfe431af4478a2ad3ed26cfdd3d1', 'JPY_API_TOKEN': '0d56cfe431af4478a2ad3ed26cfdd3d1', 'JUPYTERHUB_CLIENT_ID': 'jupyterhub-user-nandy', 'JUPYTERHUB_HOST': '', 'JUPYTERHUB_OAUTH_CALLBACK_URL': '/@/space%20word/user/nandy/oauth_callback', 'JUPYTERHUB_USER': 'nandy', 'JUPYTERHUB_SERVER_NAME': '', 'JUPYTERHUB_API_URL': 'http://127.0.0.1:8081/@/space%20word/hub/api', 'JUPYTERHUB_ACTIVITY_URL': 'http://127.0.0.1:8081/@/space%20word/hub/api/users/nandy/activity', 'JUPYTERHUB_BASE_URL': '/@/space%20word/', 'JUPYTERHUB_SERVICE_PREFIX': '/@/space%20word/user/nandy/', 'USER': 'nandy', 'HOME': '/tmp/nandy', 'SHELL': '/bin/bash'} FAILED[I 11:14.133 MockHub proxy:281] Removing user nandy from proxy (/@/space%20word/user/nandy/) ... ``` `1.0.0rc16`: ``` ... [I 2020-10-01 21:11:28.985 MockSingleUserServer auth:985] Logged-in user {'kind': 'user', 'name': 'nandy', 'admin': False, 'groups': [], 'server': '/@/space%20word/user/nandy/', 'pending': None, 'created': '2020-10-01T20:11:26.733923Z', 'last_activity': '2020-10-01T20:11:28.981594Z', 'servers': None} [I 2020-10-01 21:11:28.985 MockSingleUserServer log:181] 302 GET /@/space%20word/user/nandy/oauth_callback?code=[secret]&state=[secret] -> /@/space%20word/user/nandy/api/spec.yaml?redirects=2 (@127.0.0.1) 27.55ms [W 11:28.991 MockHub handlers:23] Serving api spec (experimental, incomplete) [I 2020-10-01 21:11:28.997 MockSingleUserServer log:181] 302 GET /@/space%20word/user/nandy/logout -> /@/space%20word/hub/logout (@127.0.0.1) 0.68ms [I 11:29.002 MockHub login:43] User logged out: nandy [D 11:29.004 MockHub base:483] Deleted 1 access tokens for nandy ... ```
2020-10-15T09:38:40Z
[]
[]
jupyterhub/jupyterhub
3,229
jupyterhub__jupyterhub-3229
[ "3228" ]
6e8517f7953fc0290c5676a464c984e4a05b5c7d
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -77,6 +77,7 @@ from .oauth.provider import make_provider from ._data import DATA_FILES_PATH from .log import CoroutineLogFormatter, log_request +from .pagination import Pagination from .proxy import Proxy, ConfigurableHTTPProxy from .traitlets import URLPrefix, Command, EntryPointType, Callable from .utils import ( @@ -279,7 +280,7 @@ class JupyterHub(Application): @default('classes') def _load_classes(self): - classes = [Spawner, Authenticator, CryptKeeper] + classes = [Spawner, Authenticator, CryptKeeper, Pagination] for name, trait in self.traits(config=True).items(): # load entry point groups into configurable class list # so that they show up in config files, etc. diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -453,7 +453,7 @@ class AdminHandler(BaseHandler): @web.authenticated @admin_only async def get(self): - page, per_page, offset = Pagination.get_page_args(self) + page, per_page, offset = Pagination(config=self.config).get_page_args(self) available = {'name', 'admin', 'running', 'last_activity'} default_sort = ['admin', 'name'] @@ -511,7 +511,11 @@ async def get(self): total = self.db.query(orm.User.id).count() pagination = Pagination( - url=self.request.uri, total=total, page=page, per_page=per_page, + url=self.request.uri, + total=total, + page=page, + per_page=per_page, + config=self.config, ) auth_state = await self.current_user.get_auth_state() diff --git a/jupyterhub/pagination.py b/jupyterhub/pagination.py --- a/jupyterhub/pagination.py +++ b/jupyterhub/pagination.py @@ -1,69 +1,94 @@ """Basic class to manage pagination utils.""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. +from traitlets import Bool +from traitlets import default +from traitlets import Integer +from traitlets import observe +from traitlets import Unicode +from traitlets import validate +from traitlets.config import Configurable + + +class Pagination(Configurable): + + # configurable options + default_per_page = Integer( + 100, + config=True, + help="Default number of entries per page for paginated results.", + ) + + max_per_page = Integer( + 250, + config=True, + help="Maximum number of entries per page for paginated results.", + ) + + # state variables + url = Unicode("") + page = Integer(1) + per_page = Integer(1, min=1) + + @default("per_page") + def _default_per_page(self): + return self.default_per_page + + @validate("per_page") + def _limit_per_page(self, proposal): + if self.max_per_page and proposal.value > self.max_per_page: + return self.max_per_page + if proposal.value <= 1: + return 1 + return proposal.value + + @observe("max_per_page") + def _apply_max(self, change): + if change.new: + self.per_page = min(change.new, self.per_page) + + total = Integer(0) + + total_pages = Integer(0) + + @default("total_pages") + def _calculate_total_pages(self): + total_pages = self.total // self.per_page + if self.total % self.per_page: + # there's a remainder, add 1 + total_pages += 1 + return total_pages + + @observe("per_page", "total") + def _update_total_pages(self, change): + """Update total_pages when per_page or total is changed""" + self.total_pages = self._calculate_total_pages() + + separator = Unicode("...") - -class Pagination: - - _page_name = 'page' - _per_page_name = 'per_page' - _default_page = 1 - _default_per_page = 100 - _max_per_page = 250 - - def __init__(self, *args, **kwargs): - """Potential parameters. - **url**: URL in request - **page**: current page in use - **per_page**: number of records to display in the page. By default 100 - **total**: total records considered while paginating - """ - self.page = kwargs.get(self._page_name, 1) - - if self.per_page > self._max_per_page: - self.per_page = self._max_per_page - - self.total = int(kwargs.get('total', 0)) - self.url = kwargs.get('url') or self.get_url() - self.init_values() - - def init_values(self): - self._cached = {} - self.skip = (self.page - 1) * self.per_page - pages = divmod(self.total, self.per_page) - self.total_pages = pages[0] + 1 if pages[1] else pages[0] - - self.has_prev = self.page > 1 - self.has_next = self.page < self.total_pages - - @classmethod def get_page_args(self, handler): """ This method gets the arguments used in the webpage to configurate the pagination In case of no arguments, it uses the default values from this class - It returns: - - self.page: The page requested for paginating or the default value (1) - - self.per_page: The number of items to return in this page. By default 100 and no more than 250 - - self.per_page * (self.page - 1): The offset to consider when managing pagination via the ORM + Returns: + - page: The page requested for paginating or the default value (1) + - per_page: The number of items to return in this page. No more than max_per_page + - offset: The offset to consider when managing pagination via the ORM """ - self.page = handler.get_argument(self._page_name, self._default_page) - self.per_page = handler.get_argument( - self._per_page_name, self._default_per_page - ) + page = handler.get_argument("page", 1) + per_page = handler.get_argument("per_page", self.default_per_page) try: - self.per_page = int(self.per_page) - if self.per_page > self._max_per_page: - self.per_page = self._max_per_page - except: + self.per_page = int(per_page) + except Exception: self.per_page = self._default_per_page try: - self.page = int(self.page) + self.page = int(page) if self.page < 1: - self.page = self._default_page + self.page = 1 except: - self.page = self._default_page + self.page = 1 return self.page, self.per_page, self.per_page * (self.page - 1) @@ -81,48 +106,54 @@ def info(self): return {'total': self.total, 'start': start, 'end': end} def calculate_pages_window(self): - """Calculates the set of pages to render later in links() method. - It returns the list of pages to render via links for the pagination + """Calculates the set of pages to render later in links() method. + It returns the list of pages to render via links for the pagination By default, as we've observed in other applications, we're going to render only a finite and predefined number of pages, avoiding visual fatigue related to a long list of pages. By default, we render 7 pages plus some inactive links with the characters '...' to point out that there are other pages that aren't explicitly rendered. - The primary way of work is to provide current webpage and 5 next pages, the last 2 ones + The primary way of work is to provide current webpage and 5 next pages, the last 2 ones (in case the current page + 5 does not overflow the total lenght of pages) and the first one for reference. """ - self.separator_character = '...' - default_pages_to_render = 7 - after_page = 5 - before_end = 2 + before_page = 2 + after_page = 2 + window_size = before_page + after_page + 1 - # Add 1 to self.total_pages since our default page is 1 and not 0 - total_pages = self.total_pages + 1 + # Add 1 to total_pages since our starting page is 1 and not 0 + last_page = self.total_pages pages = [] - if total_pages > default_pages_to_render: - if self.page > 1: - pages.extend([1, '...']) - - if total_pages < self.page + after_page: - pages.extend(list(range(self.page, total_pages))) + # will default window + start, end fit without truncation? + if self.total_pages > window_size + 2: + if self.page - before_page > 1: + # before_page will not reach page 1 + pages.append(1) + if self.page - before_page > 2: + # before_page will not reach page 2, need separator + pages.append(self.separator) + + pages.extend(range(max(1, self.page - before_page), self.page)) + # we now have up to but not including self.page + + if self.page + after_page + 1 >= last_page: + # after_page gets us to the end + pages.extend(range(self.page, last_page + 1)) else: - if total_pages >= self.page + after_page + before_end: - pages.extend(list(range(self.page, self.page + after_page))) - pages.append('...') - pages.extend(list(range(total_pages - before_end, total_pages))) - else: - pages.extend(list(range(self.page, self.page + after_page))) - if self.page + after_page < total_pages: - # show only last page when the after_page window left space to show it - pages.append('...') - pages.extend(list(range(total_pages - 1, total_pages))) + # add full after_page entries + pages.extend(range(self.page, self.page + after_page + 1)) + # add separator *if* this doesn't get to last page - 1 + if self.page + after_page < last_page - 1: + pages.append(self.separator) + pages.append(last_page) return pages else: - return list(range(1, total_pages)) + # everything will fit, nothing to think about + # always return at least one page + return list(range(1, last_page + 1)) or [1] @property def links(self): @@ -155,9 +186,11 @@ def links(self): page=page ) ) - elif page == self.separator_character: + elif page == self.separator: links.append( - '<li class="disabled"><span> <span aria-hidden="true">...</span></span></li>' + '<li class="disabled"><span> <span aria-hidden="true">{separator}</span></span></li>'.format( + separator=self.separator + ) ) else: links.append(
diff --git a/jupyterhub/tests/test_pagination.py b/jupyterhub/tests/test_pagination.py new file mode 100644 --- /dev/null +++ b/jupyterhub/tests/test_pagination.py @@ -0,0 +1,45 @@ +"""tests for pagination""" +from pytest import mark +from pytest import raises +from traitlets.config import Config + +from jupyterhub.pagination import Pagination + + +def test_per_page_bounds(): + cfg = Config() + cfg.Pagination.max_per_page = 10 + p = Pagination(config=cfg, per_page=20, total=100) + assert p.per_page == 10 + with raises(Exception): + p.per_page = 0 + + [email protected]( + "page, per_page, total, expected", + [ + (1, 10, 99, [1, 2, 3, "...", 10]), + (2, 10, 99, [1, 2, 3, 4, "...", 10]), + (3, 10, 99, [1, 2, 3, 4, 5, "...", 10]), + (4, 10, 99, [1, 2, 3, 4, 5, 6, "...", 10]), + (5, 10, 99, [1, "...", 3, 4, 5, 6, 7, "...", 10]), + (6, 10, 99, [1, "...", 4, 5, 6, 7, 8, "...", 10]), + (7, 10, 99, [1, "...", 5, 6, 7, 8, 9, 10]), + (8, 10, 99, [1, "...", 6, 7, 8, 9, 10]), + (9, 10, 99, [1, "...", 7, 8, 9, 10]), + (1, 20, 99, [1, 2, 3, 4, 5]), + (1, 10, 0, [1]), + (1, 10, 1, [1]), + (1, 10, 10, [1]), + (1, 10, 11, [1, 2]), + (1, 10, 50, [1, 2, 3, 4, 5]), + (1, 10, 60, [1, 2, 3, 4, 5, 6]), + (1, 10, 70, [1, 2, 3, 4, 5, 6, 7]), + (1, 10, 80, [1, 2, 3, "...", 8]), + ], +) +def test_window(page, per_page, total, expected): + cfg = Config() + cfg.Pagination + pagination = Pagination(page=page, per_page=per_page, total=total) + assert pagination.calculate_pages_window() == expected
Allow configuring max number of users per page in admin <!-- Thank you for contributing. These HTML comments will not render in the issue, but you can delete them once you've read them if you prefer! --> ### Proposed change Right now, it's impossible to have more than 250 users per-page in the JupyterHub admin page. However, this makes searching for a single user basically impossible - you have to manually paginate through them. Search functionality is the right way to do this, but until then, I think we should allow using a traitlet to configure how many users can be displayed on a single page. ### Alternative options Add a user search bar! But that's more work. ### Who would use this feature? Anyone with more than 250 users on their hub. ### (Optional): Suggest a solution Add a traitlet to the `JupyterHub` object that gets passed down to the Pagination class, where it can use those numbers instead of the hardcoded limits there.
2020-10-28T15:46:01Z
[]
[]
jupyterhub/jupyterhub
3,242
jupyterhub__jupyterhub-3242
[ "3241" ]
5bcbc8b328d24eb18deb4ca9b82b13d633522d76
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -2120,7 +2120,7 @@ async def check_spawner(user, name, spawner): self.log.debug( "Awaiting checks for %i possibly-running spawners", len(check_futures) ) - await gen.multi(check_futures) + await asyncio.gather(*check_futures) db.commit() # only perform this query if we are going to log it diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -1538,7 +1538,7 @@ async def _redirect_to_user_server(self, user, spawner): if redirects: self.log.warning("Redirect loop detected on %s", self.request.uri) # add capped exponential backoff where cap is 10s - await gen.sleep(min(1 * (2 ** redirects), 10)) + await asyncio.sleep(min(1 * (2 ** redirects), 10)) # rewrite target url with new `redirects` query value url_parts = urlparse(target) query_parts = parse_qs(url_parts.query) diff --git a/jupyterhub/proxy.py b/jupyterhub/proxy.py --- a/jupyterhub/proxy.py +++ b/jupyterhub/proxy.py @@ -25,7 +25,6 @@ from subprocess import Popen from urllib.parse import quote -from tornado import gen from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPError from tornado.httpclient import HTTPRequest @@ -292,7 +291,7 @@ async def add_all_services(self, service_dict): if service.server: futures.append(self.add_service(service)) # wait after submitting them all - await gen.multi(futures) + await asyncio.gather(*futures) async def add_all_users(self, user_dict): """Update the proxy table from the database. @@ -305,7 +304,7 @@ async def add_all_users(self, user_dict): if spawner.ready: futures.append(self.add_user(user, name)) # wait after submitting them all - await gen.multi(futures) + await asyncio.gather(*futures) @_one_at_a_time async def check_routes(self, user_dict, service_dict, routes=None): @@ -391,7 +390,7 @@ async def check_routes(self, user_dict, service_dict, routes=None): self.log.warning("Deleting stale route %s", routespec) futures.append(self.delete_route(routespec)) - await gen.multi(futures) + await asyncio.gather(*futures) stop = time.perf_counter() # timer stops here when user is deleted CHECK_ROUTES_DURATION_SECONDS.observe(stop - start) # histogram metric diff --git a/jupyterhub/services/auth.py b/jupyterhub/services/auth.py --- a/jupyterhub/services/auth.py +++ b/jupyterhub/services/auth.py @@ -23,7 +23,6 @@ from urllib.parse import urlencode import requests -from tornado.gen import coroutine from tornado.httputil import url_concat from tornado.log import app_log from tornado.web import HTTPError @@ -950,8 +949,7 @@ class HubOAuthCallbackHandler(HubOAuthenticated, RequestHandler): .. versionadded: 0.8 """ - @coroutine - def get(self): + async def get(self): error = self.get_argument("error", False) if error: msg = self.get_argument("error_description", error) diff --git a/jupyterhub/singleuser/mixins.py b/jupyterhub/singleuser/mixins.py --- a/jupyterhub/singleuser/mixins.py +++ b/jupyterhub/singleuser/mixins.py @@ -20,7 +20,6 @@ from jinja2 import ChoiceLoader from jinja2 import FunctionLoader -from tornado import gen from tornado import ioloop from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPRequest @@ -434,7 +433,7 @@ async def check_hub_version(self): i, RETRIES, ) - await gen.sleep(min(2 ** i, 16)) + await asyncio.sleep(min(2 ** i, 16)) else: break else: diff --git a/jupyterhub/spawner.py b/jupyterhub/spawner.py --- a/jupyterhub/spawner.py +++ b/jupyterhub/spawner.py @@ -16,8 +16,7 @@ if os.name == 'nt': import psutil -from async_generator import async_generator -from async_generator import yield_ +from async_generator import aclosing from sqlalchemy import inspect from tornado.ioloop import PeriodicCallback from traitlets import Any @@ -1024,7 +1023,6 @@ async def run_auth_state_hook(self, auth_state): def _progress_url(self): return self.user.progress_url(self.name) - @async_generator async def _generate_progress(self): """Private wrapper of progress generator @@ -1036,21 +1034,17 @@ async def _generate_progress(self): ) return - await yield_({"progress": 0, "message": "Server requested"}) - from async_generator import aclosing + yield {"progress": 0, "message": "Server requested"} async with aclosing(self.progress()) as progress: async for event in progress: - await yield_(event) + yield event - @async_generator async def progress(self): """Async generator for progress events Must be an async generator - For Python 3.5-compatibility, use the async_generator package - Should yield messages of the form: :: @@ -1067,7 +1061,7 @@ async def progress(self): .. versionadded:: 0.9 """ - await yield_({"progress": 50, "message": "Spawning server..."}) + yield {"progress": 50, "message": "Spawning server..."} async def start(self): """Start the single-user server @@ -1078,9 +1072,7 @@ async def start(self): .. versionchanged:: 0.7 Return ip, port instead of setting on self.user.server directly. """ - raise NotImplementedError( - "Override in subclass. Must be a Tornado gen.coroutine." - ) + raise NotImplementedError("Override in subclass. Must be a coroutine.") async def stop(self, now=False): """Stop the single-user server @@ -1093,9 +1085,7 @@ async def stop(self, now=False): Must be a coroutine. """ - raise NotImplementedError( - "Override in subclass. Must be a Tornado gen.coroutine." - ) + raise NotImplementedError("Override in subclass. Must be a coroutine.") async def poll(self): """Check if the single-user process is running @@ -1121,9 +1111,7 @@ async def poll(self): process has not yet completed. """ - raise NotImplementedError( - "Override in subclass. Must be a Tornado gen.coroutine." - ) + raise NotImplementedError("Override in subclass. Must be a coroutine.") def add_poll_callback(self, callback, *args, **kwargs): """Add a callback to fire when the single-user server stops""" diff --git a/jupyterhub/utils.py b/jupyterhub/utils.py --- a/jupyterhub/utils.py +++ b/jupyterhub/utils.py @@ -21,10 +21,6 @@ from operator import itemgetter from async_generator import aclosing -from async_generator import async_generator -from async_generator import asynccontextmanager -from async_generator import yield_ -from tornado import gen from tornado import ioloop from tornado import web from tornado.httpclient import AsyncHTTPClient @@ -175,7 +171,7 @@ async def exponential_backoff( dt = min(max_wait, remaining, random.uniform(0, start_wait * scale)) if dt < max_wait: scale *= scale_factor - await gen.sleep(dt) + await asyncio.sleep(dt) raise TimeoutError(fail_message) @@ -507,28 +503,12 @@ def maybe_future(obj): return asyncio.wrap_future(obj) else: # could also check for tornado.concurrent.Future - # but with tornado >= 5 tornado.Future is asyncio.Future + # but with tornado >= 5.1 tornado.Future is asyncio.Future f = asyncio.Future() f.set_result(obj) return f -@asynccontextmanager -@async_generator -async def not_aclosing(coro): - """An empty context manager for Python < 3.5.2 - which lacks the `aclose` method on async iterators - """ - await yield_(await coro) - - -if sys.version_info < (3, 5, 2): - # Python 3.5.1 is missing the aclose method on async iterators, - # so we can't close them - aclosing = not_aclosing - - -@async_generator async def iterate_until(deadline_future, generator): """An async generator that yields items from a generator until a deadline future resolves @@ -553,7 +533,7 @@ async def iterate_until(deadline_future, generator): ) if item_future.done(): try: - await yield_(item_future.result()) + yield item_future.result() except (StopAsyncIteration, asyncio.CancelledError): break elif deadline_future.done():
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -85,6 +85,8 @@ jobs: # GitHub UI when the workflow run, we avoid using true/false as # values by instead duplicating the name to signal true. include: + - python: "3.6" + oldest_dependencies: oldest_dependencies - python: "3.6" subdomain: subdomain - python: "3.7" @@ -143,6 +145,14 @@ jobs: pip install --upgrade pip pip install --upgrade . -r dev-requirements.txt + if [ "${{ matrix.oldest_dependencies }}" != "" ]; then + # take any dependencies in requirements.txt such as tornado>=5.0 + # and transform them to tornado==5.0 so we can run tests with + # the earliest-supported versions + cat requirements.txt | grep '>=' | sed -e 's@>=@==@g' > oldest-requirements.txt + pip install -r oldest-requirements.txt + fi + if [ "${{ matrix.main_dependencies }}" != "" ]; then pip install git+https://github.com/ipython/traitlets#egg=traitlets --force fi diff --git a/jupyterhub/tests/conftest.py b/jupyterhub/tests/conftest.py --- a/jupyterhub/tests/conftest.py +++ b/jupyterhub/tests/conftest.py @@ -36,7 +36,6 @@ from pytest import fixture from pytest import raises -from tornado import gen from tornado import ioloop from tornado.httpclient import HTTPError from tornado.platform.asyncio import AsyncIOMainLoop @@ -56,13 +55,16 @@ def pytest_collection_modifyitems(items): - """add asyncio marker to all async tests""" + """This function is automatically run by pytest passing all collected test + functions. + + We use it to add asyncio marker to all async tests and assert we don't use + test functions that are async generators which wouldn't make sense. + """ for item in items: if inspect.iscoroutinefunction(item.obj): item.add_marker('asyncio') - if hasattr(inspect, 'isasyncgenfunction'): - # double-check that we aren't mixing yield and async def - assert not inspect.isasyncgenfunction(item.obj) + assert not inspect.isasyncgenfunction(item.obj) @fixture(scope='module') @@ -244,17 +246,14 @@ def _mockservice(request, app, url=False): assert name in app._service_map service = app._service_map[name] - @gen.coroutine - def start(): + async def start(): # wait for proxy to be updated before starting the service - yield app.proxy.add_all_services(app._service_map) + await app.proxy.add_all_services(app._service_map) service.start() io_loop.run_sync(start) def cleanup(): - import asyncio - asyncio.get_event_loop().run_until_complete(service.stop()) app.services[:] = [] app._service_map.clear() diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -36,8 +36,6 @@ from urllib.parse import urlparse from pamela import PAMError -from tornado import gen -from tornado.concurrent import Future from tornado.ioloop import IOLoop from traitlets import Bool from traitlets import default @@ -110,19 +108,17 @@ class SlowSpawner(MockSpawner): delay = 2 _start_future = None - @gen.coroutine - def start(self): - (ip, port) = yield super().start() + async def start(self): + (ip, port) = await super().start() if self._start_future is not None: - yield self._start_future + await self._start_future else: - yield gen.sleep(self.delay) + await asyncio.sleep(self.delay) return ip, port - @gen.coroutine - def stop(self): - yield gen.sleep(self.delay) - yield super().stop() + async def stop(self): + await asyncio.sleep(self.delay) + await super().stop() class NeverSpawner(MockSpawner): @@ -134,14 +130,12 @@ def _start_timeout_default(self): def start(self): """Return a Future that will never finish""" - return Future() + return asyncio.Future() - @gen.coroutine - def stop(self): + async def stop(self): pass - @gen.coroutine - def poll(self): + async def poll(self): return 0 @@ -215,8 +209,7 @@ def system_user_exists(self, user): # skip the add-system-user bit return not user.name.startswith('dne') - @gen.coroutine - def authenticate(self, *args, **kwargs): + async def authenticate(self, *args, **kwargs): with mock.patch.multiple( 'pamela', authenticate=mock_authenticate, @@ -224,7 +217,7 @@ def authenticate(self, *args, **kwargs): close_session=mock_open_session, check_account=mock_check_account, ): - username = yield super(MockPAMAuthenticator, self).authenticate( + username = await super(MockPAMAuthenticator, self).authenticate( *args, **kwargs ) if username is None: @@ -320,14 +313,13 @@ def init_db(self): self.db.delete(group) self.db.commit() - @gen.coroutine - def initialize(self, argv=None): + async def initialize(self, argv=None): self.pid_file = NamedTemporaryFile(delete=False).name self.db_file = NamedTemporaryFile() self.db_url = os.getenv('JUPYTERHUB_TEST_DB_URL') or self.db_file.name if 'mysql' in self.db_url: self.db_kwargs['connect_args'] = {'auth_plugin': 'mysql_native_password'} - yield super().initialize([]) + await super().initialize([]) # add an initial user user = self.db.query(orm.User).filter(orm.User.name == 'user').first() @@ -358,14 +350,13 @@ def cleanup(): self.cleanup = lambda: None self.db_file.close() - @gen.coroutine - def login_user(self, name): + async def login_user(self, name): """Login a user by name, returning her cookies.""" base_url = public_url(self) external_ca = None if self.internal_ssl: external_ca = self.external_certs['files']['ca'] - r = yield async_requests.post( + r = await async_requests.post( base_url + 'hub/login', data={'username': name, 'password': name}, allow_redirects=False, @@ -407,8 +398,7 @@ def _default_url(self): _thread = None - @gen.coroutine - def start(self): + async def start(self): ip = self.ip = '127.0.0.1' port = self.port = random_port() env = self.get_env() @@ -435,14 +425,12 @@ def _run(): assert ready return (ip, port) - @gen.coroutine - def stop(self): + async def stop(self): self._app.stop() self._thread.join(timeout=30) assert not self._thread.is_alive() - @gen.coroutine - def poll(self): + async def poll(self): if self._thread is None: return 0 if self._thread.is_alive(): diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -1,19 +1,16 @@ """Tests for the REST API.""" +import asyncio import json import re import sys import uuid -from concurrent.futures import Future from datetime import datetime from datetime import timedelta from unittest import mock from urllib.parse import quote from urllib.parse import urlparse -from async_generator import async_generator -from async_generator import yield_ from pytest import mark -from tornado import gen import jupyterhub from .. import orm @@ -613,7 +610,7 @@ async def test_slow_spawn(app, no_patience, slow_spawn): async def wait_spawn(): while not app_user.running: - await gen.sleep(0.1) + await asyncio.sleep(0.1) await wait_spawn() assert not app_user.spawner._spawn_pending @@ -622,7 +619,7 @@ async def wait_spawn(): async def wait_stop(): while app_user.spawner._stop_pending: - await gen.sleep(0.1) + await asyncio.sleep(0.1) r = await api_request(app, 'users', name, 'server', method='delete') r.raise_for_status() @@ -656,7 +653,7 @@ async def test_never_spawn(app, no_patience, never_spawn): assert app.users.count_active_users()['pending'] == 1 while app_user.spawner.pending: - await gen.sleep(0.1) + await asyncio.sleep(0.1) print(app_user.spawner.pending) assert not app_user.spawner._spawn_pending @@ -682,7 +679,7 @@ async def test_slow_bad_spawn(app, no_patience, slow_bad_spawn): r = await api_request(app, 'users', name, 'server', method='post') r.raise_for_status() while user.spawner.pending: - await gen.sleep(0.1) + await asyncio.sleep(0.1) # spawn failed assert not user.running assert app.users.count_active_users()['pending'] == 0 @@ -818,32 +815,12 @@ async def test_progress_bad_slow(request, app, no_patience, slow_bad_spawn): } -@async_generator async def progress_forever(): """progress function that yields messages forever""" for i in range(1, 10): - await yield_({'progress': i, 'message': 'Stage %s' % i}) + yield {'progress': i, 'message': 'Stage %s' % i} # wait a long time before the next event - await gen.sleep(10) - - -if sys.version_info >= (3, 6): - # additional progress_forever defined as native - # async generator - # to test for issues with async_generator wrappers - exec( - """ -async def progress_forever_native(): - for i in range(1, 10): - yield { - 'progress': i, - 'message': 'Stage %s' % i, - } - # wait a long time before the next event - await gen.sleep(10) -""", - globals(), - ) + await asyncio.sleep(10) async def test_spawn_progress_cutoff(request, app, no_patience, slow_spawn): @@ -854,11 +831,7 @@ async def test_spawn_progress_cutoff(request, app, no_patience, slow_spawn): db = app.db name = 'geddy' app_user = add_user(db, app=app, name=name) - if sys.version_info >= (3, 6): - # Python >= 3.6, try native async generator - app_user.spawner.progress = globals()['progress_forever_native'] - else: - app_user.spawner.progress = progress_forever + app_user.spawner.progress = progress_forever app_user.spawner.delay = 1 r = await api_request(app, 'users', name, 'server', method='post') @@ -885,8 +858,8 @@ async def test_spawn_limit(app, no_patience, slow_spawn, request): # start two pending spawns names = ['ykka', 'hjarka'] users = [add_user(db, app=app, name=name) for name in names] - users[0].spawner._start_future = Future() - users[1].spawner._start_future = Future() + users[0].spawner._start_future = asyncio.Future() + users[1].spawner._start_future = asyncio.Future() for name in names: await api_request(app, 'users', name, 'server', method='post') assert app.users.count_active_users()['pending'] == 2 @@ -894,7 +867,7 @@ async def test_spawn_limit(app, no_patience, slow_spawn, request): # ykka and hjarka's spawns are both pending. Essun should fail with 429 name = 'essun' user = add_user(db, app=app, name=name) - user.spawner._start_future = Future() + user.spawner._start_future = asyncio.Future() r = await api_request(app, 'users', name, 'server', method='post') assert r.status_code == 429 @@ -902,7 +875,7 @@ async def test_spawn_limit(app, no_patience, slow_spawn, request): users[0].spawner._start_future.set_result(None) # wait for ykka to finish while not users[0].running: - await gen.sleep(0.1) + await asyncio.sleep(0.1) assert app.users.count_active_users()['pending'] == 1 r = await api_request(app, 'users', name, 'server', method='post') @@ -913,7 +886,7 @@ async def test_spawn_limit(app, no_patience, slow_spawn, request): for user in users[1:]: user.spawner._start_future.set_result(None) while not all(u.running for u in users): - await gen.sleep(0.1) + await asyncio.sleep(0.1) # everybody's running, pending count should be back to 0 assert app.users.count_active_users()['pending'] == 0 @@ -922,7 +895,7 @@ async def test_spawn_limit(app, no_patience, slow_spawn, request): r = await api_request(app, 'users', u.name, 'server', method='delete') r.raise_for_status() while any(u.spawner.active for u in users): - await gen.sleep(0.1) + await asyncio.sleep(0.1) @mark.slow @@ -1000,7 +973,7 @@ async def test_start_stop_race(app, no_patience, slow_spawn): r = await api_request(app, 'users', user.name, 'server', method='delete') assert r.status_code == 400 while not spawner.ready: - await gen.sleep(0.1) + await asyncio.sleep(0.1) spawner.delay = 3 # stop the spawner @@ -1008,7 +981,7 @@ async def test_start_stop_race(app, no_patience, slow_spawn): assert r.status_code == 202 assert spawner.pending == 'stop' # make sure we get past deleting from the proxy - await gen.sleep(1) + await asyncio.sleep(1) # additional stops while stopping shouldn't trigger a new stop with mock.patch.object(spawner, 'stop') as m: r = await api_request(app, 'users', user.name, 'server', method='delete') @@ -1020,7 +993,7 @@ async def test_start_stop_race(app, no_patience, slow_spawn): assert r.status_code == 400 while spawner.active: - await gen.sleep(0.1) + await asyncio.sleep(0.1) # start after stop is okay r = await api_request(app, 'users', user.name, 'server', method='post') assert r.status_code == 202 diff --git a/jupyterhub/tests/test_internal_ssl_connections.py b/jupyterhub/tests/test_internal_ssl_connections.py --- a/jupyterhub/tests/test_internal_ssl_connections.py +++ b/jupyterhub/tests/test_internal_ssl_connections.py @@ -20,8 +20,7 @@ SSL_ERROR = (SSLError, ConnectionError) [email protected] -def wait_for_spawner(spawner, timeout=10): +async def wait_for_spawner(spawner, timeout=10): """Wait for an http server to show up polling at shorter intervals for early termination @@ -32,15 +31,15 @@ def wait(): return spawner.server.wait_up(timeout=1, http=True) while time.monotonic() < deadline: - status = yield spawner.poll() + status = await spawner.poll() assert status is None try: - yield wait() + await wait() except TimeoutError: continue else: break - yield wait() + await wait() async def test_connection_hub_wrong_certs(app): diff --git a/jupyterhub/tests/test_orm.py b/jupyterhub/tests/test_orm.py --- a/jupyterhub/tests/test_orm.py +++ b/jupyterhub/tests/test_orm.py @@ -222,8 +222,7 @@ async def test_spawn_fails(db): db.commit() class BadSpawner(MockSpawner): - @gen.coroutine - def start(self): + async def start(self): raise RuntimeError("Split the party") user = User( diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -8,7 +8,6 @@ import pytest from bs4 import BeautifulSoup -from tornado import gen from tornado.escape import url_escape from tornado.httputil import url_concat @@ -586,8 +585,7 @@ async def test_login_strip(app): base_url = public_url(app) called_with = [] - @gen.coroutine - def mock_authenticate(handler, data): + async def mock_authenticate(handler, data): called_with.append(data) with mock.patch.object(app.authenticator, 'authenticate', mock_authenticate): @@ -943,8 +941,7 @@ async def test_pre_spawn_start_exc_no_form(app): exc = "pre_spawn_start error" # throw exception from pre_spawn_start - @gen.coroutine - def mock_pre_spawn_start(user, spawner): + async def mock_pre_spawn_start(user, spawner): raise Exception(exc) with mock.patch.object(app.authenticator, 'pre_spawn_start', mock_pre_spawn_start): @@ -959,8 +956,7 @@ async def test_pre_spawn_start_exc_options_form(app): exc = "pre_spawn_start error" # throw exception from pre_spawn_start - @gen.coroutine - def mock_pre_spawn_start(user, spawner): + async def mock_pre_spawn_start(user, spawner): raise Exception(exc) with mock.patch.dict( diff --git a/jupyterhub/tests/test_services.py b/jupyterhub/tests/test_services.py --- a/jupyterhub/tests/test_services.py +++ b/jupyterhub/tests/test_services.py @@ -6,9 +6,7 @@ from contextlib import contextmanager from subprocess import Popen -from async_generator import async_generator from async_generator import asynccontextmanager -from async_generator import yield_ from tornado.ioloop import IOLoop from ..utils import maybe_future @@ -24,7 +22,6 @@ @asynccontextmanager -@async_generator async def external_service(app, name='mockservice'): env = { 'JUPYTERHUB_API_TOKEN': hexlify(os.urandom(5)), @@ -35,7 +32,7 @@ async def external_service(app, name='mockservice'): proc = Popen(mockservice_cmd, env=env) try: await wait_for_http_server(env['JUPYTERHUB_SERVICE_URL']) - await yield_(env) + yield env finally: proc.terminate() diff --git a/jupyterhub/tests/test_spawner.py b/jupyterhub/tests/test_spawner.py --- a/jupyterhub/tests/test_spawner.py +++ b/jupyterhub/tests/test_spawner.py @@ -1,6 +1,7 @@ """Tests for process spawning""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. +import asyncio import logging import os import signal @@ -12,7 +13,6 @@ from urllib.parse import urlparse import pytest -from tornado import gen from .. import orm from .. import spawner as spawnermod @@ -123,7 +123,7 @@ async def test_stop_spawner_sigint_fails(db): await spawner.start() # wait for the process to get to the while True: loop - await gen.sleep(1) + await asyncio.sleep(1) status = await spawner.poll() assert status is None @@ -138,7 +138,7 @@ async def test_stop_spawner_stop_now(db): await spawner.start() # wait for the process to get to the while True: loop - await gen.sleep(1) + await asyncio.sleep(1) status = await spawner.poll() assert status is None @@ -165,7 +165,7 @@ async def test_spawner_poll(db): spawner.start_polling() # wait for the process to get to the while True: loop - await gen.sleep(1) + await asyncio.sleep(1) status = await spawner.poll() assert status is None @@ -173,12 +173,12 @@ async def test_spawner_poll(db): proc.terminate() for i in range(10): if proc.poll() is None: - await gen.sleep(1) + await asyncio.sleep(1) else: break assert proc.poll() is not None - await gen.sleep(2) + await asyncio.sleep(2) status = await spawner.poll() assert status is not None diff --git a/jupyterhub/tests/test_utils.py b/jupyterhub/tests/test_utils.py --- a/jupyterhub/tests/test_utils.py +++ b/jupyterhub/tests/test_utils.py @@ -1,21 +1,22 @@ """Tests for utilities""" import asyncio +import time +from concurrent.futures import ThreadPoolExecutor import pytest from async_generator import aclosing -from async_generator import async_generator -from async_generator import yield_ +from tornado import gen +from tornado.concurrent import run_on_executor from ..utils import iterate_until -@async_generator async def yield_n(n, delay=0.01): """Yield n items with a delay between each""" for i in range(n): if delay: await asyncio.sleep(delay) - await yield_(i) + yield i def schedule_future(io_loop, *, delay, result=None): @@ -50,13 +51,40 @@ async def test_iterate_until(io_loop, deadline, n, delay, expected): async def test_iterate_until_ready_after_deadline(io_loop): f = schedule_future(io_loop, delay=0) - @async_generator async def gen(): for i in range(5): - await yield_(i) + yield i yielded = [] async with aclosing(iterate_until(f, gen())) as items: async for item in items: yielded.append(item) assert yielded == list(range(5)) + + [email protected] +def tornado_coroutine(): + yield gen.sleep(0.05) + return "ok" + + +class TornadoCompat: + def __init__(self): + self.executor = ThreadPoolExecutor(1) + + @run_on_executor + def on_executor(self): + time.sleep(0.05) + return "executor" + + @gen.coroutine + def tornado_coroutine(self): + yield gen.sleep(0.05) + return "gen.coroutine" + + +async def test_tornado_coroutines(): + t = TornadoCompat() + # verify that tornado gen and executor methods return awaitables + assert (await t.on_executor()) == "executor" + assert (await t.tornado_coroutine()) == "gen.coroutine"
Remove py35 support for async functions and async generators - Python 3.4 has reached end of life, and we can now cleanup the code base from @gen.coroutine / yeild with async / await instead. - Python 3.5 has reached end of life, so we can cleanup the code base from @async_generator / yeild_ with async / yield instead. By doing this, we make the code base easier to understand and contribute to.
2020-11-04T03:45:26Z
[]
[]
jupyterhub/jupyterhub
3,261
jupyterhub__jupyterhub-3261
[ "3247", "3254" ]
808e8711e11d4d1dbb6dfc5839a653697235a0f4
diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -634,6 +634,12 @@ def get_next_url(self, user=None, default=None): next_url, ) + # this is where we know if next_url is coming from ?next= param or we are using a default url + if next_url: + next_url_from_param = True + else: + next_url_from_param = False + if not next_url: # custom default URL, usually passed because user landed on that page but was not logged in if default: @@ -659,7 +665,10 @@ def get_next_url(self, user=None, default=None): else: next_url = url_path_join(self.hub.base_url, 'home') - next_url = self.append_query_parameters(next_url, exclude=['next']) + if not next_url_from_param: + # when a request made with ?next=... assume all the params have already been encoded + # otherwise, preserve params from the current request across the redirect + next_url = self.append_query_parameters(next_url, exclude=['next']) return next_url def append_query_parameters(self, url, exclude=None): diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -44,7 +44,7 @@ def get(self): elif user: url = self.get_next_url(user) else: - url = self.settings['login_url'] + url = url_concat(self.settings["login_url"], dict(next=self.request.uri)) self.redirect(url)
diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -31,7 +31,7 @@ async def test_root_no_auth(app): url = ujoin(public_host(app), app.hub.base_url) r = await async_requests.get(url) r.raise_for_status() - assert r.url == ujoin(url, 'login') + assert r.url == url_concat(ujoin(url, 'login'), dict(next=app.hub.base_url)) async def test_root_auth(app): @@ -622,9 +622,16 @@ def mock_authenticate(handler, data): (False, '//other.domain', '', None), (False, '///other.domain/triple', '', None), (False, '\\\\other.domain/backslashes', '', None), - # params are handled correctly - (True, '/hub/admin', 'hub/admin?left=1&right=2', [('left', 1), ('right', 2)]), - (False, '/hub/admin', 'hub/admin?left=1&right=2', [('left', 1), ('right', 2)]), + # params are handled correctly (ignored if ?next= specified) + ( + True, + '/hub/admin?left=1&right=2', + 'hub/admin?left=1&right=2', + {"left": "abc"}, + ), + (False, '/hub/admin', 'hub/admin', [('left', 1), ('right', 2)]), + (True, '', '', {"keep": "yes"}), + (False, '', '', {"keep": "yes"}), ], ) async def test_login_redirect(app, running, next_url, location, params): @@ -633,10 +640,15 @@ async def test_login_redirect(app, running, next_url, location, params): if location: location = ujoin(app.base_url, location) elif running: + # location not specified, location = user.url + if params: + location = url_concat(location, params) else: # use default url location = ujoin(app.base_url, 'hub/spawn') + if params: + location = url_concat(location, params) url = 'login' if params: @@ -655,7 +667,73 @@ async def test_login_redirect(app, running, next_url, location, params): r = await get_page(url, app, cookies=cookies, allow_redirects=False) r.raise_for_status() assert r.status_code == 302 - assert location == r.headers['Location'] + assert r.headers["Location"] == location + + [email protected]( + 'location, next, extra_params', + [ + ( + "{base_url}hub/spawn?a=5", + None, + {"a": "5"}, + ), # no ?next= given, preserve params + ("/x", "/x", {"a": "5"}), # ?next=given, params ignored + ( + "/x?b=10", + "/x?b=10", + {"a": "5"}, + ), # ?next=given with params, additional params ignored + ], +) +async def test_next_url(app, user, location, next, extra_params): + params = {} + if extra_params: + params.update(extra_params) + if next: + params["next"] = next + url = url_concat("/", params) + cookies = await app.login_user("monster") + + # location can be a string template + location = location.format(base_url=app.base_url) + + r = await get_page(url, app, cookies=cookies, allow_redirects=False) + r.raise_for_status() + assert r.status_code == 302 + assert r.headers["Location"] == location + + +async def test_next_url_params_sequence(app, user): + """Test each step of / -> login -> spawn + + and whether they preserve url params + """ + params = {"xyz": "5"} + # first request: root page, with params, not logged in + r = await get_page("/?xyz=5", app, allow_redirects=False) + r.raise_for_status() + location = r.headers["Location"] + + # next page: login + cookies = await app.login_user(user.name) + assert location == url_concat( + ujoin(app.base_url, "/hub/login"), {"next": ujoin(app.base_url, "/hub/?xyz=5")} + ) + r = await async_requests.get( + public_host(app) + location, cookies=cookies, allow_redirects=False + ) + r.raise_for_status() + location = r.headers["Location"] + + # after login, redirect back + assert location == ujoin(app.base_url, "/hub/?xyz=5") + r = await async_requests.get( + public_host(app) + location, cookies=cookies, allow_redirects=False + ) + r.raise_for_status() + location = r.headers["Location"] + assert location == ujoin(app.base_url, "/hub/spawn?xyz=5") async def test_auto_login(app, request): @@ -669,14 +747,18 @@ def get(self): ) # no auto_login: end up at /hub/login r = await async_requests.get(base_url) - assert r.url == public_url(app, path='hub/login') + assert r.url == url_concat( + public_url(app, path="hub/login"), {"next": app.hub.base_url} + ) # enable auto_login: redirect from /hub/login to /hub/dummy authenticator = Authenticator(auto_login=True) authenticator.login_url = lambda base_url: ujoin(base_url, 'dummy') with mock.patch.dict(app.tornado_settings, {'authenticator': authenticator}): r = await async_requests.get(base_url) - assert r.url == public_url(app, path='hub/dummy') + assert r.url == url_concat( + public_url(app, path="hub/dummy"), {"next": app.hub.base_url} + ) async def test_auto_login_logout(app):
Jupyter skips spawn form after authentication <!-- Thank you for contributing. These HTML commments will not render in the issue, but you can delete them once you've read them if you prefer! --> ### Bug description We have just noticed a change in behaviour, probably coming from https://github.com/jupyterhub/jupyterhub/commit/6f2e409fb9bb4959310f26f2316bc4d4d228acc0 JupyterHub skips spawner now directly after authentication as it seems some params are passed along from auth and callback: ``` 302 GET /hub/oauth_callback?code=[secret]&state=[secret] -> /hub/spawn?code=[secret]&state=[secret] (@::ffff:10.128.2.1) 261.56ms 302 GET /hub/spawn?code=[secret]&state=[secret] -> /hub/spawn-pending/vpavlin?code=[secret]&state=[secret] ``` The `code` seems to trigger the code in the commit linked above. This is our oauth config: https://github.com/opendatahub-io/jupyterhub-odh/blob/master/.jupyter/jupyterhub_config.py#L86-L143 Is it possible that it is a misconfiguration on our side? Could it be an issue with authenticator? #### Expected behaviour Spawner is shown #### Actual behaviour Spawner is skipped ### How to reproduce I don't have a simple reproducer at the moment, but I can try to get one if this turns out to me more complicated ### Your personal set up - OpenShift 4.5 - Kubepawner, oauthenticator/openshift Exclude "code" and "state" query params from next_url This fixes our issue with JH skipping spawner UI after authentization although no query parameters were provided - `code` and `state` stay in query after auth and cause Spawner to kick off. All the details are in the issue #3247. Fixes #3247 cc @kinow - since the `append_query_parameters` is your contribution, can you take a look?
Thank you for opening your first issue in this project! Engagement like this is essential for open source projects! :hugs: <br>If you haven't done so already, check out [Jupyter's Code of Conduct](https://github.com/jupyter/governance/blob/master/conduct/code_of_conduct.md). Also, please try to follow the issue template as it helps other other community members to contribute more effectively. ![welcome](https://raw.githubusercontent.com/jupyterhub/.github/master/images/welcome.jpg) You can meet the other [Jovyans](https://jupyter.readthedocs.io/en/latest/community/content-community.html?highlight=jovyan#what-is-a-jovyan) by joining our [Discourse forum](http://discourse.jupyter.org/). There is also an intro thread there where you can stop by and say Hi! :wave: <br>Welcome to the Jupyter community! :tada: cc @mroman-redhat I believe the actual issue might be that the auth flow does not strip the `code` and `state` which are not needed in URL after the auth flow is done - https://github.com/jupyterhub/jupyterhub/blob/master/jupyterhub/services/auth.py#L987 Ok, more digging...seems like the actual culprit of the issue might be https://github.com/jupyterhub/jupyterhub/commit/14378f4cc2da8ced635841547d396d07027f56d7 - this adds the `code` and `state` query parameters which causes the spawner to spawn instead of going to UI I was able to verify that the `code` and `state` are indeed the problem - when the `pages.py` code ignores them, everything is https://github.com/vpavlin/jupyterhub/blob/bug/remove-auth-args/jupyterhub/handlers/base.py#L662 Is this the right solution? I am not sure if it can potentially break some auth in case the get_next_url is used for something else then the last step of auth Thanks for submitting your first pull request! You are awesome! :hugs: <br>If you haven't done so already, check out [Jupyter's Code of Conduct](https://github.com/jupyter/governance/blob/master/conduct/code_of_conduct.md). Also, please make sure you followed the pull request template, as this will help us review your contribution more quickly. ![welcome](https://raw.githubusercontent.com/jupyterhub/.github/master/images/welcome.jpg) You can meet the other [Jovyans](https://jupyter.readthedocs.io/en/latest/community/content-community.html?highlight=jovyan#what-is-a-jovyan) by joining our [Discourse forum](http://discourse.jupyter.org/). There is also a intro thread there where you can stop by and say Hi! :wave: <br>Welcome to the Jupyter community! :tada: HI @kinow thank you for your thoughts! This is not a problem of spawner per se. This seems to be the combination of OAuth and the changes in spawner (appending query params and picking them up and doing "auto-spawn"). OAuth actually uses the [BaseHandler.get_next_url](https://github.com/jupyterhub/oauthenticator/blob/master/oauthenticator/oauth2.py#L190), so there are potentially 2 places where to implement my change - in the BaseHandler or in the OAuth. My preference is BaseHandler since if we only remove `code` and `state` for OAuth, we could get inconsistent behaviour. Also probably worth mentioning - `code` (a temporary code for client to get access token) and `state` (a unique/random id to identify a request is coiming from a user who initiated the authentication) are used in OAuth flow, so they should not be relied upon after the auth is done. I would also consider reviewing the whole approach with the query params, since it seems to me that it does not actually work with OAuth. What happened when I tried: 1. Access `/hub?xyz=test` 2. Redirect to `/hub/login` (the query param is lost) 3. Perform login 4. Redirect to `/hub/spawn?code=...&state=...` (no `xyz` param and spawner wants to start based on `code` and `state`) So my preference woudl be to merge this PR to fix the OAuth flow and then we can dig deeper into how we can preserve the query params for OAuth. WDYT?
2020-11-17T10:31:30Z
[]
[]
jupyterhub/jupyterhub
3,266
jupyterhub__jupyterhub-3266
[ "3262" ]
5bcbc8b328d24eb18deb4ca9b82b13d633522d76
diff --git a/jupyterhub/proxy.py b/jupyterhub/proxy.py --- a/jupyterhub/proxy.py +++ b/jupyterhub/proxy.py @@ -574,6 +574,34 @@ def _remove_pid_file(self): self.log.debug("PID file %s already removed", self.pid_file) pass + def _get_ssl_options(self): + """List of cmd proxy options to use internal SSL""" + cmd = [] + proxy_api = 'proxy-api' + proxy_client = 'proxy-client' + api_key = self.app.internal_proxy_certs[proxy_api][ + 'keyfile' + ] # Check content in next test and just patch manulaly or in the config of the file + api_cert = self.app.internal_proxy_certs[proxy_api]['certfile'] + api_ca = self.app.internal_trust_bundles[proxy_api + '-ca'] + + client_key = self.app.internal_proxy_certs[proxy_client]['keyfile'] + client_cert = self.app.internal_proxy_certs[proxy_client]['certfile'] + client_ca = self.app.internal_trust_bundles[proxy_client + '-ca'] + + cmd.extend(['--api-ssl-key', api_key]) + cmd.extend(['--api-ssl-cert', api_cert]) + cmd.extend(['--api-ssl-ca', api_ca]) + cmd.extend(['--api-ssl-request-cert']) + cmd.extend(['--api-ssl-reject-unauthorized']) + + cmd.extend(['--client-ssl-key', client_key]) + cmd.extend(['--client-ssl-cert', client_cert]) + cmd.extend(['--client-ssl-ca', client_ca]) + cmd.extend(['--client-ssl-request-cert']) + cmd.extend(['--client-ssl-reject-unauthorized']) + return cmd + async def start(self): """Start the proxy process""" # check if there is a previous instance still around @@ -605,27 +633,7 @@ async def start(self): if self.ssl_cert: cmd.extend(['--ssl-cert', self.ssl_cert]) if self.app.internal_ssl: - proxy_api = 'proxy-api' - proxy_client = 'proxy-client' - api_key = self.app.internal_proxy_certs[proxy_api]['keyfile'] - api_cert = self.app.internal_proxy_certs[proxy_api]['certfile'] - api_ca = self.app.internal_trust_bundles[proxy_api + '-ca'] - - client_key = self.app.internal_proxy_certs[proxy_client]['keyfile'] - client_cert = self.app.internal_proxy_certs[proxy_client]['certfile'] - client_ca = self.app.internal_trust_bundles[proxy_client + '-ca'] - - cmd.extend(['--api-ssl-key', api_key]) - cmd.extend(['--api-ssl-cert', api_cert]) - cmd.extend(['--api-ssl-ca', api_ca]) - cmd.extend(['--api-ssl-request-cert']) - cmd.extend(['--api-ssl-reject-unauthorized']) - - cmd.extend(['--client-ssl-key', client_key]) - cmd.extend(['--client-ssl-cert', client_cert]) - cmd.extend(['--client-ssl-ca', client_ca]) - cmd.extend(['--client-ssl-request-cert']) - cmd.extend(['--client-ssl-reject-unauthorized']) + cmd.extend(self._get_ssl_options()) if self.app.statsd_host: cmd.extend( [
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -77,6 +77,10 @@ jobs: # Tests everything when the user instances are started with # jupyter_server instead of notebook. # + # ssl: + # Tests everything using internal SSL connections instead of + # unencrypted HTTP + # # main_dependencies: # Tests everything when the we use the latest available dependencies # from: ipytraitlets. @@ -89,6 +93,8 @@ jobs: subdomain: subdomain - python: "3.7" db: mysql + - python: "3.7" + ssl: ssl - python: "3.8" db: postgres - python: "3.8" @@ -109,6 +115,9 @@ jobs: echo "MYSQL_HOST=127.0.0.1" >> $GITHUB_ENV echo "JUPYTERHUB_TEST_DB_URL=mysql+mysqlconnector://[email protected]:3306/jupyterhub" >> $GITHUB_ENV fi + if [ "${{ matrix.ssl }}" == "ssl" ]; then + echo "SSL_ENABLED=1" >> $GITHUB_ENV + fi if [ "${{ matrix.db }}" == "postgres" ]; then echo "PGHOST=127.0.0.1" >> $GITHUB_ENV echo "PGUSER=test_user" >> $GITHUB_ENV diff --git a/jupyterhub/tests/conftest.py b/jupyterhub/tests/conftest.py --- a/jupyterhub/tests/conftest.py +++ b/jupyterhub/tests/conftest.py @@ -74,7 +74,9 @@ def ssl_tmpdir(tmpdir_factory): def app(request, io_loop, ssl_tmpdir): """Mock a jupyterhub app for testing""" mocked_app = None - ssl_enabled = getattr(request.module, "ssl_enabled", False) + ssl_enabled = getattr( + request.module, 'ssl_enabled', os.environ.get('SSL_ENABLED', False) + ) kwargs = dict() if ssl_enabled: kwargs.update(dict(internal_ssl=True, internal_certs_location=str(ssl_tmpdir))) diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -27,7 +27,6 @@ from .utils import auth_header from .utils import find_user - # -------------------- # Authentication tests # -------------------- diff --git a/jupyterhub/tests/test_internal_ssl_api.py b/jupyterhub/tests/test_internal_ssl_api.py deleted file mode 100644 --- a/jupyterhub/tests/test_internal_ssl_api.py +++ /dev/null @@ -1,6 +0,0 @@ -"""Tests for the SSL enabled REST API.""" -# Copyright (c) Jupyter Development Team. -# Distributed under the terms of the Modified BSD License. -from jupyterhub.tests.test_api import * - -ssl_enabled = True diff --git a/jupyterhub/tests/test_internal_ssl_app.py b/jupyterhub/tests/test_internal_ssl_app.py deleted file mode 100644 --- a/jupyterhub/tests/test_internal_ssl_app.py +++ /dev/null @@ -1,7 +0,0 @@ -"""Test the JupyterHub entry point with internal ssl""" -# Copyright (c) Jupyter Development Team. -# Distributed under the terms of the Modified BSD License. -import jupyterhub.tests.mocking -from jupyterhub.tests.test_app import * - -ssl_enabled = True diff --git a/jupyterhub/tests/test_internal_ssl_spawner.py b/jupyterhub/tests/test_internal_ssl_spawner.py deleted file mode 100644 --- a/jupyterhub/tests/test_internal_ssl_spawner.py +++ /dev/null @@ -1,6 +0,0 @@ -"""Tests for process spawning with internal_ssl""" -# Copyright (c) Jupyter Development Team. -# Distributed under the terms of the Modified BSD License. -from jupyterhub.tests.test_spawner import * - -ssl_enabled = True diff --git a/jupyterhub/tests/test_proxy.py b/jupyterhub/tests/test_proxy.py --- a/jupyterhub/tests/test_proxy.py +++ b/jupyterhub/tests/test_proxy.py @@ -9,12 +9,12 @@ import pytest from traitlets.config import Config -from .. import orm from ..utils import url_path_join as ujoin from ..utils import wait_for_http_server from .mocking import MockHub from .test_api import add_user from .test_api import api_request +from .utils import skip_if_ssl @pytest.fixture @@ -27,6 +27,7 @@ def disable_check_routes(app): app.last_activity_callback.start() +@skip_if_ssl async def test_external_proxy(request): auth_token = 'secret!' proxy_ip = '127.0.0.1' diff --git a/jupyterhub/tests/test_services.py b/jupyterhub/tests/test_services.py --- a/jupyterhub/tests/test_services.py +++ b/jupyterhub/tests/test_services.py @@ -17,6 +17,7 @@ from ..utils import wait_for_http_server from .mocking import public_url from .utils import async_requests +from .utils import skip_if_ssl mockservice_path = os.path.dirname(os.path.abspath(__file__)) mockservice_py = os.path.join(mockservice_path, 'mockservice.py') @@ -63,6 +64,7 @@ async def test_managed_service(mockservice): assert service.proc.poll() is None +@skip_if_ssl async def test_proxy_service(app, mockservice_url): service = mockservice_url name = service.name @@ -76,6 +78,7 @@ async def test_proxy_service(app, mockservice_url): assert r.text.endswith(path) +@skip_if_ssl async def test_external_service(app): name = 'external' async with external_service(app, name=name) as env: diff --git a/jupyterhub/tests/test_services_auth.py b/jupyterhub/tests/test_services_auth.py --- a/jupyterhub/tests/test_services_auth.py +++ b/jupyterhub/tests/test_services_auth.py @@ -35,6 +35,7 @@ # mock for sending monotonic counter way into the future monotonic_future = mock.patch('time.monotonic', lambda: sys.maxsize) +ssl_enabled = False def test_expiring_dict(): diff --git a/jupyterhub/tests/utils.py b/jupyterhub/tests/utils.py --- a/jupyterhub/tests/utils.py +++ b/jupyterhub/tests/utils.py @@ -1,6 +1,8 @@ import asyncio +import os from concurrent.futures import ThreadPoolExecutor +import pytest import requests from certipy import Certipy @@ -52,6 +54,12 @@ def ssl_setup(cert_dir, authority_name): return external_certs +"""Skip tests that don't work under internal-ssl when testing under internal-ssl""" +skip_if_ssl = pytest.mark.skipif( + os.environ.get('SSL_ENABLED', False), reason="Does not use internal SSL" +) + + def check_db_locks(func): """Decorator that verifies no locks are held on database upon exit.
Fewer internal_ssl tests Currently, we run our internal_ssl tests by re-running several test modules with `ssl_enabled = True`. There's a lot of redundant testing going on here, since only a small subset of these tests are covering additional functionality the second time they run. I see two ways to improve things: 1. (probably simplest, easiest to keep good coverage) remove the duplicate `internal_ssl_*` test files and switch the ssl_enabled logic to be based on an environment variable, adding ssl testing to the CI matrix. This will significantly reduce the number of tests each run goes through. 2. keep the current always-test-ssl behavior, but opt-in to a much smaller subset of tests known to cover ssl-related functionality: - starting, connecting to spawners - registering activity - services - proxy api I don't have a strong preference for which one, but I think we can speed up the tests quite a bit (times on my laptop): - with internal_ssl tests: 3:53 - without internal_ssl tests (keeping test_internal_ssl_connections): 2:22 so we are roughly doubling the runtime of all of our test runs to cover internal_ssl configurations.
2020-11-19T12:08:29Z
[]
[]
jupyterhub/jupyterhub
3,289
jupyterhub__jupyterhub-3289
[ "3280" ]
18393ec6b4c09746ad24ff7b3a361738b06f85b2
diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -40,6 +40,7 @@ from ..metrics import ServerPollStatus from ..metrics import ServerSpawnStatus from ..metrics import ServerStopStatus +from ..metrics import TOTAL_USERS from ..objects import Server from ..spawner import LocalProcessSpawner from ..user import User @@ -453,6 +454,7 @@ def user_from_username(self, username): # not found, create and register user u = orm.User(name=username) self.db.add(u) + TOTAL_USERS.inc() self.db.commit() user = self._user_from_orm(u) return user diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -69,7 +69,6 @@ def add(self, orm_user): """Add a user to the UserDict""" if orm_user.id not in self: self[orm_user.id] = self.from_orm(orm_user) - TOTAL_USERS.inc() return self[orm_user.id] def __contains__(self, key):
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -41,6 +41,7 @@ from traitlets import default from traitlets import Dict +from .. import metrics from .. import orm from ..app import JupyterHub from ..auth import PAMAuthenticator @@ -327,6 +328,7 @@ async def initialize(self, argv=None): user = orm.User(name='user') self.db.add(user) self.db.commit() + metrics.TOTAL_USERS.inc() def stop(self): super().stop() diff --git a/jupyterhub/tests/test_metrics.py b/jupyterhub/tests/test_metrics.py new file mode 100644 --- /dev/null +++ b/jupyterhub/tests/test_metrics.py @@ -0,0 +1,34 @@ +import json + +from .utils import add_user +from .utils import api_request +from jupyterhub import metrics +from jupyterhub import orm + + +async def test_total_users(app): + num_users = app.db.query(orm.User).count() + sample = metrics.TOTAL_USERS.collect()[0].samples[0] + assert sample.value == num_users + + await api_request( + app, "/users", method="post", data=json.dumps({"usernames": ["incrementor"]}) + ) + + sample = metrics.TOTAL_USERS.collect()[0].samples[0] + assert sample.value == num_users + 1 + + # GET /users used to double-count + await api_request(app, "/users") + + # populate the Users cache dict if any are missing: + for user in app.db.query(orm.User): + _ = app.users[user.id] + + sample = metrics.TOTAL_USERS.collect()[0].samples[0] + assert sample.value == num_users + 1 + + await api_request(app, "/users/incrementor", method="delete") + + sample = metrics.TOTAL_USERS.collect()[0].samples[0] + assert sample.value == num_users diff --git a/jupyterhub/tests/utils.py b/jupyterhub/tests/utils.py --- a/jupyterhub/tests/utils.py +++ b/jupyterhub/tests/utils.py @@ -4,6 +4,7 @@ import requests from certipy import Certipy +from jupyterhub import metrics from jupyterhub import orm from jupyterhub.objects import Server from jupyterhub.utils import url_path_join as ujoin @@ -97,6 +98,7 @@ def add_user(db, app=None, **kwargs): if orm_user is None: orm_user = orm.User(**kwargs) db.add(orm_user) + metrics.TOTAL_USERS.inc() else: for attr, value in kwargs.items(): setattr(orm_user, attr, value)
/hub/metrics total_users double the actual value As @ianabc reported in https://github.com/jupyterhub/jupyterhub/issues/2685#issuecomment-732310172, there is a discrepancy for the `total_users` metric reported in `/hub/metrics` with the total users reported in `/hub/admin`. I'm using a JupyterHub 1.2.1. I would guess that total_users is incremented twice per user by mistake. ## /hub/metrics ``` # HELP total_users total number of users # TYPE total_users gauge total_users 960.0 ``` ## /hub/admin ![image](https://user-images.githubusercontent.com/3837114/100183363-074cf200-2edf-11eb-8e6c-888fda72a917.png) ![image](https://user-images.githubusercontent.com/3837114/100183225-ade4c300-2ede-11eb-8245-6274cfe59d8b.png)
I think I can explain why this is happening; `init_users` in app.py [looks at the database during startup](https://github.com/jupyterhub/jupyterhub/blob/959dfb145ac1a9c5e3cf80980c73fa273f462f0b/jupyterhub/app.py#L1774) and initializes `TOTAL_USERS` from that count. Next, _something_ calls `UserListAPIHandler.get()` which is somehow able to increment `TOTAL_USERS` (in some cases - see below) double counting users. For me, and I suspect for @consideRatio, the _something_ is `jupyterhub-idle-culler`. If I disable that, my counts are correct, but I think the actual problem is with `init_users` and `UserDict.__getitem__`. I was surprised that [UserListAPIHandler.get()](https://github.com/jupyterhub/jupyterhub/blob/202efae6d85582f2cc80eff8546c3162030129b6/jupyterhub/apihandlers/users.py#L52) was able to change state so I dug a bit deeper. That method has a list comprehension which calls `user_model`, and `user_model` does this ```python user = self.users[user.id] ``` The underlying [`UserDict.__getitem__`](https://github.com/jupyterhub/jupyterhub/blob/202efae6d85582f2cc80eff8546c3162030129b6/jupyterhub/user.py#L90) calls `self.add` if the key is an integer, and `UserDict.add`, increments the count via ```python def add(self, orm_user): """Add a user to the UserDict""" if orm_user.id not in self: self[orm_user.id] = self.from_orm(orm_user) TOTAL_USERS.inc() return self[orm_user.id] ``` At startup, `init_users` sets `TOTAL_USERS` but it doesn't populate the users attribute. Later on, when something calls this method, the `if orm_user.id not in self` condition passes and users get double counted. It looks like the `add` method was designed to handle the case that the user is already in `self.users` so I made [this branch](https://github.com/jupyterhub/jupyterhub/compare/master...ianabc:fix-user-init) which alters `init_users` to populate `self.users`. This means the `if orm_user.id not in self` condition fails on subsequent calls and it seems to fix the problem. I'd be (extremely!) happy to open a pull request if that helps, but I wanted to check I was on the right path before going too far. Also, is the `self.add` in `UserDict.__getitem__` OK? It doesn't seem like that method should be allowed to update the users list.
2020-11-30T12:31:06Z
[]
[]
jupyterhub/jupyterhub
3,293
jupyterhub__jupyterhub-3293
[ "3217" ]
ff15ced3ce5b1f4a7e20edb1e432609cb4bb06a0
diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -36,7 +36,11 @@ async def get(self): user = self.get_current_user_oauth_token() if user is None: raise web.HTTPError(403) - self.write(json.dumps(self.user_model(user))) + if isinstance(user, orm.Service): + model = self.service_model(user) + else: + model = self.user_model(user) + self.write(json.dumps(model)) class UserListAPIHandler(APIHandler):
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -277,6 +277,17 @@ async def test_get_self(app): assert r.status_code == 403 +async def test_get_self_service(app, mockservice): + r = await api_request( + app, "user", headers={"Authorization": f"token {mockservice.api_token}"} + ) + r.raise_for_status() + service_info = r.json() + + assert service_info['kind'] == 'service' + assert service_info['name'] == mockservice.name + + @mark.user async def test_add_user(app): db = app.db
AttributeError: 'Service' object has no attribute 'groups' Hi, [Running 1.2.0b1] I am running the following code in a service to get information about my user: ```py import requests api_url = os.environ['JUPYTERHUB_API_URL'] api_token = os.environ['JUPYTERHUB_API_TOKEN'] r = requests.get(api_url + '/user', headers={'Authorization': 'token %s' % api_token,}) ``` The request seems to authenticate ok (I would get a 403 if I put /users for example) but it returns the following: ```py Uncaught exception GET /hub/api/user (172.17.0.2) HTTPServerRequest(protocol='http', host='172.17.0.2:8081', method='GET', uri='/hub/api/user', version='HTTP/1.1', remote_ip='172.17.0.2') Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/tornado/web.py", line 1703, in _execute result = await result File "/usr/local/lib/python3.6/dist-packages/jupyterhub/apihandlers/users.py", line 38, in get self.write(json.dumps(self.user_model(user))) File "/usr/local/lib/python3.6/dist-packages/jupyterhub/apihandlers/base.py", line 193, in user_model 'groups': [g.name for g in user.groups], AttributeError: 'Service' object has no attribute 'groups' ```
Thank you for opening your first issue in this project! Engagement like this is essential for open source projects! :hugs: <br>If you haven't done so already, check out [Jupyter's Code of Conduct](https://github.com/jupyter/governance/blob/master/conduct/code_of_conduct.md). Also, please try to follow the issue template as it helps other other community members to contribute more effectively. ![welcome](https://raw.githubusercontent.com/jupyterhub/.github/master/images/welcome.jpg) You can meet the other [Jovyans](https://jupyter.readthedocs.io/en/latest/community/content-community.html?highlight=jovyan#what-is-a-jovyan) by joining our [Discourse forum](http://discourse.jupyter.org/). There is also an intro thread there where you can stop by and say Hi! :wave: <br>Welcome to the Jupyter community! :tada: I had a same issue, when I called /user GET API. Another API(/users GET, /users/{name}/tokens GET, etc.) were operated well except above API. In my case, users were authenticated by LDAP. This should fail with 403 as it is now, but we can also make it work for services. The request being made here is asking to identify the service itself, not your user. If you want information about your users, it should send the oauth token associated with the user accessing your service, not the service's token itself.
2020-12-02T11:22:05Z
[]
[]
jupyterhub/jupyterhub
3,294
jupyterhub__jupyterhub-3294
[ "3229" ]
4b254fe5edd395e244eea730f521deaa517136dd
diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -457,7 +457,8 @@ class AdminHandler(BaseHandler): @web.authenticated @admin_only async def get(self): - page, per_page, offset = Pagination(config=self.config).get_page_args(self) + pagination = Pagination(url=self.request.uri, config=self.config) + page, per_page, offset = pagination.get_page_args(self) available = {'name', 'admin', 'running', 'last_activity'} default_sort = ['admin', 'name'] @@ -513,14 +514,7 @@ async def get(self): for u in users: running.extend(s for s in u.spawners.values() if s.active) - total = self.db.query(orm.User.id).count() - pagination = Pagination( - url=self.request.uri, - total=total, - page=page, - per_page=per_page, - config=self.config, - ) + pagination.total = self.db.query(orm.User.id).count() auth_state = await self.current_user.get_auth_state() html = await self.render_template( diff --git a/jupyterhub/pagination.py b/jupyterhub/pagination.py --- a/jupyterhub/pagination.py +++ b/jupyterhub/pagination.py @@ -1,7 +1,6 @@ """Basic class to manage pagination utils.""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. -from traitlets import Bool from traitlets import default from traitlets import Integer from traitlets import observe @@ -81,13 +80,13 @@ def get_page_args(self, handler): try: self.per_page = int(per_page) except Exception: - self.per_page = self._default_per_page + self.per_page = self.default_per_page try: self.page = int(page) if self.page < 1: self.page = 1 - except: + except Exception: self.page = 1 return self.page, self.per_page, self.per_page * (self.page - 1)
diff --git a/jupyterhub/tests/test_pagination.py b/jupyterhub/tests/test_pagination.py --- a/jupyterhub/tests/test_pagination.py +++ b/jupyterhub/tests/test_pagination.py @@ -6,11 +6,20 @@ from jupyterhub.pagination import Pagination -def test_per_page_bounds(): [email protected]( + "per_page, max_per_page, expected", + [ + (20, 10, 10), + (1000, 1000, 1000), + ], +) +def test_per_page_bounds(per_page, max_per_page, expected): cfg = Config() - cfg.Pagination.max_per_page = 10 - p = Pagination(config=cfg, per_page=20, total=100) - assert p.per_page == 10 + cfg.Pagination.max_per_page = max_per_page + p = Pagination(config=cfg) + p.per_page = per_page + p.total = 99999 + assert p.per_page == expected with raises(Exception): p.per_page = 0 @@ -39,7 +48,5 @@ def test_per_page_bounds(): ], ) def test_window(page, per_page, total, expected): - cfg = Config() - cfg.Pagination pagination = Pagination(page=page, per_page=per_page, total=total) assert pagination.calculate_pages_window() == expected
make pagination configurable add some unittests for pagination reorganize pagination a bit to make it easier to configure still need to do a bit more testing closes #3228
Awesome, @minrk!!!! @minrk I added the enhancement label because it make github-activity automatically categorize the PR for the changelog. Hmm, this seems to not work. I've the following in my extra_config: ```yaml 07-no-pagination: | c.Pagination.default_per_page = 10000 c.Pagination.max_per_page = 10000 ``` But pagination still seems to be at 250.
2020-12-02T11:53:42Z
[]
[]
jupyterhub/jupyterhub
3,347
jupyterhub__jupyterhub-3347
[ "3328" ]
1d9795c57785990cc022373ffb5d67f0cea9b72b
diff --git a/jupyterhub/services/auth.py b/jupyterhub/services/auth.py --- a/jupyterhub/services/auth.py +++ b/jupyterhub/services/auth.py @@ -19,6 +19,7 @@ import time import uuid import warnings +from unittest import mock from urllib.parse import quote from urllib.parse import urlencode @@ -832,8 +833,12 @@ def get_login_url(self): # add state argument to OAuth url state = self.hub_auth.set_state_cookie(self, next_url=self.request.uri) login_url = url_concat(login_url, {'state': state}) - app_log.debug("Redirecting to login url: %s", login_url) - return login_url + # temporary override at setting level, + # to allow any subclass overrides of get_login_url to preserve their effect + # for example, APIHandler raises 403 to prevent redirects + with mock.patch.dict(self.application.settings, {"login_url": login_url}): + app_log.debug("Redirecting to login url: %s", login_url) + return super().get_login_url() def check_hub_user(self, model): """Check whether Hub-authenticated user or service should be allowed. diff --git a/jupyterhub/singleuser/mixins.py b/jupyterhub/singleuser/mixins.py --- a/jupyterhub/singleuser/mixins.py +++ b/jupyterhub/singleuser/mixins.py @@ -9,11 +9,10 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import asyncio -import importlib import json import os import random -from datetime import datetime +import warnings from datetime import timezone from textwrap import dedent from urllib.parse import urlparse @@ -23,7 +22,6 @@ from tornado import ioloop from tornado.httpclient import AsyncHTTPClient from tornado.httpclient import HTTPRequest -from tornado.web import HTTPError from tornado.web import RequestHandler from traitlets import Any from traitlets import Bool @@ -94,9 +92,19 @@ def is_token_authenticated(handler): @staticmethod def get_user(handler): - """alternative get_current_user to query the Hub""" - # patch in HubAuthenticated class for querying the Hub for cookie authentication - if HubAuthenticatedHandler not in handler.__class__.__bases__: + """alternative get_current_user to query the Hub + + Thus shouldn't be called anymore because HubAuthenticatedHandler + should have already overridden get_current_user(). + + Keep here to prevent unlikely circumstance from losing auth. + """ + if HubAuthenticatedHandler not in handler.__class__.mro(): + warnings.warn( + f"Expected to see HubAuthenticatedHandler in {handler.__class__}.mro()", + RuntimeWarning, + stacklevel=2, + ) handler.__class__ = type( handler.__class__.__name__, (HubAuthenticatedHandler, handler.__class__), @@ -691,6 +699,7 @@ def make_singleuser_app(App): """ empty_parent_app = App() + log = empty_parent_app.log # detect base classes LoginHandler = empty_parent_app.login_handler_class @@ -707,6 +716,26 @@ def make_singleuser_app(App): "{}.base_handler_class must be defined".format(App.__name__) ) + # patch-in HubAuthenticatedHandler to BaseHandler, + # so anything inheriting from BaseHandler uses Hub authentication + if HubAuthenticatedHandler not in BaseHandler.__bases__: + new_bases = (HubAuthenticatedHandler,) + BaseHandler.__bases__ + log.debug( + f"Patching {BaseHandler}{BaseHandler.__bases__} -> {BaseHandler}{new_bases}" + ) + BaseHandler.__bases__ = new_bases + # We've now inserted our class as a parent of BaseHandler, + # but we also need to ensure BaseHandler *itself* doesn't + # override the public tornado API methods we have inserted. + # If they are defined in BaseHandler, explicitly replace them with our methods. + for name in ("get_current_user", "get_login_url"): + if name in BaseHandler.__dict__: + log.debug( + f"Overriding {BaseHandler}.{name} with HubAuthenticatedHandler.{name}" + ) + method = getattr(HubAuthenticatedHandler, name) + setattr(BaseHandler, name, method) + # create Handler classes from mixins + bases class JupyterHubLoginHandler(JupyterHubLoginHandlerMixin, LoginHandler): pass
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -404,9 +404,10 @@ def _default_url(self): Should be: - authenticated, so we are testing auth - - always available (i.e. in base ServerApp and NotebookApp + - always available (i.e. in mocked ServerApp and NotebookApp) + - *not* an API handler that raises 403 instead of redirecting """ - return "/api/status" + return "/tree" _thread = None diff --git a/jupyterhub/tests/test_singleuser.py b/jupyterhub/tests/test_singleuser.py --- a/jupyterhub/tests/test_singleuser.py +++ b/jupyterhub/tests/test_singleuser.py @@ -21,6 +21,7 @@ async def test_singleuser_auth(app): user = app.users['nandy'] if not user.running: await user.spawn() + await app.proxy.add_user(user) url = public_url(app, user) # no cookies, redirects to login page @@ -28,6 +29,11 @@ async def test_singleuser_auth(app): r.raise_for_status() assert '/hub/login' in r.url + # unauthenticated /api/ should 403, not redirect + api_url = url_path_join(url, "api/status") + r = await async_requests.get(api_url, allow_redirects=False) + assert r.status_code == 403 + # with cookies, login successful r = await async_requests.get(url, cookies=cookies) r.raise_for_status()
Auth expiration problems with JupyterLab 3.x <!-- Thank you for contributing. These HTML comments will not render in the issue, but you can delete them once you've read them if you prefer! --> ### Bug description <!-- Use this section to clearly and concisely describe the bug. --> After upgrading to JupyterLab 3.0, everything works fine until the auth token expires. Then, the UI fails to refresh the auth token due to CORS, and as a side effect it continues setting more and more cookies until its requests start getting 400 Bad Request because of the large Cookie header. #### Expected behaviour <!-- Tell us what you thought would happen. --> JupyterLab continues working as long as the tab is open #### Actual behaviour <!-- Tell us what actually happens. --> A popup appears: ``` Server Connection Error A connection to the Jupyter server could not be established. JupyterLab will continue trying to reconnect. Check your network connection or Jupyter server configuration. ``` In Chrome's Console, you can see that it's failing due to CORS: ``` lab:1 Access to fetch at 'https://jupyter.mit.edu/hub/api/oauth2/authorize?client_id=jupyterhub-user-quentin&redirect_uri=https%3A%2F%2Fquentin.jupyter.mit.edu%2Fuser%2Fquentin%2Foauth_callback&response_type=code&state=REMOVED' (redirected from 'https://quentin.jupyter.mit.edu/user/quentin/api/contents/REMOVED?content=1&1610401550583') from origin 'https://quentin.jupyter.mit.edu' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. serverconnection.js:207 GET https://jupyter.mit.edu/hub/api/oauth2/authorize?client_id=jupyterhub-user-quentin&redirect_uri=https%3A%2F%2Fquentin.jupyter.mit.edu%2Fuser%2Fquentin%2Foauth_callback&response_type=code&state=REMOVED net::ERR_FAILED ``` It looks like JupyterLab is trying to fetch /user/$user/api/contents, the auth is expired so it's redirected from $user.jupyter/user to jupyter/hub for auth, then after N cycles of that, ``` serverconnection.js:207 GET https://quentin.jupyter.mit.edu/user/quentin/api/contents/REMOVED?content=1&1610401672210 400 (Bad Request) ``` and looking at my cookies I now have cookies named `jupyterhub-user-quentin-oauth-state-FycHkGir` (for 15 different random strings, as well as one with no random suffix). Deleting those cookies and refreshing the page loads JupyterLab correctly. ### How to reproduce <!-- Use this section to describe the steps that a user would take to experience this bug. --> 1. Install the latest JupyterHub and JupyterLab 2. (Probably) configure JupyterHub to use subdomains 3. Open JupyterLab and leave the tab open. ### Your personal set up <!-- Tell us a little about the system you're using. Please include information about how you installed, e.g. are you using a distribution such as zero-to-jupyterhub or the-littlest-jupyterhub. --> JupyterHub and JupyterLab are installed directly from PIP in a VirtualEnv. All the config files are available at: https://github.com/sipb/jupyter/tree/master/ansible/roles/jupyter-jupyter/files, including the JupyterHub config file itself. - OS: <!-- [e.g. ubuntu 20.04, macOS 11.0] --> Ubuntu 20.04 - Version(s): <!-- e.g. jupyterhub --version, python --version ---> ``` $ jupyterhub --version 1.3.0 $ python --version Python 3.8.5 $ jupyter lab --version 3.0.3 ``` <details><summary>Full environment</summary> ``` AccessControl==5.0 acme==1.1.0 Acquisition==4.7 aggdraw==1.3.12 aiosqlite==0.16.0 alabaster==0.7.8 alembic==1.4.3 ansible==2.9.6 anyio==2.0.2 apache-libcloud==2.8.0 appdirs==1.4.3 argcomplete==1.8.1 argh==0.26.2 argon2-cffi==20.1.0 asn1crypto==1.4.0 astroid==2.4.2 astroplan==0.7 astropy==4.2 astrowidgets==0.1.1 async-generator==1.10 asyncpg==0.21.0 atomicwrites==1.4.0 attrs==20.3.0 AuthEncoding==4.2 Authlib==0.15.2 Automat==0.8.0 autopep8==1.5.4 Babel==2.9.0 backcall==0.2.0 beautifulsoup4==4.9.3 biopython==1.78 bitarray==1.6.1 bkcharts==0.2 bleach==3.2.1 blinker==1.4 blosc==1.10.1 bokeh==2.2.3 boto==2.49.0 boto3==1.9.253 botocore==1.16.19 Bottleneck==1.3.2 brotlipy==0.7.0 BTrees==4.7.2 CacheControl==0.12.6 Cartopy==0.18.0 certbot==0.40.0 certbot-apache==0.39.0 certbot-dns-route53==0.35.1 certifi==2019.11.28 certipy==0.1.3 cffi==1.14.4 cftime==1.2.1 Chameleon==3.8.1 chardet==4.0.0 click==7.1.2 clingkernel==0.0.2 cloud-init==20.2 cloudpickle==1.6.0 clyent==1.2.1 colorama==0.4.4 command-not-found==0.3 ConfigArgParse==0.13.0 configobj==5.0.6 constantly==15.1.0 contextlib2==0.6.0.post1 cryptography==3.3.1 cycler==0.10.0 cypari==2.4.0 Cython==0.29.21 cytoolz==0.11.0 dask==2020.12.0 databases==0.3.2 DateTime==4.3 dblatex===0.3.11py3 dbus-python==1.2.16 decorator==4.4.2 defusedxml==0.6.0 devscripts===2.20.2ubuntu2 diff-match-patch==20200713 distlib==0.3.0 distro==1.4.0 distro-info===0.23ubuntu1 dnspython==1.16.0 DocumentTemplate==4.0 docutils==0.16 ec2-hibinit-agent==1.0.0 entrypoints==0.3 et-xmlfile==1.0.1 ExtensionClass==4.5.0 fastapi==0.61.2 fastcache==1.1.0 filelock==3.0.12 flake8==3.8.4 Flask==1.1.2 fsspec==0.8.5 future==0.18.2 FXrays==1.3.3 gbp==0.9.19 GDAL==3.0.4 geomag-algorithms==1.3.5 gevent==20.12.1 ginga==3.1.0 gitdb==4.0.5 GitPython==3.1.11 glob2==0.7 gmpy2==2.1.0b3 gpg===1.13.1-unknown greenlet==0.4.17 gssapi==1.6.12 gunicorn==20.0.4 h11==0.9.0 h2==3.2.0 h5py==3.1.0 hdmedians==0.14.1 HeapDict==1.0.1 hibagent==1.0.1 hpack==3.0.0 hstspreload==2020.10.20 html5lib==1.1 httplib2==0.14.0 httptools==0.1.1 httpx==0.11.1 hyperframe==5.2.0 hyperlink==19.0.0 icu==0.0.1 idna==3.1 imageio==2.9.0 imagesize==1.2.0 importlib-metadata==3.4.0 incremental==16.10.1 iniconfig==1.1.1 intel-openmp==2021.1.2 intervaltree==3.1.0 ipaddr==2.2.0 ipyevents==0.8.1 ipykernel==5.3.4 ipympl==0.6.2 ipython==7.19.0 ipython-genutils==0.2.0 ipywidgets==7.6.3 isort==5.7.0 itsdangerous==1.1.0 jdcal==1.4.1 jedi==0.17.2 jeepney==0.5.0 Jinja2==2.11.2 jmespath==0.9.4 joblib==1.0.0 josepy==1.2.0 json5==0.9.5 jsonpatch==1.22 jsonpointer==2.0 jsonschema==3.2.0 jupyter-archive==3.0.0 jupyter-c-kernel==1.2.2 jupyter-client==6.1.7 jupyter-core==4.6.3 jupyter-lsp==1.0.0 jupyter-server==1.2.1 jupyter-telemetry==0.1.0 jupyterhub==1.3.0 jupyterhub-systemdspawner==0.15.0 jupyterlab==3.0.3 jupyterlab-apod==0.1.0 jupyterlab-git==0.23.3 jupyterlab-hdf==0.5.1 jupyterlab-kernelspy==3.0.1 jupyterlab-latex==2.0.0 jupyterlab-lsp==3.0.0 jupyterlab-pygments==0.1.2 jupyterlab-python-file==0.5.2 jupyterlab-quickopen==1.0.0 jupyterlab-server==2.1.1 jupyterlab-widgets==1.0.0 keyring==21.8.0 kiwisolver==1.3.1 language-selector==0.1 launchpadlib==1.10.13 lazr.restfulclient==0.14.2 lazr.uri==1.0.3 lazy-object-proxy==1.5.2 libarchive-c==2.9 lief==0.10.1 llvmlite==0.35.0 locket==0.2.0 lockfile==0.12.2 lxml==4.6.2 lz4==3.1.1 Mako==1.1.3 MarkupSafe==1.1.1 matplotlib==3.3.3 mccabe==0.6.1 metakernel==0.27.5 mistune==0.8.4 mkl==2021.1.1 mock==4.0.3 more-itertools==8.6.0 mpmath==1.1.0 mprofile==0.0.10 msgpack==1.0.2 MultiMapping==4.1 multipledispatch==0.6.0 natsort==7.0.1 nbclassic==0.2.6 nbclient==0.5.1 nbconvert==6.0.7 nbdime==2.1.0 nbformat==5.0.8 nest-asyncio==1.4.3 netaddr==0.7.19 netCDF4==1.5.4 netifaces==0.10.4 networkx==2.5 nltk==3.5 nose==1.3.7 notebook==6.1.6 ntlm-auth==1.1.0 numba==0.52.0 numexpr==2.7.2 numpy==1.19.5 oauthenticator==0.12.3 oauthlib==3.1.0 obspy==1.2.2 octave-kernel==0.32.0 olefile==0.46 openpyxl==3.0.5 packaging==20.8 pamela==1.0.0 pandas==1.2.0 pandoc==1.0.2 pandocfilters==1.4.3 pari-jupyter==1.3.2 parsedatetime==2.4 parso==0.7.1 partd==1.1.0 PasteDeploy==2.1.1 path==15.0.1 pathlib2==2.3.5 pathtools==0.1.2 patsy==0.5.1 pbr==5.4.5 pep517==0.8.2 pep8==1.7.1 Persistence==3.0 persistent==4.6.4 pexpect==4.8.0 pickleshare==0.7.5 Pillow==8.1.0 pkginfo==1.6.1 plink==2.3.1 pluggy==0.13.1 ply==3.11 progress==1.5 prometheus-client==0.9.0 prompt-toolkit==3.0.10 protobuf==3.6.1 psutil==5.8.0 psycopg2-binary==2.8.6 ptyprocess==0.7.0 py==1.10.0 PyAFS==0.2.3 pyasn1==0.4.2 pyasn1-modules==0.2.1 pycodestyle==2.6.0 pycosat==0.6.3 pycparser==2.20 pycrypto==2.6.1 pycurl==7.43.0.6 pydantic==1.7.2 pydocstyle==5.1.1 pyerfa==1.7.1.1 pyflakes==2.2.0 Pygments==2.7.3 PyGObject==3.36.0 PyHamcrest==1.9.0 PyHesiod==0.2.13 PyICU==2.4.2 PyJWT==1.7.1 pykerberos==1.1.14 pylint==2.6.0 pymacaroons==0.13.0 PyNaCl==1.3.0 pyodbc==4.0.30 pyOpenSSL==20.0.1 pyparsing==2.4.7 pypng==0.0.20 pypprof==0.0.1 pyproj==3.0.0.post1 pyRFC3339==1.1 pyrsistent==0.17.3 pyserial==3.4 pyshp==2.1.2 PySocks==1.7.1 pytest==6.2.1 python-apt==2.0.0+ubuntu0.20.4.1 python-augeas==0.5.0 python-dateutil==2.8.1 python-debian===0.1.36ubuntu1 python-dotenv==0.15.0 python-editor==1.0.4 python-gettext==4.0 python-json-logger==2.0.1 python-jsonrpc-server==0.4.0 python-language-server==0.36.2 python-magic==0.4.16 pytoml==0.1.21 pytz==2020.5 PyWavelets==1.1.1 pywinrm==0.3.0 pyxdg==0.27 PyYAML==5.3.1 pyzmq==20.0.0 QtPy==1.9.0 regex==2020.11.13 requests==2.25.1 requests-kerberos==0.12.0 requests-ntlm==1.1.0 requests-toolbelt==0.8.0 requests-unixsocket==0.2.0 RestrictedPython==5.1 retrying==1.3.3 rfc3986==1.4.0 roman==2.0.0 rope==0.18.0 ruamel.yaml==0.16.12 ruamel.yaml.clib==0.2.2 s3transfer==0.3.3 scikit-bio==0.5.6 scikit-dataaccess==1.9.17.post2 scikit-image==0.18.1 scikit-learn==0.24.0 scikit-rf==0.15.5 scipy==1.6.0 seaborn==0.11.1 SecretStorage==3.3.0 selinux==3.0 Send2Trash==1.5.0 service-identity==18.1.0 Shapely==1.7.1 simplegeneric==0.8.1 simplejson==3.16.0 singledispatch==3.4.0.3 sip==6.0.0 sipb-jupyter==1.0 six==1.15.0 smmap==3.0.4 snappy==2.8 snappy-manifolds==1.1.2 sniffio==1.2.0 snowballstemmer==2.0.0 sortedcollections==1.2.3 sortedcontainers==2.3.0 soupsieve==2.1 spherogram==1.8.3 Sphinx==1.8.5 sphinx-rtd-theme==0.4.3 SQLAlchemy==1.3.22 SQLAlchemy-Utc==0.11.0 ssh-import-id==5.10 starlette==0.13.6 statsmodels==0.12.1 sympy==1.7.1 systemd-python==234 tables==3.6.1 tbb==2021.1.1 tblib==1.7.0 terminado==0.9.2 testpath==0.4.4 threadpoolctl==2.1.0 tifffile==2020.10.1 toml==0.10.2 toolz==0.11.1 tornado==6.1 tqdm==4.56.0 traitlets==5.0.5 transaction==3.0.0 Twisted==18.9.0 typing==3.7.4.3 typing-extensions==3.7.4.3 ubuntu-advantage-tools==20.3 ufw==0.36 ujson==4.0.1 unattended-upgrades==0.1 unicodecsv==0.14.1 unidiff==0.5.5 urllib3==1.26.2 uvicorn==0.12.2 uvloop==0.14.0 varlink==30.3.1 virtualenv==20.0.17 wadllib==1.3.3 waitress==1.4.4 watchdog==1.0.2 watchgod==0.6 wcwidth==0.2.5 webencodings==0.5.1 WebOb==1.8.6 websockets==8.1 WebTest==2.0.35 Werkzeug==1.0.1 widgetsnbextension==3.5.1 wrapt==1.12.1 WSGIProxy2==0.4.6 wurlitzer==2.0.1 xarray==0.16.1 xlrd==2.0.1 XlsxWriter==1.3.7 xlwt==1.3.0 xmltodict==0.12.0 yapf==0.30.0 z3c.pt==3.3.0 zc.lockfile==2.0 ZConfig==3.5.0 zExceptions==4.1 zict==2.0.0 zipp==3.4.0 ZODB==5.6.0 zodbpickle==2.0.0 Zope==5.1 zope.annotation==4.7.0 zope.browser==2.3 zope.browsermenu==4.4 zope.browserpage==4.4.0 zope.browserresource==4.4 zope.cachedescriptors==4.3.1 zope.component==4.3.0 zope.configuration==4.4.0 zope.container==4.4.0 zope.contentprovider==4.2.1 zope.contenttype==4.5.0 zope.deferredimport==4.3.1 zope.deprecation==4.4.0 zope.dottedname==4.3 zope.event==4.5.0 zope.exceptions==4.4 zope.filerepresentation==5.0.0 zope.globalrequest==1.5 zope.hookable==5.0.0 zope.i18n==4.7.0 zope.i18nmessageid==5.0.1 zope.interface==5.2.0 zope.lifecycleevent==4.3 zope.location==4.2 zope.pagetemplate==4.5.0 zope.processlifetime==2.3.0 zope.proxy==4.3.5 zope.ptresource==4.2.0 zope.publisher==5.2.1 zope.schema==6.0.0 zope.security==5.1.1 zope.sequencesort==4.1.2 zope.site==4.4.0 zope.size==4.3 zope.structuredtext==4.3 zope.tal==4.4 zope.tales==5.1 zope.testbrowser==5.5.1 zope.testing==4.7 zope.traversing==4.4.1 zope.viewlet==4.2.1 zprofile==1.0.11 zstd==1.4.8.1 ``` </details> <details><summary>Configuration</summary> <!-- For JupyterHub, especially include information such as what Spawner and Authenticator are being used. Be careful not to share any sensitive information. You can paste jupyterhub_config.py below. To exclude lots of comments and empty lines from auto-generated jupyterhub_config.py, you can do: grep -v '\(^#\|^[[:space:]]*$\)' jupyterhub_config.py --> Visible at https://github.com/sipb/jupyter/blob/master/ansible/roles/jupyter-jupyter/files/jupyterhub_config.py </details> <details><summary>Logs</summary> ``` Jan 11 21:46:09 jupyter.mit.edu bash[452754]: [W 2021-01-11 21:46:09.421 SingleUserNotebookApp auth:551] Token stored in cookie may have expired Jan 11 21:46:09 jupyter.mit.edu bash[452754]: [D 2021-01-11 21:46:09.421 SingleUserNotebookApp auth:504] No user identified Jan 11 21:46:09 jupyter.mit.edu bash[452754]: [W 2021-01-11 21:46:09.421 SingleUserNotebookApp auth:682] Detected unused OAuth state cookies Jan 11 21:46:09 jupyter.mit.edu bash[452754]: [D 2021-01-11 21:46:09.421 SingleUserNotebookApp auth:835] Redirecting to login url: https://jupyter.mit.edu/hub/api/oauth2/authorize?client_id=jupyterhub-user-quentin&redirect_uri=https%3A%2F%2Fquentin.jupyter.mit.edu%2Fuser%2FquentinREMOVED Jan 11 21:46:09 jupyter.mit.edu bash[452754]: [I 2021-01-11 21:46:09.422 SingleUserNotebookApp log:181] 302 GET /user/quentin/api/terminals?1610401569386 -> https://jupyter.mit.edu/hub/api/oauth2/authorize?client_id=jupyterhub-user-quentin&redirect_uri=https%3A%2F%2Fquentin.jupyter.mit.eduREMOVED ``` ``` Jan 11 21:46:00 jupyter.mit.edu jupyterhub[448805]: [W 2021-01-11 21:46:00.731 JupyterHub log:181] 405 OPTIONS /hub/api/oauth2/authorize?client_id=jupyterhub-user-quentin&redirect_uri=https%3A%2F%2Fquentin.jupyter.mit.edu%2Fuser%2Fquentin%2Foauth_callback&response_type=code&state=[secret] > Jan 11 21:46:09 jupyter.mit.edu jupyterhub[448805]: [W 2021-01-11 21:46:09.477 JupyterHub log:181] 405 OPTIONS /hub/api/oauth2/authorize?client_id=jupyterhub-user-quentin&redirect_uri=https%3A%2F%2Fquentin.jupyter.mit.edu%2Fuser%2Fquentin%2Foauth_callback&response_type=code&state=[secret] > Jan 11 21:46:10 jupyter.mit.edu jupyterhub[448805]: [W 2021-01-11 21:46:10.801 JupyterHub log:181] 405 OPTIONS /hub/api/oauth2/authorize?client_id=jupyterhub-user-quentin&redirect_uri=https%3A%2F%2Fquentin.jupyter.mit.edu%2Fuser%2Fquentin%2Foauth_callback&response_type=code&state=[secret] > Jan 11 21:46:18 jupyter.mit.edu jupyterhub[448805]: [W 2021-01-11 21:46:18.826 JupyterHub log:181] 405 OPTIONS /hub/api/oauth2/authorize?client_id=jupyterhub-user-quentin&redirect_uri=https%3A%2F%2Fquentin.jupyter.mit.edu%2Fuser%2Fquentin%2Foauth_callback&response_type=code&state=[secret] > ``` </details>
Thank you for opening your first issue in this project! Engagement like this is essential for open source projects! :hugs: <br>If you haven't done so already, check out [Jupyter's Code of Conduct](https://github.com/jupyter/governance/blob/master/conduct/code_of_conduct.md). Also, please try to follow the issue template as it helps other other community members to contribute more effectively. ![welcome](https://raw.githubusercontent.com/jupyterhub/.github/master/images/welcome.jpg) You can meet the other [Jovyans](https://jupyter.readthedocs.io/en/latest/community/content-community.html?highlight=jovyan#what-is-a-jovyan) by joining our [Discourse forum](http://discourse.jupyter.org/). There is also an intro thread there where you can stop by and say Hi! :wave: <br>Welcome to the Jupyter community! :tada: Is there anything I can do to help move this bug forward? This is a major usability regression for us, since it's hard for users to figure out how to clear their cookies. Can you check whether it also occurs with jupyter notebook? Jupyter Notebook appears to not have any similar auth refresh logic; it appears to just have one long-running WebSocket. So I think "it doesn't occur but that's not a useful test"? I'm still catching up on holiday backlogs, but will focus on this one this week. To be clear, it was updating to jupyterlab 3.0 that caused this change? It may be that something changed in jupyterlab's error handling that it no longer prompts a fresh login, or the switch from notebook to jupyter_server. If refreshing the page fixes the issue, it is likely this needs to be brought up with jupyterlab or jupyter_server instead of jupyterhub. oauth state cookies should expire after a maximum of 10 minutes. They are also cleared on successful login, so I don't think this flooding state cookie issue is an important one when ~anything is working properly. It should also go away if you wait a few minutes and come back. I think this log line indicates the key bug: ``` Jan 11 21:46:09 jupyter.mit.edu bash[452754]: [I 2021-01-11 21:46:09.422 SingleUserNotebookApp log:181] 302 GET /user/quentin/api/terminals?1610401569386 -> ... ``` API handlers should never redirect on authentication failure. They should always 403. This is the root of the many login attempts. API requests cannot trigger a new login, so the redirects are spurious and never going to work. We just need to track down which code is responsible for these redirects. I suspect it's in jupyterhub's singleuser-wrapping code hooking up jupyterhub auth taking priority over APIHandler's force of 403 here. In case it's relevant there's a report of SingleUserNotebookApp with JupyterLAb 3.0.5 giving a 404 in https://github.com/jupyterhub/zero-to-jupyterhub-k8s/issues/2015
2021-01-28T11:23:20Z
[]
[]
jupyterhub/jupyterhub
3,398
jupyterhub__jupyterhub-3398
[ "3039" ]
77691ae4023e68ae0ef1a21ca5301bebb5107bc3
diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -457,82 +457,16 @@ class AdminHandler(BaseHandler): @web.authenticated @admin_only async def get(self): - pagination = Pagination(url=self.request.uri, config=self.config) - page, per_page, offset = pagination.get_page_args(self) - - available = {'name', 'admin', 'running', 'last_activity'} - default_sort = ['admin', 'name'] - mapping = {'running': orm.Spawner.server_id} - for name in available: - if name not in mapping: - table = orm.User if name != "last_activity" else orm.Spawner - mapping[name] = getattr(table, name) - - default_order = { - 'name': 'asc', - 'last_activity': 'desc', - 'admin': 'desc', - 'running': 'desc', - } - - sorts = self.get_arguments('sort') or default_sort - orders = self.get_arguments('order') - - for bad in set(sorts).difference(available): - self.log.warning("ignoring invalid sort: %r", bad) - sorts.remove(bad) - for bad in set(orders).difference({'asc', 'desc'}): - self.log.warning("ignoring invalid order: %r", bad) - orders.remove(bad) - - # add default sort as secondary - for s in default_sort: - if s not in sorts: - sorts.append(s) - if len(orders) < len(sorts): - for col in sorts[len(orders) :]: - orders.append(default_order[col]) - else: - orders = orders[: len(sorts)] - - # this could be one incomprehensible nested list comprehension - # get User columns - cols = [mapping[c] for c in sorts] - # get User.col.desc() order objects - ordered = [getattr(c, o)() for c, o in zip(cols, orders)] - - query = self.db.query(orm.User).outerjoin(orm.Spawner).distinct(orm.User.id) - subquery = query.subquery("users") - users = ( - self.db.query(orm.User) - .select_entity_from(subquery) - .outerjoin(orm.Spawner) - .order_by(*ordered) - .limit(per_page) - .offset(offset) - ) - - users = [self._user_from_orm(u) for u in users] - - running = [] - for u in users: - running.extend(s for s in u.spawners.values() if s.active) - - pagination.total = query.count() - auth_state = await self.current_user.get_auth_state() html = await self.render_template( 'admin.html', current_user=self.current_user, auth_state=auth_state, admin_access=self.settings.get('admin_access', False), - users=users, - running=running, - sort={s: o for s, o in zip(sorts, orders)}, allow_named_servers=self.allow_named_servers, named_server_limit_per_user=self.named_server_limit_per_user, server_version='{} {}'.format(__version__, self.version_hash), - pagination=pagination, + api_page_limit=self.settings["app"].api_page_default_limit, ) self.finish(html)
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -140,6 +140,7 @@ jobs: run: | npm install npm install -g configurable-http-proxy + npm install -g yarn npm list # NOTE: actions/setup-python@v2 make use of a cache within the GitHub base @@ -219,6 +220,9 @@ jobs: # https://github.com/actions/runner/issues/241 run: | pytest -v --maxfail=2 --color=yes --cov=jupyterhub jupyterhub/tests + - name: Run yarn jest test + run: | + cd jsx && yarn && yarn test - name: Submit codecov report run: | codecov diff --git a/jsx/src/components/AddUser/AddUser.test.js b/jsx/src/components/AddUser/AddUser.test.js new file mode 100644 --- /dev/null +++ b/jsx/src/components/AddUser/AddUser.test.js @@ -0,0 +1,77 @@ +import React from "react"; +import Enzyme, { mount } from "enzyme"; +import AddUser from "./AddUser"; +import Adapter from "@wojtekmaj/enzyme-adapter-react-17"; +import { Provider, useDispatch, useSelector } from "react-redux"; +import { createStore } from "redux"; +import { HashRouter } from "react-router-dom"; + +Enzyme.configure({ adapter: new Adapter() }); + +jest.mock("react-redux", () => ({ + ...jest.requireActual("react-redux"), + useDispatch: jest.fn(), + useSelector: jest.fn(), +})); + +describe("AddUser Component: ", () => { + var mockAsync = () => + jest + .fn() + .mockImplementation(() => Promise.resolve({ key: "value", status: 200 })); + + var addUserJsx = (callbackSpy) => ( + <Provider store={createStore(() => {}, {})}> + <HashRouter> + <AddUser + addUsers={callbackSpy} + failRegexEvent={callbackSpy} + updateUsers={callbackSpy} + history={{ push: () => {} }} + /> + </HashRouter> + </Provider> + ); + + var mockAppState = () => ({ + limit: 3, + }); + + beforeEach(() => { + useDispatch.mockImplementation(() => { + return () => {}; + }); + useSelector.mockImplementation((callback) => { + return callback(mockAppState()); + }); + }); + + afterEach(() => { + useDispatch.mockClear(); + }); + + it("Renders", () => { + let component = mount(addUserJsx(mockAsync())); + expect(component.find(".container").length).toBe(1); + }); + + it("Removes users when they fail Regex", () => { + let callbackSpy = mockAsync(), + component = mount(addUserJsx(callbackSpy)), + textarea = component.find("textarea").first(); + textarea.simulate("blur", { target: { value: "foo\nbar\n!!*&*" } }); + let submit = component.find("#submit"); + submit.simulate("click"); + expect(callbackSpy).toHaveBeenCalledWith(["foo", "bar"], false); + }); + + it("Correctly submits admin", () => { + let callbackSpy = mockAsync(), + component = mount(addUserJsx(callbackSpy)), + input = component.find("input").first(); + input.simulate("change", { target: { checked: true } }); + let submit = component.find("#submit"); + submit.simulate("click"); + expect(callbackSpy).toHaveBeenCalledWith([], true); + }); +}); diff --git a/jsx/src/components/CreateGroup/CreateGroup.test.js b/jsx/src/components/CreateGroup/CreateGroup.test.js new file mode 100644 --- /dev/null +++ b/jsx/src/components/CreateGroup/CreateGroup.test.js @@ -0,0 +1,66 @@ +import React from "react"; +import Enzyme, { mount } from "enzyme"; +import CreateGroup from "./CreateGroup"; +import Adapter from "@wojtekmaj/enzyme-adapter-react-17"; +import { Provider, useDispatch, useSelector } from "react-redux"; +import { createStore } from "redux"; +import { HashRouter } from "react-router-dom"; +import regeneratorRuntime from "regenerator-runtime"; // eslint-disable-line + +Enzyme.configure({ adapter: new Adapter() }); + +jest.mock("react-redux", () => ({ + ...jest.requireActual("react-redux"), + useDispatch: jest.fn(), + useSelector: jest.fn(), +})); + +describe("CreateGroup Component: ", () => { + var mockAsync = (result) => + jest.fn().mockImplementation(() => Promise.resolve(result)); + + var createGroupJsx = (callbackSpy) => ( + <Provider store={createStore(() => {}, {})}> + <HashRouter> + <CreateGroup + createGroup={callbackSpy} + updateGroups={callbackSpy} + history={{ push: () => {} }} + /> + </HashRouter> + </Provider> + ); + + var mockAppState = () => ({ + limit: 3, + }); + + beforeEach(() => { + useDispatch.mockImplementation(() => { + return () => () => {}; + }); + useSelector.mockImplementation((callback) => { + return callback(mockAppState()); + }); + }); + + afterEach(() => { + useDispatch.mockClear(); + }); + + it("Renders", () => { + let component = mount(createGroupJsx()); + expect(component.find(".container").length).toBe(1); + }); + + it("Calls createGroup on submit", () => { + let callbackSpy = mockAsync({ status: 200 }), + component = mount(createGroupJsx(callbackSpy)), + input = component.find("input").first(), + submit = component.find("#submit").first(); + input.simulate("change", { target: { value: "" } }); + submit.simulate("click"); + expect(callbackSpy).toHaveBeenNthCalledWith(1, ""); + expect(component.find(".alert.alert-danger").length).toBe(0); + }); +}); diff --git a/jsx/src/components/EditUser/EditUser.test.js b/jsx/src/components/EditUser/EditUser.test.js new file mode 100644 --- /dev/null +++ b/jsx/src/components/EditUser/EditUser.test.js @@ -0,0 +1,80 @@ +import React from "react"; +import Enzyme, { mount } from "enzyme"; +import EditUser from "./EditUser"; +import Adapter from "@wojtekmaj/enzyme-adapter-react-17"; +import { Provider, useDispatch, useSelector } from "react-redux"; +import { createStore } from "redux"; +import { HashRouter } from "react-router-dom"; + +Enzyme.configure({ adapter: new Adapter() }); + +jest.mock("react-redux", () => ({ + ...jest.requireActual("react-redux"), + useDispatch: jest.fn(), + useSelector: jest.fn(), +})); + +describe("EditUser Component: ", () => { + var mockAsync = () => + jest + .fn() + .mockImplementation(() => Promise.resolve({ key: "value", status: 200 })); + var mockSync = () => jest.fn(); + + var editUserJsx = (callbackSpy, empty) => ( + <Provider store={createStore(() => {}, {})}> + <HashRouter> + <EditUser + location={ + empty ? {} : { state: { username: "foo", has_admin: false } } + } + deleteUser={callbackSpy} + editUser={callbackSpy} + updateUsers={callbackSpy} + history={{ push: () => {} }} + failRegexEvent={callbackSpy} + noChangeEvent={callbackSpy} + /> + </HashRouter> + </Provider> + ); + + var mockAppState = () => ({ + limit: 3, + }); + + beforeEach(() => { + useDispatch.mockImplementation(() => { + return () => {}; + }); + useSelector.mockImplementation((callback) => { + return callback(mockAppState()); + }); + }); + + afterEach(() => { + useDispatch.mockClear(); + }); + + it("Calls the delete user function when the button is pressed", () => { + let callbackSpy = mockAsync(), + component = mount(editUserJsx(callbackSpy)), + deleteUser = component.find("#delete-user"); + deleteUser.simulate("click"); + expect(callbackSpy).toHaveBeenCalled(); + }); + + it("Submits the edits when the button is pressed", () => { + let callbackSpy = mockSync(), + component = mount(editUserJsx(callbackSpy)), + submit = component.find("#submit"); + submit.simulate("click"); + expect(callbackSpy).toHaveBeenCalled(); + }); + + it("Doesn't render when no data is provided", () => { + let callbackSpy = mockSync(), + component = mount(editUserJsx(callbackSpy, true)); + expect(component.find(".container").length).toBe(0); + }); +}); diff --git a/jsx/src/components/GroupEdit/GroupEdit.test.jsx b/jsx/src/components/GroupEdit/GroupEdit.test.jsx new file mode 100644 --- /dev/null +++ b/jsx/src/components/GroupEdit/GroupEdit.test.jsx @@ -0,0 +1,100 @@ +import React from "react"; +import Enzyme, { mount } from "enzyme"; +import GroupEdit from "./GroupEdit"; +import Adapter from "@wojtekmaj/enzyme-adapter-react-17"; +import { Provider, useSelector } from "react-redux"; +import { createStore } from "redux"; +import { HashRouter } from "react-router-dom"; +import { act } from "react-dom/test-utils"; +import regeneratorRuntime from "regenerator-runtime"; // eslint-disable-line + +Enzyme.configure({ adapter: new Adapter() }); + +jest.mock("react-redux", () => ({ + ...jest.requireActual("react-redux"), + useSelector: jest.fn(), +})); + +describe("GroupEdit Component: ", () => { + var mockAsync = () => jest.fn().mockImplementation(() => Promise.resolve()); + + var okPacket = new Promise((resolve) => resolve(true)); + + var groupEditJsx = (callbackSpy) => ( + <Provider store={createStore(() => {}, {})}> + <HashRouter> + <GroupEdit + location={{ + state: { + group_data: { users: ["foo"], name: "group" }, + callback: () => {}, + }, + }} + addToGroup={callbackSpy} + removeFromGroup={callbackSpy} + deleteGroup={callbackSpy} + history={{ push: () => callbackSpy }} + updateGroups={callbackSpy} + validateUser={jest.fn().mockImplementation(() => okPacket)} + /> + </HashRouter> + </Provider> + ); + + var mockAppState = () => ({ + limit: 3, + }); + + beforeEach(() => { + useSelector.mockImplementation((callback) => { + return callback(mockAppState()); + }); + }); + + afterEach(() => { + useSelector.mockClear(); + }); + + it("Adds user from input to user selectables on button click", async () => { + let callbackSpy = mockAsync(), + component = mount(groupEditJsx(callbackSpy)), + input = component.find("#username-input"), + validateUser = component.find("#validate-user"), + submit = component.find("#submit"); + + input.simulate("change", { target: { value: "bar" } }); + validateUser.simulate("click"); + await act(() => okPacket); + submit.simulate("click"); + expect(callbackSpy).toHaveBeenNthCalledWith(1, ["bar"], "group"); + }); + + it("Removes a user recently added from input from the selectables list", () => { + let callbackSpy = mockAsync(), + component = mount(groupEditJsx(callbackSpy)), + unsubmittedUser = component.find(".item.selected").last(); + unsubmittedUser.simulate("click"); + expect(component.find(".item").length).toBe(1); + }); + + it("Grays out a user, already in the group, when unselected and calls deleteUser on submit", () => { + let callbackSpy = mockAsync(), + component = mount(groupEditJsx(callbackSpy)), + groupUser = component.find(".item.selected").first(); + groupUser.simulate("click"); + expect(component.find(".item.unselected").length).toBe(1); + expect(component.find(".item").length).toBe(1); + // test deleteUser call + let submit = component.find("#submit"); + submit.simulate("click"); + expect(callbackSpy).toHaveBeenNthCalledWith(1, ["foo"], "group"); + }); + + it("Calls deleteGroup on button click", () => { + let callbackSpy = mockAsync(), + component = mount(groupEditJsx(callbackSpy)), + deleteGroup = component.find("#delete-group").first(); + deleteGroup.simulate("click"); + expect(callbackSpy).toHaveBeenNthCalledWith(1, "group"); + }); +}); diff --git a/jsx/src/components/Groups/Groups.test.js b/jsx/src/components/Groups/Groups.test.js new file mode 100644 --- /dev/null +++ b/jsx/src/components/Groups/Groups.test.js @@ -0,0 +1,65 @@ +import React from "react"; +import Enzyme, { mount } from "enzyme"; +import Groups from "./Groups"; +import Adapter from "@wojtekmaj/enzyme-adapter-react-17"; +import { Provider, useDispatch, useSelector } from "react-redux"; +import { createStore } from "redux"; +import { HashRouter } from "react-router-dom"; + +Enzyme.configure({ adapter: new Adapter() }); + +jest.mock("react-redux", () => ({ + ...jest.requireActual("react-redux"), + useSelector: jest.fn(), + useDispatch: jest.fn(), +})); + +describe("Groups Component: ", () => { + var mockAsync = () => + jest.fn().mockImplementation(() => Promise.resolve({ key: "value" })); + + var groupsJsx = (callbackSpy) => ( + <Provider store={createStore(() => {}, {})}> + <HashRouter> + <Groups location={{ search: "0" }} updateGroups={callbackSpy} /> + </HashRouter> + </Provider> + ); + + var mockAppState = () => ({ + user_data: JSON.parse( + '[{"kind":"user","name":"foo","admin":true,"groups":[],"server":"/user/foo/","pending":null,"created":"2020-12-07T18:46:27.112695Z","last_activity":"2020-12-07T21:00:33.336354Z","servers":{"":{"name":"","last_activity":"2020-12-07T20:58:02.437408Z","started":"2020-12-07T20:58:01.508266Z","pending":null,"ready":true,"state":{"pid":28085},"url":"/user/foo/","user_options":{},"progress_url":"/hub/api/users/foo/server/progress"}}},{"kind":"user","name":"bar","admin":false,"groups":[],"server":null,"pending":null,"created":"2020-12-07T18:46:27.115528Z","last_activity":"2020-12-07T20:43:51.013613Z","servers":{}}]' + ), + groups_data: JSON.parse( + '[{"kind":"group","name":"testgroup","users":[]}, {"kind":"group","name":"testgroup2","users":["foo", "bar"]}]' + ), + }); + + beforeEach(() => { + useSelector.mockImplementation((callback) => { + return callback(mockAppState()); + }); + useDispatch.mockImplementation(() => { + return () => {}; + }); + }); + + afterEach(() => { + useSelector.mockClear(); + }); + + it("Renders groups_data prop into links", () => { + let callbackSpy = mockAsync(), + component = mount(groupsJsx(callbackSpy)), + links = component.find("li"); + expect(links.length).toBe(2); + }); + + it("Renders nothing if required data is not available", () => { + useSelector.mockImplementation((callback) => { + return callback({}); + }); + let component = mount(groupsJsx()); + expect(component.html()).toBe("<div></div>"); + }); +}); diff --git a/jsx/src/components/ServerDashboard/ServerDashboard.test.js b/jsx/src/components/ServerDashboard/ServerDashboard.test.js new file mode 100644 --- /dev/null +++ b/jsx/src/components/ServerDashboard/ServerDashboard.test.js @@ -0,0 +1,161 @@ +import React from "react"; +import Enzyme, { mount } from "enzyme"; +import ServerDashboard from "./ServerDashboard"; +import Adapter from "@wojtekmaj/enzyme-adapter-react-17"; +import { HashRouter, Switch } from "react-router-dom"; +import { Provider, useSelector } from "react-redux"; +import { createStore } from "redux"; + +Enzyme.configure({ adapter: new Adapter() }); + +jest.mock("react-redux", () => ({ + ...jest.requireActual("react-redux"), + useSelector: jest.fn(), +})); + +describe("ServerDashboard Component: ", () => { + var serverDashboardJsx = (callbackSpy) => ( + <Provider store={createStore(() => {}, {})}> + <HashRouter> + <Switch> + <ServerDashboard + updateUsers={callbackSpy} + shutdownHub={callbackSpy} + startServer={callbackSpy} + stopServer={callbackSpy} + startAll={callbackSpy} + stopAll={callbackSpy} + /> + </Switch> + </HashRouter> + </Provider> + ); + + var mockAsync = () => + jest + .fn() + .mockImplementation(() => + Promise.resolve({ json: () => Promise.resolve({ k: "v" }) }) + ); + + var mockAppState = () => ({ + user_data: JSON.parse( + '[{"kind":"user","name":"foo","admin":true,"groups":[],"server":"/user/foo/","pending":null,"created":"2020-12-07T18:46:27.112695Z","last_activity":"2020-12-07T21:00:33.336354Z","servers":{"":{"name":"","last_activity":"2020-12-07T20:58:02.437408Z","started":"2020-12-07T20:58:01.508266Z","pending":null,"ready":true,"state":{"pid":28085},"url":"/user/foo/","user_options":{},"progress_url":"/hub/api/users/foo/server/progress"}}},{"kind":"user","name":"bar","admin":false,"groups":[],"server":null,"pending":null,"created":"2020-12-07T18:46:27.115528Z","last_activity":"2020-12-07T20:43:51.013613Z","servers":{}}]' + ), + }); + + beforeEach(() => { + useSelector.mockImplementation((callback) => { + return callback(mockAppState()); + }); + }); + + afterEach(() => { + useSelector.mockClear(); + }); + + it("Renders users from props.user_data into table", () => { + let component = mount(serverDashboardJsx(mockAsync())), + userRows = component.find(".user-row"); + expect(userRows.length).toBe(2); + }); + + it("Renders correctly the status of a single-user server", () => { + let component = mount(serverDashboardJsx(mockAsync())), + userRows = component.find(".user-row"); + // Renders .stop-button when server is started + // Should be 1 since user foo is started + expect(userRows.at(0).find(".stop-button").length).toBe(1); + // Renders .start-button when server is stopped + // Should be 1 since user bar is stopped + expect(userRows.at(1).find(".start-button").length).toBe(1); + }); + + it("Invokes the startServer event on button click", () => { + let callbackSpy = mockAsync(), + component = mount(serverDashboardJsx(callbackSpy)), + startBtn = component.find(".start-button"); + startBtn.simulate("click"); + expect(callbackSpy).toHaveBeenCalled(); + }); + + it("Invokes the stopServer event on button click", () => { + let callbackSpy = mockAsync(), + component = mount(serverDashboardJsx(callbackSpy)), + stopBtn = component.find(".stop-button"); + stopBtn.simulate("click"); + expect(callbackSpy).toHaveBeenCalled(); + }); + + it("Invokes the shutdownHub event on button click", () => { + let callbackSpy = mockAsync(), + component = mount(serverDashboardJsx(callbackSpy)), + shutdownBtn = component.find("#shutdown-button").first(); + shutdownBtn.simulate("click"); + expect(callbackSpy).toHaveBeenCalled(); + }); + + it("Sorts according to username", () => { + let component = mount(serverDashboardJsx(mockAsync())).find( + "ServerDashboard" + ), + handler = component.find("SortHandler").first(); + handler.simulate("click"); + let first = component.find(".user-row").first(); + expect(first.html().includes("bar")).toBe(true); + handler.simulate("click"); + first = component.find(".user-row").first(); + expect(first.html().includes("foo")).toBe(true); + }); + + it("Sorts according to admin", () => { + let component = mount(serverDashboardJsx(mockAsync())).find( + "ServerDashboard" + ), + handler = component.find("SortHandler").at(1); + handler.simulate("click"); + let first = component.find(".user-row").first(); + expect(first.html().includes("admin")).toBe(true); + handler.simulate("click"); + first = component.find(".user-row").first(); + expect(first.html().includes("admin")).toBe(false); + }); + + it("Sorts according to last activity", () => { + let component = mount(serverDashboardJsx(mockAsync())).find( + "ServerDashboard" + ), + handler = component.find("SortHandler").at(2); + handler.simulate("click"); + let first = component.find(".user-row").first(); + // foo used most recently + expect(first.html().includes("foo")).toBe(true); + handler.simulate("click"); + first = component.find(".user-row").first(); + // invert sort - bar used least recently + expect(first.html().includes("bar")).toBe(true); + }); + + it("Sorts according to server status (running/not running)", () => { + let component = mount(serverDashboardJsx(mockAsync())).find( + "ServerDashboard" + ), + handler = component.find("SortHandler").at(3); + handler.simulate("click"); + let first = component.find(".user-row").first(); + // foo running + expect(first.html().includes("foo")).toBe(true); + handler.simulate("click"); + first = component.find(".user-row").first(); + // invert sort - bar not running + expect(first.html().includes("bar")).toBe(true); + }); + + it("Renders nothing if required data is not available", () => { + useSelector.mockImplementation((callback) => { + return callback({}); + }); + let component = mount(serverDashboardJsx(jest.fn())); + expect(component.html()).toBe("<div></div>"); + }); +});
Make admin page a full-on react app <!-- Thank you for contributing. These HTML commments will not render in the issue, but you can delete them once you've read them if you prefer! --> ### Proposed change <!-- Use this section to describe the feature you'd like to be added. --> JupyterHub pages started out as *extremely* basic: just a start and stop button. They are getting more <del>complex</del> feature-rich with things like named servers, profiles, options forms, etc. I think it's probably time that we move to a real UI framework, and I think react is a really good fit since we are mostly displaying tables of simple data types (list of users and running servers on admin, list of spawners on named-servers, etc.). The admin page is currently our most complex page, with pagination, users, sorting, etc. I think this is probably a great place to start with rewriting as a react app with data-flow of users to display. This means, among other things, that things like pagination, etc. need to move to javascript. The HTML template can be greatly simplified and the only relevant Python code is the query for the user list (likely needs pagination in the REST API user list). ### Alternative options <!-- Use this section to describe alternative options and why you've decided on the proposed feature above. --> - Use another js framework - Leave it alone ### Who would use this feature? <!-- Describe the audience for this feature. This information will affect who chooses to work on the feature with you. --> JupyterHub admins, especially those with lots of users ### How much effort will adding it take? <!-- Try to estimate how much work adding this feature will require. This information will affect who chooses to work on the feature with you. --> A moderate amount of effort to: 1. add react as a js dependency 2. rework the admin Jinja template to do much less 3. create react app from scratch to regenerate ~the same HTML we have now ### Who can do this work? <!-- What skills are needed? Who can be recruited to add this feature? This information will affect who chooses to work on the feature with you. --> Javascript/React/frontend developers, with some REST API experience.
I'm generally in favor of adding a modern frontend JS framework. The JupyterHub instance that I maintain at Ghent University has a fairly extensive Spawner options page, which is currently using jQuery for some dynamic features. Using React in other projects, it always feels like a step back when I need to _fight_ with jQuery to implement certain features. One important note on using React is that you generally want to use Babel for transpiling the React JS code to vanilla JS for a few reasons: - React uses JSX to define visual elements, which is not supported by browsers natively - React is generally used with ES6 or higher, which is not supported by IE11 for instance. Otherwise your code gets unnecessarily complex, and a lot of the examples available won't work [without adapting them](https://reactjs.org/docs/react-without-es6.html). Bringing in Babel means that we will need to bring in Webpack and the rest of the JS-ecosystem. I've already successfully integrated this with Flask by using [flask-webpack-loader](https://pypi.org/project/flask-webpack-loader/) which makes this relatively painless. My 5-second search doesn't show a one-on-one equivalent for Tornado, so we might need to implement that first. I'm not familiar enough with Vue to do any assessment if it is usable without Babel/Webpack/etc. I support the idea of making the admin page more of an "app" as a way to handle the new features. One thing that keeps appearing on my radar more and more are libraries like https://stimulusjs.org/ (in combination with https://github.com/turbolinks/turbolinks for full "SPA feeling"). I like the idea of Stimulus as "serve plain HTML and sprinkle some JS on top". There are a few libraries like this, but I can't (re)find them in my history right now. I think one is called ~~Adrenalin~~ [AlpineJS](https://github.com/alpinejs/alpine) ~~or some such~~. A reason to adopt a tool like this instead of react is that it would increase the number of people who can actively work on the admin panel app. A reason not to use it is that there are so many react developers that would have to learn a new thing to contribute here. I've not used Stimulus for anything beyond "tutorial level" work. I thin pypi.org uses it though. So this is more a point for consideration/get feedback on instead of "lets use it". I definitely agree that adopting react (or any framework, probably) means adopting webpack as well. I think react plus `webpack --watch` is a fairly tolerable development experience for a project with our small scope. Tornado doesn't need to know anything about it since it's just a static file. I have used in-browser babel for jsx in one project (I don't even remember which one) which I found much nicer as a Python developer who bristles at compilation steps, but presumably not the right approach for production. Switching to react components may complicate some of our template customization features, so we'll need to keep an eye on that. I would guess the number of people who can actively work on a react/jsx project would be higher than stimulus/turbolinks or just about anything else these days, but I'm not sure. This is part of why I strongly want us to *not* pick up Typescript here, which I have found to be a major source of resistance for new contributors (nteract or jupyterlab folks may disagree here). I went with "no framework" because for the first few years, all we did was show two buttons and one simple list and a js framework is vast overkill for that. That's not so true anymore! So the tradeoffs are different now, and admin is our most complex page with the most view/input options (sorting, pagination, grouping) so a good place to see benefits. We could also start small and do a lighter page, like the token generation page that does close to nothing. That would shift the task to being ~all setting up the react/webpack build pipeline (and tests!), plus a token (heh) page to test on. > Using React in other projects, it always feels like a step back when I need to fight with jQuery to implement certain features. You should already be free to use react in your custom spawn form if you want to, I think. You just need to load the react code on the page yourself. Is there any scope for splitting the frontend web-UI/app from the backend JupyterHub API into a new repo? Which I guess is another way of saying could someone write an independent web-client that has all the funtionality of the current web-interface but uses only JupyterHub API calls? @minrk Your approach means that we'll need to check in a compiled version of the JS-code. The big plus for this approach is that you can still checkout the JupyterHub-repo and start the JupyterHub-process without any changes. However, we need to be careful that the sourcecode and compiled version always match each other. Maybe we should add a testsuite in Travis that compiles the sourcecode and compares this to the compiled version to verify that it's the same? While doable, we'll need to keep a close eye on potential problems with mismatched versions of NodeJS on the developers machine vs. Travis creating inconsistent end results and thus a failing test. @manics I don't think such a big bang approach is doable nor necessary. The frontend of JupyterHub is quite limited as-is, and having potentially multiple frontends to choose from has no added value whatsoever. > Your approach means that we'll need to check in a compiled version of the JS-code. It does not. It means we need to include the compiled js in releases, but not the repo. We already do this in other Jupyter projects with a web UI (jupyterlab, notebook, etc.). There's already a javascript build step in jupyterhub (less->css and bundling js dependencies). Adopting js compilation would not have a significant impact on that. > Is there any scope for splitting the frontend web-UI/app from the backend JupyterHub API into a new repo? A case can be made for creating a proper npm package to organize the js, but I wouldn't make a new repo. The trend these days, especially in js-land, is toward "monorepos" as more maintainable, even if multiple packages in the repo are versioned independently. One could do experiments this way, though. I suspect the first thing one will run into is that the paging/sorting/etc. currently implemented in admin is *not* supported by the API! So that's something we'll need to add (and should anyway), regardless. > There's already a javascript build step in jupyterhub (less->css and bundling js dependencies). Adopting js compilation would not have a significant impact on that. Okay, I haven't had to dive into that part of the code yet, so I was unaware. After some digging around I now understand that `npm` is now already executed as part of building the `.whl` for JupyterHub, which is very neat! Thanks for explaining! How would one go about replacing the current JINJA templates with a REACT app. My understanding of how the Jupyterhub system works is fairly limited, what steps can I take to better understand the current process of serving HTML files to users? EDIT Did some more reading around, it seems you would need to get a general idea of how a tornado process works since JupyterHub is a tornado process(duh)... > How would one go about replacing the current JINJA templates with a REACT app. React just needs a reference to an element in the DOM to attach to. So it suffices to add an empty div and reference it in the Javascript that initializes the React-component. eg.: ```html <div id="xyz-container"></div> ``` and ```javascript class Quiz extends React.Component { render() { return (<h1>Hello world!</h1>); } } ReactDOM.render(<ComponentXYZ />, document.querySelector('#xyz-container')); ``` Tornado doesn't need to know anything about React. It just needs to output an empty ```<div>``` Also a major decision needed here would be whether to go with server-side rendering with react or not. Wont the whole jinja templating be replaced with ajax calls? > Also a major decision needed here would be whether to go with server-side rendering with react or not. Definitely client side. > Won't the whole jinja templating be replaced with ajax calls? Not *entirely*, in that the basic frame will still come from a jinja template, but the main table of data will be moved to react, eliminating the iteration, macros, etc. from jinja. Yes, table data will instead come from REST (`GET /users`) which will need to support the query/sort/page parameters currently only implemented in the admin page handlers. > what steps can I take to better understand the current process of serving HTML files to users? The bulk of the HTML is created with a jinja template [in share/jupyterhub/templates/admin.html](https://github.com/jupyterhub/jupyterhub/blob/8a3790b01ff944c453ffcc0486149e2a58ffabea/share/jupyterhub/templates/admin.html). The user list is populated and passed to the template [in the AdminHandler](https://github.com/jupyterhub/jupyterhub/blob/8a3790b01ff944c453ffcc0486149e2a58ffabea/jupyterhub/handlers/pages.py#L469-L502). how about using Vue for the overall frontend? any thoughts with vue? Hello. This seems like an interesting task but may I clarify if this means we want to entirely replace jinja template with bundled/transpiled react app or we want to embed react components into the jinja template? Hey all, currently working on this issue and have most of the UI work / integration done. Do we want to initially wrap this up as a hub managed service until it gets merged upstream or would it be best to start a PR with it fully integrated as the `/admin` endpoint? Hey everyone, we've developed a react based JupyterHub admin front-end that should fit this issue. Currently it's packaged as a Hub service/extension and can be enabled through the config, but it'd also be easy to implement in the hub itself with a couple edits to the templates. Feel free to check it out and recommend edits / next steps: [https://github.com/MetroStar/jh-admin-dashboard](https://github.com/MetroStar/jh-admin-dashboard) I'd also be happy to open a PR to add these updates to the Hub if there's interest, please reach out and comment [here](https://github.com/MetroStar/jh-admin-dashboard/issues/4).
2021-04-05T21:01:47Z
[]
[]
jupyterhub/jupyterhub
3,438
jupyterhub__jupyterhub-3438
[ "3189" ]
f2eb40cd1a41304b1e0357e2e4e45b32b4371061
diff --git a/docs/source/conf.py b/docs/source/conf.py --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -19,7 +19,7 @@ 'autodoc_traits', 'sphinx_copybutton', 'sphinx-jsonschema', - 'recommonmark', + 'myst_parser', ] # The master toctree document. @@ -52,11 +52,6 @@ # Set the default role so we can use `foo` instead of ``foo`` default_role = 'literal' -# -- Source ------------------------------------------------------------- - -import recommonmark -from recommonmark.transform import AutoStructify - # -- Config ------------------------------------------------------------- from jupyterhub.app import JupyterHub from docutils import nodes @@ -111,9 +106,7 @@ def run(self): def setup(app): - app.add_config_value('recommonmark_config', {'enable_eval_rst': True}, True) app.add_css_file('custom.css') - app.add_transform(AutoStructify) app.add_directive('jupyterhub-generate-config', ConfigDirective) app.add_directive('jupyterhub-help-all', HelpAllDirective) @@ -219,7 +212,7 @@ def setup(app): # build both metrics and rest-api, since RTD doesn't run make from subprocess import check_call as sh - sh(['make', 'metrics', 'rest-api'], cwd=docs) + sh(['make', 'metrics', 'rest-api', 'scopes'], cwd=docs) # -- Spell checking ------------------------------------------------------- diff --git a/docs/source/rbac/generate-scope-table.py b/docs/source/rbac/generate-scope-table.py new file mode 100644 --- /dev/null +++ b/docs/source/rbac/generate-scope-table.py @@ -0,0 +1,126 @@ +import os +from collections import defaultdict +from pathlib import Path + +from pytablewriter import MarkdownTableWriter +from ruamel.yaml import YAML + +from jupyterhub.scopes import scope_definitions + +HERE = os.path.abspath(os.path.dirname(__file__)) +PARENT = Path(HERE).parent.parent.absolute() + + +class ScopeTableGenerator: + def __init__(self): + self.scopes = scope_definitions + + @classmethod + def create_writer(cls, table_name, headers, values): + writer = MarkdownTableWriter() + writer.table_name = table_name + writer.headers = headers + writer.value_matrix = values + writer.margin = 1 + return writer + + def _get_scope_relationships(self): + """Returns a tuple of dictionary of all scope-subscope pairs and a list of just subscopes: + + ({scope: subscope}, [subscopes]) + + used for creating hierarchical scope table in _parse_scopes() + """ + pairs = [] + for scope, data in self.scopes.items(): + subscopes = data.get('subscopes') + if subscopes is not None: + for subscope in subscopes: + pairs.append((scope, subscope)) + else: + pairs.append((scope, None)) + subscopes = [pair[1] for pair in pairs] + pairs_dict = defaultdict(list) + for scope, subscope in pairs: + pairs_dict[scope].append(subscope) + return pairs_dict, subscopes + + def _get_top_scopes(self, subscopes): + """Returns a list of highest level scopes + (not a subscope of any other scopes)""" + top_scopes = [] + for scope in self.scopes.keys(): + if scope not in subscopes: + top_scopes.append(scope) + return top_scopes + + def _parse_scopes(self): + """Returns a list of table rows where row: + [indented scopename string, scope description string]""" + scope_pairs, subscopes = self._get_scope_relationships() + top_scopes = self._get_top_scopes(subscopes) + + table_rows = [] + md_indent = "&nbsp;&nbsp;&nbsp;" + + def _add_subscopes(table_rows, scopename, depth=0): + description = self.scopes[scopename]['description'] + doc_description = self.scopes[scopename].get('doc_description', '') + if doc_description: + description = doc_description + table_row = [f"{md_indent * depth}`{scopename}`", description] + table_rows.append(table_row) + for subscope in scope_pairs[scopename]: + if subscope: + _add_subscopes(table_rows, subscope, depth + 1) + + for scope in top_scopes: + _add_subscopes(table_rows, scope) + + return table_rows + + def write_table(self): + """Generates the scope table in markdown format and writes it into `scope-table.md`""" + filename = f"{HERE}/scope-table.md" + table_name = "" + headers = ["Scope", "Grants permission to:"] + values = self._parse_scopes() + writer = self.create_writer(table_name, headers, values) + + title = "Table 1. Available scopes and their hierarchy" + content = f"{title}\n{writer.dumps()}" + with open(filename, 'w') as f: + f.write(content) + print(f"Generated {filename}.") + print( + "Run 'make clean' before 'make html' to ensure the built scopes.html contains latest scope table changes." + ) + + def write_api(self): + """Generates the API description in markdown format and writes it into `rest-api.yml`""" + filename = f"{PARENT}/rest-api.yml" + yaml = YAML(typ='rt') + yaml.preserve_quotes = True + scope_dict = {} + with open(filename, 'r+') as f: + content = yaml.load(f.read()) + f.seek(0) + for scope in self.scopes: + description = self.scopes[scope]['description'] + doc_description = self.scopes[scope].get('doc_description', '') + if doc_description: + description = doc_description + scope_dict[scope] = description + content['securityDefinitions']['oauth2']['scopes'] = scope_dict + yaml.dump(content, f) + f.truncate() + + +def main(): + table_generator = ScopeTableGenerator() + table_generator.write_table() + table_generator.write_api() + + +if __name__ == "__main__": + main() diff --git a/examples/external-oauth/jupyterhub_config.py b/examples/external-oauth/jupyterhub_config.py --- a/examples/external-oauth/jupyterhub_config.py +++ b/examples/external-oauth/jupyterhub_config.py @@ -13,7 +13,7 @@ c.JupyterHub.services = [ { 'name': 'external-oauth', - 'oauth_client_id': "whoami-oauth-client-test", + 'oauth_client_id': "service-oauth-client-test", 'api_token': api_token, 'oauth_redirect_uri': 'http://127.0.0.1:5555/oauth_callback', } diff --git a/examples/postgres/hub/jupyterhub_config.py b/examples/postgres/hub/jupyterhub_config.py --- a/examples/postgres/hub/jupyterhub_config.py +++ b/examples/postgres/hub/jupyterhub_config.py @@ -1,10 +1,10 @@ # Configuration file for jupyterhub (postgres example). -c = get_config() +c = get_config() # noqa # Add some users. c.JupyterHub.admin_users = {'rhea'} -c.Authenticator.whitelist = {'ganymede', 'io', 'rhea'} +c.Authenticator.allowed_users = {'ganymede', 'io', 'rhea'} # These environment variables are automatically supplied by the linked postgres # container. diff --git a/examples/service-announcement/announcement.py b/examples/service-announcement/announcement.py --- a/examples/service-announcement/announcement.py +++ b/examples/service-announcement/announcement.py @@ -13,9 +13,6 @@ class AnnouncementRequestHandler(HubAuthenticated, web.RequestHandler): """Dynamically manage page announcements""" - hub_users = [] - allow_admin = True - def initialize(self, storage): """Create storage for announcement text""" self.storage = storage diff --git a/examples/service-announcement/jupyterhub_config.py b/examples/service-announcement/jupyterhub_config.py --- a/examples/service-announcement/jupyterhub_config.py +++ b/examples/service-announcement/jupyterhub_config.py @@ -2,11 +2,18 @@ # To run the announcement service managed by the hub, add this. +port = 9999 c.JupyterHub.services = [ { 'name': 'announcement', - 'url': 'http://127.0.0.1:8888', - 'command': [sys.executable, "-m", "announcement"], + 'url': f'http://127.0.0.1:{port}', + 'command': [ + sys.executable, + "-m", + "announcement", + '--port', + str(port), + ], } ] @@ -14,3 +21,19 @@ # for an example of how to do this. c.JupyterHub.template_paths = ["templates"] + +c.Authenticator.allowed_users = {"announcer", "otheruser"} + +# grant the 'announcer' permission to access the announcement service +c.JupyterHub.load_roles = [ + { + "name": "announcers", + "users": ["announcer"], + "scopes": ["access:services!service=announcement"], + } +] + +# dummy spawner and authenticator for testing, don't actually use these! +c.JupyterHub.authenticator_class = 'dummy' +c.JupyterHub.spawner_class = 'simple' +c.JupyterHub.ip = '127.0.0.1' # let's just run on localhost while dummy auth is enabled diff --git a/examples/service-fastapi/app/models.py b/examples/service-fastapi/app/models.py --- a/examples/service-fastapi/app/models.py +++ b/examples/service-fastapi/app/models.py @@ -1,5 +1,6 @@ from datetime import datetime from typing import Any +from typing import Dict from typing import List from typing import Optional @@ -22,11 +23,12 @@ class Server(BaseModel): class User(BaseModel): name: str admin: bool - groups: List[str] + groups: Optional[List[str]] server: Optional[str] pending: Optional[str] last_activity: datetime - servers: Optional[List[Server]] + servers: Optional[Dict[str, Server]] + scopes: List[str] # https://stackoverflow.com/questions/64501193/fastapi-how-to-use-httpexception-in-responses diff --git a/examples/service-fastapi/app/security.py b/examples/service-fastapi/app/security.py --- a/examples/service-fastapi/app/security.py +++ b/examples/service-fastapi/app/security.py @@ -1,3 +1,4 @@ +import json import os from fastapi import HTTPException @@ -27,6 +28,12 @@ ### our client_secret (JUPYTERHUB_API_TOKEN) and that code to get an ### access_token, which it returns to browser, which places in Authorization header. +if os.environ.get("JUPYTERHUB_OAUTH_SCOPES"): + # typically ["access:services", "access:services!service=$service_name"] + access_scopes = json.loads(os.environ["JUPYTERHUB_OAUTH_SCOPES"]) +else: + access_scopes = ["access:services"] + ### For consideration: optimize performance with a cache instead of ### always hitting the Hub api? async def get_current_user( @@ -58,4 +65,15 @@ async def get_current_user( }, ) user = User(**resp.json()) - return user + if any(scope in user.scopes for scope in access_scopes): + return user + else: + raise HTTPException( + status.HTTP_403_FORBIDDEN, + detail={ + "msg": f"User not authorized: {user.name}", + "request_url": str(resp.request.url), + "token": token, + "user": resp.json(), + }, + ) diff --git a/examples/service-fastapi/jupyterhub_config.py b/examples/service-fastapi/jupyterhub_config.py --- a/examples/service-fastapi/jupyterhub_config.py +++ b/examples/service-fastapi/jupyterhub_config.py @@ -24,8 +24,21 @@ "name": service_name, "url": "http://127.0.0.1:10202", "command": ["uvicorn", "app:app", "--port", "10202"], - "admin": True, "oauth_redirect_uri": oauth_redirect_uri, "environment": {"PUBLIC_HOST": public_host}, } ] + +c.JupyterHub.load_roles = [ + { + "name": "user", + # grant all users access to services + "scopes": ["self", "access:services"], + }, +] + + +# dummy for testing, create test-user +c.Authenticator.allowed_users = {"test-user"} +c.JupyterHub.authenticator_class = "dummy" +c.JupyterHub.spawner_class = "simple" diff --git a/examples/service-notebook/external/jupyterhub_config.py b/examples/service-notebook/external/jupyterhub_config.py --- a/examples/service-notebook/external/jupyterhub_config.py +++ b/examples/service-notebook/external/jupyterhub_config.py @@ -1,15 +1,35 @@ # our user list -c.Authenticator.whitelist = ['minrk', 'ellisonbg', 'willingc'] +c.Authenticator.allowed_users = ['minrk', 'ellisonbg', 'willingc'] -# ellisonbg and willingc have access to a shared server: +service_name = 'shared-notebook' +service_port = 9999 +group_name = 'shared' -c.JupyterHub.load_groups = {'shared': ['ellisonbg', 'willingc']} +# ellisonbg and willingc are in a group that will access the shared server: + +c.JupyterHub.load_groups = {group_name: ['ellisonbg', 'willingc']} # start the notebook server as a service c.JupyterHub.services = [ { - 'name': 'shared-notebook', - 'url': 'http://127.0.0.1:9999', - 'api_token': 'super-secret', + 'name': service_name, + 'url': 'http://127.0.0.1:{}'.format(service_port), + 'api_token': 'c3a29e5d386fd7c9aa1e8fe9d41c282ec8b', } ] + +# This "role assignment" is what grants members of the group +# access to the service +c.JupyterHub.load_roles = [ + { + "name": "shared-notebook", + "groups": [group_name], + "scopes": [f"access:services!service={service_name}"], + }, +] + + +# dummy spawner and authenticator for testing, don't actually use these! +c.JupyterHub.authenticator_class = 'dummy' +c.JupyterHub.spawner_class = 'simple' +c.JupyterHub.ip = '127.0.0.1' # let's just run on localhost while dummy auth is enabled diff --git a/examples/service-notebook/managed/jupyterhub_config.py b/examples/service-notebook/managed/jupyterhub_config.py --- a/examples/service-notebook/managed/jupyterhub_config.py +++ b/examples/service-notebook/managed/jupyterhub_config.py @@ -1,19 +1,35 @@ # our user list -c.Authenticator.whitelist = ['minrk', 'ellisonbg', 'willingc'] - -# ellisonbg and willingc have access to a shared server: - -c.JupyterHub.load_groups = {'shared': ['ellisonbg', 'willingc']} +c.Authenticator.allowed_users = ['minrk', 'ellisonbg', 'willingc'] service_name = 'shared-notebook' service_port = 9999 group_name = 'shared' +# ellisonbg and willingc have access to a shared server: + +c.JupyterHub.load_groups = {group_name: ['ellisonbg', 'willingc']} + # start the notebook server as a service c.JupyterHub.services = [ { 'name': service_name, 'url': 'http://127.0.0.1:{}'.format(service_port), - 'command': ['jupyterhub-singleuser', '--group=shared', '--debug'], + 'command': ['jupyterhub-singleuser', '--debug'], } ] + +# This "role assignment" is what grants members of the group +# access to the service +c.JupyterHub.load_roles = [ + { + "name": "shared-notebook", + "groups": [group_name], + "scopes": [f"access:services!service={service_name}"], + }, +] + + +# dummy spawner and authenticator for testing, don't actually use these! +c.JupyterHub.authenticator_class = 'dummy' +c.JupyterHub.spawner_class = 'simple' +c.JupyterHub.ip = '127.0.0.1' # let's just run on localhost while dummy auth is enabled diff --git a/examples/service-whoami-flask/jupyterhub_config.py b/examples/service-whoami-flask/jupyterhub_config.py --- a/examples/service-whoami-flask/jupyterhub_config.py +++ b/examples/service-whoami-flask/jupyterhub_config.py @@ -5,10 +5,12 @@ 'command': ['flask', 'run', '--port=10101'], 'environment': {'FLASK_APP': 'whoami-flask.py'}, }, - { - 'name': 'whoami-oauth', - 'url': 'http://127.0.0.1:10201', - 'command': ['flask', 'run', '--port=10201'], - 'environment': {'FLASK_APP': 'whoami-oauth.py'}, - }, ] + +# dummy auth and simple spawner for testing +# any username and password will work +c.JupyterHub.spawner_class = 'simple' +c.JupyterHub.authenticator_class = 'dummy' + +# listen only on localhost while testing with wide-open auth +c.JupyterHub.ip = '127.0.0.1' diff --git a/examples/service-whoami-flask/whoami-flask.py b/examples/service-whoami-flask/whoami-flask.py --- a/examples/service-whoami-flask/whoami-flask.py +++ b/examples/service-whoami-flask/whoami-flask.py @@ -4,42 +4,48 @@ """ import json import os +import secrets from functools import wraps -from urllib.parse import quote from flask import Flask +from flask import make_response from flask import redirect from flask import request from flask import Response +from flask import session -from jupyterhub.services.auth import HubAuth +from jupyterhub.services.auth import HubOAuth prefix = os.environ.get('JUPYTERHUB_SERVICE_PREFIX', '/') -auth = HubAuth(api_token=os.environ['JUPYTERHUB_API_TOKEN'], cache_max_age=60) +auth = HubOAuth(api_token=os.environ['JUPYTERHUB_API_TOKEN'], cache_max_age=60) app = Flask(__name__) +# encryption key for session cookies +app.secret_key = secrets.token_bytes(32) def authenticated(f): - """Decorator for authenticating with the Hub""" + """Decorator for authenticating with the Hub via OAuth""" @wraps(f) def decorated(*args, **kwargs): - cookie = request.cookies.get(auth.cookie_name) - token = request.headers.get(auth.auth_header_name) - if cookie: - user = auth.user_for_cookie(cookie) - elif token: + token = session.get("token") + + if token: user = auth.user_for_token(token) else: user = None + if user: return f(user, *args, **kwargs) else: # redirect to login url on failed auth - return redirect(auth.login_url + '?next=%s' % quote(request.path)) + state = auth.generate_state(next_url=request.path) + response = make_response(redirect(auth.login_url + '&state=%s' % state)) + response.set_cookie(auth.state_cookie_name, state) + return response return decorated @@ -50,3 +56,24 @@ def whoami(user): return Response( json.dumps(user, indent=1, sort_keys=True), mimetype='application/json' ) + + [email protected](prefix + 'oauth_callback') +def oauth_callback(): + code = request.args.get('code', None) + if code is None: + return 403 + + # validate state field + arg_state = request.args.get('state', None) + cookie_state = request.cookies.get(auth.state_cookie_name) + if arg_state is None or arg_state != cookie_state: + # state doesn't match + return 403 + + token = auth.token_for_code(code) + # store token in session cookie + session["token"] = token + next_url = auth.get_next_url(cookie_state) or prefix + response = make_response(redirect(next_url)) + return response diff --git a/examples/service-whoami-flask/whoami-oauth.py b/examples/service-whoami-flask/whoami-oauth.py deleted file mode 100644 --- a/examples/service-whoami-flask/whoami-oauth.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python3 -""" -whoami service authentication with the Hub -""" -import json -import os -from functools import wraps - -from flask import Flask -from flask import make_response -from flask import redirect -from flask import request -from flask import Response - -from jupyterhub.services.auth import HubOAuth - - -prefix = os.environ.get('JUPYTERHUB_SERVICE_PREFIX', '/') - -auth = HubOAuth(api_token=os.environ['JUPYTERHUB_API_TOKEN'], cache_max_age=60) - -app = Flask(__name__) - - -def authenticated(f): - """Decorator for authenticating with the Hub via OAuth""" - - @wraps(f) - def decorated(*args, **kwargs): - token = request.cookies.get(auth.cookie_name) - if token: - user = auth.user_for_token(token) - else: - user = None - if user: - return f(user, *args, **kwargs) - else: - # redirect to login url on failed auth - state = auth.generate_state(next_url=request.path) - response = make_response(redirect(auth.login_url + '&state=%s' % state)) - response.set_cookie(auth.state_cookie_name, state) - return response - - return decorated - - [email protected](prefix) -@authenticated -def whoami(user): - return Response( - json.dumps(user, indent=1, sort_keys=True), mimetype='application/json' - ) - - [email protected](prefix + 'oauth_callback') -def oauth_callback(): - code = request.args.get('code', None) - if code is None: - return 403 - - # validate state field - arg_state = request.args.get('state', None) - cookie_state = request.cookies.get(auth.state_cookie_name) - if arg_state is None or arg_state != cookie_state: - # state doesn't match - return 403 - - token = auth.token_for_code(code) - next_url = auth.get_next_url(cookie_state) or prefix - response = make_response(redirect(next_url)) - response.set_cookie(auth.cookie_name, token) - return response diff --git a/examples/service-whoami/jupyterhub_config.py b/examples/service-whoami/jupyterhub_config.py --- a/examples/service-whoami/jupyterhub_config.py +++ b/examples/service-whoami/jupyterhub_config.py @@ -2,7 +2,7 @@ c.JupyterHub.services = [ { - 'name': 'whoami', + 'name': 'whoami-api', 'url': 'http://127.0.0.1:10101', 'command': [sys.executable, './whoami.py'], }, @@ -10,5 +10,19 @@ 'name': 'whoami-oauth', 'url': 'http://127.0.0.1:10102', 'command': [sys.executable, './whoami-oauth.py'], + 'oauth_roles': ['user'], }, ] + +c.JupyterHub.load_roles = [ + { + "name": "user", + # grant all users access to all services + "scopes": ["access:services", "self"], + } +] + +# dummy spawner and authenticator for testing, don't actually use these! +c.JupyterHub.authenticator_class = 'dummy' +c.JupyterHub.spawner_class = 'simple' +c.JupyterHub.ip = '127.0.0.1' # let's just run on localhost while dummy auth is enabled diff --git a/examples/service-whoami/whoami-oauth.py b/examples/service-whoami/whoami-oauth.py --- a/examples/service-whoami/whoami-oauth.py +++ b/examples/service-whoami/whoami-oauth.py @@ -1,6 +1,6 @@ """An example service authenticating with the Hub. -This example service serves `/services/whoami/`, +This example service serves `/services/whoami-oauth/`, authenticated with the Hub, showing the user their own info. """ @@ -20,13 +20,6 @@ class WhoAmIHandler(HubOAuthenticated, RequestHandler): - # hub_users can be a set of users who are allowed to access the service - # `getuser()` here would mean only the user who started the service - # can access the service: - - # from getpass import getuser - # hub_users = {getuser()} - @authenticated def get(self): user_model = self.get_current_user() diff --git a/examples/service-whoami/whoami.py b/examples/service-whoami/whoami.py --- a/examples/service-whoami/whoami.py +++ b/examples/service-whoami/whoami.py @@ -1,6 +1,8 @@ """An example service authenticating with the Hub. -This serves `/services/whoami/`, authenticated with the Hub, showing the user their own info. +This serves `/services/whoami-api/`, authenticated with the Hub, showing the user their own info. + +HubAuthenticated only supports token-based access. """ import json import os @@ -16,13 +18,6 @@ class WhoAmIHandler(HubAuthenticated, RequestHandler): - # hub_users can be a set of users who are allowed to access the service - # `getuser()` here would mean only the user who started the service - # can access the service: - - # from getpass import getuser - # hub_users = {getuser()} - @authenticated def get(self): user_model = self.get_current_user() diff --git a/jupyterhub/_version.py b/jupyterhub/_version.py --- a/jupyterhub/_version.py +++ b/jupyterhub/_version.py @@ -3,8 +3,8 @@ # Distributed under the terms of the Modified BSD License. version_info = ( - 1, - 5, + 2, + 0, 0, "", # release (b1, rc1, or "" for final or dev) "dev", # dev or nothing for beta/rc/stable releases diff --git a/jupyterhub/alembic/versions/833da8570507_rbac.py b/jupyterhub/alembic/versions/833da8570507_rbac.py new file mode 100644 --- /dev/null +++ b/jupyterhub/alembic/versions/833da8570507_rbac.py @@ -0,0 +1,104 @@ +""" +rbac changes for jupyterhub 2.0 + +Revision ID: 833da8570507 +Revises: 4dc2d5a8c53c +Create Date: 2021-02-17 15:03:04.360368 + +""" +# revision identifiers, used by Alembic. +revision = '833da8570507' +down_revision = '4dc2d5a8c53c' +branch_labels = None +depends_on = None + +from alembic import op +import sqlalchemy as sa + +from jupyterhub import orm + + +naming_convention = orm.meta.naming_convention + + +def upgrade(): + # associate spawners and services with their oauth clients + # op.add_column( + # 'services', sa.Column('oauth_client_id', sa.Unicode(length=255), nullable=True) + # ) + for table_name in ('services', 'spawners'): + column_name = "oauth_client_id" + target_table = "oauth_clients" + target_column = "identifier" + with op.batch_alter_table( + table_name, + schema=None, + ) as batch_op: + batch_op.add_column( + sa.Column('oauth_client_id', sa.Unicode(length=255), nullable=True), + ) + batch_op.create_foreign_key( + naming_convention["fk"] + % dict( + table_name=table_name, + column_0_name=column_name, + referred_table_name=target_table, + ), + target_table, + [column_name], + [target_column], + ondelete='SET NULL', + ) + + # FIXME, maybe: currently drops all api tokens and forces recreation! + # this ensures a consistent database, but requires: + # 1. all servers to be stopped for upgrade (maybe unavoidable anyway) + # 2. any manually issued/stored tokens to be re-issued + + # tokens loaded via configuration will be recreated on launch and unaffected + op.drop_table('api_tokens') + op.drop_table('oauth_access_tokens') + return + # TODO: explore in-place migration. This seems hard! + # 1. add new columns in api tokens + # 2. fill default fields (client_id='jupyterhub') for all api tokens + # 3. copy oauth tokens into api tokens + # 4. give oauth tokens 'identify' scopes + + +def downgrade(): + for table_name in ('services', 'spawners'): + column_name = "oauth_client_id" + target_table = "oauth_clients" + target_column = "identifier" + + with op.batch_alter_table( + table_name, + schema=None, + naming_convention=orm.meta.naming_convention, + ) as batch_op: + batch_op.drop_constraint( + naming_convention["fk"] + % dict( + table_name=table_name, + column_0_name=column_name, + referred_table_name=target_table, + ), + type_='foreignkey', + ) + batch_op.drop_column(column_name) + + # delete OAuth tokens for non-jupyterhub clients + # drop new columns from api tokens + # op.drop_constraint(None, 'api_tokens', type_='foreignkey') + # op.drop_column('api_tokens', 'session_id') + # op.drop_column('api_tokens', 'client_id') + + # FIXME: only drop tokens whose client id is not 'jupyterhub' + # until then, drop all tokens + op.drop_table("api_tokens") + + op.drop_table('api_token_role_map') + op.drop_table('service_role_map') + op.drop_table('user_role_map') + op.drop_table('roles') diff --git a/jupyterhub/apihandlers/auth.py b/jupyterhub/apihandlers/auth.py --- a/jupyterhub/apihandlers/auth.py +++ b/jupyterhub/apihandlers/auth.py @@ -1,6 +1,7 @@ """Authorization handlers""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. +import itertools import json from datetime import datetime from urllib.parse import parse_qsl @@ -13,8 +14,8 @@ from tornado import web from .. import orm -from ..user import User -from ..utils import compare_token +from .. import roles +from .. import scopes from ..utils import token_authenticated from .base import APIHandler from .base import BaseHandler @@ -23,12 +24,22 @@ class TokenAPIHandler(APIHandler): @token_authenticated def get(self, token): + # FIXME: deprecate this API for oauth token resolution, in favor of using /api/user + # TODO: require specific scope for this deprecated API, applied to service tokens only? + self.log.warning( + "/authorizations/token/:token endpoint is deprecated in JupyterHub 2.0. Use /api/user" + ) orm_token = orm.APIToken.find(self.db, token) - if orm_token is None: - orm_token = orm.OAuthAccessToken.find(self.db, token) if orm_token is None: raise web.HTTPError(404) + owner = orm_token.user or orm_token.service + if owner: + # having a token means we should be able to read the owner's model + # (this is the only thing this handler is for) + self.expanded_scopes.update(scopes.identify_scopes(owner)) + self.parsed_scopes = scopes.parse_scopes(self.expanded_scopes) + # record activity whenever we see a token now = orm_token.last_activity = datetime.utcnow() if orm_token.user: @@ -45,53 +56,20 @@ def get(self, token): self.write(json.dumps(model)) async def post(self): - warn_msg = ( - "Using deprecated token creation endpoint %s." - " Use /hub/api/users/:user/tokens instead." - ) % self.request.uri - self.log.warning(warn_msg) - requester = user = self.current_user - if user is None: - # allow requesting a token with username and password - # for authenticators where that's possible - data = self.get_json_body() - try: - requester = user = await self.login_user(data) - except Exception as e: - self.log.error("Failure trying to authenticate with form data: %s" % e) - user = None - if user is None: - raise web.HTTPError(403) - else: - data = self.get_json_body() - # admin users can request tokens for other users - if data and data.get('username'): - user = self.find_user(data['username']) - if user is not requester and not requester.admin: - raise web.HTTPError( - 403, "Only admins can request tokens for other users." - ) - if requester.admin and user is None: - raise web.HTTPError(400, "No such user '%s'" % data['username']) - - note = (data or {}).get('note') - if not note: - note = "Requested via deprecated api" - if requester is not user: - kind = 'user' if isinstance(user, User) else 'service' - note += " by %s %s" % (kind, requester.name) - - api_token = user.new_api_token(note=note) - self.write( - json.dumps( - {'token': api_token, 'warning': warn_msg, 'user': self.user_model(user)} - ) + raise web.HTTPError( + 404, + "Deprecated endpoint /hub/api/authorizations/token is removed in JupyterHub 2.0." + " Use /hub/api/users/:user/tokens instead.", ) class CookieAPIHandler(APIHandler): @token_authenticated def get(self, cookie_name, cookie_value=None): + self.log.warning( + "/authorizations/cookie endpoint is deprecated in JupyterHub 2.0. Use /api/user with OAuth tokens." + ) + cookie_name = quote(cookie_name, safe='') if cookie_value is None: self.log.warning( @@ -198,12 +176,16 @@ def _complete_login(self, uri, headers, scopes, credentials): raise self.send_oauth_response(headers, body, status) - def needs_oauth_confirm(self, user, oauth_client): + def needs_oauth_confirm(self, user, oauth_client, roles): """Return whether the given oauth client needs to prompt for access for the given user Checks list for oauth clients that don't need confirmation - (i.e. the user's own server) + Sources: + + - the user's own servers + - Clients which already have authorization for the same roles + - Explicit oauth_no_confirm_list configuration (e.g. admin-operated services) .. versionadded: 1.1 """ @@ -219,6 +201,27 @@ def needs_oauth_confirm(self, user, oauth_client): in self.settings.get('oauth_no_confirm_list', set()) ): return False + + # Check existing authorization + existing_tokens = self.db.query(orm.APIToken).filter_by( + user_id=user.id, + client_id=oauth_client.identifier, + ) + authorized_roles = set() + for token in existing_tokens: + authorized_roles.update({role.name for role in token.roles}) + + if authorized_roles: + if set(roles).issubset(authorized_roles): + self.log.debug( + f"User {user.name} has already authorized {oauth_client.identifier} for roles {roles}" + ) + return False + else: + self.log.debug( + f"User {user.name} has authorized {oauth_client.identifier}" + f" for roles {authorized_roles}, confirming additonal roles {roles}" + ) # default: require confirmation return True @@ -243,28 +246,90 @@ async def get(self): uri, http_method, body, headers = self.extract_oauth_params() try: - scopes, credentials = self.oauth_provider.validate_authorization_request( + ( + role_names, + credentials, + ) = self.oauth_provider.validate_authorization_request( uri, http_method, body, headers ) credentials = self.add_credentials(credentials) client = self.oauth_provider.fetch_by_client_id(credentials['client_id']) - if not self.needs_oauth_confirm(self.current_user, client): + allowed = False + + # check for access to target resource + if client.spawner: + scope_filter = self.get_scope_filter("access:servers") + allowed = scope_filter(client.spawner, kind='server') + elif client.service: + scope_filter = self.get_scope_filter("access:services") + allowed = scope_filter(client.service, kind='service') + else: + # client is not associated with a service or spawner. + # This shouldn't happen, but it might if this is a stale or forged request + # from a service or spawner that's since been deleted + self.log.error( + f"OAuth client {client} has no service or spawner, cannot resolve scopes." + ) + raise web.HTTPError(500, "OAuth configuration error") + + if not allowed: + self.log.error( + f"User {self.current_user} not allowed to access {client.description}" + ) + raise web.HTTPError( + 403, f"You do not have permission to access {client.description}" + ) + if not self.needs_oauth_confirm(self.current_user, client, role_names): self.log.debug( "Skipping oauth confirmation for %s accessing %s", self.current_user, client.description, ) # this is the pre-1.0 behavior for all oauth - self._complete_login(uri, headers, scopes, credentials) + self._complete_login(uri, headers, role_names, credentials) return + # resolve roles to scopes for authorization page + raw_scopes = set() + if role_names: + role_objects = ( + self.db.query(orm.Role).filter(orm.Role.name.in_(role_names)).all() + ) + raw_scopes = set( + itertools.chain(*(role.scopes for role in role_objects)) + ) + if not raw_scopes: + scope_descriptions = [ + { + "scope": None, + "description": scopes.scope_definitions['(no_scope)'][ + 'description' + ], + "filter": "", + } + ] + elif 'all' in raw_scopes: + raw_scopes = ['all'] + scope_descriptions = [ + { + "scope": "all", + "description": scopes.scope_definitions['all']['description'], + "filter": "", + } + ] + else: + scope_descriptions = scopes.describe_raw_scopes( + raw_scopes, + username=self.current_user.name, + ) # Render oauth 'Authorize application...' page auth_state = await self.current_user.get_auth_state() self.write( await self.render_template( "oauth.html", auth_state=auth_state, - scopes=scopes, + role_names=role_names, + scope_descriptions=scope_descriptions, oauth_client=client, ) ) diff --git a/jupyterhub/apihandlers/base.py b/jupyterhub/apihandlers/base.py --- a/jupyterhub/apihandlers/base.py +++ b/jupyterhub/apihandlers/base.py @@ -2,7 +2,6 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import json -from datetime import datetime from http.client import responses from sqlalchemy.exc import SQLAlchemyError @@ -131,36 +130,26 @@ def write_error(self, status_code, **kwargs): json.dumps({'status': status_code, 'message': message or status_message}) ) - def server_model(self, spawner, include_state=False): - """Get the JSON model for a Spawner""" - return { + def server_model(self, spawner): + """Get the JSON model for a Spawner + Assume server permission already granted""" + model = { 'name': spawner.name, 'last_activity': isoformat(spawner.orm_spawner.last_activity), 'started': isoformat(spawner.orm_spawner.started), 'pending': spawner.pending, 'ready': spawner.ready, - 'state': spawner.get_state() if include_state else None, 'url': url_path_join(spawner.user.url, spawner.name, '/'), 'user_options': spawner.user_options, 'progress_url': spawner._progress_url, } + scope_filter = self.get_scope_filter('admin:server_state') + if scope_filter(spawner, kind='server'): + model['state'] = spawner.get_state() + return model def token_model(self, token): """Get the JSON model for an APIToken""" - expires_at = None - if isinstance(token, orm.APIToken): - kind = 'api_token' - extra = {'note': token.note} - expires_at = token.expires_at - elif isinstance(token, orm.OAuthAccessToken): - kind = 'oauth' - extra = {'oauth_client': token.client.description or token.client.client_id} - if token.expires_at: - expires_at = datetime.fromtimestamp(token.expires_at) - else: - raise TypeError( - "token must be an APIToken or OAuthAccessToken, not %s" % type(token) - ) if token.user: owner_key = 'user' @@ -173,59 +162,148 @@ def token_model(self, token): model = { owner_key: owner, 'id': token.api_id, - 'kind': kind, + 'kind': 'api_token', + 'roles': [r.name for r in token.roles], 'created': isoformat(token.created), 'last_activity': isoformat(token.last_activity), - 'expires_at': isoformat(expires_at), + 'expires_at': isoformat(token.expires_at), + 'note': token.note, + 'oauth_client': token.oauth_client.description + or token.oauth_client.identifier, } - model.update(extra) return model - def user_model(self, user, include_servers=False, include_state=False): + def _filter_model(self, model, access_map, entity, kind, keys=None): + """ + Filter the model based on the available scopes and the entity requested for. + If keys is a dictionary, update it with the allowed keys for the model. + """ + allowed_keys = set() + for scope in access_map: + scope_filter = self.get_scope_filter(scope) + if scope_filter(entity, kind=kind): + allowed_keys |= access_map[scope] + model = {key: model[key] for key in allowed_keys if key in model} + if isinstance(keys, set): + keys.update(allowed_keys) + return model + + def user_model(self, user): """Get the JSON model for a User object""" if isinstance(user, orm.User): user = self.users[user.id] - model = { 'kind': 'user', 'name': user.name, 'admin': user.admin, + 'roles': [r.name for r in user.roles], 'groups': [g.name for g in user.groups], 'server': user.url if user.running else None, 'pending': None, 'created': isoformat(user.created), 'last_activity': isoformat(user.last_activity), + 'auth_state': None, # placeholder, filled in later + } + access_map = { + 'read:users': { + 'kind', + 'name', + 'admin', + 'roles', + 'groups', + 'server', + 'pending', + 'created', + 'last_activity', + }, + 'read:users:name': {'kind', 'name', 'admin'}, + 'read:users:groups': {'kind', 'name', 'groups'}, + 'read:users:activity': {'kind', 'name', 'last_activity'}, + 'read:servers': {'kind', 'name', 'servers'}, + 'read:roles:users': {'kind', 'name', 'roles', 'admin'}, + 'admin:auth_state': {'kind', 'name', 'auth_state'}, } - if '' in user.spawners: - model['pending'] = user.spawners[''].pending - - if not include_servers: - model['servers'] = None - return model - - servers = model['servers'] = {} - for name, spawner in user.spawners.items(): - # include 'active' servers, not just ready - # (this includes pending events) - if spawner.active: - servers[name] = self.server_model(spawner, include_state=include_state) + self.log.debug( + "Asking for user model of %s with scopes [%s]", + user.name, + ", ".join(self.expanded_scopes), + ) + allowed_keys = set() + model = self._filter_model( + model, access_map, user, kind='user', keys=allowed_keys + ) + if model: + if '' in user.spawners and 'pending' in allowed_keys: + model['pending'] = user.spawners[''].pending + + servers = model['servers'] = {} + scope_filter = self.get_scope_filter('read:servers') + for name, spawner in user.spawners.items(): + # include 'active' servers, not just ready + # (this includes pending events) + if spawner.active and scope_filter(spawner, kind='server'): + servers[name] = self.server_model(spawner) + if not servers: + model.pop('servers') return model def group_model(self, group): """Get the JSON model for a Group object""" - return { + model = { 'kind': 'group', 'name': group.name, + 'roles': [r.name for r in group.roles], 'users': [u.name for u in group.users], } + access_map = { + 'read:groups': {'kind', 'name', 'users'}, + 'read:groups:name': {'kind', 'name'}, + 'read:roles:groups': {'kind', 'name', 'roles'}, + } + model = self._filter_model(model, access_map, group, 'group') + return model def service_model(self, service): """Get the JSON model for a Service object""" - return {'kind': 'service', 'name': service.name, 'admin': service.admin} + model = { + 'kind': 'service', + 'name': service.name, + 'roles': [r.name for r in service.roles], + 'admin': service.admin, + 'url': getattr(service, 'url', ''), + 'prefix': service.server.base_url if getattr(service, 'server', '') else '', + 'command': getattr(service, 'command', ''), + 'pid': service.proc.pid if getattr(service, 'proc', '') else 0, + 'info': getattr(service, 'info', ''), + 'display': getattr(service, 'display', ''), + } + access_map = { + 'read:services': { + 'kind', + 'name', + 'admin', + 'url', + 'prefix', + 'command', + 'pid', + 'info', + 'display', + }, + 'read:services:name': {'kind', 'name', 'admin'}, + 'read:roles:services': {'kind', 'name', 'roles', 'admin'}, + } + model = self._filter_model(model, access_map, service, 'service') + return model - _user_model_types = {'name': str, 'admin': bool, 'groups': list, 'auth_state': dict} + _user_model_types = { + 'name': str, + 'admin': bool, + 'groups': list, + 'roles': list, + 'auth_state': dict, + } - _group_model_types = {'name': str, 'users': list} + _group_model_types = {'name': str, 'users': list, 'roles': list} def _check_model(self, model, model_types, name): """Check a model provided by a REST API request diff --git a/jupyterhub/apihandlers/groups.py b/jupyterhub/apihandlers/groups.py --- a/jupyterhub/apihandlers/groups.py +++ b/jupyterhub/apihandlers/groups.py @@ -6,7 +6,7 @@ from tornado import web from .. import orm -from ..utils import admin_only +from ..scopes import needs_scope from .base import APIHandler @@ -22,29 +22,29 @@ def _usernames_to_users(self, usernames): users.append(user.orm_user) return users - def find_group(self, name): + def find_group(self, group_name): """Find and return a group by name. Raise 404 if not found. """ - group = orm.Group.find(self.db, name=name) - + group = orm.Group.find(self.db, name=group_name) if group is None: - raise web.HTTPError(404, "No such group: %s", name) + raise web.HTTPError(404, "No such group: %s", group_name) return group class GroupListAPIHandler(_GroupAPIHandler): - @admin_only + @needs_scope('read:groups', 'read:groups:name', 'read:roles:groups') def get(self): """List groups""" query = self.db.query(orm.Group) offset, limit = self.get_api_pagination() query = query.offset(offset).limit(limit) - data = [self.group_model(group) for group in query] + scope_filter = self.get_scope_filter('read:groups') + data = [self.group_model(g) for g in query if scope_filter(g, kind='group')] self.write(json.dumps(data)) - @admin_only + @needs_scope('admin:groups') async def post(self): """POST creates Multiple groups """ model = self.get_json_body() @@ -77,14 +77,13 @@ async def post(self): class GroupAPIHandler(_GroupAPIHandler): """View and modify groups by name""" - @admin_only - def get(self, name): - group = self.find_group(name) - group_model = self.group_model(group) - self.write(json.dumps(group_model)) + @needs_scope('read:groups', 'read:groups:name', 'read:roles:groups') + def get(self, group_name): + group = self.find_group(group_name) + self.write(json.dumps(self.group_model(group))) - @admin_only - async def post(self, name): + @needs_scope('admin:groups') + async def post(self, group_name): """POST creates a group by name""" model = self.get_json_body() if model is None: @@ -92,28 +91,28 @@ async def post(self, name): else: self._check_group_model(model) - existing = orm.Group.find(self.db, name=name) + existing = orm.Group.find(self.db, name=group_name) if existing is not None: - raise web.HTTPError(409, "Group %s already exists" % name) + raise web.HTTPError(409, "Group %s already exists" % group_name) usernames = model.get('users', []) # check that users exist users = self._usernames_to_users(usernames) # create the group - self.log.info("Creating new group %s with %i users", name, len(users)) + self.log.info("Creating new group %s with %i users", group_name, len(users)) self.log.debug("Users: %s", usernames) - group = orm.Group(name=name, users=users) + group = orm.Group(name=group_name, users=users) self.db.add(group) self.db.commit() self.write(json.dumps(self.group_model(group))) self.set_status(201) - @admin_only - def delete(self, name): + @needs_scope('admin:groups') + def delete(self, group_name): """Delete a group by name""" - group = self.find_group(name) - self.log.info("Deleting group %s", name) + group = self.find_group(group_name) + self.log.info("Deleting group %s", group_name) self.db.delete(group) self.db.commit() self.set_status(204) @@ -122,39 +121,41 @@ def delete(self, name): class GroupUsersAPIHandler(_GroupAPIHandler): """Modify a group's user list""" - @admin_only - def post(self, name): + @needs_scope('groups') + def post(self, group_name): """POST adds users to a group""" - group = self.find_group(name) + group = self.find_group(group_name) data = self.get_json_body() self._check_group_model(data) if 'users' not in data: raise web.HTTPError(400, "Must specify users to add") - self.log.info("Adding %i users to group %s", len(data['users']), name) + self.log.info("Adding %i users to group %s", len(data['users']), group_name) self.log.debug("Adding: %s", data['users']) for user in self._usernames_to_users(data['users']): if user not in group.users: group.users.append(user) else: - self.log.warning("User %s already in group %s", user.name, name) + self.log.warning("User %s already in group %s", user.name, group_name) self.db.commit() self.write(json.dumps(self.group_model(group))) - @admin_only - async def delete(self, name): + @needs_scope('groups') + async def delete(self, group_name): """DELETE removes users from a group""" - group = self.find_group(name) + group = self.find_group(group_name) data = self.get_json_body() self._check_group_model(data) if 'users' not in data: raise web.HTTPError(400, "Must specify users to delete") - self.log.info("Removing %i users from group %s", len(data['users']), name) + self.log.info("Removing %i users from group %s", len(data['users']), group_name) self.log.debug("Removing: %s", data['users']) for user in self._usernames_to_users(data['users']): if user in group.users: group.users.remove(user) else: - self.log.warning("User %s already not in group %s", user.name, name) + self.log.warning( + "User %s already not in group %s", user.name, group_name + ) self.db.commit() self.write(json.dumps(self.group_model(group))) diff --git a/jupyterhub/apihandlers/hub.py b/jupyterhub/apihandlers/hub.py --- a/jupyterhub/apihandlers/hub.py +++ b/jupyterhub/apihandlers/hub.py @@ -8,12 +8,12 @@ from tornado.ioloop import IOLoop from .._version import __version__ -from ..utils import admin_only +from ..scopes import needs_scope from .base import APIHandler class ShutdownAPIHandler(APIHandler): - @admin_only + @needs_scope('shutdown') def post(self): """POST /api/shutdown triggers a clean shutdown @@ -56,8 +56,7 @@ class RootAPIHandler(APIHandler): def get(self): """GET /api/ returns info about the Hub and its API. - It is not an authenticated endpoint. - + It is not an authenticated endpoint For now, it just returns the version of JupyterHub itself. """ data = {'version': __version__} @@ -65,13 +64,12 @@ def get(self): class InfoAPIHandler(APIHandler): - @admin_only + @needs_scope('read:hub') def get(self): """GET /api/info returns detailed info about the Hub and its API. - It is not an authenticated endpoint. - - For now, it just returns the version of JupyterHub itself. + Currently, it returns information on the python version, spawner and authenticator. + Since this information might be sensitive, it is an authenticated endpoint """ def _class_info(typ): diff --git a/jupyterhub/apihandlers/proxy.py b/jupyterhub/apihandlers/proxy.py --- a/jupyterhub/apihandlers/proxy.py +++ b/jupyterhub/apihandlers/proxy.py @@ -5,12 +5,12 @@ from tornado import web -from ..utils import admin_only +from ..scopes import needs_scope from .base import APIHandler class ProxyAPIHandler(APIHandler): - @admin_only + @needs_scope('proxy') async def get(self): """GET /api/proxy fetches the routing table @@ -29,7 +29,7 @@ async def get(self): self.write(json.dumps(routes)) - @admin_only + @needs_scope('proxy') async def post(self): """POST checks the proxy to ensure that it's up to date. @@ -38,7 +38,7 @@ async def post(self): """ await self.proxy.check_routes(self.users, self.services) - @admin_only + @needs_scope('proxy') async def patch(self): """PATCH updates the location of the proxy diff --git a/jupyterhub/apihandlers/services.py b/jupyterhub/apihandlers/services.py --- a/jupyterhub/apihandlers/services.py +++ b/jupyterhub/apihandlers/services.py @@ -6,60 +6,26 @@ # Distributed under the terms of the Modified BSD License. import json -from tornado import web - -from .. import orm -from ..utils import admin_only +from ..scopes import needs_scope from .base import APIHandler -def service_model(service): - """Produce the model for a service""" - return { - 'name': service.name, - 'admin': service.admin, - 'url': service.url, - 'prefix': service.server.base_url if service.server else '', - 'command': service.command, - 'pid': service.proc.pid if service.proc else 0, - 'info': service.info, - 'display': service.display, - } - - class ServiceListAPIHandler(APIHandler): - @admin_only + @needs_scope('read:services', 'read:services:name', 'read:roles:services') def get(self): - data = {name: service_model(service) for name, service in self.services.items()} + data = {} + for name, service in self.services.items(): + model = self.service_model(service) + if model: + data[name] = model self.write(json.dumps(data)) -def admin_or_self(method): - """Decorator for restricting access to either the target service or admin""" - - def decorated_method(self, name): - current = self.current_user - if current is None: - raise web.HTTPError(403) - if not current.admin: - # not admin, maybe self - if not isinstance(current, orm.Service): - raise web.HTTPError(403) - if current.name != name: - raise web.HTTPError(403) - # raise 404 if not found - if name not in self.services: - raise web.HTTPError(404) - return method(self, name) - - return decorated_method - - class ServiceAPIHandler(APIHandler): - @admin_or_self - def get(self, name): - service = self.services[name] - self.write(json.dumps(service_model(service))) + @needs_scope('read:services', 'read:services:name', 'read:roles:services') + def get(self, service_name): + service = self.services[service_name] + self.write(json.dumps(self.service_model(service))) default_handlers = [ diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -14,8 +14,10 @@ from tornado.iostream import StreamClosedError from .. import orm +from .. import scopes +from ..roles import assign_default_roles +from ..scopes import needs_scope from ..user import User -from ..utils import admin_only from ..utils import isoformat from ..utils import iterate_until from ..utils import maybe_future @@ -31,15 +33,33 @@ class SelfAPIHandler(APIHandler): async def get(self): user = self.current_user - if user is None: - # whoami can be accessed via oauth token - user = self.get_current_user_oauth_token() if user is None: raise web.HTTPError(403) + + _added_scopes = set() if isinstance(user, orm.Service): - model = self.service_model(user) + # ensure we have the minimal 'identify' scopes for the token owner + identify_scopes = scopes.identify_scopes(user) + get_model = self.service_model else: - model = self.user_model(user) + identify_scopes = scopes.identify_scopes(user.orm_user) + get_model = self.user_model + + # ensure we have permission to identify ourselves + # all tokens can do this on this endpoint + for scope in identify_scopes: + if scope not in self.expanded_scopes: + _added_scopes.add(scope) + self.expanded_scopes.add(scope) + if _added_scopes: + # re-parse with new scopes + self.parsed_scopes = scopes.parse_scopes(self.expanded_scopes) + + model = get_model(user) + + # add scopes to identify model, + # but not the scopes we added to ensure we could read our own model + model["scopes"] = sorted(self.expanded_scopes.difference(_added_scopes)) self.write(json.dumps(model)) @@ -52,7 +72,14 @@ def _user_has_ready_spawner(self, orm_user): user = self.users[orm_user] return any(spawner.ready for spawner in user.spawners.values()) - @admin_only + @needs_scope( + 'read:users', + 'read:users:name', + 'read:servers', + 'read:users:groups', + 'read:users:activity', + 'read:roles:users', + ) def get(self): state_filter = self.get_argument("state", None) offset, limit = self.get_api_pagination() @@ -98,15 +125,16 @@ def get(self): query = query.offset(offset).limit(limit) - data = [ - self.user_model(u, include_servers=True, include_state=True) - for u in query - if (post_filter is None or post_filter(u)) - ] + data = [] + for u in query: + if post_filter is None or post_filter(u): + user_model = self.user_model(u) + if user_model: + data.append(user_model) self.write(json.dumps(data)) - @admin_only + @needs_scope('admin:users') async def post(self): data = self.get_json_body() if not data or not isinstance(data, dict) or not data.get('usernames'): @@ -146,7 +174,8 @@ async def post(self): user = self.user_from_username(name) if admin: user.admin = True - self.db.commit() + assign_default_roles(self.db, entity=user) + self.db.commit() try: await maybe_future(self.authenticator.add_user(user)) except Exception as e: @@ -162,82 +191,71 @@ async def post(self): self.set_status(201) -def admin_or_self(method): - """Decorator for restricting access to either the target user or admin""" - - def m(self, name, *args, **kwargs): - current = self.current_user - if current is None: - raise web.HTTPError(403) - if not (current.name == name or current.admin): - raise web.HTTPError(403) - - # raise 404 if not found - if not self.find_user(name): - raise web.HTTPError(404) - return method(self, name, *args, **kwargs) - - return m - - class UserAPIHandler(APIHandler): - @admin_or_self - async def get(self, name): - user = self.find_user(name) - model = self.user_model( - user, include_servers=True, include_state=self.current_user.admin - ) + @needs_scope( + 'read:users', + 'read:users:name', + 'read:servers', + 'read:users:groups', + 'read:users:activity', + 'read:roles:users', + ) + async def get(self, user_name): + user = self.find_user(user_name) + model = self.user_model(user) # auth state will only be shown if the requester is an admin # this means users can't see their own auth state unless they # are admins, Hub admins often are also marked as admins so they # will see their auth state but normal users won't - requester = self.current_user - if requester.admin: + if 'auth_state' in model: model['auth_state'] = await user.get_auth_state() self.write(json.dumps(model)) - @admin_only - async def post(self, name): + @needs_scope('admin:users') + async def post(self, user_name): data = self.get_json_body() - user = self.find_user(name) + user = self.find_user(user_name) if user is not None: - raise web.HTTPError(409, "User %s already exists" % name) + raise web.HTTPError(409, "User %s already exists" % user_name) - user = self.user_from_username(name) + user = self.user_from_username(user_name) if data: self._check_user_model(data) if 'admin' in data: user.admin = data['admin'] - self.db.commit() + assign_default_roles(self.db, entity=user) + self.db.commit() try: await maybe_future(self.authenticator.add_user(user)) except Exception: - self.log.error("Failed to create user: %s" % name, exc_info=True) + self.log.error("Failed to create user: %s" % user_name, exc_info=True) # remove from registry self.users.delete(user) - raise web.HTTPError(400, "Failed to create user: %s" % name) + raise web.HTTPError(400, "Failed to create user: %s" % user_name) self.write(json.dumps(self.user_model(user))) self.set_status(201) - @admin_only - async def delete(self, name): - user = self.find_user(name) + @needs_scope('admin:users') + async def delete(self, user_name): + user = self.find_user(user_name) if user is None: raise web.HTTPError(404) if user.name == self.current_user.name: raise web.HTTPError(400, "Cannot delete yourself!") if user.spawner._stop_pending: raise web.HTTPError( - 400, "%s's server is in the process of stopping, please wait." % name + 400, + "%s's server is in the process of stopping, please wait." % user_name, ) if user.running: await self.stop_single_user(user) if user.spawner._stop_pending: raise web.HTTPError( 400, - "%s's server is in the process of stopping, please wait." % name, + "%s's server is in the process of stopping, please wait." + % user_name, ) await maybe_future(self.authenticator.delete_user(user)) @@ -249,14 +267,14 @@ async def delete(self, name): self.set_status(204) - @admin_only - async def patch(self, name): - user = self.find_user(name) + @needs_scope('admin:users') + async def patch(self, user_name): + user = self.find_user(user_name) if user is None: raise web.HTTPError(404) data = self.get_json_body() self._check_user_model(data) - if 'name' in data and data['name'] != name: + if 'name' in data and data['name'] != user_name: # check if the new name is already taken inside db if self.find_user(data['name']): raise web.HTTPError( @@ -268,6 +286,8 @@ async def patch(self, name): await user.save_auth_state(value) else: setattr(user, key, value) + if key == 'admin': + assign_default_roles(self.db, entity=user) self.db.commit() user_ = self.user_model(user) user_['auth_state'] = await user.get_auth_state() @@ -277,15 +297,14 @@ async def patch(self, name): class UserTokenListAPIHandler(APIHandler): """API endpoint for listing/creating tokens""" - @admin_or_self - def get(self, name): + @needs_scope('read:tokens') + def get(self, user_name): """Get tokens for a given user""" - user = self.find_user(name) + user = self.find_user(user_name) if not user: - raise web.HTTPError(404, "No such user: %s" % name) + raise web.HTTPError(404, "No such user: %s" % user_name) now = datetime.utcnow() - api_tokens = [] def sort_key(token): @@ -299,19 +318,9 @@ def sort_key(token): continue api_tokens.append(self.token_model(token)) - oauth_tokens = [] - # OAuth tokens use integer timestamps - now_timestamp = now.timestamp() - for token in sorted(user.oauth_tokens, key=sort_key): - if token.expires_at and token.expires_at < now_timestamp: - # exclude expired tokens - self.db.delete(token) - self.db.commit() - continue - oauth_tokens.append(self.token_model(token)) - self.write(json.dumps({'api_tokens': api_tokens, 'oauth_tokens': oauth_tokens})) + self.write(json.dumps({'api_tokens': api_tokens})) - async def post(self, name): + async def post(self, user_name): body = self.get_json_body() or {} if not isinstance(body, dict): raise web.HTTPError(400, "Body must be a JSON dict or empty") @@ -339,13 +348,16 @@ async def post(self, name): if requester is None: # couldn't identify requester raise web.HTTPError(403) - user = self.find_user(name) - if requester is not user and not requester.admin: - raise web.HTTPError(403, "Only admins can request tokens for other users") - if not user: - raise web.HTTPError(404, "No such user: %s" % name) - if requester is not user: - kind = 'user' if isinstance(requester, User) else 'service' + self._jupyterhub_user = requester + self._resolve_roles_and_scopes() + user = self.find_user(user_name) + kind = 'user' if isinstance(requester, User) else 'service' + scope_filter = self.get_scope_filter('tokens') + if user is None or not scope_filter(user, kind): + raise web.HTTPError( + 403, + f"{kind.title()} {user_name} not found or no permissions to generate tokens", + ) note = body.get('note') if not note: @@ -353,9 +365,19 @@ async def post(self, name): if requester is not user: note += " by %s %s" % (kind, requester.name) - api_token = user.new_api_token( - note=note, expires_in=body.get('expires_in', None) - ) + token_roles = body.get('roles') + try: + api_token = user.new_api_token( + note=note, expires_in=body.get('expires_in', None), roles=token_roles + ) + except NameError: + raise web.HTTPError(404, "Requested roles %r not found" % token_roles) + except ValueError: + raise web.HTTPError( + 403, + "Requested roles %r cannot have higher permissions than the token owner" + % token_roles, + ) if requester is not user: self.log.info( "%s %s requested API token for %s", @@ -382,44 +404,40 @@ def find_token_by_id(self, user, token_id): (e.g. wrong owner, invalid key format, etc.) """ not_found = "No such token %s for user %s" % (token_id, user.name) - prefix, id = token_id[0], token_id[1:] - if prefix == 'a': - Token = orm.APIToken - elif prefix == 'o': - Token = orm.OAuthAccessToken - else: + prefix, id_ = token_id[:1], token_id[1:] + if prefix != 'a': raise web.HTTPError(404, not_found) try: - id = int(id) + id_ = int(id_) except ValueError: raise web.HTTPError(404, not_found) - orm_token = self.db.query(Token).filter(Token.id == id).first() + orm_token = self.db.query(orm.APIToken).filter_by(id=id_).first() if orm_token is None or orm_token.user is not user.orm_user: raise web.HTTPError(404, "Token not found %s", orm_token) return orm_token - @admin_or_self - def get(self, name, token_id): + @needs_scope('read:tokens') + def get(self, user_name, token_id): """""" - user = self.find_user(name) + user = self.find_user(user_name) if not user: - raise web.HTTPError(404, "No such user: %s" % name) + raise web.HTTPError(404, "No such user: %s" % user_name) token = self.find_token_by_id(user, token_id) self.write(json.dumps(self.token_model(token))) - @admin_or_self - def delete(self, name, token_id): + @needs_scope('tokens') + def delete(self, user_name, token_id): """Delete a token""" - user = self.find_user(name) + user = self.find_user(user_name) if not user: - raise web.HTTPError(404, "No such user: %s" % name) + raise web.HTTPError(404, "No such user: %s" % user_name) token = self.find_token_by_id(user, token_id) # deleting an oauth token deletes *all* oauth tokens for that client - if isinstance(token, orm.OAuthAccessToken): - client_id = token.client_id + client_id = token.client_id + if token.client_id != "jupyterhub": tokens = [ - token for token in user.oauth_tokens if token.client_id == client_id + token for token in user.api_tokens if token.client_id == client_id ] else: tokens = [token] @@ -433,9 +451,9 @@ def delete(self, name, token_id): class UserServerAPIHandler(APIHandler): """Start and stop single-user servers""" - @admin_or_self - async def post(self, name, server_name=''): - user = self.find_user(name) + @needs_scope('servers') + async def post(self, user_name, server_name=''): + user = self.find_user(user_name) if server_name: if not self.allow_named_servers: raise web.HTTPError(400, "Named servers are not enabled.") @@ -449,7 +467,7 @@ async def post(self, name, server_name=''): 400, "User {} already has the maximum of {} named servers." " One must be deleted before a new server can be created".format( - name, self.named_server_limit_per_user + user_name, self.named_server_limit_per_user ), ) spawner = user.spawners[server_name] @@ -478,9 +496,9 @@ async def post(self, name, server_name=''): self.set_header('Content-Type', 'text/plain') self.set_status(status) - @admin_or_self - async def delete(self, name, server_name=''): - user = self.find_user(name) + @needs_scope('servers') + async def delete(self, user_name, server_name=''): + user = self.find_user(user_name) options = self.get_json_body() remove = (options or {}).get('remove', False) @@ -505,7 +523,7 @@ async def _remove_spawner(f=None): raise web.HTTPError(400, "Named servers are not enabled.") if server_name not in user.orm_spawners: raise web.HTTPError( - 404, "%s has no server named '%s'" % (name, server_name) + 404, "%s has no server named '%s'" % (user_name, server_name) ) elif remove: raise web.HTTPError(400, "Cannot delete the default server") @@ -551,19 +569,19 @@ class UserAdminAccessAPIHandler(APIHandler): This handler sets the necessary cookie for an admin to login to a single-user server. """ - @admin_only - def post(self, name): + @needs_scope('servers') + def post(self, user_name): self.log.warning( "Deprecated in JupyterHub 0.8." " Admin access API is not needed now that we use OAuth." ) current = self.current_user self.log.warning( - "Admin user %s has requested access to %s's server", current.name, name + "Admin user %s has requested access to %s's server", current.name, user_name ) if not self.settings.get('admin_access', False): raise web.HTTPError(403, "admin access to user servers disabled") - user = self.find_user(name) + user = self.find_user(user_name) if user is None: raise web.HTTPError(404) @@ -607,12 +625,12 @@ async def keepalive(self): await asyncio.wait([self._finish_future], timeout=self.keepalive_interval) - @admin_or_self - async def get(self, username, server_name=''): + @needs_scope('read:servers') + async def get(self, user_name, server_name=''): self.set_header('Cache-Control', 'no-cache') if server_name is None: server_name = '' - user = self.find_user(username) + user = self.find_user(user_name) if user is None: # no such user raise web.HTTPError(404) @@ -750,12 +768,12 @@ def _validate_servers(self, user, servers): ) return servers - @admin_or_self - def post(self, username): - user = self.find_user(username) + @needs_scope('users:activity') + def post(self, user_name): + user = self.find_user(user_name) if user is None: # no such user - raise web.HTTPError(404, "No such user: %r", username) + raise web.HTTPError(404, "No such user: %r", user_name) body = self.get_json_body() if not isinstance(body, dict): diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -21,6 +21,7 @@ from functools import partial from getpass import getuser from glob import glob +from itertools import chain from operator import itemgetter from textwrap import dedent from urllib.parse import unquote @@ -82,6 +83,7 @@ from . import crypto from . import dbutil, orm +from . import roles from .user import UserDict from .oauth.provider import make_provider from ._data import DATA_FILES_PATH @@ -110,7 +112,6 @@ # For faking stats from .emptyclass import EmptyClass - common_aliases = { 'log-level': 'Application.log_level', 'f': 'JupyterHub.config_file', @@ -118,7 +119,6 @@ 'db': 'JupyterHub.db_url', } - aliases = { 'base-url': 'JupyterHub.base_url', 'y': 'JupyterHub.answer_yes', @@ -214,11 +214,12 @@ def start(self): hub.load_config_file(hub.config_file) hub.init_db() - def init_users(): + def init_roles_and_users(): loop = asyncio.new_event_loop() + loop.run_until_complete(hub.init_role_creation()) loop.run_until_complete(hub.init_users()) - ThreadPoolExecutor(1).submit(init_users).result() + ThreadPoolExecutor(1).submit(init_roles_and_users).result() user = orm.User.find(hub.db, self.name) if user is None: print("No such user: %s" % self.name, file=sys.stderr) @@ -321,6 +322,31 @@ def _load_classes(self): """, ).tag(config=True) + load_roles = List( + Dict(), + help="""List of predefined role dictionaries to load at startup. + + For instance:: + + load_roles = [ + { + 'name': 'teacher', + 'description': 'Access to users' information and group membership', + 'scopes': ['users', 'groups'], + 'users': ['cyclops', 'gandalf'], + 'services': [], + 'groups': [] + } + ] + + All keys apart from 'name' are optional. + See all the available scopes in the JupyterHub REST API documentation. + + Default roles are defined in roles.py. + + """, + ).tag(config=True) + config_file = Unicode('jupyterhub_config.py', help="The config file to load").tag( config=True ) @@ -369,7 +395,7 @@ def _validate_config_file(self, proposal): even if your Hub authentication is still valid. If your Hub authentication is valid, logging in may be a transparent redirect as you refresh the page. - + This does not affect JupyterHub API tokens in general, which do not expire by default. Only tokens issued during the oauth flow @@ -862,7 +888,7 @@ def _hub_prefix_default(self): "/", help=""" The routing prefix for the Hub itself. - + Override to send only a subset of traffic to the Hub. Default is to use the Hub as the default route for all requests. @@ -874,7 +900,7 @@ def _hub_prefix_default(self): may want to handle these events themselves, in which case they can register their own default target with the proxy and set e.g. `hub_routespec = /hub/` to serve only the hub's own pages, or even `/hub/api/` for api-only operation. - + Note: hub_routespec must include the base_url, if any. .. versionadded:: 1.4 @@ -1419,14 +1445,16 @@ def init_logging(self): max(self.log_level, logging.INFO) ) - # hook up tornado 3's loggers to our app handlers for log in (app_log, access_log, gen_log): # ensure all log statements identify the application they come from log.name = self.log.name - logger = logging.getLogger('tornado') - logger.propagate = True - logger.parent = self.log - logger.setLevel(self.log.level) + + # hook up tornado's and oauthlib's loggers to our own + for name in ("tornado", "oauthlib"): + logger = logging.getLogger(name) + logger.propagate = True + logger.parent = self.log + logger.setLevel(self.log.level) @staticmethod def add_url_prefix(prefix, handlers): @@ -1457,7 +1485,7 @@ def add_url_prefix(prefix, handlers): Can be a Unicode string (e.g. '/hub/home') or a callable based on the handler object: :: - + def default_url_fn(handler): user = handler.current_user if user and user.admin: @@ -1734,6 +1762,26 @@ def init_db(self): except orm.DatabaseSchemaMismatch as e: self.exit(e) + # ensure the default oauth client exists + if ( + not self.db.query(orm.OAuthClient) + .filter_by(identifier="jupyterhub") + .one_or_none() + ): + # create the oauth client for jupyterhub itself + # this allows us to distinguish between orphaned tokens + # (failed cascade deletion) and tokens issued by the hub + # it has no client_secret, which means it cannot be used + # to make requests + client = orm.OAuthClient( + identifier="jupyterhub", + secret="", + redirect_uri="", + description="JupyterHub", + ) + self.db.add(client) + self.db.commit() + def init_hub(self): """Load the Hub URL config""" hub_args = dict( @@ -1830,7 +1878,6 @@ async def init_users(self): db.add(user) else: user.admin = True - # the admin_users config variable will never be used after this point. # only the database values will be referenced. @@ -1904,31 +1951,189 @@ async def init_users(self): TOTAL_USERS.set(total_users) + async def _get_or_create_user(self, username): + """Create user if username is found in config but user does not exist""" + if not (await maybe_future(self.authenticator.check_allowed(username, None))): + raise ValueError( + "Username %r is not in Authenticator.allowed_users" % username + ) + user = orm.User.find(self.db, name=username) + if user is None: + if not self.authenticator.validate_username(username): + raise ValueError("Username %r is not valid" % username) + self.log.info(f"Creating user {username}") + user = orm.User(name=username) + self.db.add(user) + self.db.commit() + return user + async def init_groups(self): """Load predefined groups into the database""" db = self.db for name, usernames in self.load_groups.items(): group = orm.Group.find(db, name) if group is None: + self.log.info(f"Creating group {name}") group = orm.Group(name=name) db.add(group) for username in usernames: username = self.authenticator.normalize_username(username) - if not ( - await maybe_future(self.authenticator.check_allowed(username, None)) - ): - raise ValueError( - "Username %r is not in Authenticator.allowed_users" % username - ) - user = orm.User.find(db, name=username) - if user is None: - if not self.authenticator.validate_username(username): - raise ValueError("Group username %r is not valid" % username) - user = orm.User(name=username) - db.add(user) + user = await self._get_or_create_user(username) + self.log.debug(f"Adding user {username} to group {name}") group.users.append(user) db.commit() + async def init_role_creation(self): + """Load default and predefined roles into the database""" + self.log.debug('Loading default roles to database') + default_roles = roles.get_default_roles() + config_role_names = [r['name'] for r in self.load_roles] + + init_roles = default_roles + roles_with_new_permissions = [] + for role_spec in self.load_roles: + role_name = role_spec['name'] + # Check for duplicates + if config_role_names.count(role_name) > 1: + raise ValueError( + f"Role {role_name} multiply defined. Please check the `load_roles` configuration" + ) + init_roles.append(role_spec) + # Check if some roles have obtained new permissions (to avoid 'scope creep') + old_role = orm.Role.find(self.db, name=role_name) + if old_role: + if not set(role_spec['scopes']).issubset(old_role.scopes): + app_log.warning( + "Role %s has obtained extra permissions" % role_name + ) + roles_with_new_permissions.append(role_name) + if roles_with_new_permissions: + unauthorized_oauth_tokens = ( + self.db.query(orm.APIToken) + .filter( + orm.APIToken.roles.any( + orm.Role.name.in_(roles_with_new_permissions) + ) + ) + .filter(orm.APIToken.client_id != 'jupyterhub') + ) + for token in unauthorized_oauth_tokens: + app_log.warning( + "Deleting OAuth token %s; one of its roles obtained new permissions that were not authorized by user" + % token + ) + self.db.delete(token) + self.db.commit() + + init_role_names = [r['name'] for r in init_roles] + if not orm.Role.find(self.db, name='admin'): + self._rbac_upgrade = True + else: + self._rbac_upgrade = False + for role in self.db.query(orm.Role).filter( + orm.Role.name.notin_(init_role_names) + ): + app_log.info(f"Deleting role {role.name}") + self.db.delete(role) + self.db.commit() + for role in init_roles: + roles.create_role(self.db, role) + + async def init_role_assignment(self): + # tokens are added separately + kinds = ['users', 'services', 'groups'] + admin_role_objects = ['users', 'services'] + config_admin_users = set(self.authenticator.admin_users) + db = self.db + # load predefined roles from config file + if config_admin_users: + for role_spec in self.load_roles: + if role_spec['name'] == 'admin': + app_log.warning( + "Configuration specifies both admin_users and users in the admin role specification. " + "If admin role is present in config, c.authenticator.admin_users should not be used." + ) + app_log.info( + "Merging admin_users set with users list in admin role" + ) + role_spec['users'] = set(role_spec.get('users', [])) + role_spec['users'] |= config_admin_users + self.log.debug('Loading predefined roles from config file to database') + has_admin_role_spec = {role_bearer: False for role_bearer in admin_role_objects} + for predef_role in self.load_roles: + predef_role_obj = orm.Role.find(db, name=predef_role['name']) + if predef_role['name'] == 'admin': + for kind in admin_role_objects: + has_admin_role_spec[kind] = kind in predef_role + if has_admin_role_spec[kind]: + app_log.info(f"Admin role specifies static {kind} list") + else: + app_log.info( + f"Admin role does not specify {kind}, preserving admin membership in database" + ) + # add users, services, and/or groups, + # tokens need to be checked for permissions + for kind in kinds: + orm_role_bearers = [] + if kind in predef_role.keys(): + for bname in predef_role[kind]: + if kind == 'users': + bname = self.authenticator.normalize_username(bname) + if not ( + await maybe_future( + self.authenticator.check_allowed(bname, None) + ) + ): + raise ValueError( + "Username %r is not in Authenticator.allowed_users" + % bname + ) + Class = orm.get_class(kind) + orm_obj = Class.find(db, bname) + if orm_obj: + orm_role_bearers.append(orm_obj) + else: + app_log.info( + f"Found unexisting {kind} {bname} in role definition {predef_role['name']}" + ) + if kind == 'users': + orm_obj = await self._get_or_create_user(bname) + orm_role_bearers.append(orm_obj) + else: + raise ValueError( + f"{kind} {bname} defined in config role definition {predef_role['name']} but not present in database" + ) + # Ensure all with admin role have admin flag + if predef_role['name'] == 'admin': + orm_obj.admin = True + setattr(predef_role_obj, kind, orm_role_bearers) + db.commit() + if self.authenticator.allowed_users: + allowed_users = db.query(orm.User).filter( + orm.User.name.in_(self.authenticator.allowed_users) + ) + for user in allowed_users: + roles.grant_role(db, user, 'user') + admin_role = orm.Role.find(db, 'admin') + for kind in admin_role_objects: + Class = orm.get_class(kind) + for admin_obj in db.query(Class).filter_by(admin=True): + if has_admin_role_spec[kind]: + admin_obj.admin = admin_role in admin_obj.roles + else: + roles.grant_role(db, admin_obj, 'admin') + db.commit() + # make sure that on hub upgrade, all users, services and tokens have at least one role (update with default) + if getattr(self, '_rbac_upgrade', False): + app_log.warning( + "No admin role found; assuming hub upgrade. Initializing default roles for all entities" + ) + for kind in kinds: + roles.check_for_default_roles(db, kind) + + # check tokens for default roles + roles.check_for_default_roles(db, bearer='tokens') + async def _add_tokens(self, token_dict, kind): """Add tokens for users or services to the database""" if kind == 'user': @@ -1995,12 +2200,13 @@ def purge_expired_tokens(self): run periodically """ # this should be all the subclasses of Expiring - for cls in (orm.APIToken, orm.OAuthAccessToken, orm.OAuthCode): + for cls in (orm.APIToken, orm.OAuthCode): self.log.debug("Purging expired {name}s".format(name=cls.__name__)) cls.purge_expired(self.db) async def init_api_tokens(self): """Load predefined API tokens (for services) into database""" + await self._add_tokens(self.service_tokens, kind='service') await self._add_tokens(self.api_tokens, kind='user') @@ -2008,6 +2214,7 @@ async def init_api_tokens(self): # purge expired tokens hourly # we don't need to be prompt about this # because expired tokens cannot be used anyway + pc = PeriodicCallback( self.purge_expired_tokens, 1e3 * self.purge_expired_tokens_interval ) @@ -2031,6 +2238,14 @@ def init_services(self): if orm_service is None: # not found, create a new one orm_service = orm.Service(name=name) + if spec.get('admin', False): + self.log.warning( + f"Service {name} sets `admin: True`, which is deprecated in JupyterHub 2.0." + " You can assign now assign roles via `JupyterHub.load_roles` configuration." + " If you specify services in the admin role configuration, " + "the Service admin flag will be ignored." + ) + roles.update_roles(self.db, entity=orm_service, roles=['admin']) self.db.add(orm_service) orm_service.admin = spec.get('admin', False) self.db.commit() @@ -2040,6 +2255,7 @@ def init_services(self): base_url=self.base_url, db=self.db, orm=orm_service, + roles=orm_service.roles, domain=domain, host=host, hub=self.hub, @@ -2085,12 +2301,24 @@ def init_services(self): service.orm.server = None if service.oauth_available: - self.oauth_provider.add_client( + allowed_roles = [] + if service.oauth_roles: + allowed_roles = list( + self.db.query(orm.Role).filter( + orm.Role.name.in_(service.oauth_roles) + ) + ) + oauth_client = self.oauth_provider.add_client( client_id=service.oauth_client_id, client_secret=service.api_token, redirect_uri=service.oauth_redirect_uri, + allowed_roles=allowed_roles, description="JupyterHub service %s" % service.name, ) + service.orm.oauth_client = oauth_client + else: + if service.oauth_client: + self.db.delete(service.oauth_client) self._service_map[name] = service @@ -2106,7 +2334,7 @@ async def check_services_health(self): if not service.url: continue try: - await Server.from_orm(service.orm.server).wait_up(timeout=1) + await Server.from_orm(service.orm.server).wait_up(timeout=1, http=True) except TimeoutError: self.log.warning( "Cannot connect to %s service %s at %s", @@ -2276,7 +2504,7 @@ def cleanup_oauth_clients(self): This should mainly be services that have been removed from configuration or renamed. """ - oauth_client_ids = set() + oauth_client_ids = {"jupyterhub"} for service in self._service_map.values(): if service.oauth_available: oauth_client_ids.add(service.oauth_client_id) @@ -2511,10 +2739,12 @@ def _log_cls(name, cls): self.init_hub() self.init_proxy() self.init_oauth() + await self.init_role_creation() await self.init_users() await self.init_groups() self.init_services() await self.init_api_tokens() + await self.init_role_assignment() self.init_tornado_settings() self.init_handlers() self.init_tornado_application() @@ -2797,7 +3027,7 @@ async def start(self): if service.managed: self.log.info("Starting managed service %s", msg) try: - service.start() + await service.start() except Exception as e: self.log.critical( "Failed to start service %s", service_name, exc_info=True @@ -2810,11 +3040,6 @@ async def start(self): tries = 10 if service.managed else 1 for i in range(tries): try: - ssl_context = make_ssl_context( - self.internal_ssl_key, - self.internal_ssl_cert, - cafile=self.internal_ssl_ca, - ) await Server.from_orm(service.orm.server).wait_up( http=True, timeout=1, ssl_context=ssl_context ) diff --git a/jupyterhub/auth.py b/jupyterhub/auth.py --- a/jupyterhub/auth.py +++ b/jupyterhub/auth.py @@ -112,7 +112,7 @@ class Authenticator(LoggingConfigurable): Use this with supported authenticators to restrict which users can log in. This is an additional list that further restricts users, beyond whatever restrictions the - authenticator has in place. + authenticator has in place. Any user in this list is granted the 'user' role on hub startup. If empty, does not perform any additional restriction. diff --git a/jupyterhub/dbutil.py b/jupyterhub/dbutil.py --- a/jupyterhub/dbutil.py +++ b/jupyterhub/dbutil.py @@ -136,7 +136,7 @@ def upgrade_if_needed(db_url, backup=True, log=None): def shell(args=None): - """Start an IPython shell hooked up to the jupyerhub database""" + """Start an IPython shell hooked up to the jupyterhub database""" from .app import JupyterHub hub = JupyterHub() diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -2,6 +2,7 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import asyncio +import functools import json import math import random @@ -30,6 +31,8 @@ from .. import __version__ from .. import orm +from .. import roles +from .. import scopes from ..metrics import PROXY_ADD_DURATION_SECONDS from ..metrics import PROXY_DELETE_DURATION_SECONDS from ..metrics import ProxyDeleteStatus @@ -79,12 +82,13 @@ async def prepare(self): The current user (None if not logged in) may be accessed via the `self.current_user` property during the handling of any request. """ + self.expanded_scopes = set() try: await self.get_current_user() except Exception: self.log.exception("Failed to get current user") self._jupyterhub_user = None - + self._resolve_roles_and_scopes() return await maybe_future(super().prepare()) @property @@ -244,26 +248,6 @@ def get_auth_token(self): return None return match.group(1) - def get_current_user_oauth_token(self): - """Get the current user identified by OAuth access token - - Separate from API token because OAuth access tokens - can only be used for identifying users, - not using the API. - """ - token = self.get_auth_token() - if token is None: - return None - orm_token = orm.OAuthAccessToken.find(self.db, token) - if orm_token is None: - return None - - now = datetime.utcnow() - recorded = self._record_activity(orm_token, now) - if self._record_activity(orm_token.user, now) or recorded: - self.db.commit() - return self._user_from_orm(orm_token.user) - def _record_activity(self, obj, timestamp=None): """record activity on an ORM object @@ -350,23 +334,27 @@ async def refresh_auth(self, user, force=False): auth_info['auth_state'] = await user.get_auth_state() return await self.auth_to_user(auth_info, user) - def get_current_user_token(self): - """get_current_user from Authorization header token""" + def get_token(self): + """get token from authorization header""" token = self.get_auth_token() if token is None: return None orm_token = orm.APIToken.find(self.db, token) - if orm_token is None: - return None + return orm_token + def get_current_user_token(self): + """get_current_user from Authorization header token""" # record token activity + orm_token = self.get_token() + if orm_token is None: + return None now = datetime.utcnow() recorded = self._record_activity(orm_token, now) if orm_token.user: # FIXME: scopes should give us better control than this # don't consider API requests originating from a server # to be activity from the user - if not orm_token.note.startswith("Server at "): + if not orm_token.note or not orm_token.note.startswith("Server at "): recorded = self._record_activity(orm_token.user, now) or recorded if recorded: self.db.commit() @@ -429,6 +417,36 @@ async def get_current_user(self): self.log.exception("Error getting current user") return self._jupyterhub_user + def _resolve_roles_and_scopes(self): + self.expanded_scopes = set() + app_log.debug("Loading and parsing scopes") + if self.current_user: + orm_token = self.get_token() + if orm_token: + self.expanded_scopes = scopes.get_scopes_for(orm_token) + else: + self.expanded_scopes = scopes.get_scopes_for(self.current_user) + self.parsed_scopes = scopes.parse_scopes(self.expanded_scopes) + app_log.debug("Found scopes [%s]", ",".join(self.expanded_scopes)) + + @functools.lru_cache() + def get_scope_filter(self, req_scope): + """Produce a filter function for req_scope on resources + + Returns `has_access_to(orm_resource, kind)` which returns True or False + for whether the current request has access to req_scope on the given resource. + """ + + def no_access(orm_resource, kind): + return False + + if req_scope not in self.parsed_scopes: + return no_access + + sub_scope = self.parsed_scopes[req_scope] + + return functools.partial(scopes.check_scope_filter, sub_scope) + @property def current_user(self): """Override .current_user accessor from tornado @@ -454,6 +472,7 @@ def user_from_username(self, username): # not found, create and register user u = orm.User(name=username) self.db.add(u) + roles.assign_default_roles(self.db, entity=u) TOTAL_USERS.inc() self.db.commit() user = self._user_from_orm(u) @@ -474,10 +493,8 @@ def clear_login_cookie(self, name=None): # don't clear session tokens if not logged in, # because that could be a malicious logout request! count = 0 - for access_token in ( - self.db.query(orm.OAuthAccessToken) - .filter(orm.OAuthAccessToken.user_id == user.id) - .filter(orm.OAuthAccessToken.session_id == session_id) + for access_token in self.db.query(orm.APIToken).filter_by( + user_id=user.id, session_id=session_id ): self.db.delete(access_token) count += 1 @@ -738,6 +755,7 @@ async def auth_to_user(self, authenticated, user=None): # Only set `admin` if the authenticator returned an explicit value. if admin is not None and admin != user.admin: user.admin = admin + roles.assign_default_roles(self.db, entity=user) self.db.commit() # always set auth_state and commit, # because there could be key-rotation or clearing of previous values @@ -983,6 +1001,7 @@ def _track_failure_count(f): self.log.critical( "Aborting due to %i consecutive spawn failures", failure_count ) + # abort in 2 seconds to allow pending handlers to resolve # mostly propagating errors for the current failures def abort(): diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -10,14 +10,13 @@ from jinja2 import TemplateNotFound from tornado import web from tornado.httputil import url_concat -from tornado.httputil import urlparse from .. import __version__ from .. import orm from ..metrics import SERVER_POLL_DURATION_SECONDS from ..metrics import ServerPollStatus from ..pagination import Pagination -from ..utils import admin_only +from ..scopes import needs_scope from ..utils import maybe_future from ..utils import url_path_join from .base import BaseHandler @@ -455,7 +454,9 @@ class AdminHandler(BaseHandler): """Render the admin page.""" @web.authenticated - @admin_only + @needs_scope('users') # stacked decorators: all scopes must be present + @needs_scope('admin:users') + @needs_scope('admin:servers') async def get(self): auth_state = await self.current_user.get_auth_state() html = await self.render_template( @@ -484,36 +485,32 @@ def sort_key(token): return (token.last_activity or never, token.created or never) now = datetime.utcnow() - api_tokens = [] - for token in sorted(user.api_tokens, key=sort_key, reverse=True): - if token.expires_at and token.expires_at < now: - self.db.delete(token) - self.db.commit() - continue - api_tokens.append(token) # group oauth client tokens by client id - # AccessTokens have expires_at as an integer timestamp - now_timestamp = now.timestamp() - oauth_tokens = defaultdict(list) - for token in user.oauth_tokens: - if token.expires_at and token.expires_at < now_timestamp: - self.log.warning("Deleting expired token") + all_tokens = defaultdict(list) + for token in sorted(user.api_tokens, key=sort_key, reverse=True): + if token.expires_at and token.expires_at < now: + self.log.warning(f"Deleting expired token {token}") self.db.delete(token) self.db.commit() continue if not token.client_id: # token should have been deleted when client was deleted - self.log.warning("Deleting stale oauth token for %s", user.name) + self.log.warning("Deleting stale oauth token {token}") self.db.delete(token) self.db.commit() continue - oauth_tokens[token.client_id].append(token) + all_tokens[token.client_id].append(token) + # individually list tokens issued by jupyterhub itself + api_tokens = all_tokens.pop("jupyterhub", []) + + # group all other tokens issued under their owners # get the earliest created and latest last_activity # timestamp for a given oauth client oauth_clients = [] - for client_id, tokens in oauth_tokens.items(): + + for client_id, tokens in all_tokens.items(): created = tokens[0].created last_activity = tokens[0].last_activity for token in tokens[1:]: @@ -526,8 +523,9 @@ def sort_key(token): token = tokens[0] oauth_clients.append( { - 'client': token.client, - 'description': token.client.description or token.client.identifier, + 'client': token.oauth_client, + 'description': token.oauth_client.description + or token.oauth_client.identifier, 'created': created, 'last_activity': last_activity, 'tokens': tokens, diff --git a/jupyterhub/oauth/provider.py b/jupyterhub/oauth/provider.py --- a/jupyterhub/oauth/provider.py +++ b/jupyterhub/oauth/provider.py @@ -7,13 +7,11 @@ from oauthlib.oauth2 import WebApplicationServer from oauthlib.oauth2.rfc6749.grant_types import authorization_code from oauthlib.oauth2.rfc6749.grant_types import base -from tornado.escape import url_escape from tornado.log import app_log from .. import orm from ..utils import compare_token from ..utils import hash_token -from ..utils import url_path_join # patch absolute-uri check # because we want to allow relative uri oauth @@ -60,6 +58,9 @@ def authenticate_client(self, request, *args, **kwargs): ) if oauth_client is None: return False + if not client_secret or not oauth_client.secret: + # disallow authentication with no secret + return False if not compare_token(oauth_client.secret, client_secret): app_log.warning("Client secret mismatch for %s", client_id) return False @@ -146,7 +147,12 @@ def get_default_scopes(self, client_id, request, *args, **kwargs): - Resource Owner Password Credentials Grant - Client Credentials grant """ - return ['identify'] + orm_client = ( + self.db.query(orm.OAuthClient).filter_by(identifier=client_id).first() + ) + if orm_client is None: + raise ValueError("No such client: %s" % client_id) + return [role.name for role in orm_client.allowed_roles] def get_original_scopes(self, refresh_token, request, *args, **kwargs): """Get the list of scopes associated with the refresh token. @@ -246,8 +252,7 @@ def save_authorization_code(self, client_id, code, request, *args, **kwargs): code=code['code'], # oauth has 5 minutes to complete expires_at=int(orm.OAuthCode.now() + 300), - # TODO: persist oauth scopes - # scopes=request.scopes, + roles=request._jupyterhub_roles, user=request.user.orm_user, redirect_uri=orm_client.redirect_uri, session_id=request.session_id, @@ -321,10 +326,6 @@ def save_bearer_token(self, token, request, *args, **kwargs): """ log_token = {} log_token.update(token) - scopes = token['scope'].split(' ') - # TODO: - if scopes != ['identify']: - raise ValueError("Only 'identify' scope is supported") # redact sensitive keys in log for key in ('access_token', 'refresh_token', 'state'): if key in token: @@ -332,6 +333,7 @@ def save_bearer_token(self, token, request, *args, **kwargs): if isinstance(value, str): log_token[key] = 'REDACTED' app_log.debug("Saving bearer token %s", log_token) + if request.user is None: raise ValueError("No user for access token: %s" % request.user) client = ( @@ -339,19 +341,19 @@ def save_bearer_token(self, token, request, *args, **kwargs): .filter_by(identifier=request.client.client_id) .first() ) - orm_access_token = orm.OAuthAccessToken( - client=client, - grant_type=orm.GrantType.authorization_code, - expires_at=int(orm.OAuthAccessToken.now() + token['expires_in']), - refresh_token=token['refresh_token'], - # TODO: save scopes, - # scopes=scopes, + # FIXME: support refresh tokens + # These should be in a new table + token.pop("refresh_token", None) + + # APIToken.new commits the token to the db + orm.APIToken.new( + client_id=client.identifier, + expires_in=token['expires_in'], + roles=[rolename for rolename in request.scopes], token=token['access_token'], session_id=request.session_id, user=request.user, ) - self.db.add(orm_access_token) - self.db.commit() return client.redirect_uri def validate_bearer_token(self, token, scopes, request): @@ -412,6 +414,8 @@ def validate_client_id(self, client_id, request, *args, **kwargs): ) if orm_client is None: return False + if not orm_client.secret: + return False request.client = orm_client return True @@ -447,9 +451,7 @@ def validate_code(self, client_id, code, client, request, *args, **kwargs): return False request.user = orm_code.user request.session_id = orm_code.session_id - # TODO: record state on oauth codes - # TODO: specify scopes - request.scopes = ['identify'] + request.scopes = [role.name for role in orm_code.roles] return True def validate_grant_type( @@ -545,6 +547,35 @@ def validate_scopes(self, client_id, scopes, client, request, *args, **kwargs): - Resource Owner Password Credentials Grant - Client Credentials Grant """ + orm_client = ( + self.db.query(orm.OAuthClient).filter_by(identifier=client_id).one_or_none() + ) + if orm_client is None: + app_log.warning("No such oauth client %s", client_id) + return False + client_allowed_roles = {role.name: role for role in orm_client.allowed_roles} + # explicitly allow 'identify', which was the only allowed scope previously + # requesting 'identify' gets no actual permissions other than self-identification + client_allowed_roles.setdefault('identify', None) + roles = [] + requested_roles = set(scopes) + disallowed_roles = requested_roles.difference(client_allowed_roles) + if disallowed_roles: + app_log.error( + f"Role(s) not allowed for {client_id}: {','.join(disallowed_roles)}" + ) + return False + + # store resolved roles on request + app_log.debug( + f"Allowing request for role(s) for {client_id}: {','.join(requested_roles) or '[]'}" + ) + # these will be stored on the OAuthCode object + request._jupyterhub_roles = [ + client_allowed_roles[name] + for name in requested_roles + if client_allowed_roles[name] is not None + ] return True @@ -553,7 +584,9 @@ def __init__(self, db, validator, *args, **kwargs): self.db = db super().__init__(validator, *args, **kwargs) - def add_client(self, client_id, client_secret, redirect_uri, description=''): + def add_client( + self, client_id, client_secret, redirect_uri, allowed_roles=None, description='' + ): """Add a client hash its client_secret before putting it in the database. @@ -574,14 +607,20 @@ def add_client(self, client_id, client_secret, redirect_uri, description=''): app_log.info(f'Creating oauth client {client_id}') else: app_log.info(f'Updating oauth client {client_id}') - orm_client.secret = hash_token(client_secret) + if allowed_roles == None: + allowed_roles = [] + orm_client.secret = hash_token(client_secret) if client_secret else "" orm_client.redirect_uri = redirect_uri - orm_client.description = description + orm_client.description = description or client_id + orm_client.allowed_roles = allowed_roles self.db.commit() + return orm_client def fetch_by_client_id(self, client_id): """Find a client by its id""" - return self.db.query(orm.OAuthClient).filter_by(identifier=client_id).first() + client = self.db.query(orm.OAuthClient).filter_by(identifier=client_id).first() + if client and client.secret: + return client def make_provider(session_factory, url_prefix, login_url, **oauth_server_kwargs): diff --git a/jupyterhub/orm.py b/jupyterhub/orm.py --- a/jupyterhub/orm.py +++ b/jupyterhub/orm.py @@ -3,6 +3,7 @@ # Distributed under the terms of the Modified BSD License. import enum import json +import warnings from base64 import decodebytes from base64 import encodebytes from datetime import datetime @@ -15,12 +16,12 @@ from sqlalchemy import Column from sqlalchemy import create_engine from sqlalchemy import DateTime -from sqlalchemy import Enum from sqlalchemy import event from sqlalchemy import exc from sqlalchemy import ForeignKey from sqlalchemy import inspect from sqlalchemy import Integer +from sqlalchemy import MetaData from sqlalchemy import or_ from sqlalchemy import select from sqlalchemy import Table @@ -39,6 +40,10 @@ from sqlalchemy.types import TypeDecorator from tornado.log import app_log +from .roles import assign_default_roles +from .roles import create_role +from .roles import get_default_roles +from .roles import update_roles from .utils import compare_token from .utils import hash_token from .utils import new_token @@ -90,7 +95,37 @@ def process_result_value(self, value, dialect): return value -Base = declarative_base() +class JSONList(JSONDict): + """Represents an immutable structure as a json-encoded string (to be used for list type columns). + + Usage:: + + JSONList(JSONDict) + + """ + + def process_bind_param(self, value, dialect): + if isinstance(value, list) and value is not None: + value = json.dumps(value) + return value + + def process_result_value(self, value, dialect): + if value is not None: + value = json.loads(value) + return value + + +meta = MetaData( + naming_convention={ + "ix": "ix_%(column_0_label)s", + "uq": "uq_%(table_name)s_%(column_0_name)s", + "ck": "ck_%(table_name)s_%(constraint_name)s", + "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", + "pk": "pk_%(table_name)s", + } +) + +Base = declarative_base(metadata=meta) Base.log = app_log @@ -113,6 +148,65 @@ def __repr__(self): return "<Server(%s:%s)>" % (self.ip, self.port) +# lots of things have roles +# mapping tables are the same for all of them + +_role_map_tables = [] + +for has_role in ( + 'user', + 'group', + 'service', + 'api_token', + 'oauth_client', + 'oauth_code', +): + role_map = Table( + f'{has_role}_role_map', + Base.metadata, + Column( + f'{has_role}_id', + ForeignKey(f'{has_role}s.id', ondelete='CASCADE'), + primary_key=True, + ), + Column( + 'role_id', + ForeignKey('roles.id', ondelete='CASCADE'), + primary_key=True, + ), + ) + _role_map_tables.append(role_map) + + +class Role(Base): + """User Roles""" + + __tablename__ = 'roles' + id = Column(Integer, primary_key=True, autoincrement=True) + name = Column(Unicode(255), unique=True) + description = Column(Unicode(1023)) + scopes = Column(JSONList) + users = relationship('User', secondary='user_role_map', backref='roles') + services = relationship('Service', secondary='service_role_map', backref='roles') + tokens = relationship('APIToken', secondary='api_token_role_map', backref='roles') + groups = relationship('Group', secondary='group_role_map', backref='roles') + + def __repr__(self): + return "<%s %s (%s) - scopes: %s>" % ( + self.__class__.__name__, + self.name, + self.description, + self.scopes, + ) + + @classmethod + def find(cls, db, name): + """Find a role by name. + Returns None if not found. + """ + return db.query(cls).filter(cls.name == name).first() + + # user:group many:many mapping table user_group_map = Table( 'user_group_map', @@ -180,14 +274,11 @@ class User(Base): def orm_spawners(self): return {s.name: s for s in self._orm_spawners} - admin = Column(Boolean, default=False) + admin = Column(Boolean(create_constraint=False), default=False) created = Column(DateTime, default=datetime.utcnow) last_activity = Column(DateTime, nullable=True) api_tokens = relationship("APIToken", backref="user", cascade="all, delete-orphan") - oauth_tokens = relationship( - "OAuthAccessToken", backref="user", cascade="all, delete-orphan" - ) oauth_codes = relationship( "OAuthCode", backref="user", cascade="all, delete-orphan" ) @@ -245,6 +336,21 @@ class Spawner(Base): last_activity = Column(DateTime, nullable=True) user_options = Column(JSONDict) + # added in 2.0 + oauth_client_id = Column( + Unicode(255), + ForeignKey( + 'oauth_clients.identifier', + ondelete='SET NULL', + ), + ) + oauth_client = relationship( + 'OAuthClient', + backref=backref("spawner", uselist=False), + cascade="all, delete-orphan", + single_parent=True, + ) + # properties on the spawner wrapper # some APIs get these low-level objects # when the spawner isn't running, @@ -280,7 +386,7 @@ class Service(Base): # common user interface: name = Column(Unicode(255), unique=True) - admin = Column(Boolean, default=False) + admin = Column(Boolean(create_constraint=False), default=False) api_tokens = relationship( "APIToken", backref="service", cascade="all, delete-orphan" @@ -296,6 +402,21 @@ class Service(Base): ) pid = Column(Integer) + # added in 2.0 + oauth_client_id = Column( + Unicode(255), + ForeignKey( + 'oauth_clients.identifier', + ondelete='SET NULL', + ), + ) + oauth_client = relationship( + 'OAuthClient', + backref=backref("service", uselist=False), + cascade="all, delete-orphan", + single_parent=True, + ) + def new_api_token(self, token=None, **kwargs): """Create a new API token If `token` is given, load that token. @@ -438,14 +559,34 @@ def find(cls, db, token): return orm_token +# ------------------------------------ +# OAuth tables +# ------------------------------------ + + +class GrantType(enum.Enum): + # we only use authorization_code for now + authorization_code = 'authorization_code' + implicit = 'implicit' + password = 'password' + client_credentials = 'client_credentials' + refresh_token = 'refresh_token' + + class APIToken(Hashed, Base): """An API token""" __tablename__ = 'api_tokens' - user_id = Column(Integer, ForeignKey('users.id', ondelete="CASCADE"), nullable=True) + user_id = Column( + Integer, + ForeignKey('users.id', ondelete="CASCADE"), + nullable=True, + ) service_id = Column( - Integer, ForeignKey('services.id', ondelete="CASCADE"), nullable=True + Integer, + ForeignKey('services.id', ondelete="CASCADE"), + nullable=True, ) id = Column(Integer, primary_key=True) @@ -456,6 +597,27 @@ class APIToken(Hashed, Base): def api_id(self): return 'a%i' % self.id + # added in 2.0 + client_id = Column( + Unicode(255), + ForeignKey( + 'oauth_clients.identifier', + ondelete='CASCADE', + ), + ) + + # FIXME: refresh_tokens not implemented + # should be a relation to another token table + # refresh_token = Column( + # Integer, + # ForeignKey('refresh_tokens.id', ondelete="CASCADE"), + # nullable=True, + # ) + + # the browser session id associated with a given token, + # if issued during oauth to be stored in a cookie + session_id = Column(Unicode(255), nullable=True) + # token metadata for bookkeeping now = datetime.utcnow # for expiry created = Column(DateTime, default=datetime.utcnow) @@ -474,8 +636,12 @@ def __repr__(self): # this shouldn't happen kind = 'owner' name = 'unknown' - return "<{cls}('{pre}...', {kind}='{name}')>".format( - cls=self.__class__.__name__, pre=self.prefix, kind=kind, name=name + return "<{cls}('{pre}...', {kind}='{name}', client_id={client_id!r})>".format( + cls=self.__class__.__name__, + pre=self.prefix, + kind=kind, + name=name, + client_id=self.client_id, ) @classmethod @@ -496,6 +662,14 @@ def find(cls, db, token, *, kind=None): raise ValueError("kind must be 'user', 'service', or None, not %r" % kind) for orm_token in prefix_match: if orm_token.match(token): + if not orm_token.client_id: + app_log.warning( + "Deleting stale oauth token for %s with no client", + orm_token.user and orm_token.user.name, + ) + db.delete(orm_token) + db.commit() + return return orm_token @classmethod @@ -504,9 +678,13 @@ def new( token=None, user=None, service=None, + roles=None, note='', generated=True, + session_id=None, expires_in=None, + client_id='jupyterhub', + return_orm=False, ): """Generate a new API token for a user or service""" assert user or service @@ -521,7 +699,12 @@ def new( cls.check_token(db, token) # two stages to ensure orm_token.generated has been set # before token setter is called - orm_token = cls(generated=generated, note=note or '') + orm_token = cls( + generated=generated, + note=note or '', + client_id=client_id, + session_id=session_id, + ) orm_token.token = token if user: assert user.id is not None @@ -531,79 +714,22 @@ def new( orm_token.service = service if expires_in is not None: orm_token.expires_at = cls.now() + timedelta(seconds=expires_in) - db.add(orm_token) - db.commit() - return token - - -# ------------------------------------ -# OAuth tables -# ------------------------------------ - - -class GrantType(enum.Enum): - # we only use authorization_code for now - authorization_code = 'authorization_code' - implicit = 'implicit' - password = 'password' - client_credentials = 'client_credentials' - refresh_token = 'refresh_token' - - -class OAuthAccessToken(Hashed, Base): - __tablename__ = 'oauth_access_tokens' - id = Column(Integer, primary_key=True, autoincrement=True) - - @staticmethod - def now(): - return datetime.utcnow().timestamp() - - @property - def api_id(self): - return 'o%i' % self.id - - client_id = Column( - Unicode(255), ForeignKey('oauth_clients.identifier', ondelete='CASCADE') - ) - grant_type = Column(Enum(GrantType), nullable=False) - expires_at = Column(Integer) - refresh_token = Column(Unicode(255)) - # TODO: drop refresh_expires_at. Refresh tokens shouldn't expire - refresh_expires_at = Column(Integer) - user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE')) - service = None # for API-equivalence with APIToken - # the browser session id associated with a given token - session_id = Column(Unicode(255)) - - # from Hashed - hashed = Column(Unicode(255), unique=True) - prefix = Column(Unicode(16), index=True) - - created = Column(DateTime, default=datetime.utcnow) - last_activity = Column(DateTime, nullable=True) - - def __repr__(self): - return "<{cls}('{prefix}...', client_id={client_id!r}, user={user!r}, expires_in={expires_in}>".format( - cls=self.__class__.__name__, - client_id=self.client_id, - user=self.user and self.user.name, - prefix=self.prefix, - expires_in=self.expires_in, - ) - - @classmethod - def find(cls, db, token): - orm_token = super().find(db, token) - if orm_token and not orm_token.client_id: - app_log.warning( - "Deleting stale oauth token for %s with no client", - orm_token.user and orm_token.user.name, - ) + db.add(orm_token) + if not Role.find(db, 'token'): + raise RuntimeError("Default token role has not been created") + try: + if roles is not None: + update_roles(db, entity=orm_token, roles=roles) + else: + assign_default_roles(db, entity=orm_token) + except Exception: db.delete(orm_token) db.commit() - return - return orm_token + raise + + db.commit() + return token class OAuthCode(Expiring, Base): @@ -620,6 +746,8 @@ class OAuthCode(Expiring, Base): # state = Column(Unicode(1023)) user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE')) + roles = relationship('Role', secondary='oauth_code_role_map') + @staticmethod def now(): return datetime.utcnow().timestamp() @@ -633,6 +761,11 @@ def find(cls, db, code): .first() ) + def __repr__(self): + return ( + f"<{self.__class__.__name__}(id={self.id}, client_id={self.client_id!r})>" + ) + class OAuthClient(Base): __tablename__ = 'oauth_clients' @@ -647,10 +780,17 @@ def client_id(self): return self.identifier access_tokens = relationship( - OAuthAccessToken, backref='client', cascade='all, delete-orphan' + APIToken, backref='oauth_client', cascade='all, delete-orphan' ) codes = relationship(OAuthCode, backref='client', cascade='all, delete-orphan') + # these are the roles an oauth client is allowed to request + # *not* the roles of the client itself + allowed_roles = relationship('Role', secondary='oauth_client_role_map') + + def __repr__(self): + return f"<{self.__class__.__name__}(identifier={self.identifier!r})>" + # General database utilities @@ -887,3 +1027,18 @@ def new_session_factory( # this off gives us a major performance boost session_factory = sessionmaker(bind=engine, expire_on_commit=expire_on_commit) return session_factory + + +def get_class(resource_name): + """Translates resource string names to ORM classes""" + class_dict = { + 'users': User, + 'services': Service, + 'tokens': APIToken, + 'groups': Group, + } + if resource_name not in class_dict: + raise ValueError( + "Kind must be one of %s, not %s" % (", ".join(class_dict), resource_name) + ) + return class_dict[resource_name] diff --git a/jupyterhub/roles.py b/jupyterhub/roles.py new file mode 100644 --- /dev/null +++ b/jupyterhub/roles.py @@ -0,0 +1,512 @@ +"""Roles utils""" +# Copyright (c) Jupyter Development Team. +# Distributed under the terms of the Modified BSD License. +import re +from itertools import chain + +from sqlalchemy import func +from tornado.log import app_log + +from . import orm +from . import scopes + + +def get_default_roles(): + """Returns: + default roles (list): default role definitions as dictionaries: + { + 'name': role name, + 'description': role description, + 'scopes': list of scopes, + } + """ + default_roles = [ + { + 'name': 'user', + 'description': 'Standard user privileges', + 'scopes': [ + 'self', + ], + }, + { + 'name': 'admin', + 'description': 'Elevated privileges (can do anything)', + 'scopes': [ + 'admin:users', + 'admin:servers', + 'tokens', + 'admin:groups', + 'read:services', + 'read:hub', + 'proxy', + 'shutdown', + 'access:services', + 'access:servers', + 'read:roles', + ], + }, + { + 'name': 'server', + 'description': 'Post activity only', + 'scopes': [ + 'users:activity!user', + 'access:servers!user', + ], + }, + { + 'name': 'token', + 'description': 'Token with same permissions as its owner', + 'scopes': ['all'], + }, + ] + return default_roles + + +def expand_self_scope(name): + """ + Users have a metascope 'self' that should be expanded to standard user privileges. + At the moment that is a user-filtered version (optional read) access to + users + users:name + users:groups + users:activity + tokens + servers + access:servers + + + Arguments: + name (str): user name + + Returns: + expanded scopes (set): set of expanded scopes covering standard user privileges + """ + scope_list = [ + 'users', + 'read:users', + 'read:users:name', + 'read:users:groups', + 'users:activity', + 'read:users:activity', + 'servers', + 'read:servers', + 'tokens', + 'read:tokens', + 'access:servers', + ] + return {"{}!user={}".format(scope, name) for scope in scope_list} + + +def horizontal_filter(func): + """Decorator to account for horizontal filtering in scope syntax""" + + def expand_server_filter(hor_filter): + resource, mark, value = hor_filter.partition('=') + if resource == 'server': + user, mark, server = value.partition('/') + return f'read:users:name!user={user}' + + def ignore(scopename): + # temporarily remove horizontal filtering if present + scopename, mark, hor_filter = scopename.partition('!') + expanded_scope = func(scopename) + # add the filter back + full_expanded_scope = {scope + mark + hor_filter for scope in expanded_scope} + server_filter = expand_server_filter(hor_filter) + if server_filter: + full_expanded_scope.add(server_filter) + return full_expanded_scope + + return ignore + + +@horizontal_filter +def _expand_scope(scopename): + """Returns a set of all subscopes + Arguments: + scopename (str): name of the scope to expand + + Returns: + expanded scope (set): set of all scope's subscopes including the scope itself + """ + expanded_scope = [] + + def _add_subscopes(scopename): + expanded_scope.append(scopename) + if scopes.scope_definitions[scopename].get('subscopes'): + for subscope in scopes.scope_definitions[scopename].get('subscopes'): + _add_subscopes(subscope) + + _add_subscopes(scopename) + + return set(expanded_scope) + + +def expand_roles_to_scopes(orm_object): + """Get the scopes listed in the roles of the User/Service/Group/Token + If User, take into account the user's groups roles as well + + Arguments: + orm_object: orm.User, orm.Service, orm.Group or orm.APIToken + + Returns: + expanded scopes (set): set of all expanded scopes for the orm object + """ + if not isinstance(orm_object, orm.Base): + raise TypeError(f"Only orm objects allowed, got {orm_object}") + + pass_roles = [] + pass_roles.extend(orm_object.roles) + + if isinstance(orm_object, orm.User): + for group in orm_object.groups: + pass_roles.extend(group.roles) + + expanded_scopes = _get_subscopes(*pass_roles, owner=orm_object) + + return expanded_scopes + + +def _get_subscopes(*roles, owner=None): + """Returns a set of all available subscopes for a specified role or list of roles + + Arguments: + roles (obj): orm.Roles + owner (obj, optional): orm.User or orm.Service as owner of orm.APIToken + + Returns: + expanded scopes (set): set of all expanded scopes for the role(s) + """ + scopes = set() + + for role in roles: + scopes.update(role.scopes) + + expanded_scopes = set(chain.from_iterable(list(map(_expand_scope, scopes)))) + # transform !user filter to !user=ownername + for scope in expanded_scopes.copy(): + base_scope, _, filter = scope.partition('!') + if filter == 'user': + expanded_scopes.remove(scope) + if isinstance(owner, orm.APIToken): + token_owner = owner.user + if token_owner is None: + token_owner = owner.service + name = token_owner.name + else: + name = owner.name + trans_scope = f'{base_scope}!user={name}' + expanded_scopes.add(trans_scope) + if 'self' in expanded_scopes: + expanded_scopes.remove('self') + if owner and isinstance(owner, orm.User): + expanded_scopes |= expand_self_scope(owner.name) + + return expanded_scopes + + +def _check_scopes(*args, rolename=None): + """Check if provided scopes exist + + Arguments: + scope (str): name of the scope to check + or + scopes (list): list of scopes to check + + Raises NameError if scope does not exist + """ + + allowed_scopes = set(scopes.scope_definitions.keys()) + allowed_filters = ['!user=', '!service=', '!group=', '!server=', '!user'] + + if rolename: + log_role = f"for role {rolename}" + else: + log_role = "" + + for scope in args: + scopename, _, filter_ = scope.partition('!') + if scopename not in allowed_scopes: + raise NameError(f"Scope '{scope}' {log_role} does not exist") + if filter_: + full_filter = f"!{filter_}" + if not any(f in scope for f in allowed_filters): + raise NameError( + f"Scope filter '{full_filter}' in scope '{scope}' {log_role} does not exist" + ) + + +def _overwrite_role(role, role_dict): + """Overwrites role's description and/or scopes with role_dict if role not 'admin'""" + for attr in role_dict.keys(): + if attr == 'description' or attr == 'scopes': + if role.name == 'admin': + admin_role_spec = [ + r for r in get_default_roles() if r['name'] == 'admin' + ][0] + if role_dict[attr] != admin_role_spec[attr]: + raise ValueError( + 'admin role description or scopes cannot be overwritten' + ) + else: + if role_dict[attr] != getattr(role, attr): + setattr(role, attr, role_dict[attr]) + app_log.info( + 'Role %r %r attribute has been changed', role.name, attr + ) + + +_role_name_pattern = re.compile(r'^[a-z][a-z0-9\-_~\.]{1,253}[a-z0-9]$') + + +def _validate_role_name(name): + """Ensure a role has a valid name + + Raises ValueError if role name is invalid + """ + if not _role_name_pattern.match(name): + raise ValueError( + f"Invalid role name: {name!r}." + " Role names must:\n" + " - be 3-255 characters\n" + " - contain only lowercase ascii letters, numbers, and URL unreserved special characters '-.~_'\n" + " - start with a letter\n" + " - end with letter or number\n" + ) + return True + + +def create_role(db, role_dict): + """Adds a new role to database or modifies an existing one""" + default_roles = get_default_roles() + + if 'name' not in role_dict.keys(): + raise KeyError('Role definition must have a name') + else: + name = role_dict['name'] + _validate_role_name(name) + role = orm.Role.find(db, name) + + description = role_dict.get('description') + scopes = role_dict.get('scopes') + + # check if the provided scopes exist + if scopes: + _check_scopes(*scopes, rolename=role_dict['name']) + + if role is None: + if not scopes: + app_log.warning('Warning: New defined role %s has no scopes', name) + + role = orm.Role(name=name, description=description, scopes=scopes) + db.add(role) + if role_dict not in default_roles: + app_log.info('Role %s added to database', name) + else: + _overwrite_role(role, role_dict) + + db.commit() + + +def delete_role(db, rolename): + """Removes a role from database""" + # default roles are not removable + default_roles = get_default_roles() + if any(role['name'] == rolename for role in default_roles): + raise ValueError('Default role %r cannot be removed', rolename) + + role = orm.Role.find(db, rolename) + if role: + db.delete(role) + db.commit() + app_log.info('Role %s has been deleted', rolename) + else: + raise NameError('Cannot remove role %r that does not exist', rolename) + + +def existing_only(func): + """Decorator for checking if objects and roles exist""" + + def _check_existence(db, entity, rolename): + role = orm.Role.find(db, rolename) + if entity is None: + raise ValueError( + "%r of kind %r does not exist" % (entity, type(entity).__name__) + ) + elif role is None: + raise ValueError("Role %r does not exist" % rolename) + else: + func(db, entity, role) + + return _check_existence + + +@existing_only +def grant_role(db, entity, rolename): + """Adds a role for users, services, groups or tokens""" + if isinstance(entity, orm.APIToken): + entity_repr = entity + else: + entity_repr = entity.name + + if rolename not in entity.roles: + entity.roles.append(rolename) + db.commit() + app_log.info( + 'Adding role %s for %s: %s', + rolename.name, + type(entity).__name__, + entity_repr, + ) + + +@existing_only +def strip_role(db, entity, rolename): + """Removes a role for users, services, groups or tokens""" + if isinstance(entity, orm.APIToken): + entity_repr = entity + else: + entity_repr = entity.name + if rolename in entity.roles: + entity.roles.remove(rolename) + db.commit() + app_log.info( + 'Removing role %s for %s: %s', + rolename.name, + type(entity).__name__, + entity_repr, + ) + + +def _switch_default_role(db, obj, admin): + """Switch between default user/service and admin roles for users/services""" + user_role = orm.Role.find(db, 'user') + admin_role = orm.Role.find(db, 'admin') + + def add_and_remove(db, obj, current_role, new_role): + if current_role in obj.roles: + strip_role(db, entity=obj, rolename=current_role.name) + # only add new default role if the user has no other roles + if len(obj.roles) < 1: + grant_role(db, entity=obj, rolename=new_role.name) + + if admin: + add_and_remove(db, obj, user_role, admin_role) + else: + add_and_remove(db, obj, admin_role, user_role) + + +def _token_allowed_role(db, token, role): + """Checks if requested role for token does not grant the token + higher permissions than the token's owner has + + Returns: + True if requested permissions are within the owner's permissions, False otherwise + """ + owner = token.user + if owner is None: + owner = token.service + + if owner is None: + raise ValueError(f"Owner not found for {token}") + + expanded_scopes = _get_subscopes(role, owner=owner) + + implicit_permissions = {'all', 'read:all'} + explicit_scopes = expanded_scopes - implicit_permissions + # ignore horizontal filters + no_filter_scopes = { + scope.split('!', 1)[0] if '!' in scope else scope for scope in explicit_scopes + } + # find the owner's scopes + expanded_owner_scopes = expand_roles_to_scopes(owner) + # ignore horizontal filters + no_filter_owner_scopes = { + scope.split('!', 1)[0] if '!' in scope else scope + for scope in expanded_owner_scopes + } + disallowed_scopes = no_filter_scopes.difference(no_filter_owner_scopes) + if not disallowed_scopes: + # no scopes requested outside owner's own scopes + return True + else: + app_log.warning( + f"Token requesting scopes exceeding owner {owner.name}: {disallowed_scopes}" + ) + return False + + +def assign_default_roles(db, entity): + """Assigns default role to an entity: + users and services get 'user' role, or admin role if they have admin flag + tokens get 'token' role + """ + if isinstance(entity, orm.Group): + pass + elif isinstance(entity, orm.APIToken): + app_log.debug('Assigning default roles to tokens') + default_token_role = orm.Role.find(db, 'token') + if not entity.roles and (entity.user or entity.service) is not None: + default_token_role.tokens.append(entity) + app_log.info('Added role %s to token %s', default_token_role.name, entity) + db.commit() + # users and services can have 'user' or 'admin' roles as default + else: + kind = type(entity).__name__ + app_log.debug(f'Assigning default roles to {kind} {entity.name}') + _switch_default_role(db, entity, entity.admin) + + +def update_roles(db, entity, roles): + """Updates object's roles checking for requested permissions + if object is orm.APIToken + """ + standard_permissions = {'all', 'read:all'} + for rolename in roles: + if isinstance(entity, orm.APIToken): + role = orm.Role.find(db, rolename) + if role: + app_log.debug( + 'Checking token permissions against requested role %s', rolename + ) + if _token_allowed_role(db, entity, role): + role.tokens.append(entity) + app_log.info('Adding role %s to token: %s', role.name, entity) + else: + raise ValueError( + f'Requested token role {rolename} of {entity} has more permissions than the token owner' + ) + else: + raise NameError('Role %r does not exist' % rolename) + else: + app_log.debug('Assigning default roles to %s', type(entity).__name__) + grant_role(db, entity=entity, rolename=rolename) + + +def check_for_default_roles(db, bearer): + """Checks that role bearers have at least one role (default if none). + Groups can be without a role + """ + Class = orm.get_class(bearer) + if Class in {orm.Group, orm.Service}: + pass + else: + for obj in ( + db.query(Class) + .outerjoin(orm.Role, Class.roles) + .group_by(Class.id) + .having(func.count(orm.Role.id) == 0) + ): + assign_default_roles(db, obj) + db.commit() + + +def mock_roles(app, name, kind): + """Loads and assigns default roles for mocked objects""" + Class = orm.get_class(kind) + obj = Class.find(app.db, name=name) + default_roles = get_default_roles() + for role in default_roles: + create_role(app.db, role) + app_log.info('Assigning default roles to mocked %s: %s', kind[:-1], name) + assign_default_roles(db=app.db, entity=obj) diff --git a/jupyterhub/scopes.py b/jupyterhub/scopes.py new file mode 100644 --- /dev/null +++ b/jupyterhub/scopes.py @@ -0,0 +1,609 @@ +""" +General scope definitions and utilities + +Scope variable nomenclature +--------------------------- +scopes: list of scopes with abbreviations (e.g., in role definition) +expanded scopes: set of expanded scopes without abbreviations (i.e., resolved metascopes, filters and subscopes) +parsed scopes: dictionary JSON like format of expanded scopes +intersection : set of expanded scopes as intersection of 2 expanded scope sets +identify scopes: set of expanded scopes needed for identify (whoami) endpoints +""" +import functools +import inspect +import warnings +from enum import Enum +from functools import lru_cache + +import sqlalchemy as sa +from tornado import web +from tornado.log import app_log + +from . import orm +from . import roles + +"""when modifying the scope definitions, make sure that `docs/source/rbac/generate-scope-table.py` is run + so that changes are reflected in the documentation and REST API description.""" +scope_definitions = { + '(no_scope)': {'description': 'Identify the owner of the requesting entity.'}, + 'self': { + 'description': 'Your own resources', + 'doc_description': 'The user’s own resources _(metascope for users, resolves to (no_scope) for services)_', + }, + 'all': { + 'description': 'Anything you have access to', + 'doc_description': 'Everything that the token-owning entity can access _(metascope for tokens)_', + }, + 'admin:users': { + 'description': 'Read, write, create and delete users and their authentication state, not including their servers or tokens.', + 'subscopes': ['admin:auth_state', 'users', 'read:roles:users'], + }, + 'admin:auth_state': {'description': 'Read a user’s authentication state.'}, + 'users': { + 'description': 'Read and write permissions to user models (excluding servers, tokens and authentication state).', + 'subscopes': ['read:users', 'users:activity'], + }, + 'read:users': { + 'description': 'Read user models (excluding including servers, tokens and authentication state).', + 'subscopes': [ + 'read:users:name', + 'read:users:groups', + 'read:users:activity', + ], + }, + 'read:users:name': {'description': 'Read names of users.'}, + 'read:users:groups': {'description': 'Read users’ group membership.'}, + 'read:users:activity': {'description': 'Read time of last user activity.'}, + 'read:roles': { + 'description': 'Read role assignments.', + 'subscopes': ['read:roles:users', 'read:roles:services', 'read:roles:groups'], + }, + 'read:roles:users': {'description': 'Read user role assignments.'}, + 'read:roles:services': {'description': 'Read service role assignments.'}, + 'read:roles:groups': {'description': 'Read group role assignments.'}, + 'users:activity': { + 'description': 'Update time of last user activity.', + 'subscopes': ['read:users:activity'], + }, + 'admin:servers': { + 'description': 'Read, start, stop, create and delete user servers and their state.', + 'subscopes': ['admin:server_state', 'servers'], + }, + 'admin:server_state': {'description': 'Read and write users’ server state.'}, + 'servers': { + 'description': 'Start and stop user servers.', + 'subscopes': ['read:servers'], + }, + 'read:servers': { + 'description': 'Read users’ names and their server models (excluding the server state).', + 'subscopes': ['read:users:name'], + }, + 'tokens': { + 'description': 'Read, write, create and delete user tokens.', + 'subscopes': ['read:tokens'], + }, + 'read:tokens': {'description': 'Read user tokens.'}, + 'admin:groups': { + 'description': 'Read and write group information, create and delete groups.', + 'subscopes': ['groups', 'read:roles:groups'], + }, + 'groups': { + 'description': 'Read and write group information, including adding/removing users to/from groups.', + 'subscopes': ['read:groups'], + }, + 'read:groups': { + 'description': 'Read group models.', + 'subscopes': ['read:groups:name'], + }, + 'read:groups:name': {'description': 'Read group names.'}, + 'read:services': { + 'description': 'Read service models.', + 'subscopes': ['read:services:name'], + }, + 'read:services:name': {'description': 'Read service names.'}, + 'read:hub': {'description': 'Read detailed information about the Hub.'}, + 'access:servers': { + 'description': 'Access user servers via API or browser.', + }, + 'access:services': { + 'description': 'Access services via API or browser.', + }, + 'proxy': { + 'description': 'Read information about the proxy’s routing table, sync the Hub with the proxy and notify the Hub about a new proxy.' + }, + 'shutdown': {'description': 'Shutdown the hub.'}, +} + + +class Scope(Enum): + ALL = True + + +def _intersect_expanded_scopes(scopes_a, scopes_b, db=None): + """Intersect two sets of scopes by comparing their permissions + + Arguments: + scopes_a, scopes_b: sets of expanded scopes + db (optional): db connection for resolving group membership + + Returns: + intersection: set of expanded scopes as intersection of the arguments + + If db is given, group membership will be accounted for in intersections, + Otherwise, it can result in lower than intended permissions, + (i.e. users!group=x & users!user=y will be empty, even if user y is in group x.) + """ + empty_set = frozenset() + + # cached lookups for group membership of users and servers + @lru_cache() + def groups_for_user(username): + """Get set of group names for a given username""" + user = db.query(orm.User).filter_by(name=username).first() + if user is None: + return empty_set + else: + return {group.name for group in user.groups} + + @lru_cache() + def groups_for_server(server): + """Get set of group names for a given server""" + username, _, servername = server.partition("/") + return groups_for_user(username) + + parsed_scopes_a = parse_scopes(scopes_a) + parsed_scopes_b = parse_scopes(scopes_b) + + common_bases = parsed_scopes_a.keys() & parsed_scopes_b.keys() + + common_filters = {} + warned = False + for base in common_bases: + filters_a = parsed_scopes_a[base] + filters_b = parsed_scopes_b[base] + if filters_a == Scope.ALL: + common_filters[base] = filters_b + elif filters_b == Scope.ALL: + common_filters[base] = filters_a + else: + common_entities = filters_a.keys() & filters_b.keys() + all_entities = filters_a.keys() | filters_b.keys() + + # if we don't have a db session, we can't check group membership + # warn *if* there are non-overlapping user= and group= filters that we can't check + if ( + db is None + and not warned + and 'group' in all_entities + and ('user' in all_entities or 'server' in all_entities) + ): + # this could resolve wrong if there's a user or server only on one side and a group only on the other + # check both directions: A has group X not in B group list AND B has user Y not in A user list + for a, b in [(filters_a, filters_b), (filters_b, filters_a)]: + for b_key in ('user', 'server'): + if ( + not warned + and "group" in a + and b_key in b + and a["group"].difference(b.get("group", [])) + and b[b_key].difference(a.get(b_key, [])) + ): + warnings.warn( + f"{base}[!{b_key}={b[b_key]}, !group={a['group']}] combinations of filters present," + " without db access. Intersection between not considered." + " May result in lower than intended permissions.", + UserWarning, + ) + warned = True + + common_filters[base] = { + entity: filters_a[entity] & filters_b[entity] + for entity in common_entities + } + + # resolve hierarchies (group/user/server) in both directions + common_servers = common_filters[base].get("server", set()) + common_users = common_filters[base].get("user", set()) + + for a, b in [(filters_a, filters_b), (filters_b, filters_a)]: + if 'server' in a and b.get('server') != a['server']: + # skip already-added servers (includes overlapping servers) + servers = a['server'].difference(common_servers) + + # resolve user/server hierarchy + if servers and 'user' in b: + for server in servers: + username, _, servername = server.partition("/") + if username in b['user']: + common_servers.add(server) + + # resolve group/server hierarchy if db available + servers = servers.difference(common_servers) + if db is not None and servers and 'group' in b: + for server in servers: + server_groups = groups_for_server(server) + if server_groups & b['group']: + common_servers.add(server) + + # resolve group/user hierarchy if db available and user sets aren't identical + if ( + db is not None + and 'user' in a + and 'group' in b + and b.get('user') != a['user'] + ): + # skip already-added users (includes overlapping users) + users = a['user'].difference(common_users) + for username in users: + groups = groups_for_user(username) + if groups & b["group"]: + common_users.add(username) + + # add server filter if there wasn't one before + if common_servers and "server" not in common_filters[base]: + common_filters[base]["server"] = common_servers + + # add user filter if it's non-empty and there wasn't one before + if common_users and "user" not in common_filters[base]: + common_filters[base]["user"] = common_users + + return unparse_scopes(common_filters) + + +def get_scopes_for(orm_object): + """Find scopes for a given user or token from their roles and resolve permissions + + Arguments: + orm_object: orm object or User wrapper + + Returns: + expanded scopes (set) for the orm object + or + intersection (set) if orm_object == orm.APIToken + """ + expanded_scopes = set() + if orm_object is None: + return expanded_scopes + + if not isinstance(orm_object, orm.Base): + from .user import User + + if isinstance(orm_object, User): + orm_object = orm_object.orm_user + else: + raise TypeError( + f"Only allow orm objects or User wrappers, got {orm_object}" + ) + + if isinstance(orm_object, orm.APIToken): + app_log.warning(f"Authenticated with token {orm_object}") + owner = orm_object.user or orm_object.service + token_scopes = roles.expand_roles_to_scopes(orm_object) + if orm_object.client_id != "jupyterhub": + # oauth tokens can be used to access the service issuing the token, + # assuming the owner itself still has permission to do so + spawner = orm_object.oauth_client.spawner + if spawner: + token_scopes.add( + f"access:servers!server={spawner.user.name}/{spawner.name}" + ) + else: + service = orm_object.oauth_client.service + if service: + token_scopes.add(f"access:services!service={service.name}") + else: + app_log.warning( + f"Token {orm_object} has no associated service or spawner!" + ) + + owner_scopes = roles.expand_roles_to_scopes(owner) + + if token_scopes == {'all'}: + # token_scopes is only 'all', return owner scopes as-is + # short-circuit common case where we don't need to compute an intersection + return owner_scopes + + if 'all' in token_scopes: + token_scopes.remove('all') + token_scopes |= owner_scopes + + intersection = _intersect_expanded_scopes( + token_scopes, + owner_scopes, + db=sa.inspect(orm_object).session, + ) + discarded_token_scopes = token_scopes - intersection + + # Not taking symmetric difference here because token owner can naturally have more scopes than token + if discarded_token_scopes: + app_log.warning( + "discarding scopes [%s], not present in owner roles" + % ", ".join(discarded_token_scopes) + ) + expanded_scopes = intersection + else: + expanded_scopes = roles.expand_roles_to_scopes(orm_object) + return expanded_scopes + + +def _needs_scope_expansion(filter_, filter_value, sub_scope): + """ + Check if there is a requirements to expand the `group` scope to individual `user` scopes. + Assumptions: + filter_ != Scope.ALL + """ + if not (filter_ == 'user' and 'group' in sub_scope): + return False + if 'user' in sub_scope: + return filter_value not in sub_scope['user'] + else: + return True + + +def _check_user_in_expanded_scope(handler, user_name, scope_group_names): + """Check if username is present in set of allowed groups""" + user = handler.find_user(user_name) + if user is None: + raise web.HTTPError(404, "No access to resources or resources not found") + group_names = {group.name for group in user.groups} + return bool(set(scope_group_names) & group_names) + + +def _check_scope_access(api_handler, req_scope, **kwargs): + """Check if scopes satisfy requirements + Returns True for (potentially restricted) access, False for refused access + """ + # Parse user name and server name together + try: + api_name = api_handler.request.path + except AttributeError: + api_name = type(api_handler).__name__ + if 'user' in kwargs and 'server' in kwargs: + kwargs['server'] = "{}/{}".format(kwargs['user'], kwargs['server']) + if req_scope not in api_handler.parsed_scopes: + app_log.debug("No access to %s via %s", api_name, req_scope) + return False + if api_handler.parsed_scopes[req_scope] == Scope.ALL: + app_log.debug("Unrestricted access to %s via %s", api_name, req_scope) + return True + # Apply filters + sub_scope = api_handler.parsed_scopes[req_scope] + if not kwargs: + app_log.debug( + "Client has restricted access to %s via %s. Internal filtering may apply", + api_name, + req_scope, + ) + return True + for (filter_, filter_value) in kwargs.items(): + if filter_ in sub_scope and filter_value in sub_scope[filter_]: + app_log.debug("Argument-based access to %s via %s", api_name, req_scope) + return True + if _needs_scope_expansion(filter_, filter_value, sub_scope): + group_names = sub_scope['group'] + if _check_user_in_expanded_scope(api_handler, filter_value, group_names): + app_log.debug("Restricted client access supported with group expansion") + return True + app_log.debug( + "Client access refused; filters do not match API endpoint %s request" % api_name + ) + raise web.HTTPError(404, "No access to resources or resources not found") + + +def parse_scopes(scope_list): + """ + Parses scopes and filters in something akin to JSON style + + For instance, scope list ["users", "groups!group=foo", "servers!server=user/bar", "servers!server=user/baz"] + would lead to scope model + { + "users":scope.ALL, + "admin:users":{ + "user":[ + "alice" + ] + }, + "servers":{ + "server":[ + "user/bar", + "user/baz" + ] + } + } + """ + parsed_scopes = {} + for scope in scope_list: + base_scope, _, filter_ = scope.partition('!') + if not filter_: + parsed_scopes[base_scope] = Scope.ALL + elif base_scope not in parsed_scopes: + parsed_scopes[base_scope] = {} + + if parsed_scopes[base_scope] != Scope.ALL: + key, _, value = filter_.partition('=') + if key not in parsed_scopes[base_scope]: + parsed_scopes[base_scope][key] = set([value]) + else: + parsed_scopes[base_scope][key].add(value) + return parsed_scopes + + +def unparse_scopes(parsed_scopes): + """Turn a parsed_scopes dictionary back into a expanded scopes set""" + expanded_scopes = set() + for base, filters in parsed_scopes.items(): + if filters == Scope.ALL: + expanded_scopes.add(base) + else: + for entity, names_list in filters.items(): + for name in names_list: + expanded_scopes.add(f'{base}!{entity}={name}') + return expanded_scopes + + +def needs_scope(*scopes): + """Decorator to restrict access to users or services with the required scope""" + + for scope in scopes: + if scope not in scope_definitions: + raise ValueError(f"Scope {scope} is not a valid scope") + + def scope_decorator(func): + @functools.wraps(func) + def _auth_func(self, *args, **kwargs): + sig = inspect.signature(func) + bound_sig = sig.bind(self, *args, **kwargs) + bound_sig.apply_defaults() + # Load scopes in case they haven't been loaded yet + if not hasattr(self, 'expanded_scopes'): + self.expanded_scopes = {} + self.parsed_scopes = {} + + s_kwargs = {} + for resource in {'user', 'server', 'group', 'service'}: + resource_name = resource + '_name' + if resource_name in bound_sig.arguments: + resource_value = bound_sig.arguments[resource_name] + s_kwargs[resource] = resource_value + for scope in scopes: + app_log.debug("Checking access via scope %s", scope) + has_access = _check_scope_access(self, scope, **s_kwargs) + if has_access: + return func(self, *args, **kwargs) + try: + end_point = self.request.path + except AttributeError: + end_point = self.__name__ + app_log.warning( + "Not authorizing access to {}. Requires any of [{}], not derived from scopes [{}]".format( + end_point, ", ".join(scopes), ", ".join(self.expanded_scopes) + ) + ) + raise web.HTTPError( + 403, + "Action is not authorized with current scopes; requires any of [{}]".format( + ", ".join(scopes) + ), + ) + + return _auth_func + + return scope_decorator + + +def identify_scopes(obj): + """Return 'identify' scopes for an orm object + + Arguments: + obj: orm.User or orm.Service + + Returns: + identify scopes (set): set of scopes needed for 'identify' endpoints + """ + if isinstance(obj, orm.User): + return {f"read:users:{field}!user={obj.name}" for field in {"name", "groups"}} + elif isinstance(obj, orm.Service): + return {f"read:services:{field}!service={obj.name}" for field in {"name"}} + else: + raise TypeError(f"Expected orm.User or orm.Service, got {obj!r}") + + +def check_scope_filter(sub_scope, orm_resource, kind): + """Return whether a sub_scope filter applies to a given resource. + + param sub_scope: parsed_scopes filter (i.e. dict or Scope.ALL) + param orm_resource: User or Service or Group or Spawner + param kind: 'user' or 'service' or 'group' or 'server'. + + Returns True or False + """ + if sub_scope is Scope.ALL: + return True + elif kind in sub_scope and orm_resource.name in sub_scope[kind]: + return True + + if kind == 'server': + server_format = f"{orm_resource.user.name}/{orm_resource.name}" + if server_format in sub_scope.get(kind, []): + return True + # Fall back on checking if we have user access + if 'user' in sub_scope and orm_resource.user.name in sub_scope['user']: + return True + # Fall back on checking if we have group access for this user + orm_resource = orm_resource.user + kind = 'user' + + if kind == 'user' and 'group' in sub_scope: + group_names = {group.name for group in orm_resource.groups} + user_in_group = bool(group_names & set(sub_scope['group'])) + if user_in_group: + return True + return False + + +def describe_parsed_scopes(parsed_scopes, username=None): + """Return list of descriptions of parsed scopes + + Highly detailed, often redundant descriptions + """ + descriptions = [] + for scope, filters in parsed_scopes.items(): + base_text = scope_definitions[scope]["description"] + if filters == Scope.ALL: + # no filter + filter_text = "" + else: + filter_chunks = [] + for kind, names in filters.items(): + if kind == 'user' and names == {username}: + filter_chunks.append("only you") + else: + kind_text = kind + if kind == 'group': + kind_text = "users in group" + if len(names) == 1: + filter_chunks.append(f"{kind}: {list(names)[0]}") + else: + filter_chunks.append(f"{kind}s: {', '.join(names)}") + filter_text = "; or ".join(filter_chunks) + descriptions.append( + { + "scope": scope, + "description": scope_definitions[scope]["description"], + "filter": filter_text, + } + ) + return descriptions + + +def describe_raw_scopes(raw_scopes, username=None): + """Return list of descriptions of raw scopes + + A much shorter list than describe_parsed_scopes + """ + descriptions = [] + for raw_scope in raw_scopes: + scope, _, filter_ = raw_scope.partition("!") + base_text = scope_definitions[scope]["description"] + if not filter_: + # no filter + filter_text = "" + elif filter_ == "user": + filter_text = "only you" + else: + kind, _, name = filter_.partition("=") + if kind == "user" and name == username: + filter_text = "only you" + else: + kind_text = kind + if kind == 'group': + kind_text = "users in group" + filter_text = f"{kind_text} {name}" + descriptions.append( + { + "scope": scope, + "description": scope_definitions[scope]["description"], + "filter": filter_text, + } + ) + return descriptions diff --git a/jupyterhub/services/auth.py b/jupyterhub/services/auth.py --- a/jupyterhub/services/auth.py +++ b/jupyterhub/services/auth.py @@ -1,7 +1,7 @@ """Authenticating services with JupyterHub. -Cookies are sent to the Hub for verification. The Hub replies with a JSON -model describing the authenticated user. +Tokens are sent to the Hub for verification. +The Hub replies with a JSON model describing the authenticated user. ``HubAuth`` can be used in any application, even outside tornado. @@ -10,6 +10,7 @@ """ import base64 +import hashlib import json import os import random @@ -20,7 +21,6 @@ import uuid import warnings from unittest import mock -from urllib.parse import quote from urllib.parse import urlencode import requests @@ -33,13 +33,50 @@ from traitlets import Instance from traitlets import Integer from traitlets import observe +from traitlets import Set from traitlets import Unicode from traitlets import validate from traitlets.config import SingletonConfigurable +from ..scopes import _intersect_expanded_scopes from ..utils import url_path_join +def check_scopes(required_scopes, scopes): + """Check that required_scope(s) are in scopes + + Returns the subset of scopes matching required_scopes, + which is truthy if any scopes match any required scopes. + + Correctly resolves scope filters *except* for groups -> user, + e.g. require: access:server!user=x, have: access:server!group=y + will not grant access to user x even if user x is in group y. + + Parameters + ---------- + + required_scopes: set + The set of scopes required. + scopes: set + The set (or list) of scopes to check against required_scopes + + Returns + ------- + relevant_scopes: set + The set of scopes in required_scopes that are present in scopes, + which is truthy if any required scopes are present, + and falsy otherwise. + """ + if isinstance(required_scopes, str): + required_scopes = {required_scopes} + + intersection = _intersect_expanded_scopes(required_scopes, scopes) + # re-intersect with required_scopes in case the intersection + # applies stricter filters than required_scopes declares + # e.g. required_scopes = {'read:users'} and intersection has only {'read:users!user=x'} + return set(required_scopes) & intersection + + class _ExpiringDict(dict): """Dict-like cache for Hub API requests @@ -113,9 +150,15 @@ class HubAuth(SingletonConfigurable): This can be used by any application. + Use this base class only for direct, token-authenticated applications + (web APIs). + For applications that support direct visits from browsers, + use HubOAuth to enable OAuth redirect-based authentication. + + If using tornado, use via :class:`HubAuthenticated` mixin. - If using manually, use the ``.user_for_cookie(cookie_value)`` method - to identify the user corresponding to a given cookie value. + If using manually, use the ``.user_for_token(token_value)`` method + to identify the user owning a given token. The following config must be set: @@ -129,15 +172,12 @@ class HubAuth(SingletonConfigurable): - cookie_cache_max_age: the number of seconds responses from the Hub should be cached. - login_url (the *public* ``/hub/login`` URL of the Hub). - - cookie_name: the name of the cookie I should be using, - if different from the default (unlikely). - """ hub_host = Unicode( '', help="""The public host of JupyterHub - + Only used if JupyterHub is spreading servers across subdomains. """, ).tag(config=True) @@ -239,10 +279,6 @@ def _default_login_url(self): """, ).tag(config=True) - cookie_name = Unicode( - 'jupyterhub-services', help="""The name of the cookie I should be looking for""" - ).tag(config=True) - cookie_options = Dict( help="""Additional options to pass when setting cookies. @@ -286,12 +322,30 @@ def _deprecated_cookie_cache(self, change): def _default_cache(self): return _ExpiringDict(self.cache_max_age) - def _check_hub_authorization(self, url, cache_key=None, use_cache=True): + oauth_scopes = Set( + Unicode(), + help="""OAuth scopes to use for allowing access. + + Get from $JUPYTERHUB_OAUTH_SCOPES by default. + """, + ).tag(config=True) + + @default('oauth_scopes') + def _default_scopes(self): + env_scopes = os.getenv('JUPYTERHUB_OAUTH_SCOPES') + if env_scopes: + return set(json.loads(env_scopes)) + service_name = os.getenv("JUPYTERHUB_SERVICE_NAME") + if service_name: + return {f'access:services!service={service_name}'} + return set() + + def _check_hub_authorization(self, url, api_token, cache_key=None, use_cache=True): """Identify a user with the Hub Args: url (str): The API URL to check the Hub for authorization - (e.g. http://127.0.0.1:8081/hub/api/authorizations/token/abc-def) + (e.g. http://127.0.0.1:8081/hub/api/user) cache_key (str): The key for checking the cache use_cache (bool): Specify use_cache=False to skip cached cookie values (default: True) @@ -309,7 +363,12 @@ def _check_hub_authorization(self, url, cache_key=None, use_cache=True): except KeyError: app_log.debug("HubAuth cache miss: %s", cache_key) - data = self._api_request('GET', url, allow_404=True) + data = self._api_request( + 'GET', + url, + headers={"Authorization": "token " + api_token}, + allow_403=True, + ) if data is None: app_log.warning("No Hub user identified for request") else: @@ -321,7 +380,7 @@ def _check_hub_authorization(self, url, cache_key=None, use_cache=True): def _api_request(self, method, url, **kwargs): """Make an API request""" - allow_404 = kwargs.pop('allow_404', False) + allow_403 = kwargs.pop('allow_403', False) headers = kwargs.setdefault('headers', {}) headers.setdefault('Authorization', 'token %s' % self.api_token) if "cert" not in kwargs and self.certfile and self.keyfile: @@ -345,7 +404,7 @@ def _api_request(self, method, url, **kwargs): raise HTTPError(500, msg) data = None - if r.status_code == 404 and allow_404: + if r.status_code == 403 and allow_403: pass elif r.status_code == 403: app_log.error( @@ -389,26 +448,9 @@ def _api_request(self, method, url, **kwargs): return data def user_for_cookie(self, encrypted_cookie, use_cache=True, session_id=''): - """Ask the Hub to identify the user for a given cookie. - - Args: - encrypted_cookie (str): the cookie value (not decrypted, the Hub will do that) - use_cache (bool): Specify use_cache=False to skip cached cookie values (default: True) - - Returns: - user_model (dict): The user model, if a user is identified, None if authentication fails. - - The 'name' field contains the user's name. - """ - return self._check_hub_authorization( - url=url_path_join( - self.api_url, - "authorizations/cookie", - self.cookie_name, - quote(encrypted_cookie, safe=''), - ), - cache_key='cookie:{}:{}'.format(session_id, encrypted_cookie), - use_cache=use_cache, + """Deprecated and removed. Use HubOAuth to authenticate browsers.""" + raise RuntimeError( + "Identifying users by shared cookie is removed in JupyterHub 2.0. Use OAuth tokens." ) def user_for_token(self, token, use_cache=True, session_id=''): @@ -425,14 +467,19 @@ def user_for_token(self, token, use_cache=True, session_id=''): """ return self._check_hub_authorization( url=url_path_join( - self.api_url, "authorizations/token", quote(token, safe='') + self.api_url, + "user", + ), + api_token=token, + cache_key='token:{}:{}'.format( + session_id, + hashlib.sha256(token.encode("utf8", "replace")).hexdigest(), ), - cache_key='token:{}:{}'.format(session_id, token), use_cache=use_cache, ) auth_header_name = 'Authorization' - auth_header_pat = re.compile(r'token\s+(.+)', re.IGNORECASE) + auth_header_pat = re.compile(r'(?:token|bearer)\s+(.+)', re.IGNORECASE) def get_token(self, handler): """Get the user token from a request @@ -453,10 +500,8 @@ def get_token(self, handler): def _get_user_cookie(self, handler): """Get the user model from a cookie""" - encrypted_cookie = handler.get_cookie(self.cookie_name) - session_id = self.get_session_id(handler) - if encrypted_cookie: - return self.user_for_cookie(encrypted_cookie, session_id=session_id) + # overridden in HubOAuth to store the access token after oauth + return None def get_session_id(self, handler): """Get the jupyterhub session id @@ -505,10 +550,17 @@ def get_user(self, handler): app_log.debug("No user identified") return user_model + def check_scopes(self, required_scopes, user): + """Check whether the user has required scope(s)""" + return check_scopes(required_scopes, set(user["scopes"])) + class HubOAuth(HubAuth): """HubAuth using OAuth for login instead of cookies set by the Hub. + Use this class if you want users to be able to visit your service with a browser. + They will be authenticated via OAuth with the Hub. + .. versionadded: 0.8 """ @@ -557,7 +609,7 @@ def _get_user_cookie(self, handler): oauth_client_id = Unicode( help="""The OAuth client ID for this application. - + Use JUPYTERHUB_CLIENT_ID by default. """ ).tag(config=True) @@ -574,7 +626,7 @@ def _ensure_not_empty(self, proposal): oauth_redirect_uri = Unicode( help="""OAuth redirect URI - + Should generally be /base_url/oauth_callback """ ).tag(config=True) @@ -772,12 +824,26 @@ def __str__(self): ) -class HubAuthenticated(object): +class HubAuthenticated: """Mixin for tornado handlers that are authenticated with JupyterHub A handler that mixes this in must have the following attributes/properties: - .hub_auth: A HubAuth instance + - .hub_scopes: A set of JupyterHub 2.0 OAuth scopes to allow. + Default comes from .hub_auth.oauth_scopes, + which in turn is set by $JUPYTERHUB_OAUTH_SCOPES + Default values include: + - 'access:services', 'access:services!service={service_name}' for services + - 'access:servers', 'access:servers!user={user}', + 'access:servers!server={user}/{server_name}' + for single-user servers + + If hub_scopes is not used (e.g. JupyterHub 1.x), + these additional properties can be used: + + - .allow_admin: If True, allow any admin user. + Default: False. - .hub_users: A set of usernames to allow. If left unspecified or None, username will not be checked. - .hub_groups: A set of group names to allow. @@ -802,13 +868,19 @@ def get(self): hub_groups = None # set of allowed groups allow_admin = False # allow any admin user access + @property + def hub_scopes(self): + """Set of allowed scopes (use hub_auth.oauth_scopes by default)""" + return self.hub_auth.oauth_scopes or None + @property def allow_all(self): """Property indicating that all successfully identified user or service should be allowed. """ return ( - self.hub_services is None + self.hub_scopes is None + and self.hub_services is None and self.hub_users is None and self.hub_groups is None ) @@ -849,22 +921,43 @@ def check_hub_user(self, model): Returns the input if the user should be allowed, None otherwise. - Override if you want to check anything other than the username's presence in hub_users list. + Override for custom logic in authenticating users. Args: - model (dict): the user or service model returned from :class:`HubAuth` + user_model (dict): the user or service model returned from :class:`HubAuth` Returns: user_model (dict): The user model if the user should be allowed, None otherwise. """ name = model['name'] kind = model.setdefault('kind', 'user') + if self.allow_all: app_log.debug( "Allowing Hub %s %s (all Hub users and services allowed)", kind, name ) return model + if self.hub_scopes: + scopes = self.hub_auth.check_scopes(self.hub_scopes, model) + if scopes: + app_log.debug( + f"Allowing Hub {kind} {name} based on oauth scopes {scopes}" + ) + return model + else: + app_log.warning( + f"Not allowing Hub {kind} {name}: missing required scopes" + ) + app_log.debug( + f"Hub {kind} {name} needs scope(s) {self.hub_scopes}, has scope(s) {model['scopes']}" + ) + # if hub_scopes are used, *only* hub_scopes are used + # note: this means successful authentication, but insufficient permission + raise UserNotAllowed(model) + + # proceed with the pre-2.0 way if hub_scopes is not set + if self.allow_admin and model.get('admin', False): app_log.debug("Allowing Hub admin %s", name) return model diff --git a/jupyterhub/services/service.py b/jupyterhub/services/service.py --- a/jupyterhub/services/service.py +++ b/jupyterhub/services/service.py @@ -38,6 +38,7 @@ } """ +import asyncio import copy import os import pipes @@ -50,7 +51,9 @@ from traitlets import Dict from traitlets import HasTraits from traitlets import Instance +from traitlets import List from traitlets import Unicode +from traitlets import validate from traitlets.config import LoggingConfigurable from .. import orm @@ -96,6 +99,14 @@ class _ServiceSpawner(LocalProcessSpawner): cwd = Unicode() cmd = Command(minlen=0) + _service_name = Unicode() + + @default("oauth_scopes") + def _default_oauth_scopes(self): + return [ + "access:services", + f"access:services!service={self._service_name}", + ] def make_preexec_fn(self, name): if not name: @@ -188,6 +199,19 @@ class Service(LoggingConfigurable): """ ).tag(input=True) + oauth_roles = List( + help="""OAuth allowed roles. + + This sets the maximum and default roles + assigned to oauth tokens issued for this service + (i.e. tokens stored in browsers after authenticating with the server), + defining what actions the service can take on behalf of logged-in users. + + Default is an empty list, meaning minimal permissions to identify users, + no actions can be taken on their behalf. + """ + ).tag(input=True) + api_token = Unicode( help="""The API token to use for the service. @@ -267,6 +291,7 @@ def kind(self): base_url = Unicode() db = Any() orm = Any() + roles = Any() cookie_options = Dict() oauth_provider = Any() @@ -283,6 +308,15 @@ def kind(self): def _default_client_id(self): return 'service-%s' % self.name + @validate("oauth_client_id") + def _validate_client_id(self, proposal): + if not proposal.value.startswith("service-"): + raise ValueError( + f"service {self.name} has oauth_client_id='{proposal.value}'." + " Service oauth client ids must start with 'service-'" + ) + return proposal.value + oauth_redirect_uri = Unicode( help="""OAuth redirect URI for this service. @@ -305,6 +339,10 @@ def oauth_available(self): """ return bool(self.server is not None or self.oauth_redirect_uri) + @property + def oauth_client(self): + return self.orm.oauth_client + @property def server(self): if self.orm.server: @@ -332,7 +370,7 @@ def __repr__(self): managed=' managed' if self.managed else '', ) - def start(self): + async def start(self): """Start a managed service""" if not self.managed: raise RuntimeError("Cannot start unmanaged service %s" % self) @@ -359,6 +397,7 @@ def start(self): environment=env, api_token=self.api_token, oauth_client_id=self.oauth_client_id, + _service_name=self.name, cookie_options=self.cookie_options, cwd=self.cwd, hub=self.hub, @@ -369,6 +408,8 @@ def start(self): internal_certs_location=self.app.internal_certs_location, internal_trust_bundles=self.app.internal_trust_bundles, ) + if self.spawner.internal_ssl: + self.spawner.cert_paths = await self.spawner.create_certs() self.spawner.start() self.proc = self.spawner.proc self.spawner.add_poll_callback(self._proc_stopped) @@ -379,7 +420,8 @@ def _proc_stopped(self): self.log.error( "Service %s exited with status %i", self.name, self.proc.returncode ) - self.start() + # schedule start + asyncio.ensure_future(self.start()) async def stop(self): """Stop a managed service""" diff --git a/jupyterhub/singleuser/mixins.py b/jupyterhub/singleuser/mixins.py --- a/jupyterhub/singleuser/mixins.py +++ b/jupyterhub/singleuser/mixins.py @@ -161,7 +161,6 @@ def hub_auth(self): aliases = { 'user': 'SingleUserNotebookApp.user', 'group': 'SingleUserNotebookApp.group', - 'cookie-name': 'HubAuth.cookie_name', 'hub-prefix': 'SingleUserNotebookApp.hub_prefix', 'hub-host': 'SingleUserNotebookApp.hub_host', 'hub-api-url': 'SingleUserNotebookApp.hub_api_url', diff --git a/jupyterhub/spawner.py b/jupyterhub/spawner.py --- a/jupyterhub/spawner.py +++ b/jupyterhub/spawner.py @@ -216,8 +216,32 @@ def name(self): admin_access = Bool(False) api_token = Unicode() oauth_client_id = Unicode() + + oauth_scopes = List(Unicode()) + + @default("oauth_scopes") + def _default_oauth_scopes(self): + return [ + f"access:servers!server={self.user.name}/{self.name}", + f"access:servers!user={self.user.name}", + ] + handler = Any() + oauth_roles = Union( + [Callable(), List()], + help="""Allowed roles for oauth tokens. + + This sets the maximum and default roles + assigned to oauth tokens issued by a single-user server's + oauth client (i.e. tokens stored in browsers after authenticating with the server), + defining what actions the server can take on behalf of logged-in users. + + Default is an empty list, meaning minimal permissions to identify users, + no actions can be taken on their behalf. + """, + ).tag(config=True) + will_resume = Bool( False, help="""Whether the Spawner will resume on next start @@ -789,6 +813,8 @@ def get_env(self): self.user.url, self.name, 'oauth_callback' ) + env['JUPYTERHUB_OAUTH_SCOPES'] = json.dumps(self.oauth_scopes) + # Info previously passed on args env['JUPYTERHUB_USER'] = self.user.name env['JUPYTERHUB_SERVER_NAME'] = self.name diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -560,7 +560,7 @@ async def spawn(self, server_name='', options=None, handler=None): orm_server = orm.Server(base_url=base_url) db.add(orm_server) note = "Server at %s" % base_url - api_token = self.new_api_token(note=note) + api_token = self.new_api_token(note=note, roles=['server']) db.commit() spawner = self.spawners[server_name] @@ -590,16 +590,19 @@ async def spawn(self, server_name='', options=None, handler=None): client_id = spawner.oauth_client_id oauth_provider = self.settings.get('oauth_provider') if oauth_provider: - oauth_client = oauth_provider.fetch_by_client_id(client_id) - # create a new OAuth client + secret on every launch - # containers that resume will be updated below - oauth_provider.add_client( + allowed_roles = spawner.oauth_roles + if callable(allowed_roles): + allowed_roles = allowed_roles(spawner) + + oauth_client = oauth_provider.add_client( client_id, api_token, url_path_join(self.url, server_name, 'oauth_callback'), + allowed_roles=allowed_roles, description="Server at %s" % (url_path_join(self.base_url, server_name) + '/'), ) + spawner.orm_spawner.oauth_client = oauth_client db.commit() # trigger pre-spawn hook on authenticator @@ -608,7 +611,7 @@ async def spawn(self, server_name='', options=None, handler=None): spawner._start_pending = True if authenticator: - # pre_spawn_start can thow errors that can lead to a redirect loop + # pre_spawn_start can throw errors that can lead to a redirect loop # if left uncaught (see https://github.com/jupyterhub/jupyterhub/issues/2683) await maybe_future(authenticator.pre_spawn_start(self, spawner)) diff --git a/jupyterhub/utils.py b/jupyterhub/utils.py --- a/jupyterhub/utils.py +++ b/jupyterhub/utils.py @@ -253,9 +253,10 @@ def auth_decorator(check_auth): def decorator(method): def decorated(self, *args, **kwargs): - check_auth(self) + check_auth(self, **kwargs) return method(self, *args, **kwargs) + # Perhaps replace with functools.wrap decorated.__name__ = method.__name__ decorated.__doc__ = method.__doc__ return decorated @@ -286,14 +287,6 @@ def authenticated_403(self): raise web.HTTPError(403) -@auth_decorator -def admin_only(self): - """Decorator for restricting access to admin users""" - user = self.current_user - if user is None or not user.admin: - raise web.HTTPError(403) - - @auth_decorator def metrics_authentication(self): """Decorator for restricting access to metrics"""
diff --git a/jupyterhub/tests/conftest.py b/jupyterhub/tests/conftest.py --- a/jupyterhub/tests/conftest.py +++ b/jupyterhub/tests/conftest.py @@ -27,9 +27,9 @@ # Distributed under the terms of the Modified BSD License. import asyncio import inspect -import logging import os import sys +from functools import partial from getpass import getuser from subprocess import TimeoutExpired from unittest import mock @@ -44,11 +44,14 @@ from . import mocking from .. import crypto from .. import orm +from ..roles import create_role +from ..roles import get_default_roles +from ..roles import mock_roles +from ..roles import update_roles from ..utils import random_port from .mocking import MockHub from .test_services import mockservice_cmd from .utils import add_user -from .utils import ssl_setup # global db session object _db = None @@ -123,7 +126,13 @@ def db(): """Get a db session""" global _db if _db is None: - _db = orm.new_session_factory('sqlite:///:memory:')() + # make sure some initial db contents are filled out + # specifically, the 'default' jupyterhub oauth client + app = MockHub(db_url='sqlite:///:memory:') + app.init_db() + _db = app.db + for role in get_default_roles(): + create_role(_db, role) user = orm.User(name=getuser()) _db.add(user) _db.commit() @@ -162,9 +171,14 @@ def cleanup_after(request, io_loop): allows cleanup of servers between tests without having to launch a whole new app """ + try: yield finally: + if _db is not None: + # cleanup after failed transactions + _db.rollback() + if not MockHub.initialized(): return app = MockHub.instance() @@ -245,13 +259,16 @@ def _mockservice(request, app, url=False): ): app.services = [spec] app.init_services() + mock_roles(app, name, 'services') assert name in app._service_map service = app._service_map[name] + token = service.orm.api_tokens[0] + update_roles(app.db, token, roles=['token']) async def start(): # wait for proxy to be updated before starting the service await app.proxy.add_all_services(app._service_map) - service.start() + await service.start() io_loop.run_sync(start) @@ -265,7 +282,7 @@ def cleanup(): with raises(TimeoutExpired): service.proc.wait(1) if url: - io_loop.run_sync(service.server.wait_up) + io_loop.run_sync(partial(service.server.wait_up, http=True)) return service @@ -325,3 +342,79 @@ def slow_bad_spawn(app): app.tornado_settings, {'spawner_class': mocking.SlowBadSpawner} ): yield + + +@fixture +def create_temp_role(app): + """Generate a temporary role with certain scopes. + Convenience function that provides setup, database handling and teardown""" + temp_roles = [] + index = [1] + + def temp_role_creator(scopes, role_name=None): + if not role_name: + role_name = f'temp_role_{index[0]}' + index[0] += 1 + temp_role = orm.Role(name=role_name, scopes=list(scopes)) + temp_roles.append(temp_role) + app.db.add(temp_role) + app.db.commit() + return temp_role + + yield temp_role_creator + for role in temp_roles: + app.db.delete(role) + app.db.commit() + + +@fixture +def create_user_with_scopes(app, create_temp_role): + """Generate a temporary user with specific scopes. + Convenience function that provides setup, database handling and teardown""" + temp_users = [] + counter = 0 + get_role = create_temp_role + + def temp_user_creator(*scopes, name=None): + nonlocal counter + if name is None: + counter += 1 + name = f"temp_user_{counter}" + role = get_role(scopes) + orm_user = orm.User(name=name) + app.db.add(orm_user) + app.db.commit() + temp_users.append(orm_user) + update_roles(app.db, orm_user, roles=[role.name]) + return app.users[orm_user.id] + + yield temp_user_creator + for user in temp_users: + app.users.delete(user) + + +@fixture +def create_service_with_scopes(app, create_temp_role): + """Generate a temporary service with specific scopes. + Convenience function that provides setup, database handling and teardown""" + temp_service = [] + counter = 0 + role_function = create_temp_role + + def temp_service_creator(*scopes, name=None): + nonlocal counter + if name is None: + counter += 1 + name = f"temp_service_{counter}" + role = role_function(scopes) + app.services.append({'name': name}) + app.init_services() + orm_service = orm.Service.find(app.db, name) + app.db.commit() + update_roles(app.db, orm_service, roles=[role.name]) + return orm_service + + yield temp_service_creator + for service in temp_service: + app.db.delete(service) + app.db.commit() diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -43,6 +43,7 @@ from .. import metrics from .. import orm +from .. import roles from ..app import JupyterHub from ..auth import PAMAuthenticator from ..objects import Server @@ -305,13 +306,15 @@ def init_services(self): test_clean_db = Bool(True) def init_db(self): - """Ensure we start with a clean user list""" + """Ensure we start with a clean user & role list""" super().init_db() if self.test_clean_db: for user in self.db.query(orm.User): self.db.delete(user) for group in self.db.query(orm.Group): self.db.delete(group) + for role in self.db.query(orm.Role): + self.db.delete(role) self.db.commit() async def initialize(self, argv=None): @@ -329,6 +332,8 @@ async def initialize(self, argv=None): self.db.add(user) self.db.commit() metrics.TOTAL_USERS.inc() + roles.assign_default_roles(self.db, entity=user) + self.db.commit() def stop(self): super().stop() @@ -383,6 +388,10 @@ class MockSingleUserServer(SingleUserNotebookApp): def init_signal(self): pass + @default("log_level") + def _default_log_level(self): + return 10 + class StubSingleUserSpawner(MockSpawner): """Spawner that starts a MockSingleUserServer in a thread.""" @@ -420,6 +429,7 @@ def _run(): app.initialize(args) assert app.hub_auth.oauth_client_id assert app.hub_auth.api_token + assert app.hub_auth.oauth_scopes app.start() self._thread = threading.Thread(target=_run) diff --git a/jupyterhub/tests/mockservice.py b/jupyterhub/tests/mockservice.py --- a/jupyterhub/tests/mockservice.py +++ b/jupyterhub/tests/mockservice.py @@ -21,6 +21,7 @@ import requests from tornado import httpserver from tornado import ioloop +from tornado import log from tornado import web from jupyterhub.services.auth import HubAuthenticated @@ -114,7 +115,9 @@ def main(): if __name__ == '__main__': - from tornado.options import parse_command_line + from tornado.options import parse_command_line, options parse_command_line() + options.logging = 'debug' + log.enable_pretty_logging() main() diff --git a/jupyterhub/tests/populate_db.py b/jupyterhub/tests/populate_db.py --- a/jupyterhub/tests/populate_db.py +++ b/jupyterhub/tests/populate_db.py @@ -6,6 +6,7 @@ """ import os from datetime import datetime +from functools import partial import jupyterhub from jupyterhub import orm @@ -62,32 +63,35 @@ def populate_db(url): db.commit() # create some oauth objects - if jupyterhub.version_info >= (0, 8): - # create oauth client - client = orm.OAuthClient(identifier='oauth-client') - db.add(client) - db.commit() - code = orm.OAuthCode(client_id=client.identifier) - db.add(code) - db.commit() - access_token = orm.OAuthAccessToken( - client_id=client.identifier, - user_id=user.id, + client = orm.OAuthClient(identifier='oauth-client') + db.add(client) + db.commit() + code = orm.OAuthCode(client_id=client.identifier) + db.add(code) + db.commit() + if jupyterhub.version_info < (2, 0): + Token = partial( + orm.OAuthAccessToken, grant_type=orm.GrantType.authorization_code, ) - db.add(access_token) - db.commit() + else: + Token = orm.APIToken + access_token = Token( + client_id=client.identifier, + user_id=user.id, + ) + db.add(access_token) + db.commit() # set some timestamps added in 0.9 - if jupyterhub.version_info >= (0, 9): - assert user.created - assert admin.created - # set last_activity - user.last_activity = datetime.utcnow() - spawner = user.orm_spawners[''] - spawner.started = datetime.utcnow() - spawner.last_activity = datetime.utcnow() - db.commit() + assert user.created + assert admin.created + # set last_activity + user.last_activity = datetime.utcnow() + spawner = user.orm_spawners[''] + spawner.started = datetime.utcnow() + spawner.last_activity = datetime.utcnow() + db.commit() if __name__ == '__main__': diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -25,6 +25,7 @@ from .utils import auth_header from .utils import find_user + # -------------------- # Authentication tests # -------------------- @@ -63,6 +64,7 @@ async def test_auth_api(app): async def test_referer_check(app): url = ujoin(public_host(app), app.hub.base_url) host = urlparse(url).netloc + # add admin user user = find_user(app.db, 'admin') if user is None: user = add_user(app.db, name='admin', admin=True) @@ -149,13 +151,14 @@ def fill_user(model): """ model.setdefault('server', None) model.setdefault('kind', 'user') + model.setdefault('roles', []) model.setdefault('groups', []) model.setdefault('admin', False) model.setdefault('server', None) model.setdefault('pending', None) model.setdefault('created', TIMESTAMP) model.setdefault('last_activity', TIMESTAMP) - model.setdefault('servers', {}) + # model.setdefault('servers', {}) return model @@ -163,20 +166,31 @@ def fill_user(model): @mark.user [email protected] async def test_get_users(app): db = app.db - r = await api_request(app, 'users') + r = await api_request(app, 'users', headers=auth_header(db, 'admin')) assert r.status_code == 200 users = sorted(r.json(), key=lambda d: d['name']) users = [normalize_user(u) for u in users] + user_model = { + 'name': 'user', + 'admin': False, + 'roles': ['user'], + 'last_activity': None, + 'auth_state': None, + } assert users == [ - fill_user({'name': 'admin', 'admin': True}), - fill_user({'name': 'user', 'admin': False, 'last_activity': None}), + fill_user( + {'name': 'admin', 'admin': True, 'roles': ['admin'], 'auth_state': None} + ), + fill_user(user_model), ] - r = await api_request(app, 'users', headers=auth_header(db, 'user')) - assert r.status_code == 403 + assert r.status_code == 200 + r_user_model = r.json()[0] + assert r_user_model['name'] == user_model['name'] # Tests offset for pagination r = await api_request(app, 'users?offset=1') @@ -184,7 +198,11 @@ async def test_get_users(app): users = sorted(r.json(), key=lambda d: d['name']) users = [normalize_user(u) for u in users] - assert users == [fill_user({'name': 'user', 'admin': False})] + assert users == [ + fill_user( + {'name': 'user', 'admin': False, 'auth_state': None, 'roles': ['user']} + ) + ] r = await api_request(app, 'users?offset=20') assert r.status_code == 200 @@ -196,7 +214,11 @@ async def test_get_users(app): users = sorted(r.json(), key=lambda d: d['name']) users = [normalize_user(u) for u in users] - assert users == [fill_user({'name': 'admin', 'admin': True})] + assert users == [ + fill_user( + {'name': 'admin', 'admin': True, 'auth_state': None, 'roles': ['admin']} + ) + ] r = await api_request(app, 'users?limit=0') assert r.status_code == 200 @@ -283,21 +305,28 @@ async def test_get_self(app): oauth_client = orm.OAuthClient(identifier='eurydice') db.add(oauth_client) db.commit() - oauth_token = orm.OAuthAccessToken( + oauth_token = orm.APIToken( user=u.orm_user, - client=oauth_client, + oauth_client=oauth_client, token=token, - grant_type=orm.GrantType.authorization_code, ) db.add(oauth_token) db.commit() - r = await api_request(app, 'user', headers={'Authorization': 'token ' + token}) + r = await api_request( + app, + 'user', + headers={'Authorization': 'token ' + token}, + ) r.raise_for_status() model = r.json() assert model['name'] == u.name # invalid auth gets 403 - r = await api_request(app, 'user', headers={'Authorization': 'token notvalid'}) + r = await api_request( + app, + 'user', + headers={'Authorization': 'token notvalid'}, + ) assert r.status_code == 403 @@ -313,6 +342,7 @@ async def test_get_self_service(app, mockservice): @mark.user [email protected] async def test_add_user(app): db = app.db name = 'newuser' @@ -322,16 +352,25 @@ async def test_add_user(app): assert user is not None assert user.name == name assert not user.admin + # assert newuser has default 'user' role + assert orm.Role.find(db, 'user') in user.roles + assert orm.Role.find(db, 'admin') not in user.roles @mark.user [email protected] async def test_get_user(app): name = 'user' - r = await api_request(app, 'users', name) + _ = await api_request(app, 'users', name, headers=auth_header(app.db, name)) + r = await api_request( + app, + 'users', + name, + ) assert r.status_code == 200 user = normalize_user(r.json()) - assert user == fill_user({'name': name, 'auth_state': None}) + assert user == fill_user({'name': name, 'roles': ['user'], 'auth_state': None}) @mark.user @@ -359,6 +398,7 @@ async def test_add_multi_user_invalid(app): @mark.user [email protected] async def test_add_multi_user(app): db = app.db names = ['a', 'b'] @@ -375,6 +415,9 @@ async def test_add_multi_user(app): assert user is not None assert user.name == name assert not user.admin + # assert default 'user' role added + assert orm.Role.find(db, 'user') in user.roles + assert orm.Role.find(db, 'admin') not in user.roles # try to create the same users again r = await api_request( @@ -395,6 +438,7 @@ async def test_add_multi_user(app): @mark.user [email protected] async def test_add_multi_user_admin(app): db = app.db names = ['c', 'd'] @@ -414,6 +458,8 @@ async def test_add_multi_user_admin(app): assert user is not None assert user.name == name assert user.admin + assert orm.Role.find(db, 'user') not in user.roles + assert orm.Role.find(db, 'admin') in user.roles @mark.user @@ -439,6 +485,7 @@ async def test_add_user_duplicate(app): @mark.user [email protected] async def test_add_admin(app): db = app.db name = 'newadmin' @@ -450,6 +497,9 @@ async def test_add_admin(app): assert user is not None assert user.name == name assert user.admin + # assert newadmin has default 'admin' role + assert orm.Role.find(db, 'user') not in user.roles + assert orm.Role.find(db, 'admin') in user.roles @mark.user @@ -461,6 +511,7 @@ async def test_delete_user(app): @mark.user [email protected] async def test_make_admin(app): db = app.db name = 'admin2' @@ -470,15 +521,20 @@ async def test_make_admin(app): assert user is not None assert user.name == name assert not user.admin + assert orm.Role.find(db, 'user') in user.roles + assert orm.Role.find(db, 'admin') not in user.roles r = await api_request( app, 'users', name, method='patch', data=json.dumps({'admin': True}) ) + assert r.status_code == 200 user = find_user(db, name) assert user is not None assert user.name == name assert user.admin + assert orm.Role.find(db, 'user') not in user.roles + assert orm.Role.find(db, 'admin') in user.roles @mark.user @@ -509,7 +565,6 @@ async def test_user_set_auth_state(app, auth_state_enabled): assert user.name == name user_auth_state = await user.get_auth_state() assert user_auth_state is None - r = await api_request( app, 'users', @@ -518,7 +573,6 @@ async def test_user_set_auth_state(app, auth_state_enabled): data=json.dumps({'auth_state': auth_state}), headers=auth_header(app.db, name), ) - assert r.status_code == 403 user_auth_state = await user.get_auth_state() assert user_auth_state is None @@ -1161,76 +1215,13 @@ async def test_check_token(app): assert r.status_code == 404 [email protected]("headers, status", [({}, 200), ({'Authorization': 'token bad'}, 403)]) [email protected]("headers, status", [({}, 404), ({'Authorization': 'token bad'}, 404)]) async def test_get_new_token_deprecated(app, headers, status): # request a new token r = await api_request( app, 'authorizations', 'token', method='post', headers=headers ) assert r.status_code == status - if status != 200: - return - reply = r.json() - assert 'token' in reply - r = await api_request(app, 'authorizations', 'token', reply['token']) - r.raise_for_status() - reply = r.json() - assert reply['name'] == 'admin' - - -async def test_token_formdata_deprecated(app): - """Create a token for a user with formdata and no auth header""" - data = {'username': 'fake', 'password': 'fake'} - r = await api_request( - app, - 'authorizations', - 'token', - method='post', - data=json.dumps(data) if data else None, - noauth=True, - ) - assert r.status_code == 200 - reply = r.json() - assert 'token' in reply - r = await api_request(app, 'authorizations', 'token', reply['token']) - r.raise_for_status() - reply = r.json() - assert reply['name'] == data['username'] - - [email protected]( - "as_user, for_user, status", - [ - ('admin', 'other', 200), - ('admin', 'missing', 400), - ('user', 'other', 403), - ('user', 'user', 200), - ], -) -async def test_token_as_user_deprecated(app, as_user, for_user, status): - # ensure both users exist - u = add_user(app.db, app, name=as_user) - if for_user != 'missing': - add_user(app.db, app, name=for_user) - data = {'username': for_user} - headers = {'Authorization': 'token %s' % u.new_api_token()} - r = await api_request( - app, - 'authorizations', - 'token', - method='post', - data=json.dumps(data), - headers=headers, - ) - assert r.status_code == status - reply = r.json() - if status != 200: - return - assert 'token' in reply - r = await api_request(app, 'authorizations', 'token', reply['token']) - r.raise_for_status() - reply = r.json() - assert reply['name'] == data['username'] @mark.parametrize( @@ -1295,7 +1286,7 @@ async def test_get_new_token(app, headers, status, note, expires_in): "as_user, for_user, status", [ ('admin', 'other', 200), - ('admin', 'missing', 404), + ('admin', 'missing', 403), ('user', 'other', 403), ('user', 'user', 200), ], @@ -1304,7 +1295,7 @@ async def test_token_for_user(app, as_user, for_user, status): # ensure both users exist u = add_user(app.db, app, name=as_user) if for_user != 'missing': - add_user(app.db, app, name=for_user) + for_user_obj = add_user(app.db, app, name=for_user) data = {'username': for_user} headers = {'Authorization': 'token %s' % u.new_api_token()} r = await api_request( @@ -1321,6 +1312,7 @@ async def test_token_for_user(app, as_user, for_user, status): if status != 200: return assert 'token' in reply + token_id = reply['id'] r = await api_request(app, 'users', for_user, 'tokens', token_id, headers=headers) r.raise_for_status() @@ -1392,7 +1384,7 @@ async def test_token_authenticator_dict_noauth(app): [ ('admin', 'other', 200), ('admin', 'missing', 404), - ('user', 'other', 403), + ('user', 'other', 404), ('user', 'user', 200), ], ) @@ -1406,12 +1398,11 @@ async def test_token_list(app, as_user, for_user, status): if status != 200: return reply = r.json() - assert sorted(reply) == ['api_tokens', 'oauth_tokens'] + assert sorted(reply) == ['api_tokens'] assert len(reply['api_tokens']) == len(for_user_obj.api_tokens) assert all(token['user'] == for_user for token in reply['api_tokens']) - assert all(token['user'] == for_user for token in reply['oauth_tokens']) # validate individual token ids - for token in reply['api_tokens'] + reply['oauth_tokens']: + for token in reply['api_tokens']: r = await api_request( app, 'users', for_user, 'tokens', token['id'], headers=headers ) @@ -1443,8 +1434,8 @@ async def test_groups_list(app): r.raise_for_status() reply = r.json() assert reply == [ - {'kind': 'group', 'name': 'alphaflight', 'users': []}, - {'kind': 'group', 'name': 'betaflight', 'users': []}, + {'kind': 'group', 'name': 'alphaflight', 'users': [], 'roles': []}, + {'kind': 'group', 'name': 'betaflight', 'users': [], 'roles': []}, ] # Test offset for pagination @@ -1452,7 +1443,7 @@ async def test_groups_list(app): r.raise_for_status() reply = r.json() assert r.status_code == 200 - assert reply == [{'kind': 'group', 'name': 'betaflight', 'users': []}] + assert reply == [{'kind': 'group', 'name': 'betaflight', 'users': [], 'roles': []}] r = await api_request(app, "groups?offset=10") r.raise_for_status() @@ -1464,7 +1455,7 @@ async def test_groups_list(app): r.raise_for_status() reply = r.json() assert r.status_code == 200 - assert reply == [{'kind': 'group', 'name': 'alphaflight', 'users': []}] + assert reply == [{'kind': 'group', 'name': 'alphaflight', 'users': [], 'roles': []}] r = await api_request(app, "groups?limit=0") r.raise_for_status() @@ -1508,6 +1499,7 @@ async def test_group_get(app): 'kind': 'group', 'name': 'alphaflight', 'users': ['sasquatch'], + 'roles': [], } @@ -1619,8 +1611,10 @@ async def test_get_services(app, mockservice_url): services = r.json() assert services == { mockservice.name: { + 'kind': 'service', 'name': mockservice.name, 'admin': True, + 'roles': ['admin'], 'command': mockservice.command, 'pid': mockservice.proc.pid, 'prefix': mockservice.server.base_url, @@ -1629,7 +1623,6 @@ async def test_get_services(app, mockservice_url): 'display': True, } } - r = await api_request(app, 'services', headers=auth_header(db, 'user')) assert r.status_code == 403 @@ -1644,8 +1637,10 @@ async def test_get_service(app, mockservice_url): service = r.json() assert service == { + 'kind': 'service', 'name': mockservice.name, 'admin': True, + 'roles': ['admin'], 'command': mockservice.command, 'pid': mockservice.proc.pid, 'prefix': mockservice.server.base_url, @@ -1653,7 +1648,6 @@ async def test_get_service(app, mockservice_url): 'info': {}, 'display': True, } - r = await api_request( app, 'services/%s' % mockservice.name, @@ -1673,7 +1667,7 @@ async def test_root_api(app): if app.internal_ssl: kwargs['cert'] = (app.internal_ssl_cert, app.internal_ssl_key) kwargs["verify"] = app.internal_ssl_ca - r = await async_requests.get(url, **kwargs) + r = await api_request(app, bypass_proxy=True) r.raise_for_status() expected = {'version': jupyterhub.__version__} assert r.json() == expected @@ -1717,11 +1711,11 @@ async def test_update_activity_403(app, user, admin_user): data="{}", method="post", ) - assert r.status_code == 403 + assert r.status_code == 404 async def test_update_activity_admin(app, user, admin_user): - token = admin_user.new_api_token() + token = admin_user.new_api_token(roles=['admin']) r = await api_request( app, "users/{}/activity".format(user.name), diff --git a/jupyterhub/tests/test_app.py b/jupyterhub/tests/test_app.py --- a/jupyterhub/tests/test_app.py +++ b/jupyterhub/tests/test_app.py @@ -51,7 +51,7 @@ def test_raise_error_on_missing_specified_config(): process = Popen( [sys.executable, '-m', 'jupyterhub', '--config', 'not-available.py'] ) - # wait inpatiently for the process to exit like we want it to + # wait impatiently for the process to exit like we want it to for i in range(100): time.sleep(0.1) returncode = process.poll() diff --git a/jupyterhub/tests/test_db.py b/jupyterhub/tests/test_db.py --- a/jupyterhub/tests/test_db.py +++ b/jupyterhub/tests/test_db.py @@ -36,7 +36,7 @@ def generate_old_db(env_dir, hub_version, db_url): check_call([env_py, populate_db, db_url]) [email protected]('hub_version', ['0.7.2', '0.8.1', '0.9.4']) [email protected]('hub_version', ['1.0.0', "1.2.2", "1.3.0"]) async def test_upgrade(tmpdir, hub_version): db_url = os.getenv('JUPYTERHUB_TEST_DB_URL') if db_url: diff --git a/jupyterhub/tests/test_named_servers.py b/jupyterhub/tests/test_named_servers.py --- a/jupyterhub/tests/test_named_servers.py +++ b/jupyterhub/tests/test_named_servers.py @@ -52,10 +52,10 @@ async def test_default_server(app, named_servers): r.raise_for_status() user_model = normalize_user(r.json()) - print(user_model) assert user_model == fill_user( { 'name': username, + 'roles': ['user'], 'auth_state': None, 'server': user.url, 'servers': { @@ -86,7 +86,7 @@ async def test_default_server(app, named_servers): user_model = normalize_user(r.json()) assert user_model == fill_user( - {'name': username, 'servers': {}, 'auth_state': None} + {'name': username, 'roles': ['user'], 'auth_state': None} ) @@ -117,6 +117,7 @@ async def test_create_named_server(app, named_servers): assert user_model == fill_user( { 'name': username, + 'roles': ['user'], 'auth_state': None, 'servers': { servername: { @@ -142,7 +143,7 @@ async def test_delete_named_server(app, named_servers): username = 'donaar' user = add_user(app.db, app, name=username) assert user.allow_named_servers - cookies = app.login_user(username) + cookies = await app.login_user(username) servername = 'splugoth' r = await api_request(app, 'users', username, 'servers', servername, method='post') r.raise_for_status() @@ -159,7 +160,7 @@ async def test_delete_named_server(app, named_servers): user_model = normalize_user(r.json()) assert user_model == fill_user( - {'name': username, 'auth_state': None, 'servers': {}} + {'name': username, 'roles': ['user'], 'auth_state': None} ) # wrapper Spawner is gone assert servername not in user.spawners diff --git a/jupyterhub/tests/test_orm.py b/jupyterhub/tests/test_orm.py --- a/jupyterhub/tests/test_orm.py +++ b/jupyterhub/tests/test_orm.py @@ -13,6 +13,7 @@ from .. import crypto from .. import objects from .. import orm +from .. import roles from ..emptyclass import EmptyClass from ..user import User from .mocking import MockSpawner @@ -220,6 +221,10 @@ async def test_spawn_fails(db): orm_user = orm.User(name='aeofel') db.add(orm_user) db.commit() + def_roles = roles.get_default_roles() + for role in def_roles: + roles.create_role(db, role) + roles.assign_default_roles(db, orm_user) class BadSpawner(MockSpawner): async def start(self): @@ -244,10 +249,12 @@ def test_groups(db): db.commit() assert group.users == [] assert user.groups == [] + group.users.append(user) db.commit() assert group.users == [user] assert user.groups == [group] + db.delete(user) db.commit() assert group.users == [] @@ -353,8 +360,9 @@ def test_user_delete_cascade(db): spawner.server = server = orm.Server() oauth_code = orm.OAuthCode(client=oauth_client, user=user) db.add(oauth_code) - oauth_token = orm.OAuthAccessToken( - client=oauth_client, user=user, grant_type=orm.GrantType.authorization_code + oauth_token = orm.APIToken( + oauth_client=oauth_client, + user=user, ) db.add(oauth_token) db.commit() @@ -375,7 +383,7 @@ def test_user_delete_cascade(db): assert_not_found(db, orm.Spawner, spawner_id) assert_not_found(db, orm.Server, server_id) assert_not_found(db, orm.OAuthCode, oauth_code_id) - assert_not_found(db, orm.OAuthAccessToken, oauth_token_id) + assert_not_found(db, orm.APIToken, oauth_token_id) def test_oauth_client_delete_cascade(db): @@ -389,12 +397,13 @@ def test_oauth_client_delete_cascade(db): # these should all be deleted automatically when the user goes away oauth_code = orm.OAuthCode(client=oauth_client, user=user) db.add(oauth_code) - oauth_token = orm.OAuthAccessToken( - client=oauth_client, user=user, grant_type=orm.GrantType.authorization_code + oauth_token = orm.APIToken( + oauth_client=oauth_client, + user=user, ) db.add(oauth_token) db.commit() - assert user.oauth_tokens == [oauth_token] + assert user.api_tokens == [oauth_token] # record all of the ids oauth_code_id = oauth_code.id @@ -406,8 +415,8 @@ def test_oauth_client_delete_cascade(db): # verify that everything gets deleted assert_not_found(db, orm.OAuthCode, oauth_code_id) - assert_not_found(db, orm.OAuthAccessToken, oauth_token_id) - assert user.oauth_tokens == [] + assert_not_found(db, orm.APIToken, oauth_token_id) + assert user.api_tokens == [] assert user.oauth_codes == [] @@ -459,7 +468,7 @@ def test_group_delete_cascade(db): assert group2 in user2.groups # now start deleting - # 1. remove group via user.groups + # 1. remove group via user.group user1.groups.remove(group2) db.commit() assert user1 not in group2.users @@ -479,6 +488,7 @@ def test_group_delete_cascade(db): # 4. delete user object db.delete(user1) + db.delete(user2) db.commit() assert user1 not in group1.users @@ -507,32 +517,31 @@ def test_expiring_api_token(app, user): def test_expiring_oauth_token(app, user): db = app.db token = "abc123" - now = orm.OAuthAccessToken.now + now = orm.APIToken.now client = orm.OAuthClient(identifier="xxx", secret="yyy") db.add(client) - orm_token = orm.OAuthAccessToken( + orm_token = orm.APIToken( token=token, - grant_type=orm.GrantType.authorization_code, - client=client, + oauth_client=client, user=user, - expires_at=now() + 30, + expires_at=now() + timedelta(seconds=30), ) db.add(orm_token) db.commit() - found = orm.OAuthAccessToken.find(db, token) + found = orm.APIToken.find(db, token) assert found is orm_token # purge_expired doesn't delete non-expired - orm.OAuthAccessToken.purge_expired(db) - found = orm.OAuthAccessToken.find(db, token) + orm.APIToken.purge_expired(db) + found = orm.APIToken.find(db, token) assert found is orm_token - with mock.patch.object(orm.OAuthAccessToken, 'now', lambda: now() + 60): - found = orm.OAuthAccessToken.find(db, token) + with mock.patch.object(orm.APIToken, 'now', lambda: now() + timedelta(seconds=60)): + found = orm.APIToken.find(db, token) assert found is None - assert orm_token in db.query(orm.OAuthAccessToken) - orm.OAuthAccessToken.purge_expired(db) - assert orm_token not in db.query(orm.OAuthAccessToken) + assert orm_token in db.query(orm.APIToken) + orm.APIToken.purge_expired(db) + assert orm_token not in db.query(orm.APIToken) def test_expiring_oauth_code(app, user): diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -12,8 +12,10 @@ from tornado.httputil import url_concat from .. import orm +from .. import scopes from ..auth import Authenticator from ..handlers import BaseHandler +from ..utils import url_path_join from ..utils import url_path_join as ujoin from .mocking import FalsyCallableFormSpawner from .mocking import FormSpawner @@ -21,6 +23,7 @@ from .utils import add_user from .utils import api_request from .utils import async_requests +from .utils import AsyncSession from .utils import get_page from .utils import public_host from .utils import public_url @@ -869,8 +872,9 @@ async def test_oauth_token_page(app): user = app.users[orm.User.find(app.db, name)] client = orm.OAuthClient(identifier='token') app.db.add(client) - oauth_token = orm.OAuthAccessToken( - client=client, user=user, grant_type=orm.GrantType.authorization_code + oauth_token = orm.APIToken( + oauth_client=client, + user=user, ) app.db.add(oauth_token) app.db.commit() @@ -945,6 +949,62 @@ async def test_bad_oauth_get(app, params): assert r.status_code == 400 [email protected]( + "scopes, has_access", + [ + (["users"], False), + (["admin:users"], False), + (["users", "admin:users", "admin:servers"], True), + ], +) +async def test_admin_page_access(app, scopes, has_access, create_user_with_scopes): + user = create_user_with_scopes(*scopes) + cookies = await app.login_user(user.name) + r = await get_page("/admin", app, cookies=cookies) + if has_access: + assert r.status_code == 200 + else: + assert r.status_code == 403 + + +async def test_oauth_page_scope_appearance( + app, mockservice_url, create_user_with_scopes, create_temp_role +): + service_role = create_temp_role( + [ + 'self', + 'read:users!user=gawain', + 'read:tokens', + 'read:groups!group=mythos', + ] + ) + service = mockservice_url + user = create_user_with_scopes("access:services") + oauth_client = ( + app.db.query(orm.OAuthClient) + .filter_by(identifier=service.oauth_client_id) + .one() + ) + oauth_client.allowed_roles = [service_role] + app.db.commit() + + s = AsyncSession() + s.cookies = await app.login_user(user.name) + url = url_path_join(public_url(app, service) + 'owhoami/?arg=x') + r = await s.get(url) + r.raise_for_status() + soup = BeautifulSoup(r.text, "html.parser") + scopes_block = soup.find('form') + for scope in service_role.scopes: + base_scope, _, filter_ = scope.partition('!') + scope_def = scopes.scope_definitions[base_scope] + assert scope_def['description'] in scopes_block.text + if filter_: + kind, _, name = filter_.partition('=') + assert kind in scopes_block.text + assert name in scopes_block.text + + async def test_token_page(app): name = "cake" cookies = await app.login_user(name) diff --git a/jupyterhub/tests/test_roles.py b/jupyterhub/tests/test_roles.py new file mode 100644 --- /dev/null +++ b/jupyterhub/tests/test_roles.py @@ -0,0 +1,1334 @@ +"""Test roles""" +# Copyright (c) Jupyter Development Team. +# Distributed under the terms of the Modified BSD License. +import json +import os + +import pytest +from pytest import mark +from tornado.log import app_log + +from .. import orm +from .. import roles +from ..scopes import get_scopes_for +from ..scopes import scope_definitions +from ..utils import utcnow +from .mocking import MockHub +from .utils import add_user +from .utils import api_request + + [email protected] +def test_orm_roles(db): + """Test orm roles setup""" + user_role = orm.Role.find(db, name='user') + token_role = orm.Role.find(db, name='token') + service_role = orm.Role.find(db, name='service') + if not user_role: + user_role = orm.Role(name='user', scopes=['self']) + db.add(user_role) + if not token_role: + token_role = orm.Role(name='token', scopes=['all']) + db.add(token_role) + if not service_role: + service_role = orm.Role(name='service', scopes=[]) + db.add(service_role) + db.commit() + + group_role = orm.Role(name='group', scopes=['read:users']) + db.add(group_role) + db.commit() + + user = orm.User(name='falafel') + db.add(user) + db.commit() + + service = orm.Service(name='kebab') + db.add(service) + db.commit() + + group = orm.Group(name='fast-food') + db.add(group) + db.commit() + + assert user_role.users == [] + assert user_role.services == [] + assert user_role.groups == [] + assert service_role.users == [] + assert service_role.services == [] + assert service_role.groups == [] + assert user.roles == [] + assert service.roles == [] + assert group.roles == [] + + user_role.users.append(user) + service_role.services.append(service) + group_role.groups.append(group) + db.commit() + assert user_role.users == [user] + assert user.roles == [user_role] + assert service_role.services == [service] + assert service.roles == [service_role] + assert group_role.groups == [group] + assert group.roles == [group_role] + + # check token creation without specifying its role + # assigns it the default 'token' role + token = user.new_api_token() + user_token = orm.APIToken.find(db, token=token) + assert user_token in token_role.tokens + assert token_role in user_token.roles + + # check creating token with a specific role + token = service.new_api_token(roles=['service']) + service_token = orm.APIToken.find(db, token=token) + assert service_token in service_role.tokens + assert service_role in service_token.roles + + # check deleting user removes the user and the token from roles + db.delete(user) + db.commit() + assert user_role.users == [] + assert user_token not in token_role.tokens + # check deleting the service token removes it from 'service' role + db.delete(service_token) + db.commit() + assert service_token not in service_role.tokens + # check deleting the service_role removes it from service.roles + db.delete(service_role) + db.commit() + assert service.roles == [] + # check deleting the group removes it from group_roles + db.delete(group) + db.commit() + assert group_role.groups == [] + + # clean up db + db.delete(service) + db.delete(group_role) + db.commit() + + [email protected] +def test_orm_roles_delete_cascade(db): + """Orm roles cascade""" + user1 = orm.User(name='user1') + user2 = orm.User(name='user2') + role1 = orm.Role(name='role1') + role2 = orm.Role(name='role2') + db.add(user1) + db.add(user2) + db.add(role1) + db.add(role2) + db.commit() + # add user to role via user.roles + user1.roles.append(role1) + db.commit() + assert user1 in role1.users + assert role1 in user1.roles + + # add user to role via roles.users + role1.users.append(user2) + db.commit() + assert user2 in role1.users + assert role1 in user2.roles + + # fill role2 and check role1 again + role2.users.append(user1) + role2.users.append(user2) + db.commit() + assert user1 in role1.users + assert user2 in role1.users + assert user1 in role2.users + assert user2 in role2.users + assert role1 in user1.roles + assert role1 in user2.roles + assert role2 in user1.roles + assert role2 in user2.roles + + # now start deleting + # 1. remove role via user.roles + user1.roles.remove(role2) + db.commit() + assert user1 not in role2.users + assert role2 not in user1.roles + + # 2. remove user via role.users + role1.users.remove(user2) + db.commit() + assert user2 not in role1.users + assert role1 not in user2.roles + + # 3. delete role object + db.delete(role2) + db.commit() + assert role2 not in user1.roles + assert role2 not in user2.roles + + # 4. delete user object + db.delete(user1) + db.delete(user2) + db.commit() + assert user1 not in role1.users + + [email protected] [email protected]( + "scopes, subscopes", + [ + ( + ['admin:users'], + { + 'admin:users', + 'admin:auth_state', + 'users', + 'read:users', + 'users:activity', + 'read:users:name', + 'read:users:groups', + 'read:roles:users', + 'read:users:activity', + }, + ), + ( + ['users'], + { + 'users', + 'read:users', + 'users:activity', + 'read:users:name', + 'read:users:groups', + 'read:users:activity', + }, + ), + ( + ['read:users'], + { + 'read:users', + 'read:users:name', + 'read:users:groups', + 'read:users:activity', + }, + ), + (['read:servers'], {'read:servers', 'read:users:name'}), + ( + ['admin:groups'], + { + 'admin:groups', + 'groups', + 'read:groups', + 'read:roles:groups', + 'read:groups:name', + }, + ), + ( + ['admin:groups', 'read:servers'], + { + 'admin:groups', + 'groups', + 'read:groups', + 'read:roles:groups', + 'read:groups:name', + 'read:servers', + 'read:users:name', + }, + ), + ( + ['tokens!group=hobbits'], + {'tokens!group=hobbits', 'read:tokens!group=hobbits'}, + ), + ], +) +def test_get_subscopes(db, scopes, subscopes): + """Test role scopes expansion into their subscopes""" + roles.create_role(db, {'name': 'testing_scopes', 'scopes': scopes}) + role = orm.Role.find(db, name='testing_scopes') + response = roles._get_subscopes(role) + assert response == subscopes + db.delete(role) + + [email protected] +async def test_load_default_roles(tmpdir, request): + """Test loading default roles in app.py""" + kwargs = {} + ssl_enabled = getattr(request.module, "ssl_enabled", False) + if ssl_enabled: + kwargs['internal_certs_location'] = str(tmpdir) + hub = MockHub(**kwargs) + hub.init_db() + db = hub.db + await hub.init_role_creation() + # test default roles loaded to database + default_roles = roles.get_default_roles() + for role in default_roles: + assert orm.Role.find(db, role['name']) is not None + + [email protected] [email protected]( + "role, role_def, response_type, response", + [ + ( + 'new-role', + { + 'name': 'new-role', + 'description': 'Some description', + 'scopes': ['groups'], + }, + 'info', + app_log.info('Role new-role added to database'), + ), + ( + 'the-same-role', + { + 'name': 'new-role', + 'description': 'Some description', + 'scopes': ['groups'], + }, + 'no-log', + None, + ), + ('no_name', {'scopes': ['users']}, 'error', KeyError), + ( + 'no_scopes', + {'name': 'no-permissions'}, + 'warning', + app_log.warning('Warning: New defined role no-permissions has no scopes'), + ), + ( + 'admin', + {'name': 'admin', 'scopes': ['admin:users']}, + 'error', + ValueError, + ), + ( + 'admin', + {'name': 'admin', 'description': 'New description'}, + 'error', + ValueError, + ), + ( + 'user', + {'name': 'user', 'scopes': ['read:users:name']}, + 'info', + app_log.info('Role user scopes attribute has been changed'), + ), + # rewrite the user role back to 'default' + ( + 'user', + {'name': 'user', 'scopes': ['self']}, + 'info', + app_log.info('Role user scopes attribute has been changed'), + ), + ], +) +async def test_creating_roles(app, role, role_def, response_type, response): + """Test raising errors and warnings when creating/modifying roles""" + + db = app.db + + if response_type == 'error': + with pytest.raises(response): + roles.create_role(db, role_def) + + elif response_type == 'warning' or response_type == 'info': + with pytest.warns(response): + roles.create_role(db, role_def) + # check the role has been created/modified + role = orm.Role.find(db, role_def['name']) + assert role is not None + if 'description' in role_def.keys(): + assert role.description == role_def['description'] + if 'scopes' in role_def.keys(): + assert role.scopes == role_def['scopes'] + + # make sure no warnings/info logged when the role exists and its definition hasn't been changed + elif response_type == 'no-log': + with pytest.warns(response) as record: + roles.create_role(db, role_def) + assert not record.list + role = orm.Role.find(db, role_def['name']) + assert role is not None + + [email protected] [email protected]( + "role_type, rolename, response_type, response", + [ + ( + 'existing', + 'test-role1', + 'info', + app_log.info('Role user scopes attribute has been changed'), + ), + ('non-existing', 'test-role2', 'error', NameError), + ('default', 'user', 'error', ValueError), + ], +) +async def test_delete_roles(db, role_type, rolename, response_type, response): + """Test raising errors and info when deleting roles""" + + if response_type == 'info': + # add the role to db + test_role = orm.Role(name=rolename) + db.add(test_role) + db.commit() + check_role = orm.Role.find(db, rolename) + assert check_role is not None + # check the role is deleted and info raised + with pytest.warns(response): + roles.delete_role(db, rolename) + check_role = orm.Role.find(db, rolename) + assert check_role is None + + elif response_type == 'error': + with pytest.raises(response): + roles.delete_role(db, rolename) + + [email protected] [email protected]( + "role, response", + [ + ( + { + 'name': 'test-scopes-1', + 'scopes': [ + 'users', + 'users!user=charlie', + 'admin:groups', + 'read:tokens', + ], + }, + 'existing', + ), + ({'name': 'test-scopes-2', 'scopes': ['uses']}, NameError), + ({'name': 'test-scopes-3', 'scopes': ['users:activities']}, NameError), + ({'name': 'test-scopes-4', 'scopes': ['groups!goup=class-A']}, NameError), + ], +) +async def test_scope_existence(tmpdir, request, role, response): + """Test checking of scopes provided in role definitions""" + kwargs = {'load_roles': [role]} + ssl_enabled = getattr(request.module, "ssl_enabled", False) + if ssl_enabled: + kwargs['internal_certs_location'] = str(tmpdir) + hub = MockHub(**kwargs) + hub.init_db() + db = hub.db + + if response == 'existing': + roles.create_role(db, role) + added_role = orm.Role.find(db, role['name']) + assert added_role is not None + assert added_role.scopes == role['scopes'] + + elif response == NameError: + with pytest.raises(response): + roles.create_role(db, role) + added_role = orm.Role.find(db, role['name']) + assert added_role is None + + # delete the tested roles + if added_role: + roles.delete_role(db, added_role.name) + + [email protected] +async def test_load_roles_users(tmpdir, request): + """Test loading predefined roles for users in app.py""" + roles_to_load = [ + { + 'name': 'teacher', + 'description': 'Access users information, servers and groups without create/delete privileges', + 'scopes': ['users', 'groups'], + 'users': ['cyclops', 'gandalf'], + }, + ] + kwargs = {'load_roles': roles_to_load} + ssl_enabled = getattr(request.module, "ssl_enabled", False) + if ssl_enabled: + kwargs['internal_certs_location'] = str(tmpdir) + hub = MockHub(**kwargs) + hub.init_db() + db = hub.db + hub.authenticator.admin_users = ['admin'] + hub.authenticator.allowed_users = ['cyclops', 'gandalf', 'bilbo', 'gargamel'] + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + admin_role = orm.Role.find(db, 'admin') + user_role = orm.Role.find(db, 'user') + # test if every user has a role (and no duplicates) + # and admins have admin role + for user in db.query(orm.User): + assert len(user.roles) > 0 + assert len(user.roles) == len(set(user.roles)) + if user.admin: + assert admin_role in user.roles + assert user_role in user.roles + + # test if predefined roles loaded and assigned + teacher_role = orm.Role.find(db, name='teacher') + assert teacher_role is not None + gandalf_user = orm.User.find(db, name='gandalf') + assert teacher_role in gandalf_user.roles + cyclops_user = orm.User.find(db, name='cyclops') + assert teacher_role in cyclops_user.roles + + # delete the test roles + for role in roles_to_load: + roles.delete_role(db, role['name']) + + [email protected] +async def test_load_roles_services(tmpdir, request): + services = [ + {'name': 'idle-culler', 'api_token': 'some-token'}, + {'name': 'user_service', 'api_token': 'some-other-token'}, + {'name': 'admin_service', 'api_token': 'secret-token'}, + ] + service_tokens = { + 'some-token': 'idle-culler', + 'some-other-token': 'user_service', + 'secret-token': 'admin_service', + } + roles_to_load = [ + { + 'name': 'idle-culler', + 'description': 'Cull idle servers', + 'scopes': [ + 'read:users:name', + 'read:users:activity', + 'read:servers', + 'servers', + ], + 'services': ['idle-culler'], + }, + ] + kwargs = { + 'load_roles': roles_to_load, + 'services': services, + 'service_tokens': service_tokens, + } + ssl_enabled = getattr(request.module, "ssl_enabled", False) + if ssl_enabled: + kwargs['internal_certs_location'] = str(tmpdir) + hub = MockHub(**kwargs) + hub.init_db() + db = hub.db + await hub.init_role_creation() + await hub.init_api_tokens() + # make 'admin_service' admin + admin_service = orm.Service.find(db, 'admin_service') + admin_service.admin = True + db.commit() + await hub.init_role_assignment() + # test if every service has a role (and no duplicates) + admin_role = orm.Role.find(db, name='admin') + user_role = orm.Role.find(db, name='user') + + # test if predefined roles loaded and assigned + culler_role = orm.Role.find(db, name='idle-culler') + culler_service = orm.Service.find(db, name='idle-culler') + assert culler_service.roles == [culler_role] + user_service = orm.Service.find(db, name='user_service') + assert not user_service.roles + assert admin_service.roles == [admin_role] + + # delete the test services + for service in db.query(orm.Service): + db.delete(service) + db.commit() + + # delete the test tokens + for token in db.query(orm.APIToken): + db.delete(token) + db.commit() + + # delete the test roles + for role in roles_to_load: + roles.delete_role(db, role['name']) + + [email protected] +async def test_load_roles_groups(tmpdir, request): + """Test loading predefined roles for groups in app.py""" + groups_to_load = { + 'group1': ['gandalf'], + 'group2': ['bilbo', 'gargamel'], + 'group3': ['cyclops'], + } + roles_to_load = [ + { + 'name': 'assistant', + 'description': 'Access users information only', + 'scopes': ['read:users'], + 'groups': ['group2'], + }, + { + 'name': 'head', + 'description': 'Whole user access', + 'scopes': ['users', 'admin:users'], + 'groups': ['group3'], + }, + ] + kwargs = {'load_groups': groups_to_load, 'load_roles': roles_to_load} + ssl_enabled = getattr(request.module, "ssl_enabled", False) + if ssl_enabled: + kwargs['internal_certs_location'] = str(tmpdir) + hub = MockHub(**kwargs) + hub.init_db() + db = hub.db + await hub.init_role_creation() + await hub.init_groups() + await hub.init_role_assignment() + + assist_role = orm.Role.find(db, name='assistant') + head_role = orm.Role.find(db, name='head') + + group1 = orm.Group.find(db, name='group1') + group2 = orm.Group.find(db, name='group2') + group3 = orm.Group.find(db, name='group3') + + # test group roles + assert group1.roles == [] + assert group2 in assist_role.groups + assert group3 in head_role.groups + + # delete the test roles + for role in roles_to_load: + roles.delete_role(db, role['name']) + + [email protected] +async def test_load_roles_user_tokens(tmpdir, request): + user_tokens = { + 'secret-token': 'cyclops', + 'secrety-token': 'gandalf', + 'super-secret-token': 'admin', + } + roles_to_load = [ + { + 'name': 'reader', + 'description': 'Read all users models', + 'scopes': ['read:users'], + }, + ] + kwargs = { + 'load_roles': roles_to_load, + 'api_tokens': user_tokens, + } + ssl_enabled = getattr(request.module, "ssl_enabled", False) + if ssl_enabled: + kwargs['internal_certs_location'] = str(tmpdir) + hub = MockHub(**kwargs) + hub.init_db() + db = hub.db + hub.authenticator.admin_users = ['admin'] + hub.authenticator.allowed_users = ['cyclops', 'gandalf'] + await hub.init_role_creation() + await hub.init_users() + await hub.init_api_tokens() + await hub.init_role_assignment() + # test if all other tokens have default 'user' role + token_role = orm.Role.find(db, 'token') + secret_token = orm.APIToken.find(db, 'secret-token') + assert token_role in secret_token.roles + secrety_token = orm.APIToken.find(db, 'secrety-token') + assert token_role in secrety_token.roles + + # delete the test tokens + for token in db.query(orm.APIToken): + db.delete(token) + db.commit() + + # delete the test roles + for role in roles_to_load: + roles.delete_role(db, role['name']) + + [email protected] [email protected]( + "headers, rolename, scopes, status", + [ + # no role requested - gets default 'token' role + ({}, None, None, 200), + # role scopes within the user's default 'user' role + ({}, 'self-reader', ['read:users'], 200), + # role scopes outside of the user's role but within the group's role scopes of which the user is a member + ({}, 'groups-reader', ['read:groups'], 200), + # non-existing role request + ({}, 'non-existing', [], 404), + # role scopes outside of both user's role and group's role scopes + ({}, 'users-creator', ['admin:users'], 403), + ], +) +async def test_get_new_token_via_api(app, headers, rolename, scopes, status): + """Test requesting a token via API with and without roles""" + + user = add_user(app.db, app, name='user') + if rolename and rolename != 'non-existing': + roles.create_role(app.db, {'name': rolename, 'scopes': scopes}) + if rolename == 'groups-reader': + # add role for a group + roles.create_role(app.db, {'name': 'group-role', 'scopes': ['groups']}) + # create a group and add the user and group_role + group = orm.Group.find(app.db, 'test-group') + if not group: + group = orm.Group(name='test-group') + app.db.add(group) + group_role = orm.Role.find(app.db, 'group-role') + group.roles.append(group_role) + user.groups.append(group) + app.db.commit() + if rolename: + body = json.dumps({'roles': [rolename]}) + else: + body = '' + # request a new token + r = await api_request( + app, 'users/user/tokens', method='post', headers=headers, data=body + ) + assert r.status_code == status + if status != 200: + return + # check the new-token reply for roles + reply = r.json() + assert 'token' in reply + assert reply['user'] == user.name + if not rolename: + assert reply['roles'] == ['token'] + else: + assert reply['roles'] == [rolename] + token_id = reply['id'] + + # delete the token + r = await api_request(app, 'users/user/tokens', token_id, method='delete') + assert r.status_code == 204 + # verify deletion + r = await api_request(app, 'users/user/tokens', token_id) + assert r.status_code == 404 + + [email protected] [email protected]( + "kind, has_user_scopes", + [ + ('users', True), + ('services', False), + ], +) +async def test_self_expansion(app, kind, has_user_scopes): + Class = orm.get_class(kind) + orm_obj = Class(name=f'test_{kind}') + app.db.add(orm_obj) + app.db.commit() + test_role = orm.Role(name='test_role', scopes=['self']) + orm_obj.roles.append(test_role) + # test expansion of user/service scopes + scopes = roles.expand_roles_to_scopes(orm_obj) + assert bool(scopes) == has_user_scopes + if kind == 'users': + for scope in scopes: + assert scope.endswith(f"!user={orm_obj.name}") + base_scope = scope.split("!", 1)[0] + assert base_scope in scope_definitions + + # test expansion of token scopes + orm_obj.new_api_token() + print(orm_obj.api_tokens[0]) + token_scopes = get_scopes_for(orm_obj.api_tokens[0]) + print(token_scopes) + assert bool(token_scopes) == has_user_scopes + app.db.delete(orm_obj) + app.db.delete(test_role) + + [email protected] [email protected]( + "scope_list, kind, test_for_token", + [ + (['users:activity!user'], 'users', False), + (['users:activity!user', 'read:users'], 'users', False), + (['users:activity!user=otheruser', 'read:users'], 'users', False), + (['users:activity!user'], 'users', True), + (['users:activity!user=otheruser', 'groups'], 'users', True), + ], +) +async def test_user_filter_expansion(app, scope_list, kind, test_for_token): + Class = orm.get_class(kind) + orm_obj = Class(name=f'test_{kind}') + app.db.add(orm_obj) + app.db.commit() + + test_role = orm.Role(name='test_role', scopes=scope_list) + orm_obj.roles.append(test_role) + + if test_for_token: + token = orm_obj.new_api_token(roles=['test_role']) + orm_token = orm.APIToken.find(app.db, token) + expanded_scopes = roles.expand_roles_to_scopes(orm_token) + else: + expanded_scopes = roles.expand_roles_to_scopes(orm_obj) + + for scope in scope_list: + base, _, filter = scope.partition('!') + for ex_scope in expanded_scopes: + ex_base, ex__, ex_filter = ex_scope.partition('!') + # check that the filter has been expanded to include the username if '!user' filter + if scope in ex_scope and filter == 'user': + assert ex_filter == f'{filter}={orm_obj.name}' + # make sure the filter has been left unchanged if other filter provided + elif scope in ex_scope and '=' in filter: + assert ex_filter == filter + + app.db.delete(orm_obj) + app.db.delete(test_role) + + +async def test_large_filter_expansion(app, create_temp_role, create_user_with_scopes): + scope_list = roles.expand_self_scope('==') + # Mimic the role 'self' based on '!user' filter for tokens + scope_list = [scope.rstrip("=") for scope in scope_list] + filtered_role = create_temp_role(scope_list) + user = create_user_with_scopes('self') + user.new_api_token(roles=[filtered_role.name]) + user.new_api_token(roles=['token']) + manual_scope_set = get_scopes_for(user.api_tokens[0]) + auto_scope_set = get_scopes_for(user.api_tokens[1]) + assert manual_scope_set == auto_scope_set + + [email protected] [email protected]( + "name, valid", + [ + ('abc', True), + ('group', True), + ("a-pretty-long-name-with-123", True), + ("0-abc", False), # starts with number + ("role-", False), # ends with - + ("has-Uppercase", False), # Uppercase + ("a" * 256, False), # too long + ("has space", False), # space is illegal + ], +) +async def test_valid_names(name, valid): + if valid: + assert roles._validate_role_name(name) + else: + with pytest.raises(ValueError): + roles._validate_role_name(name) + + [email protected] +async def test_server_token_role(app): + user = add_user(app.db, app, name='test_user') + assert user.api_tokens == [] + spawner = user.spawner + spawner.cmd = ['jupyterhub-singleuser'] + await user.spawn() + + server_token = spawner.api_token + orm_server_token = orm.APIToken.find(app.db, server_token) + assert orm_server_token + + server_role = orm.Role.find(app.db, 'server') + token_role = orm.Role.find(app.db, 'token') + assert server_role in orm_server_token.roles + assert token_role not in orm_server_token.roles + + assert orm_server_token.user.name == user.name + assert user.api_tokens == [orm_server_token] + + await user.stop() + + [email protected] [email protected]( + "token_role, api_method, api_endpoint, for_user, response", + [ + ('server', 'post', 'activity', 'same_user', 200), + ('server', 'post', 'activity', 'other_user', 404), + ('server', 'get', 'users', 'same_user', 200), + ('token', 'post', 'activity', 'same_user', 200), + ('no_role', 'post', 'activity', 'same_user', 403), + ], +) +async def test_server_role_api_calls( + app, token_role, api_method, api_endpoint, for_user, response +): + user = add_user(app.db, app, name='test_user') + roles.grant_role(app.db, user, 'user') + app_log.debug(user.roles) + app_log.debug(roles.expand_roles_to_scopes(user.orm_user)) + if token_role == 'no_role': + api_token = user.new_api_token(roles=[]) + else: + api_token = user.new_api_token(roles=[token_role]) + + if for_user == 'same_user': + username = user.name + else: + username = 'otheruser' + + if api_endpoint == 'activity': + path = "users/{}/activity".format(username) + data = json.dumps({"servers": {"": {"last_activity": utcnow().isoformat()}}}) + elif api_endpoint == 'users': + path = "users" + data = "" + + r = await api_request( + app, + path, + headers={"Authorization": "token {}".format(api_token)}, + data=data, + method=api_method, + ) + assert r.status_code == response + + if api_endpoint == 'users' and token_role == 'server': + reply = r.json() + assert len(reply) == 1 + + user_model = reply[0] + assert user_model['name'] == username + assert 'last_activity' in user_model.keys() + assert ( + all(key for key in ['groups', 'roles', 'servers']) not in user_model.keys() + ) + + +async def test_oauth_allowed_roles(app, create_temp_role): + allowed_roles = ['oracle', 'goose'] + service = { + 'name': 'oas1', + 'api_token': 'some-token', + 'oauth_roles': ['oracle', 'goose'], + } + for role in allowed_roles: + create_temp_role('read:users', role_name=role) + app.services.append(service) + app.init_services() + app_service = app.services[0] + assert app_service['name'] == 'oas1' + assert set(app_service['oauth_roles']) == set(allowed_roles) + + +async def test_user_group_roles(app, create_temp_role): + user = add_user(app.db, app, name='jack') + another_user = add_user(app.db, app, name='jill') + + group = orm.Group.find(app.db, name='A') + if not group: + group = orm.Group(name='A') + app.db.add(group) + app.db.commit() + + if group not in user.groups: + user.groups.append(group) + app.db.commit() + + if group not in another_user.groups: + another_user.groups.append(group) + app.db.commit() + + group_role = orm.Role.find(app.db, 'student-a') + if not group_role: + create_temp_role(['read:groups!group=A'], 'student-a') + roles.grant_role(app.db, group, rolename='student-a') + group_role = orm.Role.find(app.db, 'student-a') + + # repeat check to ensure group roles don't get added to the user at all + # regression test for #3472 + roles_before = list(user.roles) + for i in range(3): + roles.expand_roles_to_scopes(user.orm_user) + user_roles = list(user.roles) + assert user_roles == roles_before + + # jack's API token + token = user.new_api_token() + + headers = {'Authorization': 'token %s' % token} + r = await api_request(app, 'users', method='get', headers=headers) + assert r.status_code == 200 + r.raise_for_status() + reply = r.json() + + print(reply) + + assert len(reply[0]['roles']) == 1 + assert reply[0]['name'] == 'jack' + assert group_role.name not in reply[0]['roles'] + + headers = {'Authorization': 'token %s' % token} + r = await api_request(app, 'groups', method='get', headers=headers) + assert r.status_code == 200 + r.raise_for_status() + reply = r.json() + + print(reply) + + headers = {'Authorization': 'token %s' % token} + r = await api_request(app, 'users', method='get', headers=headers) + assert r.status_code == 200 + r.raise_for_status() + reply = r.json() + + print(reply) + + assert len(reply[0]['roles']) == 1 + assert reply[0]['name'] == 'jack' + assert group_role.name not in reply[0]['roles'] + + +async def test_config_role_list(): + roles_to_load = [ + { + 'name': 'elephant', + 'description': 'pacing about', + 'scopes': ['read:hub'], + }, + { + 'name': 'tiger', + 'description': 'pouncing stuff', + 'scopes': ['shutdown'], + }, + ] + hub = MockHub(load_roles=roles_to_load) + hub.init_db() + hub.authenticator.admin_users = ['admin'] + await hub.init_role_creation() + for role_conf in roles_to_load: + assert orm.Role.find(hub.db, name=role_conf['name']) + # Now remove elephant from config and see if it is removed from database + roles_to_load.pop(0) + hub.load_roles = roles_to_load + await hub.init_role_creation() + assert orm.Role.find(hub.db, name='tiger') + assert not orm.Role.find(hub.db, name='elephant') + + +async def test_config_role_users(): + role_name = 'painter' + user_name = 'benny' + user_names = ['agnetha', 'bjorn', 'anni-frid', user_name] + roles_to_load = [ + { + 'name': role_name, + 'description': 'painting with colors', + 'scopes': ['users', 'groups'], + 'users': user_names, + }, + ] + hub = MockHub(load_roles=roles_to_load) + hub.init_db() + hub.authenticator.admin_users = ['admin'] + hub.authenticator.allowed_users = user_names + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + user = orm.User.find(hub.db, name=user_name) + role = orm.Role.find(hub.db, name=role_name) + assert role in user.roles + # Now reload and see if user is removed from role list + roles_to_load[0]['users'].remove(user_name) + hub.load_roles = roles_to_load + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + user = orm.User.find(hub.db, name=user_name) + role = orm.Role.find(hub.db, name=role_name) + assert role not in user.roles + + +async def test_scope_expansion_revokes_tokens(app, mockservice_url): + role_name = 'morpheus' + roles_to_load = [ + { + 'name': role_name, + 'description': 'wears sunglasses', + 'scopes': ['users', 'groups'], + }, + ] + app.load_roles = roles_to_load + await app.init_role_creation() + user = add_user(app.db, name='laurence') + for _ in range(2): + user.new_api_token() + red_token, blue_token = user.api_tokens + roles.grant_role(app.db, red_token, role_name) + service = mockservice_url + red_token.client_id = service.oauth_client_id + app.db.commit() + # Restart hub and see if token is revoked + app.load_roles[0]['scopes'].append('proxy') + await app.init_role_creation() + user = orm.User.find(app.db, name='laurence') + assert red_token not in user.api_tokens + assert blue_token in user.api_tokens + + +async def test_duplicate_role_users(): + role_name = 'painter' + user_name = 'benny' + user_names = ['agnetha', 'bjorn', 'anni-frid', user_name] + roles_to_load = [ + { + 'name': role_name, + 'description': 'painting with colors', + 'scopes': ['users', 'groups'], + 'users': user_names, + }, + { + 'name': role_name, + 'description': 'painting with colors', + 'scopes': ['users', 'groups'], + 'users': user_names, + }, + ] + hub = MockHub(load_roles=roles_to_load) + hub.init_db() + with pytest.raises(ValueError): + await hub.init_role_creation() + + +async def test_admin_role_and_flag(): + admin_role_spec = [ + { + 'name': 'admin', + 'users': ['eddy'], + } + ] + hub = MockHub(load_roles=admin_role_spec) + hub.init_db() + hub.authenticator.admin_users = ['admin'] + hub.authenticator.allowed_users = ['eddy'] + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + admin_role = orm.Role.find(hub.db, name='admin') + for user_name in ['eddy', 'admin']: + user = orm.User.find(hub.db, name=user_name) + assert user.admin + assert admin_role in user.roles + admin_role_spec[0]['users'].remove('eddy') + hub.load_roles = admin_role_spec + await hub.init_users() + await hub.init_role_assignment() + user = orm.User.find(hub.db, name='eddy') + assert not user.admin + assert admin_role not in user.roles + + +async def test_custom_role_reset(): + user_role_spec = [ + { + 'name': 'user', + 'scopes': ['self', 'shutdown'], + 'users': ['eddy'], + } + ] + hub = MockHub(load_roles=user_role_spec) + hub.init_db() + hub.authenticator.allowed_users = ['eddy'] + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + user_role = orm.Role.find(hub.db, name='user') + user = orm.User.find(hub.db, name='eddy') + assert user_role in user.roles + assert 'shutdown' in user_role.scopes + hub.load_roles = [] + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + user_role = orm.Role.find(hub.db, name='user') + user = orm.User.find(hub.db, name='eddy') + assert user_role in user.roles + assert 'shutdown' not in user_role.scopes + + +async def test_removal_config_to_db(): + role_spec = [ + { + 'name': 'user', + 'scopes': ['self', 'shutdown'], + }, + { + 'name': 'wizard', + 'scopes': ['self', 'read:groups'], + }, + ] + hub = MockHub(load_roles=role_spec) + hub.init_db() + await hub.init_role_creation() + assert orm.Role.find(hub.db, 'user') + assert orm.Role.find(hub.db, 'wizard') + hub.load_roles = [] + await hub.init_role_creation() + assert orm.Role.find(hub.db, 'user') + assert not orm.Role.find(hub.db, 'wizard') + + +async def test_no_admin_role_change(): + role_spec = [{'name': 'admin', 'scopes': ['shutdown']}] + hub = MockHub(load_roles=role_spec) + hub.init_db() + with pytest.raises(ValueError): + await hub.init_role_creation() + + +async def test_user_config_respects_memberships(): + role_spec = [ + { + 'name': 'user', + 'scopes': ['self', 'shutdown'], + } + ] + user_names = ['eddy', 'carol'] + hub = MockHub(load_roles=role_spec) + hub.init_db() + hub.authenticator.allowed_users = user_names + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + user_role = orm.Role.find(hub.db, 'user') + for user_name in user_names: + user = orm.User.find(hub.db, user_name) + assert user in user_role.users + + +async def test_admin_role_respects_config(): + role_spec = [ + { + 'name': 'admin', + } + ] + admin_users = ['eddy', 'carol'] + hub = MockHub(load_roles=role_spec) + hub.init_db() + hub.authenticator.admin_users = admin_users + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + admin_role = orm.Role.find(hub.db, 'admin') + for user_name in admin_users: + user = orm.User.find(hub.db, user_name) + assert user in admin_role.users + + +async def test_empty_admin_spec(): + role_spec = [{'name': 'admin', 'users': []}] + hub = MockHub(load_roles=role_spec) + hub.init_db() + hub.authenticator.admin_users = [] + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + admin_role = orm.Role.find(hub.db, 'admin') + assert not admin_role.users + + +async def test_no_default_service_role(): + services = [ + { + 'name': 'minesweeper', + 'api_token': 'some-token', + } + ] + hub = MockHub(services=services) + await hub.initialize() + service = orm.Service.find(hub.db, 'minesweeper') + assert not service.roles + + +async def test_hub_upgrade_detection(tmpdir): + db_url = f"sqlite:///{tmpdir.join('jupyterhub.sqlite')}" + os.environ['JUPYTERHUB_TEST_DB_URL'] = db_url + # Create hub with users and tokens + hub = MockHub(db_url=db_url) + await hub.initialize() + user_names = ['patricia', 'quentin'] + user_role = orm.Role.find(hub.db, 'user') + for name in user_names: + user = add_user(hub.db, name=name) + user.new_api_token() + assert user_role in user.roles + for role in hub.db.query(orm.Role): + hub.db.delete(role) + hub.db.commit() + # Restart hub in emulated upgrade mode: default roles for all entities + hub.test_clean_db = False + await hub.initialize() + assert getattr(hub, '_rbac_upgrade', False) + user_role = orm.Role.find(hub.db, 'user') + token_role = orm.Role.find(hub.db, 'token') + for name in user_names: + user = orm.User.find(hub.db, name) + assert user_role in user.roles + assert token_role in user.api_tokens[0].roles + # Strip all roles and see if it sticks + user_role.users = [] + token_role.tokens = [] + hub.db.commit() + + hub.init_db() + hub.init_hub() + await hub.init_role_creation() + await hub.init_users() + hub.authenticator.allowed_users = ['patricia'] + await hub.init_api_tokens() + await hub.init_role_assignment() + assert not getattr(hub, '_rbac_upgrade', False) + user_role = orm.Role.find(hub.db, 'user') + token_role = orm.Role.find(hub.db, 'token') + allowed_user = orm.User.find(hub.db, 'patricia') + rem_user = orm.User.find(hub.db, 'quentin') + assert user_role in allowed_user.roles + assert token_role not in allowed_user.api_tokens[0].roles + assert user_role not in rem_user.roles + assert token_role not in rem_user.roles + + +async def test_token_keep_roles_on_restart(): + role_spec = [ + { + 'name': 'bloop', + 'scopes': ['read:users'], + } + ] + hub = MockHub(load_roles=role_spec) + hub.init_db() + hub.authenticator.admin_users = ['ben'] + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + user = orm.User.find(hub.db, name='ben') + for _ in range(3): + user.new_api_token() + happy_token, content_token, sad_token = user.api_tokens + roles.grant_role(hub.db, happy_token, 'bloop') + roles.strip_role(hub.db, sad_token, 'token') + assert len(happy_token.roles) == 2 + assert len(content_token.roles) == 1 + assert len(sad_token.roles) == 0 + # Restart hub and see if roles are as expected + hub.load_roles = [] + await hub.init_role_creation() + await hub.init_users() + await hub.init_api_tokens() + await hub.init_role_assignment() + user = orm.User.find(hub.db, name='ben') + happy_token, content_token, sad_token = user.api_tokens + assert len(happy_token.roles) == 1 + assert len(content_token.roles) == 1 + print(sad_token.roles) + assert len(sad_token.roles) == 0 + for token in user.api_tokens: + hub.db.delete(token) + hub.db.commit() diff --git a/jupyterhub/tests/test_scopes.py b/jupyterhub/tests/test_scopes.py new file mode 100644 --- /dev/null +++ b/jupyterhub/tests/test_scopes.py @@ -0,0 +1,926 @@ +"""Test scopes for API handlers""" +from unittest import mock + +import pytest +from pytest import mark +from tornado import web +from tornado.httputil import HTTPServerRequest + +from .. import orm +from .. import roles +from ..handlers import BaseHandler +from ..scopes import _check_scope_access +from ..scopes import _intersect_expanded_scopes +from ..scopes import get_scopes_for +from ..scopes import needs_scope +from ..scopes import parse_scopes +from ..scopes import Scope +from .utils import add_user +from .utils import api_request +from .utils import auth_header + + +def get_handler_with_scopes(scopes): + handler = mock.Mock(spec=BaseHandler) + handler.parsed_scopes = parse_scopes(scopes) + return handler + + +def test_scope_constructor(): + user1 = 'george' + user2 = 'michael' + scope_list = [ + 'users', + 'read:users!user={}'.format(user1), + 'read:users!user={}'.format(user2), + ] + parsed_scopes = parse_scopes(scope_list) + + assert 'read:users' in parsed_scopes + assert parsed_scopes['users'] + assert set(parsed_scopes['read:users']['user']) == {user1, user2} + + +def test_scope_precendence(): + scope_list = ['read:users!user=maeby', 'read:users'] + parsed_scopes = parse_scopes(scope_list) + assert parsed_scopes['read:users'] == Scope.ALL + + +def test_scope_check_present(): + handler = get_handler_with_scopes(['read:users']) + assert _check_scope_access(handler, 'read:users') + assert _check_scope_access(handler, 'read:users', user='maeby') + + +def test_scope_check_not_present(): + handler = get_handler_with_scopes(['read:users!user=maeby']) + assert _check_scope_access(handler, 'read:users') + with pytest.raises(web.HTTPError): + _check_scope_access(handler, 'read:users', user='gob') + with pytest.raises(web.HTTPError): + _check_scope_access(handler, 'read:users', user='gob', server='server') + + +def test_scope_filters(): + handler = get_handler_with_scopes( + ['read:users', 'read:users!group=bluths', 'read:users!user=maeby'] + ) + assert _check_scope_access(handler, 'read:users', group='bluth') + assert _check_scope_access(handler, 'read:users', user='maeby') + + +def test_scope_multiple_filters(): + handler = get_handler_with_scopes(['read:users!user=george_michael']) + assert _check_scope_access( + handler, 'read:users', user='george_michael', group='bluths' + ) + + +def test_scope_parse_server_name(): + handler = get_handler_with_scopes( + ['servers!server=maeby/server1', 'read:users!user=maeby'] + ) + assert _check_scope_access(handler, 'servers', user='maeby', server='server1') + + +class MockAPIHandler: + def __init__(self): + self.expanded_scopes = {'users'} + self.parsed_scopes = {} + self.request = mock.Mock(spec=HTTPServerRequest) + self.request.path = '/path' + + def set_scopes(self, *scopes): + self.expanded_scopes = set(scopes) + self.parsed_scopes = parse_scopes(self.expanded_scopes) + + @needs_scope('users') + def user_thing(self, user_name): + return True + + @needs_scope('servers') + def server_thing(self, user_name, server_name): + return True + + @needs_scope('read:groups') + def group_thing(self, group_name): + return True + + @needs_scope('read:services') + def service_thing(self, service_name): + return True + + @needs_scope('users') + def other_thing(self, non_filter_argument): + # Rely on inner vertical filtering + return True + + @needs_scope('users') + @needs_scope('read:services') + def secret_thing(self): + return True + + [email protected] +def mock_handler(): + obj = MockAPIHandler() + return obj + + [email protected]( + "scopes, method, arguments, is_allowed", + [ + (['users'], 'user_thing', ('user',), True), + (['users'], 'user_thing', ('michael',), True), + ([''], 'user_thing', ('michael',), False), + (['read:users'], 'user_thing', ('gob',), False), + (['read:users'], 'user_thing', ('michael',), False), + (['users!user=george'], 'user_thing', ('george',), True), + (['users!user=george'], 'user_thing', ('fake_user',), False), + (['users!user=george'], 'user_thing', ('oscar',), False), + (['users!user=george', 'users!user=oscar'], 'user_thing', ('oscar',), True), + (['servers'], 'server_thing', ('user1', 'server_1'), True), + (['servers'], 'server_thing', ('user1', ''), True), + (['servers'], 'server_thing', ('user1', None), True), + ( + ['servers!server=maeby/bluth'], + 'server_thing', + ('maeby', 'bluth'), + True, + ), + (['servers!server=maeby/bluth'], 'server_thing', ('gob', 'bluth'), False), + ( + ['servers!server=maeby/bluth'], + 'server_thing', + ('maybe', 'bluth2'), + False, + ), + (['read:services'], 'service_thing', ('service1',), True), + ( + ['users!user=george', 'read:groups!group=bluths'], + 'group_thing', + ('bluths',), + True, + ), + ( + ['users!user=george', 'read:groups!group=bluths'], + 'group_thing', + ('george',), + False, + ), + ( + ['groups!group=george', 'read:groups!group=bluths'], + 'group_thing', + ('george',), + False, + ), + (['users'], 'other_thing', ('gob',), True), + (['read:users'], 'other_thing', ('gob',), False), + (['users!user=gob'], 'other_thing', ('gob',), True), + (['users!user=gob'], 'other_thing', ('maeby',), True), + ], +) +def test_scope_method_access(mock_handler, scopes, method, arguments, is_allowed): + mock_handler.current_user = mock.Mock(name=arguments[0]) + mock_handler.set_scopes(*scopes) + api_call = getattr(mock_handler, method) + if is_allowed: + assert api_call(*arguments) + else: + with pytest.raises(web.HTTPError): + api_call(*arguments) + + +def test_double_scoped_method_succeeds(mock_handler): + mock_handler.current_user = mock.Mock(name='lucille') + mock_handler.set_scopes('users', 'read:services') + mock_handler.parsed_scopes = parse_scopes(mock_handler.expanded_scopes) + assert mock_handler.secret_thing() + + +def test_double_scoped_method_denials(mock_handler): + mock_handler.current_user = mock.Mock(name='lucille2') + mock_handler.set_scopes('users', 'read:groups') + with pytest.raises(web.HTTPError): + mock_handler.secret_thing() + + [email protected]( + "user_name, in_group, status_code", + [ + ('martha', False, 200), + ('michael', True, 200), + ('gob', True, 200), + ('tobias', False, 404), + ('ann', False, 404), + ], +) +async def test_expand_groups(app, user_name, in_group, status_code): + test_role = { + 'name': 'test', + 'description': '', + 'users': [user_name], + 'scopes': [ + 'read:users!user=martha', + 'read:users!group=bluth', + 'read:groups', + ], + } + roles.create_role(app.db, test_role) + user = add_user(app.db, name=user_name) + group_name = 'bluth' + group = orm.Group.find(app.db, name=group_name) + if not group: + group = orm.Group(name=group_name) + app.db.add(group) + if in_group and user not in group.users: + group.users.append(user) + roles.update_roles(app.db, user, roles=['test']) + roles.strip_role(app.db, user, 'user') + app.db.commit() + r = await api_request( + app, 'users', user_name, headers=auth_header(app.db, user_name) + ) + assert r.status_code == status_code + app.db.delete(group) + app.db.commit() + + +async def test_by_fake_user(app): + user_name = 'shade' + user = add_user(app.db, name=user_name) + auth_ = auth_header(app.db, user_name) + app.users.delete(user) + app.db.commit() + r = await api_request(app, 'users', headers=auth_) + assert r.status_code == 403 + + +err_message = "No access to resources or resources not found" + + +async def test_request_fake_user(app, create_user_with_scopes): + fake_user = 'annyong' + user = create_user_with_scopes('read:users!group=stuff') + r = await api_request( + app, 'users', fake_user, headers=auth_header(app.db, user.name) + ) + assert r.status_code == 404 + # Consistency between no user and user not accessible + assert r.json()['message'] == err_message + + +async def test_refuse_exceeding_token_permissions( + app, create_user_with_scopes, create_temp_role +): + user = create_user_with_scopes('self') + user.new_api_token() + create_temp_role(['admin:users'], 'exceeding_role') + with pytest.raises(ValueError): + roles.update_roles(app.db, entity=user.api_tokens[0], roles=['exceeding_role']) + + +async def test_exceeding_user_permissions( + app, create_user_with_scopes, create_temp_role +): + user = create_user_with_scopes('read:users:groups') + api_token = user.new_api_token() + orm_api_token = orm.APIToken.find(app.db, token=api_token) + create_temp_role(['read:users'], 'reader_role') + roles.grant_role(app.db, orm_api_token, rolename='reader_role') + headers = {'Authorization': 'token %s' % api_token} + r = await api_request(app, 'users', headers=headers) + assert r.status_code == 200 + keys = {key for user in r.json() for key in user.keys()} + assert 'groups' in keys + assert 'last_activity' not in keys + + +async def test_user_service_separation(app, mockservice_url, create_temp_role): + name = mockservice_url.name + user = add_user(app.db, name=name) + + create_temp_role(['read:users'], 'reader_role') + create_temp_role(['read:users:groups'], 'subreader_role') + roles.update_roles(app.db, user, roles=['subreader_role']) + roles.update_roles(app.db, mockservice_url.orm, roles=['reader_role']) + user.roles.remove(orm.Role.find(app.db, name='user')) + api_token = user.new_api_token() + headers = {'Authorization': 'token %s' % api_token} + r = await api_request(app, 'users', headers=headers) + assert r.status_code == 200 + keys = {key for user in r.json() for key in user.keys()} + assert 'groups' in keys + assert 'last_activity' not in keys + + +async def test_request_user_outside_group(app, create_user_with_scopes): + outside_user = 'hello' + user = create_user_with_scopes('read:users!group=stuff') + add_user(app.db, name=outside_user) + r = await api_request( + app, 'users', outside_user, headers=auth_header(app.db, user.name) + ) + assert r.status_code == 404 + # Consistency between no user and user not accessible + assert r.json()['message'] == err_message + + +async def test_user_filter(app, create_user_with_scopes): + user = create_user_with_scopes( + 'read:users!user=lindsay', 'read:users!user=gob', 'read:users!user=oscar' + ) + name_in_scope = {'lindsay', 'oscar', 'gob'} + outside_scope = {'maeby', 'marta'} + group_name = 'bluth' + group = orm.Group.find(app.db, name=group_name) + if not group: + group = orm.Group(name=group_name) + app.db.add(group) + for name in name_in_scope | outside_scope: + group_user = add_user(app.db, name=name) + if name not in group.users: + group.users.append(group_user) + app.db.commit() + r = await api_request(app, 'users', headers=auth_header(app.db, user.name)) + assert r.status_code == 200 + result_names = {user['name'] for user in r.json()} + assert result_names == name_in_scope + app.db.delete(group) + app.db.commit() + + +async def test_service_filter(app, create_user_with_scopes): + services = [ + {'name': 'cull_idle', 'api_token': 'some-token'}, + {'name': 'user_service', 'api_token': 'some-other-token'}, + ] + for service in services: + app.services.append(service) + app.init_services() + user = create_user_with_scopes('read:services!service=cull_idle') + r = await api_request(app, 'services', headers=auth_header(app.db, user.name)) + assert r.status_code == 200 + service_names = set(r.json().keys()) + assert service_names == {'cull_idle'} + + +async def test_user_filter_with_group(app, create_user_with_scopes): + group_name = 'sitwell' + user1 = create_user_with_scopes(f'read:users!group={group_name}') + user2 = create_user_with_scopes('self') + external_user = create_user_with_scopes('self') + name_set = {user1.name, user2.name} + group = orm.Group.find(app.db, name=group_name) + if not group: + group = orm.Group(name=group_name) + app.db.add(group) + for user in {user1, user2}: + group.users.append(user) + app.db.commit() + + r = await api_request(app, 'users', headers=auth_header(app.db, user1.name)) + assert r.status_code == 200 + result_names = {user['name'] for user in r.json()} + assert result_names == name_set + assert external_user.name not in result_names + app.db.delete(group) + app.db.commit() + + +async def test_group_scope_filter(app, create_user_with_scopes): + in_groups = {'sitwell', 'bluth'} + out_groups = {'austero'} + user = create_user_with_scopes( + *(f'read:groups!group={group}' for group in in_groups) + ) + for group_name in in_groups | out_groups: + group = orm.Group.find(app.db, name=group_name) + if not group: + group = orm.Group(name=group_name) + app.db.add(group) + app.db.commit() + r = await api_request(app, 'groups', headers=auth_header(app.db, user.name)) + assert r.status_code == 200 + result_names = {user['name'] for user in r.json()} + assert result_names == in_groups + for group_name in in_groups | out_groups: + group = orm.Group.find(app.db, name=group_name) + app.db.delete(group) + app.db.commit() + + +async def test_vertical_filter(app, create_user_with_scopes): + user = create_user_with_scopes('read:users:name') + r = await api_request(app, 'users', headers=auth_header(app.db, user.name)) + assert r.status_code == 200 + allowed_keys = {'name', 'kind', 'admin'} + assert set([key for user in r.json() for key in user.keys()]) == allowed_keys + + +async def test_stacked_vertical_filter(app, create_user_with_scopes): + user = create_user_with_scopes('read:users:activity', 'read:users:groups') + r = await api_request(app, 'users', headers=auth_header(app.db, user.name)) + assert r.status_code == 200 + allowed_keys = {'name', 'kind', 'groups', 'last_activity'} + result_model = set([key for user in r.json() for key in user.keys()]) + assert result_model == allowed_keys + + +async def test_cross_filter(app, create_user_with_scopes): + user = create_user_with_scopes('read:users:activity', 'self') + new_users = {'britta', 'jeff', 'annie'} + for new_user_name in new_users: + add_user(app.db, name=new_user_name) + app.db.commit() + r = await api_request(app, 'users', headers=auth_header(app.db, user.name)) + assert r.status_code == 200 + restricted_keys = {'name', 'kind', 'last_activity'} + key_in_full_model = 'created' + for model_user in r.json(): + if model_user['name'] == user.name: + assert key_in_full_model in model_user + else: + assert set(model_user.keys()) == restricted_keys + + [email protected]( + "kind, has_user_scopes", + [ + ('users', True), + ('services', False), + ], +) +async def test_metascope_self_expansion( + app, kind, has_user_scopes, create_user_with_scopes, create_service_with_scopes +): + if kind == 'users': + orm_obj = create_user_with_scopes('self').orm_user + else: + orm_obj = create_service_with_scopes('self') + # test expansion of user/service scopes + scopes = roles.expand_roles_to_scopes(orm_obj) + assert bool(scopes) == has_user_scopes + + # test expansion of token scopes + orm_obj.new_api_token() + token_scopes = get_scopes_for(orm_obj.api_tokens[0]) + assert bool(token_scopes) == has_user_scopes + + +async def test_metascope_all_expansion(app, create_user_with_scopes): + user = create_user_with_scopes('self') + user.new_api_token() + token = user.api_tokens[0] + # Check 'all' expansion + token_scope_set = get_scopes_for(token) + user_scope_set = get_scopes_for(user) + assert user_scope_set == token_scope_set + + # Check no roles means no permissions + token.roles.clear() + app.db.commit() + token_scope_set = get_scopes_for(token) + assert not token_scope_set + + [email protected]( + "scopes, can_stop ,num_servers, keys_in, keys_out", + [ + (['read:servers!user=almond'], False, 2, {'name'}, {'state'}), + (['admin:users', 'read:users'], False, 0, set(), set()), + ( + ['read:servers!group=nuts', 'servers'], + True, + 2, + {'name'}, + {'state'}, + ), + ( + ['admin:server_state', 'read:servers'], + False, + 2, + {'name', 'state'}, + set(), + ), + ( + [ + 'read:servers!server=almond/bianca', + 'admin:server_state!server=almond/bianca', + ], + False, + 1, + {'name', 'state'}, + set(), + ), + ], +) +async def test_server_state_access( + app, + create_user_with_scopes, + create_service_with_scopes, + scopes, + can_stop, + num_servers, + keys_in, + keys_out, +): + with mock.patch.dict( + app.tornado_settings, + {'allow_named_servers': True, 'named_server_limit_per_user': 2}, + ): + user = create_user_with_scopes('self', name='almond') + group_name = 'nuts' + group = orm.Group.find(app.db, name=group_name) + if not group: + group = orm.Group(name=group_name) + app.db.add(group) + group.users.append(user) + app.db.commit() + server_names = ['bianca', 'terry'] + for server_name in server_names: + await api_request( + app, 'users', user.name, 'servers', server_name, method='post' + ) + service = create_service_with_scopes(*scopes) + api_token = service.new_api_token() + headers = {'Authorization': 'token %s' % api_token} + r = await api_request(app, 'users', user.name, headers=headers) + r.raise_for_status() + user_model = r.json() + if num_servers: + assert 'servers' in user_model + server_models = user_model['servers'] + assert len(server_models) == num_servers + for server, server_model in server_models.items(): + assert keys_in.issubset(server_model) + assert keys_out.isdisjoint(server_model) + else: + assert 'servers' not in user_model + r = await api_request( + app, + 'users', + user.name, + 'servers', + server_names[0], + method='delete', + headers=headers, + ) + if can_stop: + assert r.status_code == 204 + else: + assert r.status_code == 403 + app.db.delete(group) + app.db.commit() + + [email protected]( + "name, user_scopes, token_scopes, intersection_scopes", + [ + ( + 'no_filter', + ['users:activity'], + ['users:activity'], + {'users:activity', 'read:users:activity'}, + ), + ( + 'valid_own_filter', + ['read:users:activity'], + ['read:users:activity!user'], + {'read:users:activity!user=temp_user_1'}, + ), + ( + 'valid_other_filter', + ['read:users:activity'], + ['read:users:activity!user=otheruser'], + {'read:users:activity!user=otheruser'}, + ), + ( + 'no_filter_owner_filter', + ['read:users:activity!user'], + ['read:users:activity'], + {'read:users:activity!user=temp_user_1'}, + ), + ( + 'valid_own_filter', + ['read:users:activity!user'], + ['read:users:activity!user'], + {'read:users:activity!user=temp_user_1'}, + ), + ( + 'invalid_filter', + ['read:users:activity!user'], + ['read:users:activity!user=otheruser'], + set(), + ), + ( + 'subscopes_cross_filter', + ['users!user=x'], + ['read:users:name'], + {'read:users:name!user=x'}, + ), + ( + 'multiple_user_filter', + ['users!user=x', 'users!user=y'], + ['read:users:name!user=x'], + {'read:users:name!user=x'}, + ), + ( + 'no_intersection_group_user', + ['users!group=y'], + ['users!user=x'], + set(), + ), + ( + 'no_intersection_user_server', + ['servers!user=y'], + ['servers!server=x'], + set(), + ), + ( + 'users_and_groups_both', + ['users!group=x', 'users!user=y'], + ['read:users:name!group=x', 'read:users!user=y'], + { + 'read:users:name!group=x', + 'read:users!user=y', + 'read:users:name!user=y', + 'read:users:groups!user=y', + 'read:users:activity!user=y', + }, + ), + ( + 'users_and_groups_user_only', + ['users!group=x', 'users!user=y'], + ['read:users:name!group=z', 'read:users!user=y'], + { + 'read:users!user=y', + 'read:users:name!user=y', + 'read:users:groups!user=y', + 'read:users:activity!user=y', + }, + ), + ], +) +async def test_resolve_token_permissions( + app, + create_user_with_scopes, + create_temp_role, + name, + user_scopes, + token_scopes, + intersection_scopes, +): + orm_user = create_user_with_scopes(*user_scopes).orm_user + create_temp_role(token_scopes, 'active-posting') + api_token = orm_user.new_api_token(roles=['active-posting']) + orm_api_token = orm.APIToken.find(app.db, token=api_token) + + # get expanded !user filter scopes for check + user_scopes = roles.expand_roles_to_scopes(orm_user) + token_scopes = roles.expand_roles_to_scopes(orm_api_token) + + token_retained_scopes = get_scopes_for(orm_api_token) + + assert token_retained_scopes == intersection_scopes + + [email protected]( + "scopes, model_keys", + [ + ( + {'read:services'}, + { + 'command', + 'name', + 'kind', + 'info', + 'display', + 'pid', + 'admin', + 'prefix', + 'url', + }, + ), + ( + {'read:roles:services', 'read:services:name'}, + {'name', 'kind', 'roles', 'admin'}, + ), + ({'read:services:name'}, {'name', 'kind', 'admin'}), + ], +) +async def test_service_model_filtering( + app, scopes, model_keys, create_user_with_scopes, create_service_with_scopes +): + user = create_user_with_scopes(*scopes, name='teddy') + service = create_service_with_scopes() + r = await api_request( + app, 'services', service.name, headers=auth_header(app.db, user.name) + ) + assert r.status_code == 200 + assert model_keys == r.json().keys() + + [email protected]( + "scopes, model_keys", + [ + ( + {'read:groups'}, + { + 'name', + 'kind', + 'users', + }, + ), + ( + {'read:roles:groups', 'read:groups:name'}, + {'name', 'kind', 'roles'}, + ), + ({'read:groups:name'}, {'name', 'kind'}), + ], +) +async def test_group_model_filtering( + app, scopes, model_keys, create_user_with_scopes, create_service_with_scopes +): + user = create_user_with_scopes(*scopes, name='teddy') + group_name = 'baker_street' + group = orm.Group.find(app.db, name=group_name) + if not group: + group = orm.Group(name=group_name) + app.db.add(group) + app.db.commit() + r = await api_request( + app, 'groups', group_name, headers=auth_header(app.db, user.name) + ) + assert r.status_code == 200 + assert model_keys == r.json().keys() + app.db.delete(group) + app.db.commit() + + +async def test_roles_access(app, create_service_with_scopes, create_user_with_scopes): + user = add_user(app.db, name='miranda') + read_user = create_user_with_scopes('read:roles:users') + r = await api_request( + app, 'users', user.name, headers=auth_header(app.db, read_user.name) + ) + assert r.status_code == 200 + model_keys = {'kind', 'name', 'roles', 'admin'} + assert model_keys == r.json().keys() + + [email protected]( + "left, right, expected, should_warn", + [ + (set(), set(), set(), False), + (set(), set(["users"]), set(), False), + # no warning if users and groups only on the same side + ( + set(["users!user=x", "users!group=y"]), + set([]), + set([]), + False, + ), + # no warning if users are on both sizes + ( + set(["users!user=x", "users!user=y", "users!group=y"]), + set(["users!user=x"]), + set(["users!user=x"]), + False, + ), + # no warning if users and groups are both defined + # on both sides + ( + set(["users!user=x", "users!group=y"]), + set(["users!user=x", "users!group=y", "users!user=z"]), + set(["users!user=x", "users!group=y"]), + False, + ), + # warn if there's a user on one side and a group on the other + # which *may* intersect + ( + set(["users!group=y", "users!user=z"]), + set(["users!user=x"]), + set([]), + True, + ), + # same for group->server + ( + set(["users!group=y", "users!user=z"]), + set(["users!server=x/y"]), + set([]), + True, + ), + # this one actually shouldn't warn because server=x/y is under user=x, + # but we don't need to overcomplicate things just for a warning + ( + set(["users!group=y", "users!user=x"]), + set(["users!server=x/y"]), + set(["users!server=x/y"]), + True, + ), + # resolves server under user, without warning + ( + set(["read:servers!user=abc"]), + set(["read:servers!server=abc/xyz"]), + set(["read:servers!server=abc/xyz"]), + False, + ), + # user->server, no match + ( + set(["read:servers!user=abc"]), + set(["read:servers!server=abcd/xyz"]), + set([]), + False, + ), + ], +) +def test_intersect_expanded_scopes(left, right, expected, should_warn, recwarn): + # run every test in both directions, to ensure symmetry of the inputs + for a, b in [(left, right), (right, left)]: + intersection = _intersect_expanded_scopes(set(left), set(right)) + assert intersection == set(expected) + + if should_warn: + assert len(recwarn) == 1 + else: + assert len(recwarn) == 0 + + [email protected]( + "left, right, expected, groups", + [ + ( + ["users!group=gx"], + ["users!user=ux"], + ["users!user=ux"], + {"gx": ["ux"]}, + ), + ( + ["read:users!group=gx"], + ["read:users!user=nosuchuser"], + [], + {}, + ), + ( + ["read:users!group=gx"], + ["read:users!server=nosuchuser/server"], + [], + {}, + ), + ( + ["read:users!group=gx"], + ["read:users!server=ux/server"], + ["read:users!server=ux/server"], + {"gx": ["ux"]}, + ), + ( + ["read:users!group=gx"], + ["read:users!server=ux/server", "read:users!user=uy"], + ["read:users!server=ux/server"], + {"gx": ["ux"], "gy": ["uy"]}, + ), + ( + ["read:users!group=gy"], + ["read:users!server=ux/server", "read:users!user=uy"], + ["read:users!user=uy"], + {"gx": ["ux"], "gy": ["uy"]}, + ), + ], +) +def test_intersect_groups(request, db, left, right, expected, groups): + if isinstance(left, str): + left = set([left]) + if isinstance(right, str): + right = set([right]) + + # if we have a db connection, we can actually resolve + created = [] + for groupname, members in groups.items(): + group = orm.Group.find(db, name=groupname) + if not group: + group = orm.Group(name=groupname) + db.add(group) + created.append(group) + db.commit() + for username in members: + user = orm.User.find(db, name=username) + if user is None: + user = orm.User(name=username) + db.add(user) + created.append(user) + user.groups.append(group) + db.commit() + + def _cleanup(): + for obj in created: + db.delete(obj) + db.commit() + + request.addfinalizer(_cleanup) + + # run every test in both directions, to ensure symmetry of the inputs + for a, b in [(left, right), (right, left)]: + intersection = _intersect_expanded_scopes(set(left), set(right), db) + assert intersection == set(expected) diff --git a/jupyterhub/tests/test_services.py b/jupyterhub/tests/test_services.py --- a/jupyterhub/tests/test_services.py +++ b/jupyterhub/tests/test_services.py @@ -3,12 +3,13 @@ import os import sys from binascii import hexlify -from contextlib import contextmanager from subprocess import Popen from async_generator import asynccontextmanager -from tornado.ioloop import IOLoop +from .. import orm +from ..roles import update_roles +from ..utils import exponential_backoff from ..utils import maybe_future from ..utils import random_port from ..utils import url_path_join @@ -51,11 +52,11 @@ async def test_managed_service(mockservice): assert proc.poll() is not None # ensure Hub notices service is down and brings it back up: - for i in range(20): - if service.proc is not proc: - break - else: - await asyncio.sleep(0.2) + await exponential_backoff( + lambda: service.proc is not proc, + "Process was never replaced", + timeout=20, + ) assert service.proc.pid != first_pid assert service.proc.poll() is None @@ -85,13 +86,20 @@ async def test_external_service(app): 'admin': True, 'url': env['JUPYTERHUB_SERVICE_URL'], 'api_token': env['JUPYTERHUB_API_TOKEN'], + 'oauth_roles': ['user'], } ] await maybe_future(app.init_services()) await app.init_api_tokens() await app.proxy.add_all_services(app._service_map) + await app.init_role_assignment() service = app._service_map[name] + assert service.oauth_available + assert service.oauth_client is not None + assert service.oauth_client.allowed_roles == [orm.Role.find(app.db, "user")] + api_token = service.orm.api_tokens[0] + update_roles(app.db, api_token, roles=['token']) url = public_url(app, service) + '/api/users' r = await async_requests.get(url, allow_redirects=False) r.raise_for_status() diff --git a/jupyterhub/tests/test_services_auth.py b/jupyterhub/tests/test_services_auth.py --- a/jupyterhub/tests/test_services_auth.py +++ b/jupyterhub/tests/test_services_auth.py @@ -1,33 +1,20 @@ """Tests for service authentication""" -import asyncio import copy -import json import os import sys from binascii import hexlify -from functools import partial -from queue import Queue -from threading import Thread from unittest import mock +from urllib.parse import parse_qs from urllib.parse import urlparse -import requests -import requests_mock +import pytest from pytest import raises -from tornado.httpserver import HTTPServer from tornado.httputil import url_concat -from tornado.ioloop import IOLoop -from tornado.web import Application -from tornado.web import authenticated -from tornado.web import HTTPError -from tornado.web import RequestHandler from .. import orm +from .. import roles from ..services.auth import _ExpiringDict -from ..services.auth import HubAuth -from ..services.auth import HubAuthenticated from ..utils import url_path_join -from .mocking import public_host from .mocking import public_url from .test_api import add_user from .utils import async_requests @@ -74,192 +61,29 @@ def test_expiring_dict(): assert cache.get('key', 'default') == 'cached value' -def test_hub_auth(): - auth = HubAuth(cookie_name='foo') - mock_model = {'name': 'onyxia'} - url = url_path_join(auth.api_url, "authorizations/cookie/foo/bar") - with requests_mock.Mocker() as m: - m.get(url, text=json.dumps(mock_model)) - user_model = auth.user_for_cookie('bar') - assert user_model == mock_model - # check cache - user_model = auth.user_for_cookie('bar') - assert user_model == mock_model - - with requests_mock.Mocker() as m: - m.get(url, status_code=404) - user_model = auth.user_for_cookie('bar', use_cache=False) - assert user_model is None - - # invalidate cache with timer - mock_model = {'name': 'willow'} - with monotonic_future, requests_mock.Mocker() as m: - m.get(url, text=json.dumps(mock_model)) - user_model = auth.user_for_cookie('bar') - assert user_model == mock_model - - with requests_mock.Mocker() as m: - m.get(url, status_code=500) - with raises(HTTPError) as exc_info: - user_model = auth.user_for_cookie('bar', use_cache=False) - assert exc_info.value.status_code == 502 - - with requests_mock.Mocker() as m: - m.get(url, status_code=400) - with raises(HTTPError) as exc_info: - user_model = auth.user_for_cookie('bar', use_cache=False) - assert exc_info.value.status_code == 500 - - -def test_hub_authenticated(request): - auth = HubAuth(cookie_name='jubal') - mock_model = {'name': 'jubalearly', 'groups': ['lions']} - cookie_url = url_path_join(auth.api_url, "authorizations/cookie", auth.cookie_name) - good_url = url_path_join(cookie_url, "early") - bad_url = url_path_join(cookie_url, "late") - - class TestHandler(HubAuthenticated, RequestHandler): - hub_auth = auth - - @authenticated - def get(self): - self.finish(self.get_current_user()) - - # start hub-authenticated service in a thread: - port = 50505 - q = Queue() - - def run(): - asyncio.set_event_loop(asyncio.new_event_loop()) - app = Application([('/*', TestHandler)], login_url=auth.login_url) - - http_server = HTTPServer(app) - http_server.listen(port) - loop = IOLoop.current() - loop.add_callback(lambda: q.put(loop)) - loop.start() - - t = Thread(target=run) - t.start() - - def finish_thread(): - loop.add_callback(loop.stop) - t.join(timeout=30) - assert not t.is_alive() - - request.addfinalizer(finish_thread) - - # wait for thread to start - loop = q.get(timeout=10) - - with requests_mock.Mocker(real_http=True) as m: - # no cookie - r = requests.get('http://127.0.0.1:%i' % port, allow_redirects=False) - r.raise_for_status() - assert r.status_code == 302 - assert auth.login_url in r.headers['Location'] - - # wrong cookie - m.get(bad_url, status_code=404) - r = requests.get( - 'http://127.0.0.1:%i' % port, - cookies={'jubal': 'late'}, - allow_redirects=False, - ) - r.raise_for_status() - assert r.status_code == 302 - assert auth.login_url in r.headers['Location'] - - # clear the cache because we are going to request - # the same url again with a different result - auth.cache.clear() - - # upstream 403 - m.get(bad_url, status_code=403) - r = requests.get( - 'http://127.0.0.1:%i' % port, - cookies={'jubal': 'late'}, - allow_redirects=False, - ) - assert r.status_code == 500 - - m.get(good_url, text=json.dumps(mock_model)) - - # no specific allowed user - r = requests.get( - 'http://127.0.0.1:%i' % port, - cookies={'jubal': 'early'}, - allow_redirects=False, - ) - r.raise_for_status() - assert r.status_code == 200 - - # pass allowed user - TestHandler.hub_users = {'jubalearly'} - r = requests.get( - 'http://127.0.0.1:%i' % port, - cookies={'jubal': 'early'}, - allow_redirects=False, - ) - r.raise_for_status() - assert r.status_code == 200 - - # no pass allowed ser - TestHandler.hub_users = {'kaylee'} - r = requests.get( - 'http://127.0.0.1:%i' % port, - cookies={'jubal': 'early'}, - allow_redirects=False, - ) - assert r.status_code == 403 - - # pass allowed group - TestHandler.hub_groups = {'lions'} - r = requests.get( - 'http://127.0.0.1:%i' % port, - cookies={'jubal': 'early'}, - allow_redirects=False, - ) - r.raise_for_status() - assert r.status_code == 200 - - # no pass allowed group - TestHandler.hub_groups = {'tigers'} - r = requests.get( - 'http://127.0.0.1:%i' % port, - cookies={'jubal': 'early'}, - allow_redirects=False, - ) - assert r.status_code == 403 - - -async def test_hubauth_cookie(app, mockservice_url): - """Test HubAuthenticated service with user cookies""" - cookies = await app.login_user('badger') - r = await async_requests.get( - public_url(app, mockservice_url) + '/whoami/', cookies=cookies - ) - r.raise_for_status() - print(r.text) - reply = r.json() - sub_reply = {key: reply.get(key, 'missing') for key in ['name', 'admin']} - assert sub_reply == {'name': 'badger', 'admin': False} - - -async def test_hubauth_token(app, mockservice_url): +async def test_hubauth_token(app, mockservice_url, create_user_with_scopes): """Test HubAuthenticated service with user API tokens""" - u = add_user(app.db, name='river') + u = create_user_with_scopes("access:services") token = u.new_api_token() + no_access_token = u.new_api_token(roles=[]) app.db.commit() + # token without sufficient permission in Authorization header + r = await async_requests.get( + public_url(app, mockservice_url) + '/whoami/', + headers={'Authorization': f'token {no_access_token}'}, + ) + assert r.status_code == 403 + # token in Authorization header r = await async_requests.get( public_url(app, mockservice_url) + '/whoami/', - headers={'Authorization': 'token %s' % token}, + headers={'Authorization': f'token {token}'}, ) + r.raise_for_status() reply = r.json() sub_reply = {key: reply.get(key, 'missing') for key in ['name', 'admin']} - assert sub_reply == {'name': 'river', 'admin': False} + assert sub_reply == {'name': u.name, 'admin': False} # token in ?token parameter r = await async_requests.get( @@ -268,7 +92,7 @@ async def test_hubauth_token(app, mockservice_url): r.raise_for_status() reply = r.json() sub_reply = {key: reply.get(key, 'missing') for key in ['name', 'admin']} - assert sub_reply == {'name': 'river', 'admin': False} + assert sub_reply == {'name': u.name, 'admin': False} r = await async_requests.get( public_url(app, mockservice_url) + '/whoami/?token=no-such-token', @@ -281,34 +105,95 @@ async def test_hubauth_token(app, mockservice_url): assert path.endswith('/hub/login') -async def test_hubauth_service_token(app, mockservice_url): [email protected]( + "scopes, allowed", + [ + ( + [ + "access:services", + ], + True, + ), + ( + [ + "access:services!service=$service", + ], + True, + ), + ( + [ + "access:services!service=other-service", + ], + False, + ), + ( + [ + "access:servers!user=$service", + ], + False, + ), + ], +) +async def test_hubauth_service_token(request, app, mockservice_url, scopes, allowed): """Test HubAuthenticated service with service API tokens""" + scopes = [scope.replace('$service', mockservice_url.name) for scope in scopes] + token = hexlify(os.urandom(5)).decode('utf8') name = 'test-api-service' app.service_tokens[token] = name await app.init_api_tokens() + orm_service = app.db.query(orm.Service).filter_by(name=name).one() + role_name = "test-hubauth-service-token" + + roles.create_role( + app.db, + { + "name": role_name, + "description": "role for test", + "scopes": scopes, + }, + ) + request.addfinalizer(lambda: roles.delete_role(app.db, role_name)) + roles.grant_role(app.db, orm_service, role_name) + # token in Authorization header r = await async_requests.get( - public_url(app, mockservice_url) + '/whoami/', + public_url(app, mockservice_url) + 'whoami/', headers={'Authorization': 'token %s' % token}, + allow_redirects=False, ) - r.raise_for_status() - reply = r.json() - assert reply == {'kind': 'service', 'name': name, 'admin': False} - assert not r.cookies + service_model = { + 'kind': 'service', + 'name': name, + 'admin': False, + 'scopes': scopes, + } + if allowed: + r.raise_for_status() + assert r.status_code == 200 + reply = r.json() + assert service_model.items() <= reply.items() + assert not r.cookies + else: + assert r.status_code == 403 # token in ?token parameter r = await async_requests.get( - public_url(app, mockservice_url) + '/whoami/?token=%s' % token + public_url(app, mockservice_url) + 'whoami/?token=%s' % token ) - r.raise_for_status() - reply = r.json() - assert reply == {'kind': 'service', 'name': name, 'admin': False} + if allowed: + r.raise_for_status() + assert r.status_code == 200 + reply = r.json() + assert service_model.items() <= reply.items() + assert not r.cookies + else: + assert r.status_code == 403 r = await async_requests.get( - public_url(app, mockservice_url) + '/whoami/?token=no-such-token', + public_url(app, mockservice_url) + 'whoami/?token=no-such-token', allow_redirects=False, ) assert r.status_code == 302 @@ -318,12 +203,55 @@ async def test_hubauth_service_token(app, mockservice_url): assert path.endswith('/hub/login') -async def test_oauth_service(app, mockservice_url): [email protected]( + "client_allowed_roles, request_roles, expected_roles", + [ + # allow empty roles + ([], [], []), + # allow original 'identify' scope to map to no role + ([], ["identify"], []), + # requesting roles outside client list doesn't work + ([], ["admin"], None), + ([], ["token"], None), + # requesting nonexistent roles fails in the same way (no server error) + ([], ["nosuchrole"], None), + # requesting exactly client allow list works + (["user"], ["user"], ["user"]), + # no explicit request, defaults to all + (["token", "user"], [], ["token", "user"]), + # explicit 'identify' maps to none + (["token", "user"], ["identify"], []), + # any item outside the list isn't allowed + (["token", "user"], ["token", "server"], None), + # requesting subset + (["admin", "user"], ["user"], ["user"]), + (["user", "token", "server"], ["token", "user"], ["token", "user"]), + ], +) +async def test_oauth_service_roles( + app, + mockservice_url, + create_user_with_scopes, + client_allowed_roles, + request_roles, + expected_roles, +): service = mockservice_url + oauth_client = ( + app.db.query(orm.OAuthClient) + .filter_by(identifier=service.oauth_client_id) + .one() + ) + oauth_client.allowed_roles = [ + orm.Role.find(app.db, role_name) for role_name in client_allowed_roles + ] + app.db.commit() url = url_path_join(public_url(app, mockservice_url) + 'owhoami/?arg=x') # first request is only going to login and get us to the oauth form page s = AsyncSession() - name = 'link' + user = create_user_with_scopes("access:services") + roles.grant_role(app.db, user, "user") + name = user.name s.cookies = await app.login_user(name) r = await s.get(url) @@ -334,7 +262,18 @@ async def test_oauth_service(app, mockservice_url): assert set(r.history[0].cookies.keys()) == {'service-%s-oauth-state' % service.name} # submit the oauth form to complete authorization - r = await s.post(r.url, data={'scopes': ['identify']}, headers={'Referer': r.url}) + data = {} + if request_roles: + data["scopes"] = request_roles + r = await s.post(r.url, data=data, headers={'Referer': r.url}) + if expected_roles is None: + # expected failed auth, stop here + # verify expected 'invalid scope' error, not server error + dest_url, _, query = r.url.partition("?") + assert dest_url == public_url(app, mockservice_url) + "oauth_callback" + assert parse_qs(query).get("error") == ["invalid_scope"] + assert r.status_code == 400 + return r.raise_for_status() assert r.url == url # verify oauth cookie is set @@ -348,7 +287,7 @@ async def test_oauth_service(app, mockservice_url): assert r.status_code == 200 reply = r.json() sub_reply = {key: reply.get(key, 'missing') for key in ('kind', 'name')} - assert sub_reply == {'name': 'link', 'kind': 'user'} + assert sub_reply == {'name': user.name, 'kind': 'user'} # token-authenticated request to HubOAuth token = app.users[name].new_api_token() @@ -368,12 +307,122 @@ async def test_oauth_service(app, mockservice_url): assert reply['name'] == name -async def test_oauth_cookie_collision(app, mockservice_url): [email protected]( + "access_scopes, expect_success", + [ + (["access:services"], True), + (["access:services!service=$service"], True), + (["access:services!service=other-service"], False), + (["self"], False), + ([], False), + ], +) +async def test_oauth_access_scopes( + app, + mockservice_url, + create_user_with_scopes, + access_scopes, + expect_success, +): + """Check that oauth/authorize validates access scopes""" + service = mockservice_url + access_scopes = [s.replace("$service", service.name) for s in access_scopes] + url = url_path_join(public_url(app, mockservice_url) + 'owhoami/?arg=x') + # first request is only going to login and get us to the oauth form page + s = AsyncSession() + user = create_user_with_scopes(*access_scopes) + name = user.name + s.cookies = await app.login_user(name) + + r = await s.get(url) + if not expect_success: + assert r.status_code == 403 + return + r.raise_for_status() + # we should be looking at the oauth confirmation page + assert urlparse(r.url).path == app.base_url + 'hub/api/oauth2/authorize' + # verify oauth state cookie was set at some point + assert set(r.history[0].cookies.keys()) == {'service-%s-oauth-state' % service.name} + + # submit the oauth form to complete authorization + r = await s.post(r.url, headers={'Referer': r.url}) + r.raise_for_status() + assert r.url == url + # verify oauth cookie is set + assert 'service-%s' % service.name in set(s.cookies.keys()) + # verify oauth state cookie has been consumed + assert 'service-%s-oauth-state' % service.name not in set(s.cookies.keys()) + + # second request should be authenticated, which means no redirects + r = await s.get(url, allow_redirects=False) + r.raise_for_status() + assert r.status_code == 200 + reply = r.json() + sub_reply = {key: reply.get(key, 'missing') for key in ('kind', 'name')} + assert sub_reply == {'name': name, 'kind': 'user'} + + # revoke user access, should result in 403 + user.roles = [] + app.db.commit() + + # reset session id to avoid cached response + s.cookies.pop('jupyterhub-session-id') + + r = await s.get(url, allow_redirects=False) + assert r.status_code == 403 + + [email protected]( + "token_roles, hits_page", + [([], True), (['writer'], True), (['writer', 'reader'], False)], +) +async def test_oauth_page_hit( + app, + mockservice_url, + create_user_with_scopes, + create_temp_role, + token_roles, + hits_page, +): + test_roles = { + 'reader': create_temp_role(['read:users'], role_name='reader'), + 'writer': create_temp_role(['users:activity'], role_name='writer'), + } + service = mockservice_url + user = create_user_with_scopes("access:services", "self") + user.new_api_token() + token = user.api_tokens[0] + token.roles = [test_roles[t] for t in token_roles] + + oauth_client = ( + app.db.query(orm.OAuthClient) + .filter_by(identifier=service.oauth_client_id) + .one() + ) + oauth_client.allowed_roles = list(test_roles.values()) + token.client_id = service.oauth_client_id + app.db.commit() + s = AsyncSession() + s.cookies = await app.login_user(user.name) + url = url_path_join(public_url(app, service) + 'owhoami/?arg=x') + r = await s.get(url) + r.raise_for_status() + if hits_page: + # hit auth page to confirm permissions + assert urlparse(r.url).path == app.base_url + 'hub/api/oauth2/authorize' + else: + # skip auth page, permissions are granted + assert r.status_code == 200 + assert r.url == url + + +async def test_oauth_cookie_collision(app, mockservice_url, create_user_with_scopes): service = mockservice_url url = url_path_join(public_url(app, mockservice_url), 'owhoami/') print(url) s = AsyncSession() name = 'mypha' + user = create_user_with_scopes("access:services", name=name) s.cookies = await app.login_user(name) state_cookie_name = 'service-%s-oauth-state' % service.name service_cookie_name = 'service-%s' % service.name @@ -426,7 +475,7 @@ async def test_oauth_cookie_collision(app, mockservice_url): assert state_cookies == [] -async def test_oauth_logout(app, mockservice_url): +async def test_oauth_logout(app, mockservice_url, create_user_with_scopes): """Verify that logout via the Hub triggers logout for oauth services 1. clears session id cookie @@ -440,15 +489,11 @@ async def test_oauth_logout(app, mockservice_url): # first request is only going to set login cookie s = AsyncSession() name = 'propha' - app_user = add_user(app.db, app=app, name=name) + user = create_user_with_scopes("access:services", name=name) def auth_tokens(): """Return list of OAuth access tokens for the user""" - return list( - app.db.query(orm.OAuthAccessToken).filter( - orm.OAuthAccessToken.user_id == app_user.id - ) - ) + return list(app.db.query(orm.APIToken).filter_by(user_id=user.id)) # ensure we start empty assert auth_tokens() == [] diff --git a/jupyterhub/tests/test_singleuser.py b/jupyterhub/tests/test_singleuser.py --- a/jupyterhub/tests/test_singleuser.py +++ b/jupyterhub/tests/test_singleuser.py @@ -3,7 +3,10 @@ from subprocess import check_output from urllib.parse import urlparse +import pytest + import jupyterhub +from .. import orm from ..utils import url_path_join from .mocking import public_url from .mocking import StubSingleUserSpawner @@ -11,7 +14,33 @@ from .utils import AsyncSession -async def test_singleuser_auth(app): [email protected]( + "access_scopes, server_name, expect_success", + [ + (["access:servers!group=$group"], "", True), + (["access:servers!group=other-group"], "", False), + (["access:servers"], "", True), + (["access:servers"], "named", True), + (["access:servers!user=$user"], "", True), + (["access:servers!user=$user"], "named", True), + (["access:servers!server=$server"], "", True), + (["access:servers!server=$server"], "named-server", True), + (["access:servers!server=$user/other"], "", False), + (["access:servers!server=$user/other"], "some-name", False), + (["access:servers!user=$other"], "", False), + (["access:servers!user=$other"], "named", False), + (["access:services"], "", False), + (["self"], "named", False), + ([], "", False), + ], +) +async def test_singleuser_auth( + app, + create_user_with_scopes, + access_scopes, + server_name, + expect_success, +): # use StubSingleUserSpawner to launch a single-user app in a thread app.spawner_class = StubSingleUserSpawner app.tornado_settings['spawner_class'] = StubSingleUserSpawner @@ -19,10 +48,21 @@ async def test_singleuser_auth(app): # login, start the server cookies = await app.login_user('nandy') user = app.users['nandy'] - if not user.running: - await user.spawn() - await app.proxy.add_user(user) - url = public_url(app, user) + + group = orm.Group.find(app.db, name="visitors") + if group is None: + group = orm.Group(name="visitors") + app.db.add(group) + app.db.commit() + if group not in user.groups: + user.groups.append(group) + app.db.commit() + + if server_name not in user.spawners or not user.spawners[server_name].active: + await user.spawn(server_name) + await app.proxy.add_user(user, server_name) + spawner = user.spawners[server_name] + url = url_path_join(public_url(app, user), server_name) # no cookies, redirects to login page r = await async_requests.get(url) @@ -40,7 +80,11 @@ async def test_singleuser_auth(app): assert ( urlparse(r.url) .path.rstrip('/') - .endswith(url_path_join('/user/nandy', user.spawner.default_url or "/tree")) + .endswith( + url_path_join( + f'/user/{user.name}', spawner.name, spawner.default_url or "/tree" + ) + ) ) assert r.status_code == 200 @@ -49,19 +93,40 @@ async def test_singleuser_auth(app): assert len(r.cookies) == 0 # accessing another user's server hits the oauth confirmation page + access_scopes = [s.replace("$user", user.name) for s in access_scopes] + access_scopes = [ + s.replace("$server", f"{user.name}/{server_name}") for s in access_scopes + ] + access_scopes = [s.replace("$group", f"{group.name}") for s in access_scopes] + other_user = create_user_with_scopes(*access_scopes, name="burgess") + cookies = await app.login_user('burgess') s = AsyncSession() s.cookies = cookies r = await s.get(url) assert urlparse(r.url).path.endswith('/oauth2/authorize') + if not expect_success: + # user isn't authorized, should raise 403 + assert r.status_code == 403 + return + r.raise_for_status() # submit the oauth form to complete authorization r = await s.post(r.url, data={'scopes': ['identify']}, headers={'Referer': r.url}) - assert ( - urlparse(r.url) - .path.rstrip('/') - .endswith(url_path_join('/user/nandy', user.spawner.default_url or "/tree")) + final_url = urlparse(r.url).path.rstrip('/') + final_path = url_path_join( + '/user/', user.name, spawner.name, spawner.default_url or "/tree" ) - # user isn't authorized, should raise 403 + assert final_url.endswith(final_path) + r.raise_for_status() + + # revoke user access, should result in 403 + other_user.roles = [] + app.db.commit() + + # reset session id to avoid cached response + s.cookies.pop('jupyterhub-session-id') + + r = await s.get(r.url, allow_redirects=False) assert r.status_code == 403 assert 'burgess' in r.text diff --git a/jupyterhub/tests/test_spawner.py b/jupyterhub/tests/test_spawner.py --- a/jupyterhub/tests/test_spawner.py +++ b/jupyterhub/tests/test_spawner.py @@ -426,3 +426,9 @@ async def test_hub_connect_url(db): env["JUPYTERHUB_ACTIVITY_URL"] == "https://example.com/api/users/%s/activity" % name ) + + +async def test_spawner_oauth_roles(app): + allowed_roles = ['lotsa', 'roles'] + spawner = new_spawner(app.db, oauth_roles=allowed_roles) + assert spawner.oauth_roles == allowed_roles diff --git a/jupyterhub/tests/utils.py b/jupyterhub/tests/utils.py --- a/jupyterhub/tests/utils.py +++ b/jupyterhub/tests/utils.py @@ -1,4 +1,5 @@ import asyncio +import inspect import os from concurrent.futures import ThreadPoolExecutor @@ -9,6 +10,8 @@ from jupyterhub import metrics from jupyterhub import orm from jupyterhub.objects import Server +from jupyterhub.roles import assign_default_roles +from jupyterhub.roles import update_roles from jupyterhub.utils import url_path_join as ujoin @@ -78,14 +81,26 @@ def api_request(app, *api_path, **kwargs): """ def new_func(app, *args, **kwargs): - retval = func(app, *args, **kwargs) - - temp_session = app.session_factory() - temp_session.execute('CREATE TABLE dummy (foo INT)') - temp_session.execute('DROP TABLE dummy') - temp_session.close() - - return retval + maybe_future = func(app, *args, **kwargs) + + def _check(_=None): + temp_session = app.session_factory() + try: + temp_session.execute('CREATE TABLE dummy (foo INT)') + temp_session.execute('DROP TABLE dummy') + finally: + temp_session.close() + + async def await_then_check(): + result = await maybe_future + _check() + return result + + if inspect.isawaitable(maybe_future): + return await_then_check() + else: + _check() + return maybe_future return new_func @@ -110,6 +125,11 @@ def add_user(db, app=None, **kwargs): for attr, value in kwargs.items(): setattr(orm_user, attr, value) db.commit() + requested_roles = kwargs.get('roles') + if requested_roles: + update_roles(db, entity=orm_user, roles=requested_roles) + else: + assign_default_roles(db, entity=orm_user) if app: return app.users[orm_user.id] else: @@ -137,7 +157,6 @@ async def api_request( else: base_url = public_url(app, path='hub') headers = kwargs.setdefault('headers', {}) - if 'Authorization' not in headers and not noauth and 'cookies' not in kwargs: # make a copy to avoid modifying arg in-place kwargs['headers'] = h = {}
auth state visible to self ### Proposed change Currently a normal/non admin user is unable to see its own auth state and this is on purpose, according to the comment in the code. I would like to ask if there is a possible security problem or any other particular reason for this decision and, if not, wether it will be possible to change it and make the auth state visible to the corresponding user as well. ### Who would use this feature? In our JH deployment, we need to forward the oAuth token we obtain from the authenticator to the user container/environment (so that other processes/extensions can use it). Of course this can already be done (by injecting it via the spawner), but then the user container (or some sidecar container/process/etc) needs to be responsible for the renewal (which seems to be the way others are doing it). But, if for some reason a re-authentication is required, then that process will get stuck and the session will have to be restarted completely. JH already has a renewal functionality baked inside and tightly coupled with everything that needs authentication. If the authenticator implements `refresh_user`, all of this will be handled automatically. If the auth state was visible to the logged-in user, then Jupyter extensions would be able to fetch the valid token just by querying the user API. This has the added advantage of keeping all the auth code in a single place, which would allow switching authenticators (which would have to implement the refresh) without having to worry about all of these extra sidecar containers/processes. ### Alternative options If this information is considered sensitive and you don't think it should be public by default (especially since this field can be used by any authenticator), it would be beneficial to have an extra field in user model that allows us to inject extra public information from the authenticator or other place. Please let me know what you think.
Thank you for opening your first issue in this project! Engagement like this is essential for open source projects! :hugs: <br>If you haven't done so already, check out [Jupyter's Code of Conduct](https://github.com/jupyter/governance/blob/master/conduct/code_of_conduct.md). Also, please try to follow the issue template as it helps other other community members to contribute more effectively. ![welcome](https://raw.githubusercontent.com/jupyterhub/.github/master/images/welcome.jpg) You can meet the other [Jovyans](https://jupyter.readthedocs.io/en/latest/community/content-community.html?highlight=jovyan#what-is-a-jovyan) by joining our [Discourse forum](http://discourse.jupyter.org/). There is also an intro thread there where you can stop by and say Hi! :wave: <br>Welcome to the Jupyter community! :tada: `auth_state` may contain tokens and other secrets that shouldn't be visible to a user. They're available to the Spawner though, so you can inject them into a user's environment, e.g. as environment variables. Will this solve your problem? Not really. As I mentioned in the ticket, I already do that. But then I need to get the **refreshed token** to continue to be able to use it (I believe that since JH already handles everything related to auth, it should be able to provide some of this info to Jupyter). Allowing extra info to be available in some other (public) field, or making the the visibility of `auth_state` configurable, would help. Hello, I am having the same issue/question like @diocas. I have this scenario: Each user should have an jupyterhub api token and with that i want to retreive the auth_state -> access_token / refresh_token / id_token for him - **not for other users** and update afterwards the env variables of the containers with the new tokens. Currently this doesn't work because the user needs to be an admin and not all of them should be admins. This is covered here: https://github.com/jupyterhub/oauthenticator/issues/211#issuecomment-569637559 (I was having the same issue) @chainlink I didn't see that ticket, but I have implemented the same workaround they suggest. But I would prefer not to have workarounds and have this properly implemented in the upstream. I don't mind implementing it and making a PR, I just wanted to know what the Jupyter team thinks is the best idea. So far I have 3 options: * We enable auth state for everyone in the self endpoint (which is the workaround suggested and might not be advisable as a general rule); * We put a switch in the config to make the auth state in the self endpoint visible or not; * We create an extra field for public information in the user state, thus allowing the authenticators to publish the tokens there. This issue has been mentioned on **Jupyter Community Forum**. There might be relevant details there: https://discourse.jupyter.org/t/accessing-upstream-oauth2-token-from-python-code-within-singleuser-notebook-server/8211/2 > I didn't see that ticket, but I have implemented the same workaround they suggest. But I would prefer not to have workarounds and have this properly implemented in the upstream. > > I don't mind implementing it and making a PR, I just wanted to know what the Jupyter team thinks is the best idea. So far I have 3 options: > > * We enable auth state for everyone in the self endpoint (which is the workaround suggested and might not be advisable as a general rule); > * We put a switch in the config to make the auth state in the self endpoint visible or not; > * We create an extra field for public information in the user state, thus allowing the authenticators to publish the tokens there. Hello together, I would really love to see this enhancement - or read reasons why we shouldn't do it (for security reasons or other reasons I can't see at the moment). From my view there is no difference in security, if we include the upstream token in the auth_state, because a logged in user may see it already, if the pre_spawn_start hook forwards it. @diocas Could you share your workaround as patch or point me to a fork? @warwing We [wrap JupyterHub](https://github.com/swan-cern/jupyterhub-extensions/blob/master/SwanHub/swanhub/app.py) (we call this wrapper SwanHub), and [replace the SelfApiHandler](https://github.com/swan-cern/jupyterhub-extensions/blob/master/SwanHub/swanhub/userapi_handler.py) with a version that always exposes the state. I recommend you do the same and create a wrapper of JH. I do not recommend you use our SwanHub cause we do other things as well. @diocas Thanks for pointing me to this. You're wrapper pattern is very nice :)
2021-04-22T12:16:24Z
[]
[]
jupyterhub/jupyterhub
3,454
jupyterhub__jupyterhub-3454
[ "3451" ]
1f7e54f652b0f6864715cd71f704242f5af56d79
diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -242,11 +242,7 @@ async def delete(self, name): await maybe_future(self.authenticator.delete_user(user)) - # allow the spawner to cleanup any persistent resources associated with the user - try: - await user.spawner.delete_forever() - except Exception as e: - self.log.error("Error cleaning up persistent resources: %s" % e) + await user.delete_spawners() # remove from registry self.users.delete(user) @@ -488,10 +484,18 @@ async def delete(self, name, server_name=''): options = self.get_json_body() remove = (options or {}).get('remove', False) - def _remove_spawner(f=None): - if f and f.exception(): - return + async def _remove_spawner(f=None): + """Remove the spawner object + + only called after it stops successfully + """ + if f: + # await f, stop on error, + # leaving resources in the db in case of failure to stop + await f self.log.info("Deleting spawner %s", spawner._log_name) + await maybe_future(user._delete_spawner(spawner)) + self.db.delete(spawner.orm_spawner) user.spawners.pop(server_name, None) self.db.commit() @@ -512,7 +516,8 @@ def _remove_spawner(f=None): self.set_header('Content-Type', 'text/plain') self.set_status(202) if remove: - spawner._stop_future.add_done_callback(_remove_spawner) + # schedule remove when stop completes + asyncio.ensure_future(_remove_spawner(spawner._stop_future)) return if spawner.pending: @@ -530,9 +535,10 @@ def _remove_spawner(f=None): if remove: if stop_future: - stop_future.add_done_callback(_remove_spawner) + # schedule remove when stop completes + asyncio.ensure_future(_remove_spawner(spawner._stop_future)) else: - _remove_spawner() + await _remove_spawner() status = 202 if spawner._stop_pending else 204 self.set_header('Content-Type', 'text/plain') diff --git a/jupyterhub/spawner.py b/jupyterhub/spawner.py --- a/jupyterhub/spawner.py +++ b/jupyterhub/spawner.py @@ -1141,6 +1141,18 @@ async def poll(self): """ raise NotImplementedError("Override in subclass. Must be a coroutine.") + def delete_forever(self): + """Called when a user or server is deleted. + + This can do things like request removal of resources such as persistent storage. + Only called on stopped spawners, and is usually the last action ever taken for the user. + + Will only be called once on each Spawner, immediately prior to removal. + + Stopping a server does *not* call this method. + """ + pass + def add_poll_callback(self, callback, *args, **kwargs): """Add a callback to fire when the single-user server stops""" if args or kwargs: diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -252,6 +252,35 @@ async def get_auth_state(self): await self.save_auth_state(auth_state) return auth_state + async def delete_spawners(self): + """Call spawner cleanup methods + + Allows the spawner to cleanup persistent resources + """ + for name in self.orm_user.orm_spawners.keys(): + await self._delete_spawner(name) + + async def _delete_spawner(self, name_or_spawner): + """Delete a single spawner""" + # always ensure full Spawner + # this may instantiate the Spawner if it wasn't already running, + # just to delete it + if isinstance(name_or_spawner, str): + spawner = self.spawners[name_or_spawner] + else: + spawner = name_or_spawner + + if spawner.active: + raise RuntimeError( + f"Spawner {spawner._log_name} is active and cannot be deleted." + ) + try: + await maybe_future(spawner.delete_forever()) + except Exception as e: + self.log.exception( + f"Error cleaning up persistent resources on {spawner._log_name}" + ) + def all_spawners(self, include_default=True): """Generator yielding all my spawners
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -93,16 +93,6 @@ def user_env(self, env): def _cmd_default(self): return [sys.executable, '-m', 'jupyterhub.tests.mocksu'] - async def delete_forever(self): - """Called when a user is deleted. - - This can do things like request removal of resources such as persistent storage. - Only called on stopped spawners, and is likely the last action ever taken for the user. - - Will only be called once on the user's default Spawner. - """ - pass - use_this_api_token = None def start(self):
Implementation details about the delete_forever hook optionally on a Spawner object #3337 introduced a `delete_forever` hook for the Spawner base class and I want to deliberate around some details. The only change besides a test case is the following lines of code. https://github.com/jupyterhub/jupyterhub/blob/3fec19d191119e4203c243f44c43e74c8fe62f04/jupyterhub/apihandlers/users.py#L241-L245 ## Question 1 Do we want the Spawner base class to implement a placeholder function that only have `pass` in it? It would become an entrypoint to write documentation ## Question 2 If not a yes on Question 1, do we want this check added? Now we will write an error message for all Spawners no matter if they have this functionality. ```diff # allow the spawner to cleanup any persistent resources associated with the user try: + if user.spawner.delete_forever: await user.spawner.delete_forever() except Exception as e: self.log.error("Error cleaning up persistent resources: %s" % e) ```
> Do we want the Spawner base class to implement a placeholder function that only have pass in it? It would become an entrypoint to write documentation I thought we had this! Oops! I missed in review that the `delete_forever` method addd in #3337 was defined in the tests, and not in the base class. It should definitely be in the base class. I'll do a PR cleaning up a bit of the logic that I see isn't quite correct.
2021-05-05T10:00:01Z
[]
[]
jupyterhub/jupyterhub
3,460
jupyterhub__jupyterhub-3460
[ "3441" ]
2b1ed086a5f0ae1f4ec21228299b5a4e0e0219ab
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -21,6 +21,7 @@ from functools import partial from getpass import getuser from glob import glob +from itertools import chain from operator import itemgetter from textwrap import dedent from urllib.parse import unquote @@ -329,11 +330,10 @@ def _load_classes(self): load_roles = [ { 'name': 'teacher', - 'description': 'Access users information, servers and groups without create/delete privileges', + 'description': 'Access to users' information and group membership', 'scopes': ['users', 'groups'], 'users': ['cyclops', 'gandalf'], 'services': [], - 'tokens': [], 'groups': [] } ] @@ -1975,25 +1975,70 @@ async def init_groups(self): group.users.append(user) db.commit() - async def init_roles(self): + async def init_role_creation(self): """Load default and predefined roles into the database""" - db = self.db - # tokens are added separately - role_bearers = ['users', 'services', 'groups'] - - # load default roles self.log.debug('Loading default roles to database') default_roles = roles.get_default_roles() - for role in default_roles: - roles.create_role(db, role) + config_role_names = [r['name'] for r in self.load_roles] + init_roles = default_roles + for role_name in config_role_names: + if config_role_names.count(role_name) > 1: + raise ValueError( + f"Role {role_name} multiply defined. Please check the `load_roles` configuration" + ) + for role_spec in self.load_roles: + init_roles.append(role_spec) + init_role_names = [r['name'] for r in init_roles] + if not orm.Role.find(self.db, name='admin'): + self._rbac_upgrade = True + else: + self._rbac_upgrade = False + for role in self.db.query(orm.Role).filter( + orm.Role.name.notin_(init_role_names) + ): + app_log.info(f"Deleting role {role.name}") + self.db.delete(role) + self.db.commit() + for role in init_roles: + roles.create_role(self.db, role) + + async def init_role_assignment(self): + # tokens are added separately + role_bearers = ['users', 'services', 'groups'] + admin_role_objects = ['users', 'services'] + config_admin_users = set(self.authenticator.admin_users) + db = self.db # load predefined roles from config file + if config_admin_users: + for role_spec in self.load_roles: + if role_spec['name'] == 'admin': + app_log.warning( + "Configuration specifies both admin_users and users in the admin role specification. " + "If admin role is present in config, c.authenticator.admin_users should not be used." + ) + app_log.info( + "Merging admin_users set with users list in admin role" + ) + role_spec['users'] = set(role_spec.get('users', [])) + role_spec['users'] |= config_admin_users self.log.debug('Loading predefined roles from config file to database') + has_admin_role_spec = {role_bearer: False for role_bearer in admin_role_objects} for predef_role in self.load_roles: - roles.create_role(db, predef_role) + predef_role_obj = orm.Role.find(db, name=predef_role['name']) + if predef_role['name'] == 'admin': + for bearer in admin_role_objects: + has_admin_role_spec[bearer] = bearer in predef_role + if has_admin_role_spec[bearer]: + app_log.info(f"Admin role specifies static {bearer} list") + else: + app_log.info( + f"Admin role does not specify {bearer}, preserving admin membership in database" + ) # add users, services, and/or groups, # tokens need to be checked for permissions for bearer in role_bearers: + orm_role_bearers = [] if bearer in predef_role.keys(): for bname in predef_role[bearer]: if bearer == 'users': @@ -2009,22 +2054,40 @@ async def init_roles(self): ) Class = orm.get_class(bearer) orm_obj = Class.find(db, bname) - roles.grant_role( - db, entity=orm_obj, rolename=predef_role['name'] - ) - # make sure that on no admin situation, all roles are reset - admin_role = orm.Role.find(db, name='admin') - if not admin_role.users: + if orm_obj: + orm_role_bearers.append(orm_obj) + else: + app_log.warning( + f"User {bname} not added, only found in role definition" + ) + # Todo: Add users to allowed_users + # Ensure all with admin role have admin flag + if predef_role['name'] == 'admin': + orm_obj.admin = True + setattr(predef_role_obj, bearer, orm_role_bearers) + db.commit() + allowed_users = db.query(orm.User).filter( + orm.User.name.in_(self.authenticator.allowed_users) + ) + for user in allowed_users: + roles.grant_role(db, user, 'user') + admin_role = orm.Role.find(db, 'admin') + for bearer in admin_role_objects: + Class = orm.get_class(bearer) + for admin_obj in db.query(Class).filter_by(admin=True): + if has_admin_role_spec[bearer]: + admin_obj.admin = admin_role in admin_obj.roles + else: + roles.grant_role(db, admin_obj, 'admin') + db.commit() + # make sure that on hub upgrade, all users, services and tokens have at least one role (update with default) + if getattr(self, '_rbac_upgrade', False): app_log.warning( - "No admin users found; assuming hub upgrade. Initializing default roles for all entities" + "No admin role found; assuming hub upgrade. Initializing default roles for all entities" ) - # make sure all users, services and tokens have at least one role (update with default) for bearer in role_bearers: roles.check_for_default_roles(db, bearer) - # now add roles to tokens if their owner's permissions allow - roles.add_predef_roles_tokens(db, self.load_roles) - # check tokens for default roles roles.check_for_default_roles(db, bearer='tokens') @@ -2067,13 +2130,6 @@ async def _add_tokens(self, token_dict, kind): db.add(obj) db.commit() self.log.info("Adding API token for %s: %s", kind, name) - # If we have roles in the configuration file, they will be added later - # Todo: works but ugly - config_roles = None - for config_role in self.load_roles: - if 'tokens' in config_role and token in config_role['tokens']: - config_roles = [] - break try: # set generated=False to ensure that user-provided tokens # get extra hashing (don't trust entropy of user-provided tokens) @@ -2081,7 +2137,6 @@ async def _add_tokens(self, token_dict, kind): token, note="from config", generated=self.trust_user_provided_tokens, - roles=config_roles, ) except Exception: if created: @@ -2140,6 +2195,12 @@ def init_services(self): # not found, create a new one orm_service = orm.Service(name=name) if spec.get('admin', False): + self.log.warning( + f"Service {name} sets `admin: True`, which is deprecated in JupyterHub 2.0." + " You can assign now assign roles via `JupyterHub.load_roles` configuration." + " If you specify services in the admin role configuration, " + "the Service admin flag will be ignored." + ) roles.update_roles(self.db, entity=orm_service, roles=['admin']) self.db.add(orm_service) orm_service.admin = spec.get('admin', False) @@ -2623,11 +2684,12 @@ def _log_cls(name, cls): self.init_hub() self.init_proxy() self.init_oauth() + await self.init_role_creation() await self.init_users() await self.init_groups() self.init_services() await self.init_api_tokens() - await self.init_roles() + await self.init_role_assignment() self.init_tornado_settings() self.init_handlers() self.init_tornado_application() diff --git a/jupyterhub/auth.py b/jupyterhub/auth.py --- a/jupyterhub/auth.py +++ b/jupyterhub/auth.py @@ -112,7 +112,7 @@ class Authenticator(LoggingConfigurable): Use this with supported authenticators to restrict which users can log in. This is an additional list that further restricts users, beyond whatever restrictions the - authenticator has in place. + authenticator has in place. Any user in this list is granted the 'user' role on hub startup. If empty, does not perform any additional restriction. diff --git a/jupyterhub/roles.py b/jupyterhub/roles.py --- a/jupyterhub/roles.py +++ b/jupyterhub/roles.py @@ -193,10 +193,14 @@ def _overwrite_role(role, role_dict): for attr in role_dict.keys(): if attr == 'description' or attr == 'scopes': - if role.name == 'admin' and role_dict[attr] != getattr(role, attr): - raise ValueError( - 'admin role description or scopes cannot be overwritten' - ) + if role.name == 'admin': + admin_role_spec = [ + r for r in get_default_roles() if r['name'] == 'admin' + ][0] + if role_dict[attr] != admin_role_spec[attr]: + raise ValueError( + 'admin role description or scopes cannot be overwritten' + ) else: if role_dict[attr] != getattr(role, attr): setattr(role, attr, role_dict[attr]) @@ -399,7 +403,6 @@ def assign_default_roles(db, entity): db.commit() # users and services can have 'user' or 'admin' roles as default else: - # todo: when we deprecate admin flag: replace with role check app_log.debug('Assigning default roles to %s', type(entity).__name__) _switch_default_role(db, entity, entity.admin) @@ -428,25 +431,6 @@ def update_roles(db, entity, roles): grant_role(db, entity=entity, rolename=rolename) -def add_predef_roles_tokens(db, predef_roles): - - """Adds tokens to predefined roles in config file - if their permissions allow""" - - for predef_role in predef_roles: - if 'tokens' in predef_role.keys(): - token_role = orm.Role.find(db, name=predef_role['name']) - for token_name in predef_role['tokens']: - token = orm.APIToken.find(db, token_name) - if token is None: - raise ValueError( - "Token %r does not exist and cannot assign it to role %r" - % (token_name, token_role.name) - ) - else: - update_roles(db, token, roles=[token_role.name]) - - def check_for_default_roles(db, bearer): """Checks that role bearers have at least one role (default if none).
diff --git a/jupyterhub/tests/test_roles.py b/jupyterhub/tests/test_roles.py --- a/jupyterhub/tests/test_roles.py +++ b/jupyterhub/tests/test_roles.py @@ -2,11 +2,13 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import json +import os from itertools import chain import pytest from pytest import mark from tornado.log import app_log +from traitlets.config import Config from .. import orm from .. import roles @@ -247,7 +249,7 @@ async def test_load_default_roles(tmpdir, request): hub = MockHub(**kwargs) hub.init_db() db = hub.db - await hub.init_roles() + await hub.init_role_creation() # test default roles loaded to database default_roles = roles.get_default_roles() for role in default_roles: @@ -444,9 +446,9 @@ async def test_load_roles_users(tmpdir, request): db = hub.db hub.authenticator.admin_users = ['admin'] hub.authenticator.allowed_users = ['cyclops', 'gandalf', 'bilbo', 'gargamel'] + await hub.init_role_creation() await hub.init_users() - await hub.init_roles() - + await hub.init_role_assignment() admin_role = orm.Role.find(db, 'admin') user_role = orm.Role.find(db, 'user') # test if every user has a role (and no duplicates) @@ -456,7 +458,7 @@ async def test_load_roles_users(tmpdir, request): assert len(user.roles) == len(set(user.roles)) if user.admin: assert admin_role in user.roles - assert user_role not in user.roles + assert user_role in user.roles # test if predefined roles loaded and assigned teacher_role = orm.Role.find(db, name='teacher') @@ -507,13 +509,13 @@ async def test_load_roles_services(tmpdir, request): hub = MockHub(**kwargs) hub.init_db() db = hub.db + await hub.init_role_creation() await hub.init_api_tokens() # make 'admin_service' admin admin_service = orm.Service.find(db, 'admin_service') admin_service.admin = True db.commit() - await hub.init_roles() - + await hub.init_role_assignment() # test if every service has a role (and no duplicates) admin_role = orm.Role.find(db, name='admin') user_role = orm.Role.find(db, name='user') @@ -580,8 +582,9 @@ async def test_load_roles_groups(tmpdir, request): hub = MockHub(**kwargs) hub.init_db() db = hub.db + await hub.init_role_creation() await hub.init_groups() - await hub.init_roles() + await hub.init_role_assignment() assist_role = orm.Role.find(db, name='assistant') head_role = orm.Role.find(db, name='head') @@ -612,7 +615,6 @@ async def test_load_roles_user_tokens(tmpdir, request): 'name': 'reader', 'description': 'Read all users models', 'scopes': ['read:users'], - 'tokens': ['super-secret-token'], }, ] kwargs = { @@ -627,15 +629,10 @@ async def test_load_roles_user_tokens(tmpdir, request): db = hub.db hub.authenticator.admin_users = ['admin'] hub.authenticator.allowed_users = ['cyclops', 'gandalf'] + await hub.init_role_creation() await hub.init_users() await hub.init_api_tokens() - await hub.init_roles() - - # test if gandalf's token has the 'reader' role - reader_role = orm.Role.find(db, 'reader') - token = orm.APIToken.find(db, 'super-secret-token') - assert reader_role in token.roles - + await hub.init_role_assignment() # test if all other tokens have default 'user' role token_role = orm.Role.find(db, 'token') secret_token = orm.APIToken.find(db, 'secret-token') @@ -653,163 +650,6 @@ async def test_load_roles_user_tokens(tmpdir, request): roles.delete_role(db, role['name']) [email protected] -async def test_load_roles_user_tokens_not_allowed(tmpdir, request): - user_tokens = { - 'secret-token': 'bilbo', - } - roles_to_load = [ - { - 'name': 'user-creator', - 'description': 'Creates/deletes any user', - 'scopes': ['admin:users'], - 'tokens': ['secret-token'], - }, - ] - kwargs = { - 'load_roles': roles_to_load, - 'api_tokens': user_tokens, - } - ssl_enabled = getattr(request.module, "ssl_enabled", False) - if ssl_enabled: - kwargs['internal_certs_location'] = str(tmpdir) - hub = MockHub(**kwargs) - hub.init_db() - db = hub.db - hub.authenticator.allowed_users = ['bilbo'] - await hub.init_users() - await hub.init_api_tokens() - - response = 'allowed' - # bilbo has only default 'user' role - # while bilbo's token is requesting role with higher permissions - with pytest.raises(ValueError): - await hub.init_roles() - - # delete the test tokens - for token in db.query(orm.APIToken): - db.delete(token) - db.commit() - - # delete the test roles - for role in roles_to_load: - roles.delete_role(db, role['name']) - - [email protected] -async def test_load_roles_service_tokens(tmpdir, request): - services = [ - {'name': 'idle-culler', 'api_token': 'another-secret-token'}, - ] - service_tokens = { - 'another-secret-token': 'idle-culler', - } - roles_to_load = [ - { - 'name': 'idle-culler', - 'description': 'Cull idle servers', - 'scopes': [ - 'read:users:name', - 'read:users:activity', - 'read:users:servers', - 'users:servers', - ], - 'services': ['idle-culler'], - 'tokens': ['another-secret-token'], - }, - ] - kwargs = { - 'load_roles': roles_to_load, - 'services': services, - 'service_tokens': service_tokens, - } - ssl_enabled = getattr(request.module, "ssl_enabled", False) - if ssl_enabled: - kwargs['internal_certs_location'] = str(tmpdir) - hub = MockHub(**kwargs) - hub.init_db() - db = hub.db - await hub.init_api_tokens() - await hub.init_roles() - - # test if another-secret-token has idle-culler role - service = orm.Service.find(db, 'idle-culler') - culler_role = orm.Role.find(db, 'idle-culler') - token = orm.APIToken.find(db, 'another-secret-token') - assert len(token.roles) == 1 - assert culler_role in token.roles - - # delete the test services - for service in db.query(orm.Service): - db.delete(service) - db.commit() - - # delete the test tokens - for token in db.query(orm.APIToken): - db.delete(token) - db.commit() - - # delete the test roles - for role in roles_to_load: - roles.delete_role(db, role['name']) - - [email protected] -async def test_load_roles_service_tokens_not_allowed(tmpdir, request): - services = [{'name': 'some-service', 'api_token': 'secret-token'}] - service_tokens = { - 'secret-token': 'some-service', - } - roles_to_load = [ - { - 'name': 'user-reader', - 'description': 'Read-only user models', - 'scopes': ['read:users'], - 'services': ['some-service'], - }, - # 'idle-culler' role has higher permissions that the token's owner 'some-service' - { - 'name': 'idle-culler', - 'description': 'Cull idle servers', - 'scopes': [ - 'read:users:name', - 'read:users:activity', - 'read:users:servers', - 'users:servers', - ], - 'tokens': ['secret-token'], - }, - ] - kwargs = { - 'load_roles': roles_to_load, - 'services': services, - 'service_tokens': service_tokens, - } - ssl_enabled = getattr(request.module, "ssl_enabled", False) - if ssl_enabled: - kwargs['internal_certs_location'] = str(tmpdir) - hub = MockHub(**kwargs) - hub.init_db() - db = hub.db - await hub.init_api_tokens() - with pytest.raises(ValueError): - await hub.init_roles() - - # delete the test services - for service in db.query(orm.Service): - db.delete(service) - db.commit() - - # delete the test tokens - for token in db.query(orm.APIToken): - db.delete(token) - db.commit() - - # delete the test roles - for role in roles_to_load: - roles.delete_role(db, role['name']) - - @mark.role @mark.parametrize( "headers, rolename, scopes, status", @@ -1124,3 +964,315 @@ async def test_user_group_roles(app, create_temp_role): assert len(reply[0]['roles']) == 1 assert reply[0]['name'] == 'jack' assert group_role.name not in reply[0]['roles'] + + +async def test_config_role_list(): + roles_to_load = [ + { + 'name': 'elephant', + 'description': 'pacing about', + 'scopes': ['read:hub'], + }, + { + 'name': 'tiger', + 'description': 'pouncing stuff', + 'scopes': ['shutdown'], + }, + ] + hub = MockHub(load_roles=roles_to_load) + hub.init_db() + hub.authenticator.admin_users = ['admin'] + await hub.init_role_creation() + for role_conf in roles_to_load: + assert orm.Role.find(hub.db, name=role_conf['name']) + # Now remove elephant from config and see if it is removed from database + roles_to_load.pop(0) + hub.load_roles = roles_to_load + await hub.init_role_creation() + assert orm.Role.find(hub.db, name='tiger') + assert not orm.Role.find(hub.db, name='elephant') + + +async def test_config_role_users(): + role_name = 'painter' + user_name = 'benny' + user_names = ['agnetha', 'bjorn', 'anni-frid', user_name] + roles_to_load = [ + { + 'name': role_name, + 'description': 'painting with colors', + 'scopes': ['users', 'groups'], + 'users': user_names, + }, + ] + hub = MockHub(load_roles=roles_to_load) + hub.init_db() + hub.authenticator.admin_users = ['admin'] + hub.authenticator.allowed_users = user_names + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + user = orm.User.find(hub.db, name=user_name) + role = orm.Role.find(hub.db, name=role_name) + assert role in user.roles + # Now reload and see if user is removed from role list + roles_to_load[0]['users'].remove(user_name) + hub.load_roles = roles_to_load + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + user = orm.User.find(hub.db, name=user_name) + role = orm.Role.find(hub.db, name=role_name) + assert role not in user.roles + + +async def test_duplicate_role_users(): + role_name = 'painter' + user_name = 'benny' + user_names = ['agnetha', 'bjorn', 'anni-frid', user_name] + roles_to_load = [ + { + 'name': role_name, + 'description': 'painting with colors', + 'scopes': ['users', 'groups'], + 'users': user_names, + }, + { + 'name': role_name, + 'description': 'painting with colors', + 'scopes': ['users', 'groups'], + 'users': user_names, + }, + ] + hub = MockHub(load_roles=roles_to_load) + hub.init_db() + with pytest.raises(ValueError): + await hub.init_role_creation() + + +async def test_admin_role_and_flag(): + admin_role_spec = [ + { + 'name': 'admin', + 'users': ['eddy'], + } + ] + hub = MockHub(load_roles=admin_role_spec) + hub.init_db() + hub.authenticator.admin_users = ['admin'] + hub.authenticator.allowed_users = ['eddy'] + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + admin_role = orm.Role.find(hub.db, name='admin') + for user_name in ['eddy', 'admin']: + user = orm.User.find(hub.db, name=user_name) + assert user.admin + assert admin_role in user.roles + admin_role_spec[0]['users'].remove('eddy') + hub.load_roles = admin_role_spec + await hub.init_users() + await hub.init_role_assignment() + user = orm.User.find(hub.db, name='eddy') + assert not user.admin + assert admin_role not in user.roles + + +async def test_custom_role_reset(): + user_role_spec = [ + { + 'name': 'user', + 'scopes': ['self', 'shutdown'], + 'users': ['eddy'], + } + ] + hub = MockHub(load_roles=user_role_spec) + hub.init_db() + hub.authenticator.allowed_users = ['eddy'] + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + user_role = orm.Role.find(hub.db, name='user') + user = orm.User.find(hub.db, name='eddy') + assert user_role in user.roles + assert 'shutdown' in user_role.scopes + hub.load_roles = [] + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + user_role = orm.Role.find(hub.db, name='user') + user = orm.User.find(hub.db, name='eddy') + assert user_role in user.roles + assert 'shutdown' not in user_role.scopes + + +async def test_removal_config_to_db(): + role_spec = [ + { + 'name': 'user', + 'scopes': ['self', 'shutdown'], + }, + { + 'name': 'wizard', + 'scopes': ['self', 'read:groups'], + }, + ] + hub = MockHub(load_roles=role_spec) + hub.init_db() + await hub.init_role_creation() + assert orm.Role.find(hub.db, 'user') + assert orm.Role.find(hub.db, 'wizard') + hub.load_roles = [] + await hub.init_role_creation() + assert orm.Role.find(hub.db, 'user') + assert not orm.Role.find(hub.db, 'wizard') + + +async def test_no_admin_role_change(): + role_spec = [{'name': 'admin', 'scopes': ['shutdown']}] + hub = MockHub(load_roles=role_spec) + hub.init_db() + with pytest.raises(ValueError): + await hub.init_role_creation() + + +async def test_user_config_respects_memberships(): + role_spec = [ + { + 'name': 'user', + 'scopes': ['self', 'shutdown'], + } + ] + user_names = ['eddy', 'carol'] + hub = MockHub(load_roles=role_spec) + hub.init_db() + hub.authenticator.allowed_users = user_names + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + user_role = orm.Role.find(hub.db, 'user') + for user_name in user_names: + user = orm.User.find(hub.db, user_name) + assert user in user_role.users + + +async def test_admin_role_respects_config(): + role_spec = [ + { + 'name': 'admin', + } + ] + admin_users = ['eddy', 'carol'] + hub = MockHub(load_roles=role_spec) + hub.init_db() + hub.authenticator.admin_users = admin_users + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + admin_role = orm.Role.find(hub.db, 'admin') + for user_name in admin_users: + user = orm.User.find(hub.db, user_name) + assert user in admin_role.users + + +async def test_empty_admin_spec(): + role_spec = [{'name': 'admin', 'users': []}] + hub = MockHub(load_roles=role_spec) + hub.init_db() + hub.authenticator.admin_users = [] + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + admin_role = orm.Role.find(hub.db, 'admin') + assert not admin_role.users + + +# Todo: Test that services don't get default roles on any startup + + +async def test_hub_upgrade_detection(tmpdir): + db_url = f"sqlite:///{tmpdir.join('jupyterhub.sqlite')}" + os.environ['JUPYTERHUB_TEST_DB_URL'] = db_url + # Create hub with users and tokens + hub = MockHub(db_url=db_url) + await hub.initialize() + user_names = ['patricia', 'quentin'] + user_role = orm.Role.find(hub.db, 'user') + for name in user_names: + user = add_user(hub.db, name=name) + user.new_api_token() + assert user_role in user.roles + for role in hub.db.query(orm.Role): + hub.db.delete(role) + hub.db.commit() + # Restart hub in emulated upgrade mode: default roles for all entities + hub.test_clean_db = False + await hub.initialize() + assert getattr(hub, '_rbac_upgrade', False) + user_role = orm.Role.find(hub.db, 'user') + token_role = orm.Role.find(hub.db, 'token') + for name in user_names: + user = orm.User.find(hub.db, name) + assert user_role in user.roles + assert token_role in user.api_tokens[0].roles + # Strip all roles and see if it sticks + user_role.users = [] + token_role.tokens = [] + hub.db.commit() + + hub.init_db() + hub.init_hub() + await hub.init_role_creation() + await hub.init_users() + hub.authenticator.allowed_users = ['patricia'] + await hub.init_api_tokens() + await hub.init_role_assignment() + assert not getattr(hub, '_rbac_upgrade', False) + user_role = orm.Role.find(hub.db, 'user') + token_role = orm.Role.find(hub.db, 'token') + allowed_user = orm.User.find(hub.db, 'patricia') + rem_user = orm.User.find(hub.db, 'quentin') + assert user_role in allowed_user.roles + assert token_role not in allowed_user.api_tokens[0].roles + assert user_role not in rem_user.roles + assert token_role not in rem_user.roles + + +async def test_token_keep_roles_on_restart(): + role_spec = [ + { + 'name': 'bloop', + 'scopes': ['read:users'], + } + ] + + hub = MockHub(load_roles=role_spec) + hub.init_db() + hub.authenticator.admin_users = ['ben'] + await hub.init_role_creation() + await hub.init_users() + await hub.init_role_assignment() + user = orm.User.find(hub.db, name='ben') + for _ in range(3): + user.new_api_token() + happy_token, content_token, sad_token = user.api_tokens + roles.grant_role(hub.db, happy_token, 'bloop') + roles.strip_role(hub.db, sad_token, 'token') + assert len(happy_token.roles) == 2 + assert len(content_token.roles) == 1 + assert len(sad_token.roles) == 0 + # Restart hub and see if roles are as expected + hub.load_roles = [] + await hub.init_role_creation() + await hub.init_users() + await hub.init_api_tokens() + await hub.init_role_assignment() + user = orm.User.find(hub.db, name='ben') + happy_token, content_token, sad_token = user.api_tokens + assert len(happy_token.roles) == 1 + assert len(content_token.roles) == 1 + print(sad_token.roles) + assert len(sad_token.roles) == 0 + for token in user.api_tokens: + hub.db.delete(token) + hub.db.commit() diff --git a/jupyterhub/tests/test_scopes.py b/jupyterhub/tests/test_scopes.py --- a/jupyterhub/tests/test_scopes.py +++ b/jupyterhub/tests/test_scopes.py @@ -311,7 +311,7 @@ def temp_user_creator(*scopes, name=None): def create_service_with_scopes(app, create_temp_role): """Generate a temporary service with specific scopes. Convenience function that provides setup, database handling and teardown""" - temp_service = [] + temp_services = [] counter = 0 role_function = create_temp_role @@ -325,11 +325,12 @@ def temp_service_creator(*scopes, name=None): app.init_services() orm_service = orm.Service.find(app.db, name) app.db.commit() + temp_services.append(orm_service) roles.update_roles(app.db, orm_service, roles=[role.name]) return orm_service yield temp_service_creator - for service in temp_service: + for service in temp_services: app.db.delete(service) app.db.commit() @@ -619,7 +620,6 @@ async def test_server_state_access( ) service = create_service_with_scopes(*scopes) api_token = service.new_api_token() - await app.init_roles() headers = {'Authorization': 'token %s' % api_token} r = await api_request(app, 'users', user.name, headers=headers) r.raise_for_status() diff --git a/jupyterhub/tests/test_services.py b/jupyterhub/tests/test_services.py --- a/jupyterhub/tests/test_services.py +++ b/jupyterhub/tests/test_services.py @@ -89,10 +89,10 @@ async def test_external_service(app): } ] await maybe_future(app.init_services()) - await maybe_future(app.init_roles()) + await maybe_future(app.init_role_creation()) await app.init_api_tokens() await app.proxy.add_all_services(app._service_map) - await app.init_roles() + await app.init_role_assignment() service = app._service_map[name] api_token = service.orm.api_tokens[0]
[rbac] separate role creation from assignment Right now, `init_roles` does two things: 1. define the roles, and 2. assign users, services, groups, tokens to those roles The second part has to run after users and services exist, while the first part has to run before e.g. services with `admin: true` are created. I just encountered this because jupyterhub with an admin service will fail to start because the admin role doesn't exist yet because `init_roles()` is called after `init_services()`. I think we should rearrange this a bit to: 1. create roles before init_users or other entities 2. have a separate `init_role_assignments` stage that assigns entities to roles And also probably *remove* support for assigning roles directly to tokens. Looking at it, I think that's maybe more complicated and niche than we need. Let's keep role assignment from config only to the other encapsulating entities. Question: **Do we still have a single `load_roles` config with both role definitions and assignments, or two separate `load_roles` and `assign_roles` config inputs for the two stages?** We should also make it *very* clear what happens between two jupyterhub starts with: 1. launch with load_roles with `{name: "myrole", users: ['alice', 'bob']}` 2. launch with load_roles with `{name: "myrole", users: ['alice'] }` Does bob still have role `myrole` or not? If he does, how should I update bob's role assignment to remove `myrole`?
Thank you for opening your first issue in this project! Engagement like this is essential for open source projects! :hugs: <br>If you haven't done so already, check out [Jupyter's Code of Conduct](https://github.com/jupyter/governance/blob/master/conduct/code_of_conduct.md). Also, please try to follow the issue template as it helps other other community members to contribute more effectively. ![welcome](https://raw.githubusercontent.com/jupyterhub/.github/master/images/welcome.jpg) You can meet the other [Jovyans](https://jupyter.readthedocs.io/en/latest/community/content-community.html?highlight=jovyan#what-is-a-jovyan) by joining our [Discourse forum](http://discourse.jupyter.org/). There is also an intro thread there where you can stop by and say Hi! :wave: <br>Welcome to the Jupyter community! :tada: > I think we should rearrange this a bit to: > > 1. create roles before init_users or other entities > 2. have a separate `init_role_assignments` stage that assigns entities to roles > > And also probably _remove_ support for assigning roles directly to tokens. Looking at it, I think that's maybe more complicated and niche than we need. Let's keep role assignment from config only to the other encapsulating entities. Agree, I'll look into this. > Question: **Do we still have a single `load_roles` config with both role definitions and assignments, or two separate `load_roles` and `assign_roles` config inputs for the two stages?** I am inclined to the latter, having separate definitions and assignments will be clearer. > We should also make it _very_ clear what happens between two jupyterhub starts with: > > 1. launch with load_roles with `{name: "myrole", users: ['alice', 'bob']}` > 2. launch with load_roles with `{name: "myrole", users: ['alice'] }` > > Does bob still have role `myrole` or not? If he does, how should I update bob's role assignment to remove `myrole`? Right now bob will still have `myrole` (docs do mention this as well). We thought that removing roles will be left to APIs once we implement them. But I can see that we should indeed provide a way to do this now as well. If we split the definitions and assignments, it will be easier to track who has the role so removing a user/service/group from assignment part should result in them losing the role. @0mar what do you think? I agree, having the hub initialize roles before initializing the users and services leads to some awkward constructions in the code base. Splitting this would resolve it. As far as the config assignments are concerned, I don't really know what is the best solution. I would propose to make sure that each time the hub is restarted, it reinitializes all roles for the users/services mentioned in the configuration file (perhaps with a warning when overwriting roles). This way, there is no need to define any delete/remove methods in the configuration, since I think that could lead to inconsistent situations (what if a role is assigned and stripped in the same configuration?) A downside is that any assignments and removals are reset when the hub is reset, which might not be ideal. So perhaps, a compromise would be to reinitialize all roles only for the users/services that do not exist in the database yet. What do you think?
2021-05-07T14:30:08Z
[]
[]
jupyterhub/jupyterhub
3,477
jupyterhub__jupyterhub-3477
[ "3472" ]
be7ad39b10327f6f5ca76a65c87c6e4b7e0b9d09
diff --git a/jupyterhub/roles.py b/jupyterhub/roles.py --- a/jupyterhub/roles.py +++ b/jupyterhub/roles.py @@ -164,13 +164,12 @@ def expand_roles_to_scopes(orm_object): if not isinstance(orm_object, orm.Base): raise TypeError(f"Only orm objects allowed, got {orm_object}") - pass_roles = orm_object.roles + pass_roles = [] + pass_roles.extend(orm_object.roles) if isinstance(orm_object, orm.User): - groups_roles = [] for group in orm_object.groups: - groups_roles.extend(group.roles) - pass_roles.extend(groups_roles) + pass_roles.extend(group.roles) scopes = _get_subscopes(*pass_roles, owner=orm_object)
diff --git a/jupyterhub/tests/test_roles.py b/jupyterhub/tests/test_roles.py --- a/jupyterhub/tests/test_roles.py +++ b/jupyterhub/tests/test_roles.py @@ -1046,3 +1046,71 @@ async def test_oauth_allowed_roles(app, create_temp_role): app_service = app.services[0] assert app_service['name'] == 'oas1' assert set(app_service['oauth_roles']) == set(allowed_roles) + + +async def test_user_group_roles(app, create_temp_role): + user = add_user(app.db, app, name='jack') + another_user = add_user(app.db, app, name='jill') + + group = orm.Group.find(app.db, name='A') + if not group: + group = orm.Group(name='A') + app.db.add(group) + app.db.commit() + + if group not in user.groups: + user.groups.append(group) + app.db.commit() + + if group not in another_user.groups: + another_user.groups.append(group) + app.db.commit() + + group_role = orm.Role.find(app.db, 'student-a') + if not group_role: + create_temp_role(['read:groups!group=A'], 'student-a') + roles.grant_role(app.db, group, rolename='student-a') + group_role = orm.Role.find(app.db, 'student-a') + + # repeat check to ensure group roles don't get added to the user at all + # regression test for #3472 + roles_before = list(user.roles) + for i in range(3): + roles.expand_roles_to_scopes(user.orm_user) + user_roles = list(user.roles) + assert user_roles == roles_before + + # jack's API token + token = user.new_api_token() + + headers = {'Authorization': 'token %s' % token} + r = await api_request(app, 'users', method='get', headers=headers) + assert r.status_code == 200 + r.raise_for_status() + reply = r.json() + + print(reply) + + assert len(reply[0]['roles']) == 1 + assert reply[0]['name'] == 'jack' + assert group_role.name not in reply[0]['roles'] + + headers = {'Authorization': 'token %s' % token} + r = await api_request(app, 'groups', method='get', headers=headers) + assert r.status_code == 200 + r.raise_for_status() + reply = r.json() + + print(reply) + + headers = {'Authorization': 'token %s' % token} + r = await api_request(app, 'users', method='get', headers=headers) + assert r.status_code == 200 + r.raise_for_status() + reply = r.json() + + print(reply) + + assert len(reply[0]['roles']) == 1 + assert reply[0]['name'] == 'jack' + assert group_role.name not in reply[0]['roles']
[rbac] Group roles in user model role list <!-- Thank you for contributing. These HTML comments will not render in the issue, but you can delete them once you've read them if you prefer! --> ### Bug description <!-- Use this section to clearly and concisely describe the bug. --> Occurs when a user is a member of a group which has a role. The group role is added to the user's role list (and multiplies) every time the user makes an API request, i.e., after 3 requests the user's model will show the group role in the user's role list 3 times. #### Expected behaviour <!-- Tell us what you thought would happen. --> The user's own roles should not include any group roles. These are only used to extend the user's privileges during API requests but the users themselves are not bearers of their group roles. #### Actual behaviour <!-- Tell us what actually happens. --> As mentioned above, a user's group role is added to the user's roles every time they make a request. ### How to reproduce <!-- Use this section to describe the steps that a user would take to experience this bug. --> 1. Create a user (either with or without specific roles) 2. Create a group and assign it some role 3. Add the user to the group 4. Issue an API token for the user 5. Make few API requests using the user's token 6. Check the user's model which will show the group's role in the user's role list as many times as performed API requests ### Your personal set up <!-- Tell us a little about the system you're using. Please include information about how you installed, e.g. are you using a distribution such as zero-to-jupyterhub or the-littlest-jupyterhub. --> Development install - OS: <!-- [e.g. ubuntu 20.04, macOS 11.0] --> ubuntu 20.04 - Version(s): <!-- e.g. jupyterhub --version, python --version ---> jupyterhub 2.0.0.dev, python 3.8.5 - <details><summary>Full environment</summary> <!-- For reproduction, it's useful to have the full environment. For example, the output of `pip freeze` or `conda list` ---> ``` # Name Version Build Channel _libgcc_mutex 0.1 main alabaster 0.7.12 pypi_0 pypi alabaster-jupyterhub 0.1.8 pypi_0 pypi alembic 1.4.3 pypi_0 pypi appdirs 1.4.4 pypi_0 pypi argon2-cffi 20.1.0 pypi_0 pypi async-generator 1.10 pypi_0 pypi attrs 20.3.0 pypi_0 pypi autodoc-traits 0.1.0.dev0 pypi_0 pypi babel 2.9.0 pypi_0 pypi backcall 0.2.0 pypi_0 pypi beautifulsoup4 4.9.3 pypi_0 pypi bleach 3.2.1 pypi_0 pypi brotlipy 0.7.0 py38h27cfd23_1003 ca-certificates 2021.4.13 h06a4308_1 certifi 2020.12.5 py38h06a4308_0 certipy 0.1.3 pypi_0 pypi cffi 1.14.5 py38h261ae71_0 cfgv 3.2.0 pypi_0 pypi chardet 4.0.0 py38h06a4308_1003 codecov 2.1.10 pypi_0 pypi commonmark 0.9.1 pypi_0 pypi conda 4.10.0 py38h06a4308_0 conda-package-handling 1.7.3 py38h27cfd23_1 coverage 5.3 pypi_0 pypi cryptography 3.4.7 py38hd23ed53_0 dataproperty 0.50.0 pypi_0 pypi decorator 4.4.2 pypi_0 pypi defusedxml 0.6.0 pypi_0 pypi distlib 0.3.1 pypi_0 pypi docutils 0.16 pypi_0 pypi entrypoints 0.3 pypi_0 pypi filelock 3.0.12 pypi_0 pypi html5lib 1.1 pypi_0 pypi identify 1.5.10 pypi_0 pypi idna 2.10 pyhd3eb1b0_0 imagesize 1.2.0 pypi_0 pypi iniconfig 1.1.1 pypi_0 pypi ipykernel 5.4.2 pypi_0 pypi ipython 7.19.0 pypi_0 pypi ipython-genutils 0.2.0 pypi_0 pypi jedi 0.17.2 pypi_0 pypi jinja2 2.11.2 pypi_0 pypi jsonpointer 2.0 pypi_0 pypi jsonschema 3.2.0 pypi_0 pypi jupyter-client 6.1.7 pypi_0 pypi jupyter-core 4.7.0 pypi_0 pypi jupyter-telemetry 0.1.0 pypi_0 pypi jupyterhub 1.4.0.dev0 dev_0 <develop> jupyterlab-pygments 0.1.2 pypi_0 pypi ld_impl_linux-64 2.33.1 h53a641e_7 libffi 3.3 he6710b0_2 libgcc-ng 9.1.0 hdf63c60_0 libstdcxx-ng 9.1.0 hdf63c60_0 mako 1.1.3 pypi_0 pypi markdown-it-py 0.6.2 pypi_0 pypi markupsafe 1.1.1 pypi_0 pypi mbstrdecoder 1.0.1 pypi_0 pypi mdit-py-plugins 0.2.6 pypi_0 pypi mistune 0.8.4 pypi_0 pypi mock 4.0.3 pypi_0 pypi msgfy 0.1.0 pypi_0 pypi myst-parser 0.13.5 pypi_0 pypi nbclient 0.5.1 pypi_0 pypi nbconvert 6.0.7 pypi_0 pypi nbformat 5.0.8 pypi_0 pypi ncurses 6.2 he6710b0_1 nest-asyncio 1.4.3 pypi_0 pypi nodeenv 1.5.0 pypi_0 pypi nodejs 10.13.0 he6710b0_0 notebook 6.1.5 pypi_0 pypi oauthlib 3.1.0 pypi_0 pypi openssl 1.1.1k h27cfd23_0 packaging 20.8 pypi_0 pypi pamela 1.0.0 pypi_0 pypi pandocfilters 1.4.3 pypi_0 pypi parso 0.7.1 pypi_0 pypi pathvalidate 2.3.2 pypi_0 pypi pexpect 4.8.0 pypi_0 pypi pickleshare 0.7.5 pypi_0 pypi pip 21.0.1 py38h06a4308_0 pluggy 0.13.1 pypi_0 pypi pre-commit 2.9.3 pypi_0 pypi prometheus-client 0.9.0 pypi_0 pypi prompt-toolkit 3.0.8 pypi_0 pypi ptyprocess 0.6.0 pypi_0 pypi py 1.10.0 pypi_0 pypi pycosat 0.6.3 py38h7b6447c_1 pycparser 2.20 py_2 pydata-sphinx-theme 0.4.1 pypi_0 pypi pygments 2.7.3 pypi_0 pypi pyopenssl 20.0.1 pyhd3eb1b0_1 pyparsing 2.4.7 pypi_0 pypi pyrsistent 0.17.3 pypi_0 pypi pysocks 1.7.1 py38h06a4308_0 pytablewriter 0.58.0 pypi_0 pypi pytest 6.2.0 pypi_0 pypi pytest-asyncio 0.14.0 pypi_0 pypi pytest-cov 2.10.1 pypi_0 pypi python 3.8.5 h7579374_1 python-dateutil 2.8.1 pypi_0 pypi python-editor 1.0.4 pypi_0 pypi python-json-logger 2.0.1 pypi_0 pypi pytz 2020.5 pypi_0 pypi pyyaml 5.3.1 pypi_0 pypi pyzmq 20.0.0 pypi_0 pypi readline 8.1 h27cfd23_0 recommonmark 0.7.1 pypi_0 pypi requests 2.25.1 pyhd3eb1b0_0 requests-mock 1.8.0 pypi_0 pypi ruamel.yaml 0.16.12 py38h7b6447c_1 ruamel.yaml.clib 0.2.2 py38h7b6447c_0 ruamel_yaml 0.15.100 py38h27cfd23_0 send2trash 1.5.0 pypi_0 pypi setuptools 52.0.0 py38h06a4308_0 six 1.15.0 py38h06a4308_0 snowballstemmer 2.0.0 pypi_0 pypi soupsieve 2.1 pypi_0 pypi sphinx 3.4.3 pypi_0 pypi sphinx-copybutton 0.3.1 pypi_0 pypi sphinx-jsonschema 1.16.7 pypi_0 pypi sphinxcontrib-applehelp 1.0.2 pypi_0 pypi sphinxcontrib-devhelp 1.0.2 pypi_0 pypi sphinxcontrib-htmlhelp 1.0.3 pypi_0 pypi sphinxcontrib-jsmath 1.0.1 pypi_0 pypi sphinxcontrib-qthelp 1.0.3 pypi_0 pypi sphinxcontrib-serializinghtml 1.1.4 pypi_0 pypi sqlalchemy 1.3.20 pypi_0 pypi sqlite 3.35.4 hdfb4753_0 tabledata 1.1.3 pypi_0 pypi tcolorpy 0.0.8 pypi_0 pypi terminado 0.9.1 pypi_0 pypi testpath 0.4.4 pypi_0 pypi tk 8.6.10 hbc83047_0 toml 0.10.2 pypi_0 pypi tornado 6.1 pypi_0 pypi tqdm 4.59.0 pyhd3eb1b0_1 traitlets 5.0.5 pypi_0 pypi typepy 1.1.2 pypi_0 pypi urllib3 1.26.4 pyhd3eb1b0_0 virtualenv 20.2.2 pypi_0 pypi wcwidth 0.2.5 pypi_0 pypi webencodings 0.5.1 pypi_0 pypi wheel 0.36.2 pyhd3eb1b0_0 xz 5.2.5 h7b6447c_0 yaml 0.2.5 h7b6447c_0 zlib 1.2.11 h7b6447c_3 ``` </details> - <details><summary>Configuration</summary> <!-- For JupyterHub, especially include information such as what Spawner and Authenticator are being used. Be careful not to share any sensitive information. You can paste jupyterhub_config.py below. To exclude lots of comments and empty lines from auto-generated jupyterhub_config.py, you can do: grep -v '\(^#\|^[[:space:]]*$\)' jupyterhub_config.py --> Testing: ```python async def test_user_model_roles(app, create_temp_role): user = add_user(app.db, app, name='jack') another_user = add_user(app.db, app, name='jill') group = orm.Group.find(app.db, name='A') if not group: group = orm.Group(name='A') app.db.add(group) app.db.commit() if user not in group.users: group.users.append(user) app.db.commit() if another_user not in group.users: group.users.append(another_user) app.db.commit() group_role = orm.Role.find(app.db, 'student-a') if not group_role: create_temp_role(['read:groups!group=A'], 'student-a') roles.grant_role(app.db, group, rolename='student-a') group_role = orm.Role.find(app.db, 'student-a') # jack's API token token = user.new_api_token() headers = {'Authorization': 'token %s' % token} r = await api_request(app, 'users', method='get', headers=headers) assert r.status_code == 200 r.raise_for_status() reply = r.json() print(reply) # right now this fails as it has the group role once in jack's roles (first use of the API token) #assert len(reply) == 1 #assert reply[0]['name'] == 'jack' #assert group_role not in reply[0]['roles'] headers = {'Authorization': 'token %s' % token} r = await api_request(app, 'groups', method='get', headers=headers) assert r.status_code == 200 r.raise_for_status() reply = r.json() print(reply) headers = {'Authorization': 'token %s' % token} r = await api_request(app, 'users', method='get', headers=headers) assert r.status_code == 200 r.raise_for_status() reply = r.json() print(reply) # this also fails as it has the group role 3 times (!) in jack's roles (3rd use of the API token) #assert len(reply) == 1 #assert reply[0]['name'] == 'jack' # make it fail to get print statements assert group_role not in reply[0]['roles'] ``` </details> - <details><summary>Logs</summary> <!-- Errors are often logged by jupytehub. How you get logs depends on your deployment. With kubernetes it might be: kubectl get pod # hub pod name starts with hub... kubectl logs hub-... # or for a single-user server kubectl logs jupyter-username Or the-littlest-jupyterhub: journalctl -u jupyterhub # or for a single-user server journalctl -u jupyter-username --> ```python [D 09:22.476 MockHub roles:450] Assigning default roles to User [I 09:22.482 MockHub roles:353] Adding role user for User: jack [D 09:22.497 MockHub roles:450] Assigning default roles to User [I 09:22.501 MockHub roles:353] Adding role user for User: jill [I 09:22.525 MockHub roles:353] Adding role student-a for Group: A [D 09:22.530 MockHub roles:442] Assigning default roles to tokens [I 09:22.532 MockHub roles:445] Added role token to token <APIToken('e7e2...', user='jack', client_id='jupyterhub')> [D 09:22.551 MockHub base:266] Recording first activity for <APIToken('e7e2...', user='jack', client_id='jupyterhub')> [D 09:22.551 MockHub base:266] Recording first activity for <User(jack 0/1 running)> [D 09:22.556 MockHub base:311] Refreshing auth for jack [D 09:22.556 MockHub base:421] Loading and parsing scopes [W 09:22.557 MockHub scopes:89] Authenticated with token <APIToken('e7e2...', user='jack', client_id='jupyterhub')> [W 09:22.559 MockHub scopes:56] [!user=, !group=] or [!user=, !server=] combinations of filters present, intersection between not considered. May result in lower than intended permissions. [D 09:22.559 MockHub base:429] Found scopes [read:users:tokens!user=jack,read:groups!group=A,users:tokens!user=jack,users:servers!user=jack,users:name!user=jack,read:users:servers!user=jack,read:users:name!user=jack,users:activity!user=jack,users:groups!user=jack,read:users:activity!user=jack,users!user=jack,read:users!user=jack,read:users:groups!user=jack] [D 09:22.559 MockHub scopes:232] Checking access via scope read:users [D 09:22.559 MockHub scopes:154] Client has restricted access to /@/space%20word/hub/api/users via read:users. Internal filtering may apply [D 09:22.566 MockHub base:254] Asking for user model of admin with scopes [read:users:tokens!user=jack, read:groups!group=A, users:tokens!user=jack, users:servers!user=jack, users:name!user=jack, read:users:servers!user=jack, read:users:name!user=jack, users:activity!user=jack, users:groups!user=jack, read:users:activity!user=jack, users!user=jack, read:users!user=jack, read:users:groups!user=jack] [D 09:22.571 MockHub base:254] Asking for user model of user with scopes [read:users:tokens!user=jack, read:groups!group=A, users:tokens!user=jack, users:servers!user=jack, users:name!user=jack, read:users:servers!user=jack, read:users:name!user=jack, users:activity!user=jack, users:groups!user=jack, read:users:activity!user=jack, users!user=jack, read:users!user=jack, read:users:groups!user=jack] [D 09:22.571 MockHub base:254] Asking for user model of jack with scopes [read:users:tokens!user=jack, read:groups!group=A, users:tokens!user=jack, users:servers!user=jack, users:name!user=jack, read:users:servers!user=jack, read:users:name!user=jack, users:activity!user=jack, users:groups!user=jack, read:users:activity!user=jack, users!user=jack, read:users!user=jack, read:users:groups!user=jack] [D 09:22.571 MockHub base:254] Asking for user model of jill with scopes [read:users:tokens!user=jack, read:groups!group=A, users:tokens!user=jack, users:servers!user=jack, users:name!user=jack, read:users:servers!user=jack, read:users:name!user=jack, users:activity!user=jack, users:groups!user=jack, read:users:activity!user=jack, users!user=jack, read:users!user=jack, read:users:groups!user=jack] [I 09:22.574 MockHub log:189] 200 GET /@/space%20word/hub/api/users ([email protected]) 25.29ms [D 09:22.586 MockHub base:421] Loading and parsing scopes [W 09:22.587 MockHub scopes:89] Authenticated with token <APIToken('e7e2...', user='jack', client_id='jupyterhub')> [W 09:22.587 MockHub scopes:56] [!user=, !group=] or [!user=, !server=] combinations of filters present, intersection between not considered. May result in lower than intended permissions. [D 09:22.587 MockHub base:429] Found scopes [read:users:tokens!user=jack,read:groups!group=A,users:tokens!user=jack,users:servers!user=jack,users:name!user=jack,read:users:servers!user=jack,read:users:name!user=jack,users:activity!user=jack,users:groups!user=jack,read:users:activity!user=jack,users!user=jack,read:users!user=jack,read:users:groups!user=jack] [D 09:22.587 MockHub scopes:232] Checking access via scope read:groups [D 09:22.587 MockHub scopes:154] Client has restricted access to /@/space%20word/hub/api/groups via read:groups. Internal filtering may apply [I 09:22.590 MockHub log:189] 200 GET /@/space%20word/hub/api/groups ([email protected]) 6.41ms [D 09:22.604 MockHub base:421] Loading and parsing scopes [W 09:22.605 MockHub scopes:89] Authenticated with token <APIToken('e7e2...', user='jack', client_id='jupyterhub')> [W 09:22.605 MockHub scopes:56] [!user=, !group=] or [!user=, !server=] combinations of filters present, intersection between not considered. May result in lower than intended permissions. [D 09:22.605 MockHub base:429] Found scopes [read:users:tokens!user=jack,read:groups!group=A,users:tokens!user=jack,users:servers!user=jack,users:name!user=jack,read:users:servers!user=jack,read:users:name!user=jack,users:activity!user=jack,users:groups!user=jack,read:users:activity!user=jack,users!user=jack,read:users!user=jack,read:users:groups!user=jack] [D 09:22.605 MockHub scopes:232] Checking access via scope read:users [D 09:22.605 MockHub scopes:154] Client has restricted access to /@/space%20word/hub/api/users via read:users. Internal filtering may apply [D 09:22.607 MockHub base:254] Asking for user model of admin with scopes [read:users:tokens!user=jack, read:groups!group=A, users:tokens!user=jack, users:servers!user=jack, users:name!user=jack, read:users:servers!user=jack, read:users:name!user=jack, users:activity!user=jack, users:groups!user=jack, read:users:activity!user=jack, users!user=jack, read:users!user=jack, read:users:groups!user=jack] [D 09:22.607 MockHub base:254] Asking for user model of user with scopes [read:users:tokens!user=jack, read:groups!group=A, users:tokens!user=jack, users:servers!user=jack, users:name!user=jack, read:users:servers!user=jack, read:users:name!user=jack, users:activity!user=jack, users:groups!user=jack, read:users:activity!user=jack, users!user=jack, read:users!user=jack, read:users:groups!user=jack] [D 09:22.607 MockHub base:254] Asking for user model of jack with scopes [read:users:tokens!user=jack, read:groups!group=A, users:tokens!user=jack, users:servers!user=jack, users:name!user=jack, read:users:servers!user=jack, read:users:name!user=jack, users:activity!user=jack, users:groups!user=jack, read:users:activity!user=jack, users!user=jack, read:users!user=jack, read:users:groups!user=jack] [D 09:22.607 MockHub base:254] Asking for user model of jill with scopes [read:users:tokens!user=jack, read:groups!group=A, users:tokens!user=jack, users:servers!user=jack, users:name!user=jack, read:users:servers!user=jack, read:users:name!user=jack, users:activity!user=jack, users:groups!user=jack, read:users:activity!user=jack, users!user=jack, read:users!user=jack, read:users:groups!user=jack] [I 09:22.608 MockHub log:189] 200 GET /@/space%20word/hub/api/users ([email protected]) 6.87ms ``` </details>
Thank you for opening your first issue in this project! Engagement like this is essential for open source projects! :hugs: <br>If you haven't done so already, check out [Jupyter's Code of Conduct](https://github.com/jupyter/governance/blob/master/conduct/code_of_conduct.md). Also, please try to follow the issue template as it helps other other community members to contribute more effectively. ![welcome](https://raw.githubusercontent.com/jupyterhub/.github/master/images/welcome.jpg) You can meet the other [Jovyans](https://jupyter.readthedocs.io/en/latest/community/content-community.html?highlight=jovyan#what-is-a-jovyan) by joining our [Discourse forum](http://discourse.jupyter.org/). There is also an intro thread there where you can stop by and say Hi! :wave: <br>Welcome to the Jupyter community! :tada: When I run this test with the current rbac branch (gafe43f32), this test passes, even with the commented-out asserts back in. Maybe something's not quite right in the test? What's the exact commit you are testing? Strange issue: when I run the test and the token-via-api, the test fails with a very weird database lock error, which indicates an unhandled error. I cannot track down what could be the cause at the moment. db issue appears to be fixed by #3475 . Not sure if that's related to your underlying issue here, since I can't seem to reproduce the failure yet. @minrk Thank you for trying it out, apologies for posting incomplete test. The corrections are: 1. `assert len(reply) == 1` is missing the relation to roles list should be `assert len(reply[0]['roles']) == 1` 2. `assert group_role not in reply[0]['roles']` is missing the `name` attr of the `group_role` and should be `assert group_role.name not in reply[0]['roles']` The correct test is: ```python async def test_user_model_roles(app, create_temp_role): user = add_user(app.db, app, name='jack') another_user = add_user(app.db, app, name='jill') group = orm.Group.find(app.db, name='A') if not group: group = orm.Group(name='A') app.db.add(group) app.db.commit() if user not in group.users: group.users.append(user) app.db.commit() if another_user not in group.users: group.users.append(another_user) app.db.commit() group_role = orm.Role.find(app.db, 'student-a') if not group_role: create_temp_role(['read:groups!group=A'], 'student-a') roles.grant_role(app.db, group, rolename='student-a') group_role = orm.Role.find(app.db, 'student-a') # jack's API token token = user.new_api_token() headers = {'Authorization': 'token %s' % token} r = await api_request(app, 'users', method='get', headers=headers) assert r.status_code == 200 r.raise_for_status() reply = r.json() print(reply) # right now this fails as it has the group role once in jack's roles (first use of the API token) #assert len(reply[0]['roles']) == 1 #assert reply[0]['name'] == 'jack' #assert group_role.name not in reply[0]['roles'] headers = {'Authorization': 'token %s' % token} r = await api_request(app, 'groups', method='get', headers=headers) assert r.status_code == 200 r.raise_for_status() reply = r.json() print(reply) headers = {'Authorization': 'token %s' % token} r = await api_request(app, 'users', method='get', headers=headers) assert r.status_code == 200 r.raise_for_status() reply = r.json() print(reply) # this also fails as it has the group role 3 times (!) in jack's roles (3rd use of the API token) #assert len(reply[0]['roles']) == 1 #assert reply[0]['name'] == 'jack' # make it fail to get print statements assert group_role.name not in reply[0]['roles'] ``` > db issue appears to be fixed by #3475 It looks good to me and I've tried it out but I'm still getting the 'db is locked' error when running all role tests.
2021-05-21T14:44:54Z
[]
[]
jupyterhub/jupyterhub
3,616
jupyterhub__jupyterhub-3616
[ "3608" ]
8a30f015c9a8ef4714a1e44dc9cdd87e23ab0abc
diff --git a/jupyterhub/apihandlers/groups.py b/jupyterhub/apihandlers/groups.py --- a/jupyterhub/apihandlers/groups.py +++ b/jupyterhub/apihandlers/groups.py @@ -129,7 +129,7 @@ async def post(self, group_name): self.write(json.dumps(self.group_model(group))) self.set_status(201) - @needs_scope('admin:groups') + @needs_scope('delete:groups') def delete(self, group_name): """Delete a group by name""" group = self.find_group(group_name) diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -266,7 +266,7 @@ async def post(self, user_name): self.write(json.dumps(self.user_model(user))) self.set_status(201) - @needs_scope('admin:users') + @needs_scope('delete:users') async def delete(self, user_name): user = self.find_user(user_name) if user is None: @@ -525,7 +525,7 @@ async def post(self, user_name, server_name=''): self.set_header('Content-Type', 'text/plain') self.set_status(status) - @needs_scope('servers') + @needs_scope('delete:servers') async def delete(self, user_name, server_name=''): user = self.find_user(user_name) options = self.get_json_body() diff --git a/jupyterhub/roles.py b/jupyterhub/roles.py --- a/jupyterhub/roles.py +++ b/jupyterhub/roles.py @@ -89,6 +89,7 @@ def expand_self_scope(name): 'users:activity', 'read:users:activity', 'servers', + 'delete:servers', 'read:servers', 'tokens', 'read:tokens', diff --git a/jupyterhub/scopes.py b/jupyterhub/scopes.py --- a/jupyterhub/scopes.py +++ b/jupyterhub/scopes.py @@ -36,13 +36,16 @@ }, 'admin:users': { 'description': 'Read, write, create and delete users and their authentication state, not including their servers or tokens.', - 'subscopes': ['admin:auth_state', 'users', 'read:roles:users'], + 'subscopes': ['admin:auth_state', 'users', 'read:roles:users', 'delete:users'], }, 'admin:auth_state': {'description': 'Read a user’s authentication state.'}, 'users': { 'description': 'Read and write permissions to user models (excluding servers, tokens and authentication state).', 'subscopes': ['read:users', 'list:users', 'users:activity'], }, + 'delete:users': { + 'description': "Delete users.", + }, 'list:users': { 'description': 'List users, including at least their names.', 'subscopes': ['read:users:name'], @@ -76,12 +79,13 @@ 'admin:server_state': {'description': 'Read and write users’ server state.'}, 'servers': { 'description': 'Start and stop user servers.', - 'subscopes': ['read:servers'], + 'subscopes': ['read:servers', 'delete:servers'], }, 'read:servers': { 'description': 'Read users’ names and their server models (excluding the server state).', 'subscopes': ['read:users:name'], }, + 'delete:servers': {'description': "Stop and delete users' servers."}, 'tokens': { 'description': 'Read, write, create and delete user tokens.', 'subscopes': ['read:tokens'], @@ -89,7 +93,7 @@ 'read:tokens': {'description': 'Read user tokens.'}, 'admin:groups': { 'description': 'Read and write group information, create and delete groups.', - 'subscopes': ['groups', 'read:roles:groups'], + 'subscopes': ['groups', 'read:roles:groups', 'delete:groups'], }, 'groups': { 'description': 'Read and write group information, including adding/removing users to/from groups.', @@ -104,6 +108,9 @@ 'subscopes': ['read:groups:name'], }, 'read:groups:name': {'description': 'Read group names.'}, + 'delete:groups': { + 'description': "Delete groups.", + }, 'list:services': { 'description': 'List services, including at least their names.', 'subscopes': ['read:services:name'],
diff --git a/jupyterhub/tests/test_roles.py b/jupyterhub/tests/test_roles.py --- a/jupyterhub/tests/test_roles.py +++ b/jupyterhub/tests/test_roles.py @@ -182,6 +182,7 @@ def test_orm_roles_delete_cascade(db): 'admin:users', 'admin:auth_state', 'users', + 'delete:users', 'list:users', 'read:users', 'users:activity', @@ -218,6 +219,7 @@ def test_orm_roles_delete_cascade(db): { 'admin:groups', 'groups', + 'delete:groups', 'list:groups', 'read:groups', 'read:roles:groups', @@ -229,6 +231,7 @@ def test_orm_roles_delete_cascade(db): { 'admin:groups', 'groups', + 'delete:groups', 'list:groups', 'read:groups', 'read:roles:groups',
delete:users|servers|groups scope ? Currently, add/delete permissions are represented as a single scope - `admin:users`, `admin:groups`, `servers`, `tokens`, etc. I.e. you have to have permission to *create* something in order to delete it. The practical consequence: the cull-idle service must be granted permission to *start* servers in order to have permission to stop them, though it will only ever use the stop function. Same goes for culling idle users - it must have permission to *create* users if it wants permission to delete them. More scopes is more complex, so we have to think of where the boundary is for when a scope makes sense to add. But this should probably be consistent across all resources, whether we add it or not. ### Proposed change We could add a `delete:` subscope on users, groups, tokens, and servers to allow services only permission to delete resources, without needing permission to start servers, issue tokens, create users, etc. ### Alternative options Keep it as-is, and bundle creation and deletion in one scope. It's always possible to add more finer-grained scopes, it's harder to remove them. ### Who would use this feature? deployments of the cull-idle service (most deployments!) who want limited permissions.
With `create` you can do a lot more than with `delete` in this case. I think it is a quite relevant distinction. I'm :+1: inclined.
2021-09-23T09:30:33Z
[]
[]
jupyterhub/jupyterhub
3,646
jupyterhub__jupyterhub-3646
[ "3642" ]
9209ccd0deba7a0bb7cb0bafead293b76231a063
diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -421,6 +421,7 @@ async def post(self, user_name): token_model = self.token_model(orm.APIToken.find(self.db, api_token)) token_model['token'] = api_token self.write(json.dumps(token_model)) + self.set_status(201) class UserTokenAPIHandler(APIHandler):
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -1366,8 +1366,8 @@ async def test_get_new_token_deprecated(app, headers, status): @mark.parametrize( "headers, status, note, expires_in", [ - ({}, 200, 'test note', None), - ({}, 200, '', 100), + ({}, 201, 'test note', None), + ({}, 201, '', 100), ({'Authorization': 'token bad'}, 403, '', None), ], ) @@ -1386,7 +1386,7 @@ async def test_get_new_token(app, headers, status, note, expires_in): app, 'users/admin/tokens', method='post', headers=headers, data=body ) assert r.status_code == status - if status != 200: + if status != 201: return # check the new-token reply reply = r.json() @@ -1424,10 +1424,10 @@ async def test_get_new_token(app, headers, status, note, expires_in): @mark.parametrize( "as_user, for_user, status", [ - ('admin', 'other', 200), + ('admin', 'other', 201), ('admin', 'missing', 403), ('user', 'other', 403), - ('user', 'user', 200), + ('user', 'user', 201), ], ) async def test_token_for_user(app, as_user, for_user, status): @@ -1448,7 +1448,7 @@ async def test_token_for_user(app, as_user, for_user, status): ) assert r.status_code == status reply = r.json() - if status != 200: + if status != 201: return assert 'token' in reply @@ -1486,7 +1486,7 @@ async def test_token_authenticator_noauth(app): data=json.dumps(data) if data else None, noauth=True, ) - assert r.status_code == 200 + assert r.status_code == 201 reply = r.json() assert 'token' in reply r = await api_request(app, 'authorizations', 'token', reply['token']) @@ -1509,7 +1509,7 @@ async def test_token_authenticator_dict_noauth(app): data=json.dumps(data) if data else None, noauth=True, ) - assert r.status_code == 200 + assert r.status_code == 201 reply = r.json() assert 'token' in reply r = await api_request(app, 'authorizations', 'token', reply['token']) diff --git a/jupyterhub/tests/test_roles.py b/jupyterhub/tests/test_roles.py --- a/jupyterhub/tests/test_roles.py +++ b/jupyterhub/tests/test_roles.py @@ -661,11 +661,11 @@ async def test_load_roles_user_tokens(tmpdir, request): "headers, rolename, scopes, status", [ # no role requested - gets default 'token' role - ({}, None, None, 200), + ({}, None, None, 201), # role scopes within the user's default 'user' role - ({}, 'self-reader', ['read:users'], 200), + ({}, 'self-reader', ['read:users'], 201), # role scopes outside of the user's role but within the group's role scopes of which the user is a member - ({}, 'groups-reader', ['read:groups'], 200), + ({}, 'groups-reader', ['read:groups'], 201), # non-existing role request ({}, 'non-existing', [], 404), # role scopes outside of both user's role and group's role scopes
New user token returns `200` instead of `201` ### Bug description The api docs for stable & latest list the following response status: ``` 201 Created The newly created token ``` But currently returns a status of `200` #### Expected behaviour Should return a response status of `201` #### Actual behaviour Currently returns a response status of `200` ### How to reproduce Make a request to `POST /users/{name}/tokens` See (https://jupyterhub.readthedocs.io/en/latest/_static/rest-api/index.html#path--users--name--tokens)
Thank you for opening your first issue in this project! Engagement like this is essential for open source projects! :hugs: <br>If you haven't done so already, check out [Jupyter's Code of Conduct](https://github.com/jupyter/governance/blob/master/conduct/code_of_conduct.md). Also, please try to follow the issue template as it helps other other community members to contribute more effectively. ![welcome](https://raw.githubusercontent.com/jupyterhub/.github/master/images/welcome.jpg) You can meet the other [Jovyans](https://jupyter.readthedocs.io/en/latest/community/content-community.html?highlight=jovyan#what-is-a-jovyan) by joining our [Discourse forum](http://discourse.jupyter.org/). There is also an intro thread there where you can stop by and say Hi! :wave: <br>Welcome to the Jupyter community! :tada:
2021-10-07T22:03:08Z
[]
[]
jupyterhub/jupyterhub
3,664
jupyterhub__jupyterhub-3664
[ "3622" ]
dca6d372dfda198fdc36c226b28cbef5854af194
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -2109,7 +2109,7 @@ async def init_role_assignment(self): ) Class = orm.get_class(kind) orm_obj = Class.find(db, bname) - if orm_obj: + if orm_obj is not None: orm_role_bearers.append(orm_obj) else: app_log.info( @@ -2118,6 +2118,11 @@ async def init_role_assignment(self): if kind == 'users': orm_obj = await self._get_or_create_user(bname) orm_role_bearers.append(orm_obj) + elif kind == 'groups': + group = orm.Group(name=bname) + db.add(group) + db.commit() + orm_role_bearers.append(group) else: raise ValueError( f"{kind} {bname} defined in config role definition {predef_role['name']} but not present in database"
diff --git a/jupyterhub/tests/test_roles.py b/jupyterhub/tests/test_roles.py --- a/jupyterhub/tests/test_roles.py +++ b/jupyterhub/tests/test_roles.py @@ -578,7 +578,7 @@ async def test_load_roles_groups(tmpdir, request): 'name': 'head', 'description': 'Whole user access', 'scopes': ['users', 'admin:users'], - 'groups': ['group3'], + 'groups': ['group3', "group4"], }, ] kwargs = {'load_groups': groups_to_load, 'load_roles': roles_to_load} @@ -598,11 +598,13 @@ async def test_load_roles_groups(tmpdir, request): group1 = orm.Group.find(db, name='group1') group2 = orm.Group.find(db, name='group2') group3 = orm.Group.find(db, name='group3') + group4 = orm.Group.find(db, name='group4') # test group roles assert group1.roles == [] assert group2 in assist_role.groups assert group3 in head_role.groups + assert group4 in head_role.groups # delete the test roles for role in roles_to_load:
load_roles referencing users and groups: not found users are created, not found groups cause errors - is it wanted behavior? I was surprised that users were automatically created without a warning, but groups not found caused an error. I think it could be okay, but I'm not sure and wanted to raise it for a consideration - is there something we want to change about this? ```python c.JupyterHub.load_roles = [ { "name": "test-role-1:", "description": "Access to users' information and group membership", "scopes": ["users", "groups"], "users": ["cyclops", "gandalf"], "services": ["test"], # adding a group not defined would raise an error # there is a load_groups function but not a load_users function though "groups": [], } ] ``` ``` [I 2021-09-26 01:03:16.454 JupyterHub app:2095] Found unexisting users gandalf in role definition test-role-1 [I 2021-09-26 01:03:16.455 JupyterHub app:1963] Creating user gandalf ```
My initial expectation is that neither users nor groups are automatically created just because they're mentioned in a role. Ideally they'd be lazy loaded, so e.g. if a user is permitted to login by external oauth but has never logged in before then that role would automatically take effect when they first logged in. Alternatively the role could ignore (or warn about) unknown users/groups. I'm interested to hear other perspectives though. I do think groups and users should probably be handled consistently, at the very least. > Ideally they'd be lazy loaded, That would make sense in the abstract, but in practice it can't work that way because role membership is currently a db relationship - a user can't have a role if the User record isn't in the database. I think it would be a lot more complicated to preserve the list of users assigned roles that don't yet exist, and do new role assignments if/when they eventually show up, than it is to create populate the user row immediately. That simplifies things greatly and is very cheap. I think it's a tricky balance between redundancy of overly-verbose config (where users must all appear in *both* the `allowed_users` set *and* in any role the user is assigned). But I suppose separating role assignment from user creation may have some benefit that I don't see. One reason users are created when declared in roles is that the `allowed_users` set is now basically an alias for populating the users role. The only difference is that for backward-compatibility purposes, `allowed_users` is an *initial* set which can be expanded via API requests (e.g. the admin page), whereas if you specify the `user` role membership list explicitly, any user not in that list *loses* that role on startup. We've never been able to do permission revocation on startup before. As it is now, there are also cases that cannot be supported if users assigned to roles *must* first be declared separately, for example: - no allowed_users set (any successful login is allowed), and - some users are assigned to a special role admins / teachers / etc. That common pattern (almost every Hub I've deployed) cannot be accomplished unless we also add a *separate* `load_users` list that's almost the same as `allowed_users`, but is purely declaring users to exist without granting any permissions. I see this as redundant with populating from role assignments, since all it seems to accomplish is making sure every config has every username at least twice. So my perspective is that a username or group appearing in a role should result in creating that user or group in the database. But I'm open to other suggestions! Feel free to sketch what you'd *like* a config file to look like, and we can try to make it work.
2021-10-27T19:01:17Z
[]
[]
jupyterhub/jupyterhub
3,665
jupyterhub__jupyterhub-3665
[ "3620" ]
b34120ed81ffa8f290fc623070e66d1d521405dd
diff --git a/docs/source/conf.py b/docs/source/conf.py --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -215,7 +215,7 @@ def setup(app): # build both metrics and rest-api, since RTD doesn't run make from subprocess import check_call as sh - sh(['make', 'metrics', 'rest-api', 'scopes'], cwd=docs) + sh(['make', 'metrics', 'scopes'], cwd=docs) # -- Spell checking ------------------------------------------------------- diff --git a/docs/source/rbac/generate-scope-table.py b/docs/source/rbac/generate-scope-table.py --- a/docs/source/rbac/generate-scope-table.py +++ b/docs/source/rbac/generate-scope-table.py @@ -5,10 +5,12 @@ from pytablewriter import MarkdownTableWriter from ruamel.yaml import YAML +import jupyterhub from jupyterhub.scopes import scope_definitions HERE = os.path.abspath(os.path.dirname(__file__)) -PARENT = Path(HERE).parent.parent.absolute() +DOCS = Path(HERE).parent.parent.absolute() +REST_API_YAML = DOCS.joinpath("source", "_static", "rest-api.yml") class ScopeTableGenerator: @@ -98,22 +100,24 @@ def write_table(self): def write_api(self): """Generates the API description in markdown format and writes it into `rest-api.yml`""" - filename = f"{PARENT}/rest-api.yml" + filename = REST_API_YAML yaml = YAML(typ='rt') yaml.preserve_quotes = True scope_dict = {} - with open(filename, 'r+') as f: + with open(filename) as f: content = yaml.load(f.read()) - f.seek(0) - for scope in self.scopes: - description = self.scopes[scope]['description'] - doc_description = self.scopes[scope].get('doc_description', '') - if doc_description: - description = doc_description - scope_dict[scope] = description - content['securityDefinitions']['oauth2']['scopes'] = scope_dict + + content["info"]["version"] = jupyterhub.__version__ + for scope in self.scopes: + description = self.scopes[scope]['description'] + doc_description = self.scopes[scope].get('doc_description', '') + if doc_description: + description = doc_description + scope_dict[scope] = description + content['securityDefinitions']['oauth2']['scopes'] = scope_dict + + with open(filename, 'w') as f: yaml.dump(content, f) - f.truncate() def main(): diff --git a/jupyterhub/_version.py b/jupyterhub/_version.py --- a/jupyterhub/_version.py +++ b/jupyterhub/_version.py @@ -1,13 +1,14 @@ """JupyterHub version info""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. - version_info = ( 2, 0, 0, "b3", # release (b1, rc1, or "" for final or dev) # "dev", # dev or nothing for beta/rc/stable releases + # when updating, make sure to update version in docs/source/_static/rest-api.yml as well + # `cd docs; make scopes` will do this ) # pep 440 version: no dot before beta/rc, but before .dev
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -14,8 +14,28 @@ on: env: # UTF-8 content may be interpreted as ascii and causes errors without this. LANG: C.UTF-8 + PYTEST_ADDOPTS: "--verbose --color=yes" jobs: + rest-api: + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v2 + - name: Validate REST API + uses: char0n/swagger-editor-validate@182d1a5d26ff5c2f4f452c43bd55e2c7d8064003 + with: + definition-file: docs/source/_static/rest-api.yml + + - uses: actions/setup-python@v2 + with: + python-version: "3.9" + # in addition to the doc requirements + # the docs *tests* require pre-commit and pytest + - run: | + pip install -r docs/requirements.txt pytest pre-commit -e . + - run: | + pytest docs/ + # Run "pytest jupyterhub/tests" in various configurations pytest: runs-on: ubuntu-20.04 @@ -182,10 +202,8 @@ jobs: fi - name: Run pytest - # FIXME: --color=yes explicitly set because: - # https://github.com/actions/runner/issues/241 run: | - pytest -v --maxfail=2 --color=yes --cov=jupyterhub jupyterhub/tests + pytest --maxfail=2 --cov=jupyterhub jupyterhub/tests - name: Run yarn jest test run: | cd jsx && yarn && yarn test diff --git a/docs/test_docs.py b/docs/test_docs.py new file mode 100644 --- /dev/null +++ b/docs/test_docs.py @@ -0,0 +1,45 @@ +import sys +from pathlib import Path +from subprocess import run + +from ruamel.yaml import YAML + +yaml = YAML(typ="safe") + +here = Path(__file__).absolute().parent +root = here.parent + + +def test_rest_api_version(): + version_py = root.joinpath("jupyterhub", "_version.py") + rest_api_yaml = root.joinpath("docs", "source", "_static", "rest-api.yml") + ns = {} + with version_py.open() as f: + exec(f.read(), {}, ns) + jupyterhub_version = ns["__version__"] + + with rest_api_yaml.open() as f: + rest_api = yaml.load(f) + rest_api_version = rest_api["info"]["version"] + + assert jupyterhub_version == rest_api_version + + +def test_restapi_scopes(): + run([sys.executable, "source/rbac/generate-scope-table.py"], cwd=here, check=True) + run( + ['pre-commit', 'run', 'prettier', '--files', 'source/_static/rest-api.yml'], + cwd=here, + check=False, + ) + run( + [ + "git", + "diff", + "--no-pager", + "--exit-code", + str(here.joinpath("source", "_static", "rest-api.yml")), + ], + cwd=here, + check=True, + )
JupyterHub OpenAPI spec contains errors ### Bug description The Swagger validator reports errors in the current JupyterHub OpenAPI spec: [![](https://validator.swagger.io/validator/?url=https%3A%2F%2Fraw.githubusercontent.com%2Fjupyterhub%2Fjupyterhub%2FHEAD%2Fdocs%2Frest-api.yml)](https://validator.swagger.io/validator/?url=https%3A%2F%2Fraw.githubusercontent.com%2Fjupyterhub%2Fjupyterhub%2FHEAD%2Fdocs%2Frest-api.yml) https://validator.swagger.io/validator/debug?url=https%3A%2F%2Fraw.githubusercontent.com%2Fjupyterhub%2Fjupyterhub%2Fmain%2Fdocs%2Frest-api.yml In addition the API version should be bumped to `2.0.0`, currently it still says `1.4.0`: https://github.com/jupyterhub/jupyterhub/blob/4f6ef54b50ea577bb67f2726bc98a5ce909ebc92/docs/rest-api.yml#L4-L6 #### Expected behaviour Schema should validate without errors #### Actual behaviour ```json { "messages": [ "attribute paths.'/users'(get).[limit].requred is unexpected", "attribute paths.'/proxy'(get).[limit].requred is unexpected" ], "schemaValidationMessages": [ { "level": "error", "domain": "validation", "keyword": "oneOf", "message": "instance failed to match exactly one schema (matched 0 out of 2)", "schema": { "loadingURI": "http://swagger.io/v2/schema.json#", "pointer": "/definitions/parametersList/items" }, "instance": { "pointer": "/paths/~1proxy/get/parameters/1" } } ] } ``` Note there are no errors in 1.4.0: [![](https://validator.swagger.io/validator/?url=https%3A%2F%2Fraw.githubusercontent.com%2Fjupyterhub%2Fjupyterhub%2F1.4.0%2Fdocs%2Frest-api.yml)](https://validator.swagger.io/validator/?url=https%3A%2F%2Fraw.githubusercontent.com%2Fjupyterhub%2Fjupyterhub%2F1.4.0%2Fdocs%2Frest-api.yml)
2021-10-27T20:15:29Z
[]
[]
jupyterhub/jupyterhub
3,701
jupyterhub__jupyterhub-3701
[ "3027" ]
85e37e7f8c3220421f2041b674e6f172843cf137
diff --git a/jupyterhub/apihandlers/base.py b/jupyterhub/apihandlers/base.py --- a/jupyterhub/apihandlers/base.py +++ b/jupyterhub/apihandlers/base.py @@ -58,7 +58,8 @@ def check_referer(self): - allow unspecified host/referer (e.g. scripts) """ - host = self.request.headers.get(self.app.forwarded_host_header or "Host") + host_header = self.app.forwarded_host_header or "Host" + host = self.request.headers.get(host_header) referer = self.request.headers.get("Referer") # If no header is provided, assume it comes from a script/curl. @@ -70,13 +71,24 @@ def check_referer(self): self.log.warning("Blocking API request with no referer") return False - host_path = url_path_join(host, self.hub.base_url) - referer_path = referer.split('://', 1)[-1] - if not (referer_path + '/').startswith(host_path): + proto = self.request.protocol + full_host = f"{proto}://{host}{self.hub.base_url}" + host_url = urlparse(full_host) + referer_url = urlparse(referer) + # resolve default ports for http[s] + referer_port = referer_url.port or ( + 443 if referer_url.scheme == 'https' else 80 + ) + host_port = host_url.port or (443 if host_url.scheme == 'https' else 80) + if ( + referer_url.scheme != host_url.scheme + or referer_url.hostname != host_url.hostname + or referer_port != host_port + or not (referer_url.path + "/").startswith(host_url.path) + ): self.log.warning( - "Blocking Cross Origin API request. Referer: %s, Host: %s", - referer, - host_path, + f"Blocking Cross Origin API request. Referer: {referer}," + " {host_header}: {host}, Host URL: {full_host}", ) return False return True
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -9,6 +9,7 @@ from unittest import mock from urllib.parse import quote from urllib.parse import urlparse +from urllib.parse import urlunparse from pytest import fixture from pytest import mark @@ -65,7 +66,15 @@ async def test_auth_api(app): assert r.status_code == 403 -async def test_cors_checks(request, app): [email protected]( + "content_type, status", + [ + ("text/plain", 403), + # accepted, but invalid + ("application/json; charset=UTF-8", 400), + ], +) +async def test_post_content_type(app, content_type, status): url = ujoin(public_host(app), app.hub.base_url) host = urlparse(url).netloc # add admin user @@ -74,42 +83,6 @@ async def test_cors_checks(request, app): user = add_user(app.db, name='admin', admin=True) cookies = await app.login_user('admin') - r = await api_request( - app, 'users', headers={'Authorization': '', 'Referer': 'null'}, cookies=cookies - ) - assert r.status_code == 403 - - r = await api_request( - app, - 'users', - headers={ - 'Authorization': '', - 'Referer': 'http://attack.com/csrf/vulnerability', - }, - cookies=cookies, - ) - assert r.status_code == 403 - - r = await api_request( - app, - 'users', - headers={'Authorization': '', 'Referer': url, 'Host': host}, - cookies=cookies, - ) - assert r.status_code == 200 - - r = await api_request( - app, - 'users', - headers={ - 'Authorization': '', - 'Referer': ujoin(url, 'foo/bar/baz/bat'), - 'Host': host, - }, - cookies=cookies, - ) - assert r.status_code == 200 - r = await api_request( app, 'users', @@ -117,24 +90,62 @@ async def test_cors_checks(request, app): data='{}', headers={ "Authorization": "", - "Content-Type": "text/plain", + "Content-Type": content_type, }, cookies=cookies, ) - assert r.status_code == 403 + assert r.status_code == status - r = await api_request( - app, - 'users', - method='post', - data='{}', - headers={ - "Authorization": "", - "Content-Type": "application/json; charset=UTF-8", - }, - cookies=cookies, - ) - assert r.status_code == 400 # accepted, but invalid + [email protected]( + "host, referer, status", + [ + ('$host', '$url', 200), + (None, None, 200), + (None, 'null', 403), + (None, 'http://attack.com/csrf/vulnerability', 403), + ('$host', {"path": "/user/someuser"}, 403), + ('$host', {"path": "{path}/foo/bar/subpath"}, 200), + # mismatch host + ("mismatch.com", "$url", 403), + # explicit host, matches + ("fake.example", {"netloc": "fake.example"}, 200), + # explicit port, matches implicit port + ("fake.example:80", {"netloc": "fake.example"}, 200), + # explicit port, mismatch + ("fake.example:81", {"netloc": "fake.example"}, 403), + # implicit ports, mismatch proto + ("fake.example", {"netloc": "fake.example", "scheme": "https"}, 403), + ], +) +async def test_cors_check(request, app, host, referer, status): + url = ujoin(public_host(app), app.hub.base_url) + real_host = urlparse(url).netloc + if host == "$host": + host = real_host + + if referer == '$url': + referer = url + elif isinstance(referer, dict): + parsed_url = urlparse(url) + # apply {} + url_ns = {key: getattr(parsed_url, key) for key in parsed_url._fields} + for key, value in referer.items(): + referer[key] = value.format(**url_ns) + referer = urlunparse(parsed_url._replace(**referer)) + + # disable default auth header, cors is for cookie auth + headers = {"Authorization": ""} + if host is not None: + headers['X-Forwarded-Host'] = host + if referer is not None: + headers['Referer'] = referer + + # add admin user + user = find_user(app.db, 'admin') + if user is None: + user = add_user(app.db, name='admin', admin=True) + cookies = await app.login_user('admin') # test custom forwarded_host_header behavior app.forwarded_host_header = 'X-Forwarded-Host' @@ -148,28 +159,10 @@ def reset_header(): r = await api_request( app, 'users', - headers={ - 'Authorization': '', - 'Referer': url, - 'Host': host, - 'X-Forwarded-Host': 'example.com', - }, - cookies=cookies, - ) - assert r.status_code == 403 - - r = await api_request( - app, - 'users', - headers={ - 'Authorization': '', - 'Referer': url, - 'Host': host, - 'X-Forwarded-Host': host, - }, + headers=headers, cookies=cookies, ) - assert r.status_code == 200 + assert r.status_code == status # --------------
Cross site scripting false positive A load balancer in front of my jupyterhub service is adding a :443 into the host header. This is undesired but valid according to the http spec and causes a false positive when performing the cross site scripting check. This pull request modifies the value read from the host header to strip the :443 or :80 if a load balancer has added it. In our case it is an azure load balancer and we cant control it. https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23 Host = "Host" ":" host [ ":" **port** ] ; Section 3.2.2 Error seen in logs during false positive: [W 2020-04-17 11:51:29.470 JupyterHub base:60] Blocking Cross Origin API request. Referer: https://jupyter.myurl.fi/hub/spawn-pending/user, Host: **jupyter.myurl.fi:443**/hub/ [W 2020-04-17 11:51:29.471 JupyterHub log:174] 403 GET /hub/api/users/xxx/server/progress (@myip) 6.40ms
Seems like a reasonable change to make given it is part of the spec. Having to "parse" the value of the `Host` header manually with `.endswith()` triggers my "seems fragile and like it might create hard to debug weirdness" senses. Have you investigated if there is something "ready made" that we can use to split the header value into "hostname" and "port"? I don't think https://docs.python.org/3/library/urllib.parse.html contains the answer but it is the equivalent for handling URLs. Alternatively what do you think of `hostname, port = host_value.split(":", maxsplit=1)` as a way to also handle other ports? I updated the code based on your comments. I still make changes only to host_headers with 80 and 443 in them. For example, if someone wants to run on port 8080 they still could. It is not in the spec but standard behavior of many clients and servers will truncate the 80 and 443 from a request. For example if you curl -v https://www.google.com:443, their host header will be www.google.com without the 443. I'm slightly concerned by why this is necessary. Do you know if it's Tornado or JupyterHub that's stripping the `80` or `443` in the first place causing the comparison here to fail? For instance there's a very unlikely edge case where someone runs a `http:80` and `http:443` (***not*** `https:443`) on the same server. These should be treated as different hosts, but here they'd be treated the same. This isn't necessary a blocker to this PR, but I thought I mention it as this this change could affect security so we should at least state our assumptions upfront. @manics Jupyterhub was not stripping the 80/443 from the hosts header so the comparison against what should have been equal referer failed. My code strips the 80/443 so that the comparison can succeed. This check compares the value of the referrer and the value of the host headers. Do we understand why the referrer doesn't contain a port but the host header does? That is how I understand the situation you are in @scivm, correct? In addition to the above, could you also confirm it's an Azure Load Balancer and not an Azure Application Gateway which includes load balancing? I've been searching Google since this sounds like something that would affect other applications. @betatim I believe it is a standard behavior to remove 80 and 443 ports by clients and servers. The referer header likely had the port removed in the browser. It was not every request where the issue was manifesting either. It would happen during the poll for a user workspace starting and also in the hub control panel when you tried to shutdown your server. @manics I confirmed that it is Azure Application Gateway which has load balancing and firewall built in. The load balancer is in default configuration. The firewall implements a standard OWASP rule set (there are configurable versions but we are using 3.0). We found for jupyterhub we needed to disable 920230-Multiple URL Encoding Detected, 942370-Detects classic SQL injection probings 2/2 for jupyterhub to work. We are investigating these and they could easily be false positives. We also closed off the firewall to own country now so it will be easier to test without an attack going on. Could you try modifying the `X-Forwarded-For` header as suggested here: https://azure.microsoft.com/en-gb/blog/rewrite-http-headers-with-azure-application-gateway/ That might give you a workaround whilst we figure out whether this is OK to merge. > Do we understand why the referrer doesn't contain a port but the host header does? Referer is set by the browser, the original post says that a Load Balancer is modifying the Host header (in a technically valid, but not normal or common way). What we really want to check is Origin here, which includes protocol (and thereby port) and why our checks here are fiddly. Unfortunately, browsers don't consistently send Origin (some send Origin for all cross-origin requests, others—firefox—*don't* send them for all cross-origin requests). And we specifically want to use this check to block requests originating from single-user servers, which are not cross-origin and thus usually lack an Origin header. Aside: I think it was a big mistake by browser folks to not send Origin for *all* requests. Since we want to check origin, we should be getting the *protocol* as well and resolving the port if over-specified: ```python proto = self.requests.protocol host = self.request.get_header('Host') hostname, _, port = host.partition(":") # elide over-specified default ports if proto == 'https' and port == '443': port = '' if proto == 'http' and port == '80': port = '' if port: port = ':' + port origin = f"{proto}://{hostname}{port}" ``` Comparison could be done with parsed URL objects, in which case we want to check protocol, host, port, path prefix: ```python host_url = urlparse(f"{origin}{self.hub.base_url}") referer_url = urlparse(referer) if referer_url.scheme != host_url.scheme: # fail if referer_url.hostname != host_url.hostname: # fail # resolve default ports (no need for elide block above if we do this) referer_port = referer_url.port or (443 if referer_url.scheme == 'https' else 80) host_port = host_url.port or (443 if host_url.scheme == 'https' else 80) if referer_port != host_port: # fail if not referer_url.path.startswith(host_url.path): # fail ```
2021-12-02T10:03:13Z
[]
[]
jupyterhub/jupyterhub
3,708
jupyterhub__jupyterhub-3708
[ "3703" ]
c2cbeda9e422e6a039d488ea51d0549d18c6fed9
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -2015,14 +2015,25 @@ async def init_groups(self): async def init_role_creation(self): """Load default and predefined roles into the database""" - self.log.debug('Loading default roles to database') + self.log.debug('Loading roles into database') default_roles = roles.get_default_roles() config_role_names = [r['name'] for r in self.load_roles] - init_roles = default_roles + default_roles_dict = {role["name"]: role for role in default_roles} + init_roles = [] roles_with_new_permissions = [] for role_spec in self.load_roles: role_name = role_spec['name'] + if role_name in default_roles_dict: + self.log.debug(f"Overriding default role {role_name}") + # merge custom role spec with default role spec when overriding + # so the new role can be partially defined + default_role_spec = default_roles_dict.pop(role_name) + merged_role_spec = {} + merged_role_spec.update(default_role_spec) + merged_role_spec.update(role_spec) + role_spec = merged_role_spec + # Check for duplicates if config_role_names.count(role_name) > 1: raise ValueError( @@ -2033,10 +2044,13 @@ async def init_role_creation(self): old_role = orm.Role.find(self.db, name=role_name) if old_role: if not set(role_spec['scopes']).issubset(old_role.scopes): - app_log.warning( + self.log.warning( "Role %s has obtained extra permissions" % role_name ) roles_with_new_permissions.append(role_name) + + # make sure we load any default roles not overridden + init_roles = list(default_roles_dict.values()) + init_roles if roles_with_new_permissions: unauthorized_oauth_tokens = ( self.db.query(orm.APIToken) @@ -2048,7 +2062,7 @@ async def init_role_creation(self): .filter(orm.APIToken.client_id != 'jupyterhub') ) for token in unauthorized_oauth_tokens: - app_log.warning( + self.log.warning( "Deleting OAuth token %s; one of its roles obtained new permissions that were not authorized by user" % token ) @@ -2056,14 +2070,19 @@ async def init_role_creation(self): self.db.commit() init_role_names = [r['name'] for r in init_roles] - if not orm.Role.find(self.db, name='admin'): + if ( + self.db.query(orm.Role).first() is None + and self.db.query(orm.User).first() is not None + ): + # apply rbac-upgrade default role assignment if there are users in the db, + # but not any roles self._rbac_upgrade = True else: self._rbac_upgrade = False for role in self.db.query(orm.Role).filter( orm.Role.name.notin_(init_role_names) ): - app_log.info(f"Deleting role {role.name}") + self.log.warning(f"Deleting role {role.name}") self.db.delete(role) self.db.commit() for role in init_roles: @@ -2079,71 +2098,89 @@ async def init_role_assignment(self): if config_admin_users: for role_spec in self.load_roles: if role_spec['name'] == 'admin': - app_log.warning( + self.log.warning( "Configuration specifies both admin_users and users in the admin role specification. " "If admin role is present in config, c.Authenticator.admin_users should not be used." ) - app_log.info( + self.log.info( "Merging admin_users set with users list in admin role" ) role_spec['users'] = set(role_spec.get('users', [])) role_spec['users'] |= config_admin_users - self.log.debug('Loading predefined roles from config file to database') + self.log.debug('Loading role assignments from config') has_admin_role_spec = {role_bearer: False for role_bearer in admin_role_objects} - for predef_role in self.load_roles: - predef_role_obj = orm.Role.find(db, name=predef_role['name']) - if predef_role['name'] == 'admin': + for role_spec in self.load_roles: + role = orm.Role.find(db, name=role_spec['name']) + role_name = role_spec["name"] + if role_name == 'admin': for kind in admin_role_objects: - has_admin_role_spec[kind] = kind in predef_role + has_admin_role_spec[kind] = kind in role_spec if has_admin_role_spec[kind]: - app_log.info(f"Admin role specifies static {kind} list") + self.log.info(f"Admin role specifies static {kind} list") else: - app_log.info( + self.log.info( f"Admin role does not specify {kind}, preserving admin membership in database" ) # add users, services, and/or groups, # tokens need to be checked for permissions for kind in kinds: orm_role_bearers = [] - if kind in predef_role.keys(): - for bname in predef_role[kind]: + if kind in role_spec: + for name in role_spec[kind]: if kind == 'users': - bname = self.authenticator.normalize_username(bname) + name = self.authenticator.normalize_username(name) if not ( await maybe_future( - self.authenticator.check_allowed(bname, None) + self.authenticator.check_allowed(name, None) ) ): raise ValueError( - "Username %r is not in Authenticator.allowed_users" - % bname + f"Username {name} is not in Authenticator.allowed_users" ) Class = orm.get_class(kind) - orm_obj = Class.find(db, bname) + orm_obj = Class.find(db, name) if orm_obj is not None: orm_role_bearers.append(orm_obj) else: - app_log.info( - f"Found unexisting {kind} {bname} in role definition {predef_role['name']}" + self.log.info( + f"Found unexisting {kind} {name} in role definition {role_name}" ) if kind == 'users': - orm_obj = await self._get_or_create_user(bname) + orm_obj = await self._get_or_create_user(name) orm_role_bearers.append(orm_obj) elif kind == 'groups': - group = orm.Group(name=bname) + group = orm.Group(name=name) db.add(group) db.commit() orm_role_bearers.append(group) else: raise ValueError( - f"{kind} {bname} defined in config role definition {predef_role['name']} but not present in database" + f"{kind} {name} defined in config role definition {role_name} but not present in database" ) # Ensure all with admin role have admin flag - if predef_role['name'] == 'admin': + if role_name == 'admin': orm_obj.admin = True - setattr(predef_role_obj, kind, orm_role_bearers) + # explicitly defined list + # ensure membership list is exact match (adds and revokes permissions) + setattr(role, kind, orm_role_bearers) + else: + # no defined members + # leaving 'users' undefined in overrides of the default 'user' role + # should not clear membership on startup + # since allowed users could be managed by the authenticator + if kind == "users" and role_name == "user": + # Default user lists can be managed by the Authenticator, + # if unspecified in role config + pass + else: + # otherwise, omitting a member category is equivalent to specifying an empty list + setattr(role, kind, []) + db.commit() if self.authenticator.allowed_users: + self.log.debug( + f"Assigning {len(self.authenticator.allowed_users)} allowed_users to the user role" + ) allowed_users = db.query(orm.User).filter( orm.User.name.in_(self.authenticator.allowed_users) ) @@ -2160,8 +2197,8 @@ async def init_role_assignment(self): db.commit() # make sure that on hub upgrade, all users, services and tokens have at least one role (update with default) if getattr(self, '_rbac_upgrade', False): - app_log.warning( - "No admin role found; assuming hub upgrade. Initializing default roles for all entities" + self.log.warning( + "No roles found; assuming hub upgrade. Initializing default roles for all entities" ) for kind in kinds: roles.check_for_default_roles(db, kind) diff --git a/jupyterhub/roles.py b/jupyterhub/roles.py --- a/jupyterhub/roles.py +++ b/jupyterhub/roles.py @@ -239,26 +239,6 @@ def _check_scopes(*args, rolename=None): ) -def _overwrite_role(role, role_dict): - """Overwrites role's description and/or scopes with role_dict if role not 'admin'""" - for attr in role_dict.keys(): - if attr == 'description' or attr == 'scopes': - if role.name == 'admin': - admin_role_spec = [ - r for r in get_default_roles() if r['name'] == 'admin' - ][0] - if role_dict[attr] != admin_role_spec[attr]: - raise ValueError( - 'admin role description or scopes cannot be overwritten' - ) - else: - if role_dict[attr] != getattr(role, attr): - setattr(role, attr, role_dict[attr]) - app_log.info( - 'Role %r %r attribute has been changed', role.name, attr - ) - - _role_name_pattern = re.compile(r'^[a-z][a-z0-9\-_~\.]{1,253}[a-z0-9]$') @@ -293,6 +273,17 @@ def create_role(db, role_dict): description = role_dict.get('description') scopes = role_dict.get('scopes') + if name == "admin": + for _role in get_default_roles(): + if _role["name"] == "admin": + admin_spec = _role + break + for key in ["description", "scopes"]: + if key in role_dict and role_dict[key] != admin_spec[key]: + raise ValueError( + f"Cannot override admin role admin.{key} = {role_dict[key]}" + ) + # check if the provided scopes exist if scopes: _check_scopes(*scopes, rolename=role_dict['name']) @@ -306,8 +297,22 @@ def create_role(db, role_dict): if role_dict not in default_roles: app_log.info('Role %s added to database', name) else: - _overwrite_role(role, role_dict) - + for attr in ["description", "scopes"]: + try: + new_value = role_dict[attr] + except KeyError: + continue + old_value = getattr(role, attr) + if new_value != old_value: + setattr(role, attr, new_value) + app_log.info( + f'Role attribute {role.name}.{attr} has been changed', + ) + app_log.debug( + f'Role attribute {role.name}.{attr} changed from %r to %r', + old_value, + new_value, + ) db.commit()
diff --git a/jupyterhub/tests/test_roles.py b/jupyterhub/tests/test_roles.py --- a/jupyterhub/tests/test_roles.py +++ b/jupyterhub/tests/test_roles.py @@ -1183,24 +1183,36 @@ async def test_no_admin_role_change(): await hub.init_role_creation() -async def test_user_config_respects_memberships(): - role_spec = [ - { - 'name': 'user', - 'scopes': ['self', 'shutdown'], - } - ] - user_names = ['eddy', 'carol'] - hub = MockHub(load_roles=role_spec) [email protected]( + "in_db, role_users, allowed_users, expected_members", + [ + # users in the db, not specified in custom user role + # no change to membership + (["alpha", "beta"], None, None, ["alpha", "beta"]), + # allowed_users is additive, not strict + (["alpha", "beta"], None, {"gamma"}, ["alpha", "beta", "gamma"]), + # explicit empty revokes all assignments + (["alpha", "beta"], [], None, []), + # explicit value is respected exactly + (["alpha", "beta"], ["alpha", "gamma"], None, ["alpha", "gamma"]), + ], +) +async def test_user_role_from_config( + in_db, role_users, allowed_users, expected_members +): + role_spec = { + 'name': 'user', + 'scopes': ['self', 'shutdown'], + } + if role_users is not None: + role_spec['users'] = role_users + hub = MockHub(load_roles=[role_spec]) hub.init_db() - hub.authenticator.allowed_users = user_names + db = hub.db + hub.authenticator.admin_users = set() + if allowed_users: + hub.authenticator.allowed_users = allowed_users await hub.init_role_creation() - await hub.init_users() - await hub.init_role_assignment() - user_role = orm.Role.find(hub.db, 'user') - for user_name in user_names: - user = orm.User.find(hub.db, user_name) - assert user in user_role.users async def test_user_config_creates_default_role(): @@ -1243,16 +1255,45 @@ async def test_admin_role_respects_config(): assert user in admin_role.users -async def test_empty_admin_spec(): - role_spec = [{'name': 'admin', 'users': []}] - hub = MockHub(load_roles=role_spec) [email protected]( + "in_db, role_users, admin_users, expected_members", + [ + # users in the db, not specified in custom user role + # no change to membership + (["alpha", "beta"], None, None, ["alpha", "beta"]), + # admin_users is additive, not strict + (["alpha", "beta"], None, {"gamma"}, ["alpha", "beta", "gamma"]), + # explicit empty revokes all assignments + (["alpha", "beta"], [], None, []), + # explicit value is respected exactly + (["alpha", "beta"], ["alpha", "gamma"], None, ["alpha", "gamma"]), + ], +) +async def test_admin_role_membership(in_db, role_users, admin_users, expected_members): + + load_roles = [] + if role_users is not None: + load_roles.append({"name": "admin", "users": role_users}) + if not admin_users: + admin_users = set() + hub = MockHub(load_roles=load_roles, db_url="sqlite:///:memory:") hub.init_db() - hub.authenticator.admin_users = [] await hub.init_role_creation() + db = hub.db + hub.authenticator.admin_users = admin_users + # add in_db users to the database + # this is the 'before' state of who had the role before startup + for username in in_db or []: + user = orm.User(name=username) + db.add(user) + db.commit() + roles.grant_role(db, user, "admin") + db.commit() await hub.init_users() await hub.init_role_assignment() - admin_role = orm.Role.find(hub.db, 'admin') - assert not admin_role.users + admin_role = orm.Role.find(db, 'admin') + role_members = sorted(user.name for user in admin_role.users) + assert role_members == expected_members async def test_no_default_service_role():
Problems overriding the default roles <!-- Thank you for contributing. These HTML comments will not render in the issue, but you can delete them once you've read them if you prefer! --> ### Bug description It seems that overriding the role `user` is not functioning correctly. Specifically, on jh 2.0.0 if I set up the following role config (see [here](https://discourse.jupyter.org/t/plans-on-bringing-rtc-to-jupyterhub/9813/11?u=anton_akhmerov) for motivation) ```python c.JupyterHub.load_roles = [ { "name": "user", "description": "Allow users to access the shared server in addition to default perms", "scopes": ["self", "access:servers!user=shared"], } ] ``` Now after starting the hub, any non-admin user that existed on the hub before the start is unable to launch their server and sees a 500 error: ![image](https://user-images.githubusercontent.com/2069677/144727721-6f6b5578-41f6-4704-9ffa-11c08428f7fc.png) After deleting and recreating the user from the hub admin panel, everything seems to function normally.
@akhmerov thanks for the report! I'll dig into this. In the meantime, do you have the log line that starts with `Token requesting role`? It should show specifically what permissions are conflicting. Sure: ``` [W 2021-12-06 13:19:17.896 JupyterHub roles:436] Token requesting role server with scopes not held by owner shared: {'access:servers', 'users:activity', 'read:users:activity'} ``` Have you specified the `server` role as well? No, what wrote above is the complete role spec. Is it necessary to set something for the server? I thought `server` inherits the subset of scopes. Plus if it was necessary to specify the server then it wouldn't explain why deleting and readding the user changes the behavior. > Is it necessary to set something for the server? You shouldn't need to, I'm just trying to track down the source of the problem, since I haven't been able to reproduce it myself just yet. The relevant details: 1. `user` role defines the permissions held by all JupyterHub users 2. `server` role defines the permissions of the $JUPYTERHUB_API_TOKEN that the server itself uses. The [default][] is ```python [ 'users:activity!user', 'access:servers!user', ], ``` where `!user` is an alias for `!user=$name` for the _owner_ of the server 3. when issuing a token owned by a user, JupyterHub [checks][] that the token isn't being given permissions that its owner doesn't have. What you are experiencing is the token issued during server startup for hte user `shared` is requesting the role `server`, but the user `shared` doesn't have a superset of the the requested permissions for starting a server. Here's a question: is the `shared` user in your `allowed_users` list? I believe that would cause the issue, because then the shared user might not have any role assigned. How are you starting the shared server? [default]: https://github.com/jupyterhub/jupyterhub/blob/2.0.0/jupyterhub/roles.py#L50-L54 [checks]: https://github.com/jupyterhub/jupyterhub/blob/2.0.0/jupyterhub/roles.py#L402-L439 The problem doesn't only apply to the `shared` user. Rather all users except for admins encounter this problem with their own servers. It appears both if I attempt to launch a user's server via the admin panel or if a user tries to do it on their own. Hmm, we don't have `allowed_users` explicitly specified in the config. Most users are created by the oauthenticator, and `shared` was created via the admin interface. Ah, gotcha. and the issue mainly occurs on Hub restart? Then I think I know where to look. My guess is that users are being stripped of their membership in the `user` role because you have defined a custom user role, but not specified any members. This would be the right thing to do if you had specified an explicit empty list (`"users": []`), but perhaps it behaves the same if the membership is simply omitted. There are too many places user creation can happen! Indeed, the problem occurs after hub restart with every non-admin user that is in the database before the hub has restarted. I have no custom roles defined, only `user` and no non-admin users defined in the config.
2021-12-07T14:58:56Z
[]
[]
jupyterhub/jupyterhub
3,715
jupyterhub__jupyterhub-3715
[ "3711" ]
bb20002aea97b11c2469dd5dd453f18ce48a2d84
diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -465,6 +465,7 @@ async def get(self): named_server_limit_per_user=self.named_server_limit_per_user, server_version=f'{__version__} {self.version_hash}', api_page_limit=self.settings["api_page_default_limit"], + base_url=self.settings["base_url"], ) self.finish(html)
diff --git a/jsx/src/components/ServerDashboard/ServerDashboard.test.js b/jsx/src/components/ServerDashboard/ServerDashboard.test.js --- a/jsx/src/components/ServerDashboard/ServerDashboard.test.js +++ b/jsx/src/components/ServerDashboard/ServerDashboard.test.js @@ -33,11 +33,7 @@ var serverDashboardJsx = (spy) => ( ); var mockAsync = (data) => - jest - .fn() - .mockImplementation(() => - Promise.resolve({ json: () => Promise.resolve(data ? data : { k: "v" }) }) - ); + jest.fn().mockImplementation(() => Promise.resolve(data ? data : { k: "v" })); var mockAsyncRejection = () => jest.fn().mockImplementation(() => Promise.reject());
Empty Admin page when base_url is set ### Bug description <!-- Use this section to clearly and concisely describe the bug. --> If `JupyterHub.base_url` is set in `jupyterhub_config.py`, visitig the Admin tab on jupyterhub v.2.0.0 shows the empty page. #### Expected behaviour <!-- Tell us what you thought would happen. --> Without setting `JupyterHub.base_url` the Admin page displays the list of users: <img width="857" alt="Screenshot 2021-12-10 at 17 41 29" src="https://user-images.githubusercontent.com/2140361/145609729-d5ee0c2c-bdb4-4e77-a730-ccb2ddbbc07a.png"> #### Actual behaviour <!-- Tell us what actually happens. --> The page shows only the version number: <img width="767" alt="Screenshot 2021-12-10 at 17 29 16" src="https://user-images.githubusercontent.com/2140361/145608037-34be2e43-e02d-40a6-b643-79c4628d8915.png"> I see some errors in the log: ``` I 2021-12-10 16:25:47.787 JupyterHub log:189] 200 GET /test/hub/admin (user@::ffff:172.17.0.1) 42.95ms 16:25:48.067 [ConfigProxy] error: 404 GET /hub/api/users 16:25:48.076 [ConfigProxy] error: 404 GET /hub/api/groups ``` ### How to reproduce <!-- Use this section to describe the steps that a user would take to experience this bug. --> 1. Create `Dockerfile` with the following content: ``` FROM jupyterhub/jupyterhub:2.0.0 COPY jupyterhub_config.py /etc/jupyterhub/ CMD jupyterhub -f /etc/jupyterhub/jupyterhub_config.py ``` 2. In the same directory create `jupyterhub_config.py`: ``` c.JupyterHub.base_url = '/test/' c.Authenticator.allowed_users = {'user'} c.Authenticator.admin_users = {'user'} c.JupyterHub.authenticator_class = 'dummy' c.JupyterHub.spawner_class = 'simple' ``` 3. Compile docker image: ``` docker build -t jupyterhub-test . ``` 4. Start the container: ``` docker run -it -p 8000:8000 jupyterhub-test ``` 5. Open the page: http://127.0.0.1:8000/test/hub/admin 6. Enter the user name `user` ### Your personal set up <!-- Tell us a little about the system you're using. Please include information about how you installed, e.g. are you using a distribution such as zero-to-jupyterhub or the-littlest-jupyterhub. --> - OS: MacOS 12.0.1 - Version(s): ``` % docker --version Docker version 20.10.11, build dea9396 ``` <details><summary>Logs</summary> ``` % docker run -it -p 8000:8000 jupyterhub-test [I 2021-12-10 16:49:35.000 JupyterHub app:2717] Running JupyterHub version 2.0.0 [I 2021-12-10 16:49:35.001 JupyterHub app:2747] Using Authenticator: jupyterhub.auth.DummyAuthenticator-2.0.0 [I 2021-12-10 16:49:35.003 JupyterHub app:2747] Using Spawner: jupyterhub.spawner.SimpleLocalProcessSpawner-2.0.0 [I 2021-12-10 16:49:35.004 JupyterHub app:2747] Using Proxy: jupyterhub.proxy.ConfigurableHTTPProxy-2.0.0 [I 2021-12-10 16:49:35.023 JupyterHub app:1641] Writing cookie_secret to /srv/jupyterhub/jupyterhub_cookie_secret [I 2021-12-10 16:49:35.101 alembic.runtime.migration migration:201] Context impl SQLiteImpl. [I 2021-12-10 16:49:35.101 alembic.runtime.migration migration:204] Will assume non-transactional DDL. [I 2021-12-10 16:49:35.152 alembic.runtime.migration migration:615] Running stamp_revision -> 833da8570507 [I 2021-12-10 16:49:35.485 JupyterHub proxy:496] Generating new CONFIGPROXY_AUTH_TOKEN [I 2021-12-10 16:49:35.629 JupyterHub roles:358] Adding role user for User: user [I 2021-12-10 16:49:35.650 JupyterHub roles:358] Adding role admin for User: user [W 2021-12-10 16:49:35.656 JupyterHub app:2152] No admin role found; assuming hub upgrade. Initializing default roles for all entities [I 2021-12-10 16:49:35.727 JupyterHub app:2786] Initialized 0 spawners in 0.008 seconds [W 2021-12-10 16:49:35.739 JupyterHub proxy:687] Running JupyterHub without SSL. I hope there is SSL termination happening somewhere else... [I 2021-12-10 16:49:35.739 JupyterHub proxy:691] Starting proxy @ http://:8000/test/ 16:49:36.527 [ConfigProxy] info: Proxying http://*:8000 to (no default) 16:49:36.536 [ConfigProxy] info: Proxy API at http://127.0.0.1:8001/api/routes 16:49:36.846 [ConfigProxy] info: 200 GET /api/routes [I 2021-12-10 16:49:36.847 JupyterHub app:3035] Hub API listening on http://127.0.0.1:8081/test/hub/ 16:49:36.852 [ConfigProxy] info: 200 GET /api/routes [I 2021-12-10 16:49:36.857 JupyterHub proxy:431] Adding route for Hub: /test/ => http://127.0.0.1:8081 16:49:36.870 [ConfigProxy] info: Adding route /test -> http://127.0.0.1:8081 16:49:36.874 [ConfigProxy] info: Route added /test -> http://127.0.0.1:8081 16:49:36.875 [ConfigProxy] info: 201 POST /api/routes/test [I 2021-12-10 16:49:36.878 JupyterHub app:3101] JupyterHub is now running at http://:8000/test/ [W 2021-12-10 16:49:56.934 JupyterHub base:391] Invalid or expired cookie token [I 2021-12-10 16:49:56.944 JupyterHub log:189] 302 GET /test/hub/admin -> /test/hub/login?next=%2Ftest%2Fhub%2Fadmin (@::ffff:172.17.0.1) 12.91ms [I 2021-12-10 16:49:57.036 JupyterHub log:189] 200 GET /test/hub/login?next=%2Ftest%2Fhub%2Fadmin (@::ffff:172.17.0.1) 63.43ms [I 2021-12-10 16:50:01.674 JupyterHub base:796] User logged in: user [I 2021-12-10 16:50:01.677 JupyterHub log:189] 302 POST /test/hub/login?next=%2Ftest%2Fhub%2Fadmin -> /test/hub/admin (user@::ffff:172.17.0.1) 59.37ms [I 2021-12-10 16:50:01.741 JupyterHub log:189] 200 GET /test/hub/admin (user@::ffff:172.17.0.1) 45.71ms 16:50:01.985 [ConfigProxy] error: 404 GET /hub/api/groups 16:50:02.004 [ConfigProxy] error: 404 GET /hub/api/users [I 2021-12-10 16:50:02.043 JupyterHub log:189] 200 GET /test/hub/error/404?url=%2Fhub%2Fapi%2Fusers%3Foffset%3D0%26limit%3D50 (@127.0.0.1) 22.30ms [I 2021-12-10 16:50:02.061 JupyterHub log:189] 200 GET /test/hub/error/404?url=%2Fhub%2Fapi%2Fgroups%3Foffset%3D0%26limit%3D50 (@127.0.0.1) 14.26ms ``` </details>
@naatebarber sounds like there might be an absolute URL assumption somewhere in the new admin js? Yeah `base_url` isn't being passed, will create a branch.
2021-12-14T01:45:57Z
[]
[]
jupyterhub/jupyterhub
3,735
jupyterhub__jupyterhub-3735
[ "3734" ]
39b331df1b338ea27efaa23afeef59afce015dc1
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -1903,6 +1903,7 @@ async def init_users(self): user = orm.User.find(db, name) if user is None: user = orm.User(name=name, admin=True) + roles.assign_default_roles(self.db, entity=user) new_users.append(user) db.add(user) else:
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -188,6 +188,8 @@ def normalize_user(user): """ for key in ('created', 'last_activity'): user[key] = normalize_timestamp(user[key]) + if 'roles' in user: + user['roles'] = sorted(user['roles']) if 'servers' in user: for server in user['servers'].values(): for key in ('started', 'last_activity'): @@ -240,7 +242,12 @@ async def test_get_users(app): } assert users == [ fill_user( - {'name': 'admin', 'admin': True, 'roles': ['admin'], 'auth_state': None} + { + 'name': 'admin', + 'admin': True, + 'roles': ['admin', 'user'], + 'auth_state': None, + } ), fill_user(user_model), ]
Tests are failing on main branch I've run the tests on the main branch and conclude they are currently failing. See https://github.com/jupyterhub/jupyterhub/actions/runs/1609109514. It seems that while #3722 was merged with succeeded tests, the PRs listed below had been merged in between #3722 was tested and #3722 was merged - and consistent test failures followed. - #3720 - #3705 - #3708 - #3727 ### Failure ``` ________________________________ test_get_users ________________________________ app = <jupyterhub.tests.mocking.MockHub object at 0x7f9a3c845f60> @mark.user @mark.role async def test_get_users(app): db = app.db r = await api_request(app, 'users', headers=auth_header(db, 'admin')) assert r.status_code == 200 users = sorted(r.json(), key=lambda d: d['name']) users = [normalize_user(u) for u in users] user_model = { 'name': 'user', 'admin': False, 'roles': ['user'], 'auth_state': None, } > assert users == [ fill_user( {'name': 'admin', 'admin': True, 'roles': ['admin'], 'auth_state': None} ), fill_user(user_model), ] E AssertionError: assert [{'admin': Tr...ps': [], ...}] == [{'admin': Tr...ps': [], ...}] E At index 0 diff: {'server': None, 'admin': True, 'created': '0000-00-00T00:00:00Z', 'groups': [], 'auth_state': None, 'roles': ['admin', 'user'], 'last_activity': '0000-00-00T00:00:00Z', 'pending': None, 'kind': 'user', 'name': 'admin', 'servers': {}} != {'name': 'admin', 'admin': True, 'roles': ['admin'], 'auth_state': None, 'server': None, 'kind': 'user', 'groups': [], 'pending': None, 'created': '0000-00-00T00:00:00Z', 'last_activity': '0000-00-00T00:00:00Z', 'servers': {}} E Full diff: E [ E {'admin': True, E 'auth_state': None, E 'created': '0000-00-00T00:00:00Z', E 'groups': [], E 'kind': 'user', E 'last_activity': '0000-00-00T00:00:00Z', E 'name': 'admin', E 'pending': None, E - 'roles': ['admin'], E + 'roles': ['admin', 'user'], E ? ++++++++ E 'server': None, E 'servers': {}}, E {'admin': False, E 'auth_state': None, E 'created': '0000-00-00T00:00:00Z', E 'groups': [], E 'kind': 'user', E 'last_activity': '0000-00-00T00:00:00Z', E 'name': 'user', E 'pending': None, E 'roles': ['user'], E 'server': None, E 'servers': {}}, E ] jupyterhub/tests/test_api.py:241: AssertionError ```
Ping @manics btw who experienced a test failure in unrelated #3733.
2021-12-22T09:08:26Z
[]
[]
jupyterhub/jupyterhub
3,757
jupyterhub__jupyterhub-3757
[ "3737" ]
a2ba55756d036e8007830fbb4b67665d2b30692c
diff --git a/jupyterhub/apihandlers/auth.py b/jupyterhub/apihandlers/auth.py --- a/jupyterhub/apihandlers/auth.py +++ b/jupyterhub/apihandlers/auth.py @@ -16,6 +16,7 @@ from .. import orm from .. import roles from .. import scopes +from ..utils import get_browser_protocol from ..utils import token_authenticated from .base import APIHandler from .base import BaseHandler @@ -115,7 +116,10 @@ def make_absolute_redirect_uri(self, uri): # make absolute local redirects full URLs # to satisfy oauthlib's absolute URI requirement redirect_uri = ( - self.request.protocol + "://" + self.request.headers['Host'] + redirect_uri + get_browser_protocol(self.request) + + "://" + + self.request.host + + redirect_uri ) parsed_url = urlparse(uri) query_list = parse_qsl(parsed_url.query, keep_blank_values=True) diff --git a/jupyterhub/apihandlers/base.py b/jupyterhub/apihandlers/base.py --- a/jupyterhub/apihandlers/base.py +++ b/jupyterhub/apihandlers/base.py @@ -14,6 +14,7 @@ from .. import orm from ..handlers import BaseHandler +from ..utils import get_browser_protocol from ..utils import isoformat from ..utils import url_path_join @@ -60,6 +61,8 @@ def check_referer(self): """ host_header = self.app.forwarded_host_header or "Host" host = self.request.headers.get(host_header) + if host and "," in host: + host = host.split(",", 1)[0].strip() referer = self.request.headers.get("Referer") # If no header is provided, assume it comes from a script/curl. @@ -71,7 +74,8 @@ def check_referer(self): self.log.warning("Blocking API request with no referer") return False - proto = self.request.protocol + proto = get_browser_protocol(self.request) + full_host = f"{proto}://{host}{self.hub.base_url}" host_url = urlparse(full_host) referer_url = urlparse(referer) diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -49,6 +49,7 @@ from ..user import User from ..utils import AnyTimeoutError from ..utils import get_accepted_mimetype +from ..utils import get_browser_protocol from ..utils import maybe_future from ..utils import url_path_join @@ -632,12 +633,10 @@ def get_next_url(self, user=None, default=None): next_url = self.get_argument('next', default='') # protect against some browsers' buggy handling of backslash as slash next_url = next_url.replace('\\', '%5C') - if (next_url + '/').startswith( - ( - f'{self.request.protocol}://{self.request.host}/', - f'//{self.request.host}/', - ) - ) or ( + proto = get_browser_protocol(self.request) + host = self.request.host + + if (next_url + '/').startswith((f'{proto}://{host}/', f'//{host}/',)) or ( self.subdomain_host and urlparse(next_url).netloc and ("." + urlparse(next_url).netloc).endswith( diff --git a/jupyterhub/services/auth.py b/jupyterhub/services/auth.py --- a/jupyterhub/services/auth.py +++ b/jupyterhub/services/auth.py @@ -53,6 +53,7 @@ from traitlets.config import SingletonConfigurable from ..scopes import _intersect_expanded_scopes +from ..utils import get_browser_protocol from ..utils import url_path_join @@ -772,7 +773,7 @@ def set_state_cookie(self, handler, next_url=None): # OAuth that doesn't complete shouldn't linger too long. 'max_age': 600, } - if handler.request.protocol == 'https': + if get_browser_protocol(handler.request) == 'https': kwargs['secure'] = True # load user cookie overrides kwargs.update(self.cookie_options) @@ -812,7 +813,7 @@ def get_state_cookie_name(self, b64_state=''): def set_cookie(self, handler, access_token): """Set a cookie recording OAuth result""" kwargs = {'path': self.base_url, 'httponly': True} - if handler.request.protocol == 'https': + if get_browser_protocol(handler.request) == 'https': kwargs['secure'] = True # load user cookie overrides kwargs.update(self.cookie_options) diff --git a/jupyterhub/utils.py b/jupyterhub/utils.py --- a/jupyterhub/utils.py +++ b/jupyterhub/utils.py @@ -683,3 +683,44 @@ async def catching(self, *args, **kwargs): return r return catching + + +def get_browser_protocol(request): + """Get the _protocol_ seen by the browser + + Like tornado's _apply_xheaders, + but in the case of multiple proxy hops, + use the outermost value (what the browser likely sees) + instead of the innermost value, + which is the most trustworthy. + + We care about what the browser sees, + not where the request actually came from, + so trusting possible spoofs is the right thing to do. + """ + headers = request.headers + # first choice: Forwarded header + forwarded_header = headers.get("Forwarded") + if forwarded_header: + first_forwarded = forwarded_header.split(",", 1)[0].strip() + fields = {} + forwarded_dict = {} + for field in first_forwarded.split(";"): + key, _, value = field.partition("=") + fields[key.strip().lower()] = value.strip() + if "proto" in fields and fields["proto"].lower() in {"http", "https"}: + return fields["proto"].lower() + else: + app_log.warning( + f"Forwarded header present without protocol: {forwarded_header}" + ) + + # second choice: X-Scheme or X-Forwarded-Proto + proto_header = headers.get("X-Scheme", headers.get("X-Forwarded-Proto", None)) + if proto_header: + proto_header = proto_header.split(",")[0].strip().lower() + if proto_header in {"http", "https"}: + return proto_header + + # no forwarded headers + return request.protocol
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -118,16 +118,39 @@ async def test_post_content_type(app, content_type, status): ("fake.example", {"netloc": "fake.example", "scheme": "https"}, {}, 403), # explicit ports, match ("fake.example:81", {"netloc": "fake.example:81"}, {}, 200), - # Test proxy defined headers taken into account by xheaders=True in - # https://github.com/jupyterhub/jupyterhub/blob/2.0.1/jupyterhub/app.py#L3065 + # Test proxy protocol defined headers taken into account by utils.get_browser_protocol ( "fake.example", {"netloc": "fake.example", "scheme": "https"}, - # note {"X-Forwarded-Proto": "https"} does not work {'X-Scheme': 'https'}, 200, ), + ( + "fake.example", + {"netloc": "fake.example", "scheme": "https"}, + {'X-Forwarded-Proto': 'https'}, + 200, + ), + ( + "fake.example", + {"netloc": "fake.example", "scheme": "https"}, + { + 'Forwarded': 'host=fake.example;proto=https,for=1.2.34;proto=http', + 'X-Scheme': 'http', + }, + 200, + ), + ( + "fake.example", + {"netloc": "fake.example", "scheme": "https"}, + { + 'Forwarded': 'host=fake.example;proto=http,for=1.2.34;proto=http', + 'X-Scheme': 'https', + }, + 403, + ), ("fake.example", {"netloc": "fake.example"}, {'X-Scheme': 'https'}, 403), + ("fake.example", {"netloc": "fake.example"}, {'X-Scheme': 'https, http'}, 403), ], ) async def test_cors_check(request, app, host, referer, extraheaders, status): diff --git a/jupyterhub/tests/test_utils.py b/jupyterhub/tests/test_utils.py --- a/jupyterhub/tests/test_utils.py +++ b/jupyterhub/tests/test_utils.py @@ -2,12 +2,16 @@ import asyncio import time from concurrent.futures import ThreadPoolExecutor +from unittest.mock import Mock import pytest from async_generator import aclosing from tornado import gen from tornado.concurrent import run_on_executor +from tornado.httpserver import HTTPRequest +from tornado.httputil import HTTPHeaders +from .. import utils from ..utils import iterate_until @@ -88,3 +92,33 @@ async def test_tornado_coroutines(): # verify that tornado gen and executor methods return awaitables assert (await t.on_executor()) == "executor" assert (await t.tornado_coroutine()) == "gen.coroutine" + + [email protected]( + "forwarded, x_scheme, x_forwarded_proto, expected", + [ + ("", "", "", "_attr_"), + ("for=1.2.3.4", "", "", "_attr_"), + ("for=1.2.3.4,proto=https", "", "", "_attr_"), + ("", "https", "http", "https"), + ("", "https, http", "", "https"), + ("", "https, http", "http", "https"), + ("proto=http ; for=1.2.3.4, proto=https", "https, http", "", "http"), + ("proto=invalid;for=1.2.3.4,proto=http", "https, http", "", "https"), + ("for=1.2.3.4,proto=http", "https, http", "", "https"), + ("", "invalid, http", "", "_attr_"), + ], +) +def test_browser_protocol(x_scheme, x_forwarded_proto, forwarded, expected): + request = Mock(spec=HTTPRequest) + request.protocol = "_attr_" + request.headers = HTTPHeaders() + if x_scheme: + request.headers["X-Scheme"] = x_scheme + if x_forwarded_proto: + request.headers["X-Forwarded-Proto"] = x_forwarded_proto + if forwarded: + request.headers["Forwarded"] = forwarded + + proto = utils.get_browser_protocol(request) + assert proto == expected
Empty Admin page when the hub is behind nginx proxy <!-- Thank you for contributing. These HTML comments will not render in the issue, but you can delete them once you've read them if you prefer! --> ### Bug description <!-- Use this section to clearly and concisely describe the bug. --> Merry Christmas! The Admin settings of jupyterhub v. 2.0.1 are not shown if the hub is behind a reverse nginx proxy. The symptoms appear to be similar to #3711 except that they are now not caused by `base_url`. #### Expected behaviour <!-- Tell us what you thought would happen. --> Admin page when the hub is accessed directly: <img width="684" alt="Screenshot 2021-12-25 at 09 32 58" src="https://user-images.githubusercontent.com/2140361/147381008-67c6e49d-a583-47d0-aab2-bc1246976b1e.png"> #### Actual behaviour <!-- Tell us what actually happens. --> Admin page when the hub is accessed through a proxy: <img width="683" alt="Screenshot 2021-12-25 at 09 34 48" src="https://user-images.githubusercontent.com/2140361/147381033-be241b38-db3f-410c-a439-2d4eb3f71f33.png"> This message looks suspicious (see the full log below): ``` jupyterhub_1 | [W 2021-12-25 08:58:25.156 JupyterHub base:89] Blocking Cross Origin API request. Referer: http://127.0.0.1:8080/hub/admin, Host: 127.0.0.1, Host URL: http://127.0.0.1/hub/ ``` There is no problem with `jupyterhub/jupyterhub:1.5.0` ### How to reproduce <!-- Use this section to describe the steps that a user would take to experience this bug. --> 1. Ensure the following directory structure: ``` . ├── docker-compose.yml ├── jupyterhub │ ├── Dockerfile │ └── jupyterhub_config.py └── nginx ├── Dockerfile └── nginx.conf ``` 2. Ensure the following file contents: - `docker-compose.yml`: ``` version: '3' services: nginx: image: nginx build: nginx ports: - 8080:80 jupyterhub: image: jupyterhub build: jupyterhub expose: - "8000" ``` - `jupyterhub/Dockerfile`: ``` FROM jupyterhub/jupyterhub:2.0.1 COPY jupyterhub_config.py /etc/jupyterhub/ CMD jupyterhub -f /etc/jupyterhub/jupyterhub_config.py --debug ``` - `jupyterhub/jupyterhub_config.py`: ``` c.Authenticator.admin_users = {'user'} c.JupyterHub.authenticator_class = 'dummy' ``` - `nginx/Dockerfile`: ``` FROM nginx:1.21.4 COPY nginx.conf /etc/nginx/ ``` - `nginx/nginx.conf` ([as documented](https://jupyterhub.readthedocs.io/en/stable/reference/config-proxy.html#nginx) but without ssl): ``` events {} http { server { listen 0.0.0.0:80; server_name localhost; location / { proxy_pass http://jupyterhub:8000/; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # websocket headers proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection upgrade; proxy_set_header X-Scheme $scheme; proxy_buffering off; } real_ip_header proxy_protocol; set_real_ip_from 127.0.0.1; } } ``` 3. Build containers: `docker-compose build` 4. Start the containers: `docker-compose up` 5. Visit the page: http://127.0.0.1:8080/hub/admin 6. Enter the user name `user` ### Your personal set up <!-- Tell us a little about the system you're using. Please include information about how you installed, e.g. are you using a distribution such as zero-to-jupyterhub or the-littlest-jupyterhub. --> - OS: MacOS 12.1 - Version(s): ``` % docker --version Docker version 20.10.11, build dea9396 % docker-compose --version Docker Compose version v2.2.1 ``` <details><summary>Logs</summary> - docker-compose: ``` % docker-compose up [+] Running 2/0 ⠿ Container jupyterhub-test1_jupyterhub_1 Created 0.0s ⠿ Container jupyterhub-test1_nginx_1 Created 0.0s Attaching to jupyterhub_1, nginx_1 nginx_1 | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration nginx_1 | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ nginx_1 | /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh nginx_1 | 10-listen-on-ipv6-by-default.sh: info: IPv6 listen already enabled nginx_1 | /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh nginx_1 | /docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh nginx_1 | /docker-entrypoint.sh: Configuration complete; ready for start up jupyterhub_1 | [D 2021-12-25 08:58:14.902 JupyterHub application:731] Looking for /etc/jupyterhub/jupyterhub_config in /srv/jupyterhub jupyterhub_1 | [D 2021-12-25 08:58:14.902 JupyterHub application:753] Loaded config file: /etc/jupyterhub/jupyterhub_config.py jupyterhub_1 | [I 2021-12-25 08:58:14.912 JupyterHub app:2766] Running JupyterHub version 2.0.1 jupyterhub_1 | [I 2021-12-25 08:58:14.912 JupyterHub app:2796] Using Authenticator: jupyterhub.auth.DummyAuthenticator-2.0.1 jupyterhub_1 | [I 2021-12-25 08:58:14.912 JupyterHub app:2796] Using Spawner: jupyterhub.spawner.LocalProcessSpawner-2.0.1 jupyterhub_1 | [I 2021-12-25 08:58:14.912 JupyterHub app:2796] Using Proxy: jupyterhub.proxy.ConfigurableHTTPProxy-2.0.1 jupyterhub_1 | [I 2021-12-25 08:58:14.924 JupyterHub app:1606] Loading cookie_secret from /srv/jupyterhub/jupyterhub_cookie_secret jupyterhub_1 | [D 2021-12-25 08:58:14.930 JupyterHub app:1773] Connecting to db: sqlite:///jupyterhub.sqlite jupyterhub_1 | [D 2021-12-25 08:58:14.959 JupyterHub orm:955] database schema version found: 833da8570507 jupyterhub_1 | [I 2021-12-25 08:58:15.017 JupyterHub proxy:496] Generating new CONFIGPROXY_AUTH_TOKEN jupyterhub_1 | [D 2021-12-25 08:58:15.017 JupyterHub app:2019] Loading roles into database jupyterhub_1 | [I 2021-12-25 08:58:15.035 JupyterHub app:1924] Not using allowed_users. Any authenticated user will be allowed. jupyterhub_1 | [D 2021-12-25 08:58:15.042 JupyterHub app:2278] Purging expired APITokens jupyterhub_1 | [D 2021-12-25 08:58:15.047 JupyterHub app:2278] Purging expired OAuthCodes jupyterhub_1 | [D 2021-12-25 08:58:15.053 JupyterHub app:2111] Loading role assignments from config jupyterhub_1 | [D 2021-12-25 08:58:15.076 JupyterHub app:2424] Initializing spawners jupyterhub_1 | [D 2021-12-25 08:58:15.080 JupyterHub app:2555] Loaded users: jupyterhub_1 | jupyterhub_1 | [I 2021-12-25 08:58:15.081 JupyterHub app:2835] Initialized 0 spawners in 0.006 seconds jupyterhub_1 | [W 2021-12-25 08:58:15.087 JupyterHub proxy:565] Found proxy pid file: /srv/jupyterhub/jupyterhub-proxy.pid jupyterhub_1 | [W 2021-12-25 08:58:15.088 JupyterHub proxy:577] Proxy no longer running at pid=12 jupyterhub_1 | [D 2021-12-25 08:58:15.088 JupyterHub proxy:618] Removing proxy pid file jupyterhub-proxy.pid jupyterhub_1 | [W 2021-12-25 08:58:15.090 JupyterHub proxy:687] Running JupyterHub without SSL. I hope there is SSL termination happening somewhere else... jupyterhub_1 | [I 2021-12-25 08:58:15.090 JupyterHub proxy:691] Starting proxy @ http://:8000 jupyterhub_1 | [D 2021-12-25 08:58:15.090 JupyterHub proxy:692] Proxy cmd: ['configurable-http-proxy', '--ip', '', '--port', '8000', '--api-ip', '127.0.0.1', '--api-port', '8001', '--error-target', 'http://127.0.0.1:8081/hub/error'] jupyterhub_1 | [D 2021-12-25 08:58:15.098 JupyterHub proxy:610] Writing proxy pid file: jupyterhub-proxy.pid jupyterhub_1 | 08:58:16.203 [ConfigProxy] info: Proxying http://*:8000 to (no default) jupyterhub_1 | 08:58:16.210 [ConfigProxy] info: Proxy API at http://127.0.0.1:8001/api/routes jupyterhub_1 | [D 2021-12-25 08:58:16.219 JupyterHub proxy:728] Proxy started and appears to be up jupyterhub_1 | [D 2021-12-25 08:58:16.221 JupyterHub proxy:821] Proxy: Fetching GET http://127.0.0.1:8001/api/routes jupyterhub_1 | 08:58:16.244 [ConfigProxy] info: 200 GET /api/routes jupyterhub_1 | [I 2021-12-25 08:58:16.251 JupyterHub app:3084] Hub API listening on http://127.0.0.1:8081/hub/ jupyterhub_1 | [D 2021-12-25 08:58:16.252 JupyterHub proxy:343] Fetching routes to check jupyterhub_1 | [D 2021-12-25 08:58:16.252 JupyterHub proxy:821] Proxy: Fetching GET http://127.0.0.1:8001/api/routes jupyterhub_1 | 08:58:16.265 [ConfigProxy] info: 200 GET /api/routes jupyterhub_1 | [D 2021-12-25 08:58:16.271 JupyterHub proxy:346] Checking routes jupyterhub_1 | [I 2021-12-25 08:58:16.273 JupyterHub proxy:431] Adding route for Hub: / => http://127.0.0.1:8081 jupyterhub_1 | [D 2021-12-25 08:58:16.276 JupyterHub proxy:821] Proxy: Fetching POST http://127.0.0.1:8001/api/routes/ jupyterhub_1 | 08:58:16.282 [ConfigProxy] info: Adding route / -> http://127.0.0.1:8081 jupyterhub_1 | 08:58:16.287 [ConfigProxy] info: Route added / -> http://127.0.0.1:8081 jupyterhub_1 | 08:58:16.290 [ConfigProxy] info: 201 POST /api/routes/ jupyterhub_1 | [I 2021-12-25 08:58:16.293 JupyterHub app:3150] JupyterHub is now running at http://:8000 jupyterhub_1 | [D 2021-12-25 08:58:16.296 JupyterHub app:2759] It took 1.401 seconds for the Hub to start jupyterhub_1 | [I 2021-12-25 08:58:17.444 JupyterHub log:189] 302 GET /hub/admin -> /hub/login?next=%2Fhub%2Fadmin (@172.20.0.1) 1.23ms nginx_1 | 172.20.0.1 - - [25/Dec/2021:08:58:17 +0000] "GET /hub/admin HTTP/1.1" 302 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [I 2021-12-25 08:58:17.534 JupyterHub log:189] 200 GET /hub/login?next=%2Fhub%2Fadmin (@172.20.0.1) 43.03ms nginx_1 | 172.20.0.1 - - [25/Dec/2021:08:58:17 +0000] "GET /hub/login?next=%2Fhub%2Fadmin HTTP/1.1" 200 5473 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [D 2021-12-25 08:58:17.563 JupyterHub log:189] 304 GET /hub/static/js/admin-react.js (@172.20.0.1) 1.67ms nginx_1 | 172.20.0.1 - - [25/Dec/2021:08:58:17 +0000] "GET /hub/static/js/admin-react.js HTTP/1.1" 304 0 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [D 2021-12-25 08:58:24.862 JupyterHub roles:449] Assigning default role to User user jupyterhub_1 | [D 2021-12-25 08:58:24.875 JupyterHub base:557] Setting cookie jupyterhub-session-id: {'httponly': True, 'path': '/'} jupyterhub_1 | [D 2021-12-25 08:58:24.876 JupyterHub base:561] Setting cookie for user: jupyterhub-hub-login jupyterhub_1 | [D 2021-12-25 08:58:24.877 JupyterHub base:557] Setting cookie jupyterhub-hub-login: {'httponly': True, 'path': '/hub/'} jupyterhub_1 | [I 2021-12-25 08:58:24.878 JupyterHub base:797] User logged in: user jupyterhub_1 | [I 2021-12-25 08:58:24.884 JupyterHub log:189] 302 POST /hub/login?next=%2Fhub%2Fadmin -> /hub/admin ([email protected]) 30.40ms nginx_1 | 172.20.0.1 - - [25/Dec/2021:08:58:24 +0000] "POST /hub/login?next=%2Fhub%2Fadmin HTTP/1.1" 302 0 "http://127.0.0.1:8080/hub/login?next=%2Fhub%2Fadmin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [D 2021-12-25 08:58:24.937 JupyterHub scopes:488] Checking access via scope admin:users jupyterhub_1 | [D 2021-12-25 08:58:24.937 JupyterHub scopes:386] Unrestricted access to /hub/admin via admin:users jupyterhub_1 | [D 2021-12-25 08:58:24.937 JupyterHub scopes:488] Checking access via scope admin:servers jupyterhub_1 | [D 2021-12-25 08:58:24.938 JupyterHub scopes:386] Unrestricted access to /hub/admin via admin:servers jupyterhub_1 | [D 2021-12-25 08:58:24.954 JupyterHub user:347] Creating <class 'jupyterhub.spawner.LocalProcessSpawner'> for user: jupyterhub_1 | [I 2021-12-25 08:58:24.963 JupyterHub log:189] 200 GET /hub/admin ([email protected]) 48.74ms nginx_1 | 172.20.0.1 - - [25/Dec/2021:08:58:24 +0000] "GET /hub/admin HTTP/1.1" 200 5162 "http://127.0.0.1:8080/hub/login?next=%2Fhub%2Fadmin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" nginx_1 | 172.20.0.1 - - [25/Dec/2021:08:58:25 +0000] "GET /logo HTTP/1.1" 302 0 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [I 2021-12-25 08:58:25.021 JupyterHub log:189] 302 GET /logo -> /hub/logo (@172.20.0.1) 3.75ms nginx_1 | 172.20.0.1 - - [25/Dec/2021:08:58:25 +0000] "GET /hub/static/js/admin-react.js HTTP/1.1" 304 0 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [D 2021-12-25 08:58:25.062 JupyterHub log:189] 304 GET /hub/static/js/admin-react.js (@172.20.0.1) 2.92ms jupyterhub_1 | [D 2021-12-25 08:58:25.079 JupyterHub log:189] 200 GET /hub/logo (@172.20.0.1) 3.64ms nginx_1 | 172.20.0.1 - - [25/Dec/2021:08:58:25 +0000] "GET /hub/logo HTTP/1.1" 200 11453 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [D 2021-12-25 08:58:25.142 JupyterHub log:189] 200 GET /hub/static/js/admin.js?v=20211225085815 (@172.20.0.1) 4.37ms nginx_1 | 172.20.0.1 - - [25/Dec/2021:08:58:25 +0000] "GET /hub/static/js/admin.js?v=20211225085815 HTTP/1.1" 200 8013 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [W 2021-12-25 08:58:25.156 JupyterHub base:89] Blocking Cross Origin API request. Referer: http://127.0.0.1:8080/hub/admin, Host: 127.0.0.1, Host URL: http://127.0.0.1/hub/ jupyterhub_1 | [D 2021-12-25 08:58:25.165 JupyterHub scopes:488] Checking access via scope list:groups jupyterhub_1 | [D 2021-12-25 08:58:25.168 JupyterHub scopes:383] No access to /hub/api/groups via list:groups jupyterhub_1 | [W 2021-12-25 08:58:25.169 JupyterHub scopes:496] Not authorizing access to /hub/api/groups. Requires any of [list:groups], not derived from scopes [] jupyterhub_1 | [W 2021-12-25 08:58:25.177 JupyterHub web:1787] 403 GET /hub/api/groups?offset=0&limit=50 (172.20.0.1): Action is not authorized with current scopes; requires any of [list:groups] jupyterhub_1 | [W 2021-12-25 08:58:25.184 JupyterHub log:189] 403 GET /hub/api/groups?offset=0&limit=50 (@172.20.0.1) 40.88ms jupyterhub_1 | [W 2021-12-25 08:58:25.190 JupyterHub base:89] Blocking Cross Origin API request. Referer: http://127.0.0.1:8080/hub/admin, Host: 127.0.0.1, Host URL: http://127.0.0.1/hub/ jupyterhub_1 | [D 2021-12-25 08:58:25.190 JupyterHub scopes:488] Checking access via scope list:users jupyterhub_1 | [D 2021-12-25 08:58:25.190 JupyterHub scopes:383] No access to /hub/api/users via list:users jupyterhub_1 | [W 2021-12-25 08:58:25.191 JupyterHub scopes:496] Not authorizing access to /hub/api/users. Requires any of [list:users], not derived from scopes [] jupyterhub_1 | [W 2021-12-25 08:58:25.191 JupyterHub web:1787] 403 GET /hub/api/users?offset=0&limit=50 (172.20.0.1): Action is not authorized with current scopes; requires any of [list:users] jupyterhub_1 | [W 2021-12-25 08:58:25.192 JupyterHub log:189] 403 GET /hub/api/users?offset=0&limit=50 (@172.20.0.1) 43.34ms nginx_1 | 172.20.0.1 - - [25/Dec/2021:08:58:25 +0000] "GET /hub/api/groups?offset=0&limit=50 HTTP/1.1" 403 105 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" nginx_1 | 172.20.0.1 - - [25/Dec/2021:08:58:25 +0000] "GET /hub/api/users?offset=0&limit=50 HTTP/1.1" 403 104 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [D 2021-12-25 08:58:25.227 JupyterHub log:189] 200 GET /hub/static/js/jhapi.js?v=20211225085815 (@172.20.0.1) 2.09ms nginx_1 | 172.20.0.1 - - [25/Dec/2021:08:58:25 +0000] "GET /hub/static/js/jhapi.js?v=20211225085815 HTTP/1.1" 200 4446 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [D 2021-12-25 08:58:25.236 JupyterHub log:189] 200 GET /hub/static/components/moment/moment.js?v=20211225085815 (@172.20.0.1) 10.13ms jupyterhub_1 | [D 2021-12-25 08:58:25.243 JupyterHub log:189] 200 GET /hub/static/js/utils.js?v=20211225085815 (@172.20.0.1) 17.01ms nginx_1 | 172.20.0.1 - - [25/Dec/2021:08:58:25 +0000] "GET /hub/static/components/moment/moment.js?v=20211225085815 HTTP/1.1" 200 173902 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" nginx_1 | 172.20.0.1 - - [25/Dec/2021:08:58:25 +0000] "GET /hub/static/js/utils.js?v=20211225085815 HTTP/1.1" 200 4383 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" ``` - Errors in the browser console (Safari 15.2): ``` [Error] Failed to load resource: the server responded with a status of 403 (Forbidden) (users, line 0) [Error] Failed to load resource: the server responded with a status of 403 (Forbidden) (groups, line 0) [Error] TypeError: undefined is not a function (near '...u.map...') — admin-react.js:2:28870 ri (admin-react.js:2:146088) (anonymous function) (admin-react.js:2:148187) co (admin-react.js:2:112238) si (admin-react.js:2:149923) Cu (admin-react.js:2:166325) Cu (anonymous function) (admin-react.js:2:194357) xu (admin-react.js:2:163064) du (admin-react.js:2:159263) du (anonymous function) (admin-react.js:2:108745) (anonymous function) (admin-react.js:2:194357) Va (admin-react.js:2:108691) Ha (admin-react.js:2:108626) pu (admin-react.js:2:159359) notify (admin-react.js:2:919) (anonymous function) (admin-react.js:2:494) (anonymous function) (admin-react.js:2:569) (anonymous function) p (admin-react.js:2:52697) promiseReactionJob ``` </details>
I am experiencing the same issue here. Also note that this looks like a regression in 2.0.1. 2.0.0 appears to be working just fine. Related comment: https://github.com/jupyterhub/jupyterhub/pull/3701#issuecomment-1002750092 I think there might be two related problems. ## Proxied https Following up from https://github.com/jupyterhub/jupyterhub/pull/3701#issuecomment-1003421641 https://github.com/jupyterhub/jupyterhub/blob/345805781f39b203dd135b65ad60890eaf155c1d/jupyterhub/app.py#L3065 but the Tornado docs are unclear. https://www.tornadoweb.org/en/stable/httpserver.html#http-server says `X-Real-Ip`/`X-Forwarded-For` and `X-Scheme`/`X-Forwarded-Proto` are supported but https://www.tornadoweb.org/en/stable/httputil.html#tornado.httputil.HTTPServerRequest.protocol suggests that only `X-Scheme` is used. I don't know which docs apply to JupyterHub in https://github.com/jupyterhub/jupyterhub/blob/345805781f39b203dd135b65ad60890eaf155c1d/jupyterhub/apihandlers/base.py#L74 ## Nginx host port [Nginx `$host` doesn't include the port number](https://stackoverflow.com/questions/15414810/whats-the-difference-of-host-and-http-host-in-nginx/15414811#15414811 ) so the Tornado docs suggest `proxy_set_header Host $http_host`: https://www.tornadoweb.org/en/stable/guide/running.html?highlight=x-scheme%20xheaders#running-behind-a-load-balancer which means the JupyterHub docs should be updated https://jupyterhub.readthedocs.io/en/stable/reference/config-proxy.html#nginx @jakob-keller > Also note that this looks like a regression in 2.0.1. 2.0.0 appears to be working just fine. I cannot confirm this. The same problem also happens if I use `jupyterhub/jupyterhub:2.0.0` in Dockerfile: <img width="574" alt="Screenshot 2022-01-01 at 20 00 36" src="https://user-images.githubusercontent.com/2140361/147858118-8d476409-4d37-45fb-bbc0-0ce870170cb5.png"> Although this time there appear to be no cross origin warninings (see the log below). So it could be that there are several (possibly unrelated) problems. <details> <summary>Log</summary> ``` % docker-compose up [+] Running 3/3 ⠿ Network jupyterhub-test1_default Created 0.1s ⠿ Container jupyterhub-test1_jupyterhub_1 Created 0.2s ⠿ Container jupyterhub-test1_nginx_1 Created 0.2s Attaching to jupyterhub_1, nginx_1 nginx_1 | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration nginx_1 | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ nginx_1 | /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh nginx_1 | 10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf nginx_1 | 10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf nginx_1 | /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh nginx_1 | /docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh nginx_1 | /docker-entrypoint.sh: Configuration complete; ready for start up jupyterhub_1 | [D 2022-01-01 18:54:35.117 JupyterHub application:731] Looking for /etc/jupyterhub/jupyterhub_config in /srv/jupyterhub jupyterhub_1 | [D 2022-01-01 18:54:35.118 JupyterHub application:753] Loaded config file: /etc/jupyterhub/jupyterhub_config.py jupyterhub_1 | [I 2022-01-01 18:54:35.127 JupyterHub app:2717] Running JupyterHub version 2.0.0 jupyterhub_1 | [I 2022-01-01 18:54:35.127 JupyterHub app:2747] Using Authenticator: jupyterhub.auth.DummyAuthenticator-2.0.0 jupyterhub_1 | [I 2022-01-01 18:54:35.127 JupyterHub app:2747] Using Spawner: jupyterhub.spawner.LocalProcessSpawner-2.0.0 jupyterhub_1 | [I 2022-01-01 18:54:35.127 JupyterHub app:2747] Using Proxy: jupyterhub.proxy.ConfigurableHTTPProxy-2.0.0 jupyterhub_1 | [D 2022-01-01 18:54:35.525 JupyterHub app:1636] Generating new cookie_secret jupyterhub_1 | [I 2022-01-01 18:54:35.526 JupyterHub app:1641] Writing cookie_secret to /srv/jupyterhub/jupyterhub_cookie_secret jupyterhub_1 | [D 2022-01-01 18:54:35.528 JupyterHub app:1763] Connecting to db: sqlite:///jupyterhub.sqlite jupyterhub_1 | [D 2022-01-01 18:54:35.615 JupyterHub orm:924] Stamping empty database with alembic revision 833da8570507 jupyterhub_1 | [I 2022-01-01 18:54:35.630 alembic.runtime.migration migration:201] Context impl SQLiteImpl. jupyterhub_1 | [I 2022-01-01 18:54:35.631 alembic.runtime.migration migration:204] Will assume non-transactional DDL. jupyterhub_1 | [I 2022-01-01 18:54:35.654 alembic.runtime.migration migration:615] Running stamp_revision -> 833da8570507 jupyterhub_1 | [D 2022-01-01 18:54:35.654 alembic.runtime.migration migration:815] new branch insert 833da8570507 jupyterhub_1 | [I 2022-01-01 18:54:35.885 JupyterHub proxy:496] Generating new CONFIGPROXY_AUTH_TOKEN jupyterhub_1 | [D 2022-01-01 18:54:35.886 JupyterHub app:2007] Loading default roles to database jupyterhub_1 | [I 2022-01-01 18:54:35.950 JupyterHub app:1913] Not using allowed_users. Any authenticated user will be allowed. jupyterhub_1 | [D 2022-01-01 18:54:35.971 JupyterHub app:2229] Purging expired APITokens jupyterhub_1 | [D 2022-01-01 18:54:35.984 JupyterHub app:2229] Purging expired OAuthCodes jupyterhub_1 | [D 2022-01-01 18:54:35.988 JupyterHub app:2080] Loading predefined roles from config file to database jupyterhub_1 | [I 2022-01-01 18:54:36.018 JupyterHub roles:358] Adding role admin for User: user jupyterhub_1 | [W 2022-01-01 18:54:36.023 JupyterHub app:2152] No admin role found; assuming hub upgrade. Initializing default roles for all entities jupyterhub_1 | [D 2022-01-01 18:54:36.063 JupyterHub app:2375] Initializing spawners jupyterhub_1 | [D 2022-01-01 18:54:36.067 JupyterHub app:2506] Loaded users: jupyterhub_1 | jupyterhub_1 | [I 2022-01-01 18:54:36.068 JupyterHub app:2786] Initialized 0 spawners in 0.006 seconds jupyterhub_1 | [W 2022-01-01 18:54:36.075 JupyterHub proxy:687] Running JupyterHub without SSL. I hope there is SSL termination happening somewhere else... jupyterhub_1 | [I 2022-01-01 18:54:36.075 JupyterHub proxy:691] Starting proxy @ http://:8000 jupyterhub_1 | [D 2022-01-01 18:54:36.076 JupyterHub proxy:692] Proxy cmd: ['configurable-http-proxy', '--ip', '', '--port', '8000', '--api-ip', '127.0.0.1', '--api-port', '8001', '--error-target', 'http://127.0.0.1:8081/hub/error'] jupyterhub_1 | [D 2022-01-01 18:54:36.090 JupyterHub proxy:610] Writing proxy pid file: jupyterhub-proxy.pid jupyterhub_1 | 18:54:37.670 [ConfigProxy] info: Proxying http://*:8000 to (no default) jupyterhub_1 | 18:54:37.682 [ConfigProxy] info: Proxy API at http://127.0.0.1:8001/api/routes jupyterhub_1 | [D 2022-01-01 18:54:37.763 JupyterHub proxy:728] Proxy started and appears to be up jupyterhub_1 | [D 2022-01-01 18:54:37.770 JupyterHub proxy:821] Proxy: Fetching GET http://127.0.0.1:8001/api/routes jupyterhub_1 | [I 2022-01-01 18:54:37.820 JupyterHub app:3035] Hub API listening on http://127.0.0.1:8081/hub/ jupyterhub_1 | [D 2022-01-01 18:54:37.820 JupyterHub proxy:343] Fetching routes to check jupyterhub_1 | 18:54:37.820 [ConfigProxy] info: 200 GET /api/routes jupyterhub_1 | [D 2022-01-01 18:54:37.822 JupyterHub proxy:821] Proxy: Fetching GET http://127.0.0.1:8001/api/routes jupyterhub_1 | 18:54:37.831 [ConfigProxy] info: 200 GET /api/routes jupyterhub_1 | [D 2022-01-01 18:54:37.833 JupyterHub proxy:346] Checking routes jupyterhub_1 | [I 2022-01-01 18:54:37.834 JupyterHub proxy:431] Adding route for Hub: / => http://127.0.0.1:8081 jupyterhub_1 | [D 2022-01-01 18:54:37.838 JupyterHub proxy:821] Proxy: Fetching POST http://127.0.0.1:8001/api/routes/ jupyterhub_1 | 18:54:37.847 [ConfigProxy] info: Adding route / -> http://127.0.0.1:8081 jupyterhub_1 | 18:54:37.854 [ConfigProxy] info: Route added / -> http://127.0.0.1:8081 jupyterhub_1 | 18:54:37.858 [ConfigProxy] info: 201 POST /api/routes/ jupyterhub_1 | [I 2022-01-01 18:54:37.861 JupyterHub app:3101] JupyterHub is now running at http://:8000 jupyterhub_1 | [D 2022-01-01 18:54:37.863 JupyterHub app:2710] It took 2.766 seconds for the Hub to start jupyterhub_1 | [W 2022-01-01 18:54:48.353 JupyterHub base:391] Invalid or expired cookie token nginx_1 | 172.22.0.1 - - [01/Jan/2022:18:54:48 +0000] "GET /hub/admin HTTP/1.1" 302 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [I 2022-01-01 18:54:48.357 JupyterHub log:189] 302 GET /hub/admin -> /hub/login?next=%2Fhub%2Fadmin (@172.22.0.1) 5.06ms jupyterhub_1 | [I 2022-01-01 18:54:48.540 JupyterHub log:189] 200 GET /hub/login?next=%2Fhub%2Fadmin (@172.22.0.1) 127.20ms nginx_1 | 172.22.0.1 - - [01/Jan/2022:18:54:48 +0000] "GET /hub/login?next=%2Fhub%2Fadmin HTTP/1.1" 200 5473 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [D 2022-01-01 18:54:48.741 JupyterHub log:189] 304 GET /hub/logo (@172.22.0.1) 154.68ms nginx_1 | 172.22.0.1 - - [01/Jan/2022:18:54:48 +0000] "GET /hub/logo HTTP/1.1" 304 0 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" nginx_1 | 172.22.0.1 - - [01/Jan/2022:18:54:48 +0000] "GET /hub/logo HTTP/1.1" 304 0 "http://127.0.0.1:8080/hub/login?next=%2Fhub%2Fadmin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [D 2022-01-01 18:54:48.749 JupyterHub log:189] 304 GET /hub/logo (@172.22.0.1) 1.66ms jupyterhub_1 | [D 2022-01-01 18:54:51.651 JupyterHub base:561] Setting cookie for user: jupyterhub-hub-login jupyterhub_1 | [D 2022-01-01 18:54:51.651 JupyterHub base:557] Setting cookie jupyterhub-hub-login: {'httponly': True, 'path': '/hub/'} jupyterhub_1 | [I 2022-01-01 18:54:51.654 JupyterHub base:796] User logged in: user jupyterhub_1 | [I 2022-01-01 18:54:51.655 JupyterHub log:189] 302 POST /hub/login?next=%2Fhub%2Fadmin -> /hub/admin ([email protected]) 35.86ms nginx_1 | 172.22.0.1 - - [01/Jan/2022:18:54:51 +0000] "POST /hub/login?next=%2Fhub%2Fadmin HTTP/1.1" 302 0 "http://127.0.0.1:8080/hub/login?next=%2Fhub%2Fadmin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [D 2022-01-01 18:54:51.700 JupyterHub base:279] Recording first activity for <User(user 0/1 running)> jupyterhub_1 | [D 2022-01-01 18:54:51.753 JupyterHub scopes:488] Checking access via scope admin:users jupyterhub_1 | [D 2022-01-01 18:54:51.753 JupyterHub scopes:386] Unrestricted access to /hub/admin via admin:users jupyterhub_1 | [D 2022-01-01 18:54:51.753 JupyterHub scopes:488] Checking access via scope admin:servers jupyterhub_1 | [D 2022-01-01 18:54:51.754 JupyterHub scopes:386] Unrestricted access to /hub/admin via admin:servers jupyterhub_1 | [D 2022-01-01 18:54:51.781 JupyterHub user:347] Creating <class 'jupyterhub.spawner.LocalProcessSpawner'> for user: jupyterhub_1 | [I 2022-01-01 18:54:51.792 JupyterHub log:189] 200 GET /hub/admin ([email protected]) 96.21ms nginx_1 | 172.22.0.1 - - [01/Jan/2022:18:54:51 +0000] "GET /hub/admin HTTP/1.1" 200 5160 "http://127.0.0.1:8080/hub/login?next=%2Fhub%2Fadmin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [D 2022-01-01 18:54:51.944 JupyterHub log:189] 304 GET /hub/static/js/admin-react.js (@172.22.0.1) 5.83ms nginx_1 | 172.22.0.1 - - [01/Jan/2022:18:54:51 +0000] "GET /hub/static/js/admin-react.js HTTP/1.1" 304 0 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [D 2022-01-01 18:54:52.093 JupyterHub log:189] 200 GET /hub/static/js/admin.js?v=20220101185436 (@172.22.0.1) 4.35ms nginx_1 | 172.22.0.1 - - [01/Jan/2022:18:54:52 +0000] "GET /hub/static/js/admin.js?v=20220101185436 HTTP/1.1" 200 8013 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [W 2022-01-01 18:54:52.193 JupyterHub log:189] 404 GET /hub/undefinedhub/api/users?offset=0&limit=50 ([email protected]) 94.41ms nginx_1 | 172.22.0.1 - - [01/Jan/2022:18:54:52 +0000] "GET /hub/undefinedhub/api/users?offset=0&limit=50 HTTP/1.1" 404 5481 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [W 2022-01-01 18:54:52.220 JupyterHub log:189] 404 GET /hub/undefinedhub/api/groups?offset=0&limit=50 ([email protected]) 8.78ms nginx_1 | 172.22.0.1 - - [01/Jan/2022:18:54:52 +0000] "GET /hub/undefinedhub/api/groups?offset=0&limit=50 HTTP/1.1" 404 5481 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" jupyterhub_1 | [D 2022-01-01 18:54:52.246 JupyterHub log:189] 200 GET /hub/static/components/moment/moment.js?v=20220101185436 (@172.22.0.1) 32.91ms jupyterhub_1 | [D 2022-01-01 18:54:52.286 JupyterHub log:189] 200 GET /hub/static/js/jhapi.js?v=20220101185436 (@172.22.0.1) 71.16ms jupyterhub_1 | [D 2022-01-01 18:54:52.316 JupyterHub log:189] 200 GET /hub/static/js/utils.js?v=20220101185436 (@172.22.0.1) 100.85ms nginx_1 | 172.22.0.1 - - [01/Jan/2022:18:54:52 +0000] "GET /hub/static/components/moment/moment.js?v=20220101185436 HTTP/1.1" 200 173902 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" nginx_1 | 172.22.0.1 - - [01/Jan/2022:18:54:52 +0000] "GET /hub/static/js/jhapi.js?v=20220101185436 HTTP/1.1" 200 4446 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" nginx_1 | 172.22.0.1 - - [01/Jan/2022:18:54:52 +0000] "GET /hub/static/js/utils.js?v=20220101185436 HTTP/1.1" 200 4383 "http://127.0.0.1:8080/hub/admin" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15" ``` </details> @manics Thanks for the hint! Setting `proxy_set_header Host $http_host;` in nginx.conf indeed solves the problem! For proxying http behind https the recommended config gives me an error with lti authentifier: `401 : Unauthorized Invalid oauth_signature`: ``` D 2022-01-01 20:32:05.770 JupyterHub auth:143] Origin protocol is: http [D 2022-01-01 20:32:05.770 JupyterHub auth:147] Launch url is: http://my-host.org/hub/lti/launch [D 2022-01-01 20:32:05.772 JupyterHub validator:124] signature in request: FvP0C45EOUEFJ+oqOd9OrojGEAE= [D 2022-01-01 20:32:05.772 JupyterHub validator:125] calculated signature: du6SDCTpUUkNg84ZYm4bEgqXH8U= [W 2022-01-01 20:32:05.772 JupyterHub web:1787] 401 POST /hub/lti/launch (XX.XXX.XXX.XXX): Invalid oauth_signature [D 2022-01-01 20:32:05.772 JupyterHub base:1323] No template for 401 ``` (the host name and ip address have been redacted) I am not sure if it is related to the proxied https issue described above. The admin page in both cases seem to work fine (after changing `$host` to `$http_host`). After adding the following setting for ` X-Forwarded-Proto` this error disappears: ``` proxy_set_header X-Forwarded-Proto $scheme ``` In fact, after adding the `X-Forwarded-Proto` header, the proxy works even without the `X-Forwarded-For` header. I'm also experiencing this issue using **Traefik** as a reverse proxy. Unlike **Nginx** which can replace X-Forwarded-Proto, Traefik can only append. This line will return the last scheme (https://github.com/tornadoweb/tornado/pull/2162#discussion_r149954591) https://github.com/jupyterhub/jupyterhub/blob/46e7a231fe3ae2a6081fb7fcc6282d1cdf1cbad7/jupyterhub/apihandlers/base.py#L74 which is not correct because JupyterHub gets something like below: X-Real-Ip: {client_ip} X-Forwarded-Server: e08629887b62 X-Forwarded-Proto: https,http X-Forwarded-Port: 443,80 X-Forwarded-Host: {hub_domain} X-Forwarded-For": {client_ip}, {proxy_1_ip}, {proxy_2_ip} > I am experiencing the same issue here. To be more precise: I am seeing an empty admin page, but instead of proxying behind nginx, my setup consists of an AWS Application Load Balancer (for TLS termination, authentication etc.) that proxies to the containerized JupyterHub instance. AWS ALBs [automatically set relevant headers](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/x-forwarded-headers.html). The connection between client and ALB is https, whereas the connection between ALB and JupyterHub is http. > @jakob-keller > > > Also note that this looks like a regression in 2.0.1. 2.0.0 appears to be working just fine. > > I cannot confirm this. The same problem also happens if I use `jupyterhub/jupyterhub:2.0.0` in Dockerfile: > > <img alt="Screenshot 2022-01-01 at 20 00 36" width="574" src="https://user-images.githubusercontent.com/2140361/147858118-8d476409-4d37-45fb-bbc0-0ce870170cb5.png"> > > Although this time there appear to be no cross origin warninings (see the log below). So it could be that there are several (possibly unrelated) problems. > > Log I double-checked and in [my setup](https://github.com/jupyterhub/jupyterhub/issues/3737#issuecomment-1004801257), JupyterHub 2.0.0 works (after clearing browser caches!), whereas with 2.0.1 the admin page appears empty with the suspicious message being logged. @jakob-keller can you provide any logs? It could be a different issue. > @jakob-keller can you provide any logs? It could be a different issue. Sure, here are relevant log snippets: <details> <summary>JupyterHub 2.0.0</summary> ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | timestamp | message | |---------------|-----------------------------------------------------------------------------------------------------------------------------------------------| | 1641302415403 | [I 2022-01-04 13:20:15.403 JupyterHub app:2717] Running JupyterHub version 2.0.0 | | 1641302415403 | [I 2022-01-04 13:20:15.403 JupyterHub app:2747] Using Authenticator: my_custom_authenticator.ALBAuthenticator | | 1641302415403 | [I 2022-01-04 13:20:15.403 JupyterHub app:2747] Using Spawner: fargatespawner.fargatespawner.FargateSpawner | | 1641302415403 | [I 2022-01-04 13:20:15.403 JupyterHub app:2747] Using Proxy: jupyterhub.proxy.ConfigurableHTTPProxy-2.0.0 | | 1641302415405 | [I 2022-01-04 13:20:15.405 JupyterHub app:1592] Loading cookie_secret from env[JPY_COOKIE_SECRET] | | 1641302416723 | [I 2022-01-04 13:20:16.723 JupyterHub app:1913] Not using allowed_users. Any authenticated user will be allowed. | | 1641302417438 | [I 2022-01-04 13:20:17.438 JupyterHub app:2786] Initialized 0 spawners in 0.066 seconds | | 1641302417510 | [W 2022-01-04 13:20:17.510 JupyterHub proxy:687] Running JupyterHub without SSL. I hope there is SSL termination happening somewhere else... | | 1641302417510 | [I 2022-01-04 13:20:17.510 JupyterHub proxy:691] Starting proxy @ http://:8000 | | 1641302418500 | 13:20:18.422 [ConfigProxy] info: Proxying http://*:8000 to (no default) | | 1641302418501 | 13:20:18.501 [ConfigProxy] info: Proxy API at http://127.0.0.1:8001/api/routes | | 1641302418561 | 13:20:18.561 [ConfigProxy] info: 200 GET /api/routes | | 1641302418600 | [I 2022-01-04 13:20:18.600 JupyterHub app:3035] Hub API listening on http://*:8081/hub/ | | 1641302418600 | [I 2022-01-04 13:20:18.600 JupyterHub app:3037] Private Hub API connect url http://jupyter-hub.internal:8081/hub/ | | 1641302418603 | 13:20:18.603 [ConfigProxy] info: 200 GET /api/routes | | 1641302418604 | [I 2022-01-04 13:20:18.603 JupyterHub proxy:431] Adding route for Hub: / => http://jupyter-hub.internal:8081 | | 1641302418606 | 13:20:18.606 [ConfigProxy] info: Adding route / -> http://jupyter-hub.internal:8081 | | 1641302418607 | 13:20:18.607 [ConfigProxy] info: Route added / -> http://jupyter-hub.internal:8081 | | 1641302418607 | 13:20:18.607 [ConfigProxy] info: 201 POST /api/routes/ | | 1641302418608 | [I 2022-01-04 13:20:18.608 JupyterHub app:3101] JupyterHub is now running at http://:8000 | | 1641302498352 | [I 2022-01-04 13:21:38.352 JupyterHub log:189] 200 GET /hub/admin (jk@::ffff:10.100.2.225) 27.58ms | | 1641302498621 | [I 2022-01-04 13:21:38.621 JupyterHub log:189] 200 GET /hub/api/users?offset=0&limit=50 (jk@::ffff:10.100.2.225) 115.72ms | | 1641302498739 | [I 2022-01-04 13:21:38.739 JupyterHub log:189] 200 GET /hub/api/groups?offset=0&limit=50 (jk@::ffff:10.100.2.225) 233.14ms | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- </details> <details> <summary>JupyterHub 2.0.1</summary> --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | timestamp | message | |---------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | 1641302860083 | [I 2022-01-04 13:27:40.083 JupyterHub app:2766] Running JupyterHub version 2.0.1 | | 1641302860083 | [I 2022-01-04 13:27:40.083 JupyterHub app:2796] Using Authenticator: my_custom_authenticator.ALBAuthenticator | | 1641302860083 | [I 2022-01-04 13:27:40.083 JupyterHub app:2796] Using Spawner: fargatespawner.fargatespawner.FargateSpawner | | 1641302860084 | [I 2022-01-04 13:27:40.083 JupyterHub app:2796] Using Proxy: jupyterhub.proxy.ConfigurableHTTPProxy-2.0.1 | | 1641302860085 | [I 2022-01-04 13:27:40.085 JupyterHub app:1602] Loading cookie_secret from env[JPY_COOKIE_SECRET] | | 1641302861213 | [I 2022-01-04 13:27:41.212 JupyterHub app:1924] Not using allowed_users. Any authenticated user will be allowed. | | 1641302861662 | [I 2022-01-04 13:27:41.662 JupyterHub app:2835] Initialized 0 spawners in 0.060 seconds | | 1641302861727 | [W 2022-01-04 13:27:41.727 JupyterHub proxy:687] Running JupyterHub without SSL. I hope there is SSL termination happening somewhere else... | | 1641302861728 | [I 2022-01-04 13:27:41.727 JupyterHub proxy:691] Starting proxy @ http://:8000 | | 1641302862672 | 13:27:42.671 [ConfigProxy] info: Proxying http://*:8000 to (no default) | | 1641302862673 | 13:27:42.673 [ConfigProxy] info: Proxy API at http://127.0.0.1:8001/api/routes | | 1641302862776 | 13:27:42.776 [ConfigProxy] info: 200 GET /api/routes | | 1641302862777 | [I 2022-01-04 13:27:42.776 JupyterHub app:3084] Hub API listening on http://*:8081/hub/ | | 1641302862777 | [I 2022-01-04 13:27:42.777 JupyterHub app:3086] Private Hub API connect url http://jupyter-hub.internal:8081/hub/ | | 1641302862778 | 13:27:42.778 [ConfigProxy] info: 200 GET /api/routes | | 1641302862779 | [I 2022-01-04 13:27:42.779 JupyterHub proxy:431] Adding route for Hub: / => http://jupyter-hub.internal:8081 | | 1641302862781 | 13:27:42.781 [ConfigProxy] info: Adding route / -> http://jupyter-hub.internal:8081 | | 1641302862782 | 13:27:42.782 [ConfigProxy] info: Route added / -> http://jupyter-hub.internal:8081 | | 1641302862783 | 13:27:42.783 [ConfigProxy] info: 201 POST /api/routes/ | | 1641302862783 | [I 2022-01-04 13:27:42.783 JupyterHub app:3150] JupyterHub is now running at http://:8000 | | 1641302963540 | [I 2022-01-04 13:29:23.539 JupyterHub log:189] 200 GET /hub/admin (jk@::ffff:10.100.0.45) 25.41ms | | 1641302963610 | [I 2022-01-04 13:29:23.610 JupyterHub log:189] 302 GET /logo -> /hub/logo (@::ffff:10.100.0.45) 0.96ms | | 1641302963700 | [W 2022-01-04 13:29:23.700 JupyterHub base:89] Blocking Cross Origin API request. Referer: https://jupyter.mydomain.com/hub/admin, Host: jupyter.mydomain.com, Host URL: http://jupyter.mydomain.com/hub/ | | 1641302963701 | [W 2022-01-04 13:29:23.701 JupyterHub scopes:496] Not authorizing access to /hub/api/users. Requires any of [list:users], not derived from scopes [] | | 1641302963701 | [W 2022-01-04 13:29:23.701 JupyterHub web:1787] 403 GET /hub/api/users?offset=0&limit=50 (::ffff:10.100.0.45): Action is not authorized with current scopes; requires any of [list:users] | | 1641302963702 | [W 2022-01-04 13:29:23.702 JupyterHub log:189] 403 GET /hub/api/users?offset=0&limit=50 (@::ffff:10.100.0.45) 25.52ms | | 1641302963726 | [W 2022-01-04 13:29:23.726 JupyterHub base:89] Blocking Cross Origin API request. Referer: https://jupyter.mydomain.com/hub/admin, Host: jupyter.mydomain.com, Host URL: http://jupyter.mydomain.com/hub/ | | 1641302963726 | [W 2022-01-04 13:29:23.726 JupyterHub scopes:496] Not authorizing access to /hub/api/groups. Requires any of [list:groups], not derived from scopes [] | | 1641302963727 | [W 2022-01-04 13:29:23.726 JupyterHub web:1787] 403 GET /hub/api/groups?offset=0&limit=50 (::ffff:10.100.0.45): Action is not authorized with current scopes; requires any of [list:groups] | | 1641302963727 | [W 2022-01-04 13:29:23.727 JupyterHub log:189] 403 GET /hub/api/groups?offset=0&limit=50 (@::ffff:10.100.0.45) 25.29ms | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- </details> If it's indeed a different issue, it might at least be closely related. Can confirm the same issue that @sam-mosleh has happens with Traefik in my institution's `docker-compose` setup. This issue has been mentioned on **Jupyter Community Forum**. There might be relevant details there: https://discourse.jupyter.org/t/admin-panel-not-accessible-in-jupyterhub-2-0-1/12457/3
2022-01-07T13:19:56Z
[]
[]
jupyterhub/jupyterhub
3,770
jupyterhub__jupyterhub-3770
[ "3769" ]
f86d53a234a550868fc1f25cf9b9cdf41640dde0
diff --git a/jupyterhub/handlers/metrics.py b/jupyterhub/handlers/metrics.py --- a/jupyterhub/handlers/metrics.py +++ b/jupyterhub/handlers/metrics.py @@ -12,6 +12,8 @@ class MetricsHandler(BaseHandler): Handler to serve Prometheus metrics """ + _accept_token_auth = True + @metrics_authentication async def get(self): self.set_header('Content-Type', CONTENT_TYPE_LATEST) diff --git a/jupyterhub/scopes.py b/jupyterhub/scopes.py --- a/jupyterhub/scopes.py +++ b/jupyterhub/scopes.py @@ -131,6 +131,9 @@ 'description': 'Read information about the proxy’s routing table, sync the Hub with the proxy and notify the Hub about a new proxy.' }, 'shutdown': {'description': 'Shutdown the hub.'}, + 'read:metrics': { + 'description': "Read prometheus metrics.", + }, } diff --git a/jupyterhub/utils.py b/jupyterhub/utils.py --- a/jupyterhub/utils.py +++ b/jupyterhub/utils.py @@ -320,9 +320,11 @@ def admin_only(self): @auth_decorator def metrics_authentication(self): """Decorator for restricting access to metrics""" - user = self.current_user - if user is None and self.authenticate_prometheus: - raise web.HTTPError(403) + if not self.authenticate_prometheus: + return + scope = 'read:metrics' + if scope not in self.parsed_scopes: + raise web.HTTPError(403, f"Access to metrics requires scope '{scope}'") # Token utilities
diff --git a/jupyterhub/tests/test_metrics.py b/jupyterhub/tests/test_metrics.py --- a/jupyterhub/tests/test_metrics.py +++ b/jupyterhub/tests/test_metrics.py @@ -1,9 +1,13 @@ import json +from unittest import mock + +import pytest -from .utils import add_user from .utils import api_request +from .utils import get_page from jupyterhub import metrics from jupyterhub import orm +from jupyterhub import roles async def test_total_users(app): @@ -32,3 +36,42 @@ async def test_total_users(app): sample = metrics.TOTAL_USERS.collect()[0].samples[0] assert sample.value == num_users + + [email protected]( + "authenticate_prometheus, authenticated, authorized, success", + [ + (True, True, True, True), + (True, True, False, False), + (True, False, False, False), + (False, True, True, True), + (False, False, False, True), + ], +) +async def test_metrics_auth( + app, + authenticate_prometheus, + authenticated, + authorized, + success, + create_temp_role, + user, +): + if authorized: + role = create_temp_role(["read:metrics"]) + roles.grant_role(app.db, user, role) + + headers = {} + if authenticated: + token = user.new_api_token() + headers["Authorization"] = f"token {token}" + + with mock.patch.dict( + app.tornado_settings, {"authenticate_prometheus": authenticate_prometheus} + ): + r = await get_page("metrics", app, headers=headers) + if success: + assert r.status_code == 200 + else: + assert r.status_code == 403 + assert 'read:metrics' in r.text diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -1110,19 +1110,6 @@ async def test_server_not_running_api_request_legacy_status(app): assert r.status_code == 503 -async def test_metrics_no_auth(app): - r = await get_page("metrics", app) - assert r.status_code == 403 - - -async def test_metrics_auth(app): - cookies = await app.login_user('river') - metrics_url = ujoin(public_host(app), app.hub.base_url, 'metrics') - r = await get_page("metrics", app, cookies=cookies) - assert r.status_code == 200 - assert r.url == metrics_url - - async def test_health_check_request(app): r = await get_page('health', app) assert r.status_code == 200
Metrics endpoint doesn't accept token request anymore ### Bug description Prior to version 2 the hub/metrics endpoint could be accessed via token and this was used e.g. to scrape the metrics of a protected jupyterhub instance via prometheus. Since the latest update the metrics endpoint does not allow token based access anymore (see https://github.com/jupyterhub/jupyterhub/pull/3686) Thanks to @minrk for pointing this out. Suggestion: Mention at e.g. the metrics configuration that its a known problem and a workaround is available: ``` from jupyterhub.handlers.metrics import MetricsHandler MetricsHandler._accept_token_auth = True ``` #### Expected behaviour Token auth works #### Actual behaviour Jupyterhub returns 403 forbidden ### How to reproduce Request the hub/metrics endpoint with token authorization ### Your personal set up - OS: CentOS Stream 9 - Version(s): jupyterhub 2.0.2 </details> - <details><summary>Configuration</summary> Not relevant - PR that introduced the problem was mentioned previously. </details> - <details><summary>Logs</summary> ``` WARNING:JupyterHub:403 GET /jupyterhub-dev/hub/metrics (@10.11.193.72) 1.86ms [D 2022-01-18 13:18:12.616 JupyterHub base:1322] No template for 403 ``` </details>
Thank you for opening your first issue in this project! Engagement like this is essential for open source projects! :hugs: <br>If you haven't done so already, check out [Jupyter's Code of Conduct](https://github.com/jupyter/governance/blob/master/conduct/code_of_conduct.md). Also, please try to follow the issue template as it helps other other community members to contribute more effectively. ![welcome](https://raw.githubusercontent.com/jupyterhub/.github/master/images/welcome.jpg) You can meet the other [Jovyans](https://jupyter.readthedocs.io/en/latest/community/content-community.html?highlight=jovyan#what-is-a-jovyan) by joining our [Discourse forum](http://discourse.jupyter.org/). There is also an intro thread there where you can stop by and say Hi! :wave: <br>Welcome to the Jupyter community! :tada:
2022-01-18T13:48:12Z
[]
[]
jupyterhub/jupyterhub
3,773
jupyterhub__jupyterhub-3773
[ "3772" ]
dcf21d53fd9e6c131a269550c0a46f08ca9df5bb
diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -376,6 +376,7 @@ def _new_spawner(self, server_name, spawner_class=None, **kwargs): oauth_client_id=client_id, cookie_options=self.settings.get('cookie_options', {}), trusted_alt_names=trusted_alt_names, + user_options=orm_spawner.user_options or {}, ) if self.settings.get('internal_ssl'):
diff --git a/jupyterhub/tests/test_spawner.py b/jupyterhub/tests/test_spawner.py --- a/jupyterhub/tests/test_spawner.py +++ b/jupyterhub/tests/test_spawner.py @@ -81,6 +81,18 @@ async def test_spawner(db, request): assert isinstance(status, int) +def test_spawner_from_db(app, user): + spawner = user.spawners['name'] + user_options = {"test": "value"} + spawner.orm_spawner.user_options = user_options + app.db.commit() + # delete and recreate the spawner from the db + user.spawners.pop('name') + new_spawner = user.spawners['name'] + assert new_spawner.orm_spawner.user_options == user_options + assert new_spawner.user_options == user_options + + async def wait_for_spawner(spawner, timeout=10): """Wait for an http server to show up
user_options returning empty at users rest api after jupyterhub restart ### Bug description I’ve noticed that after jupyterhub is restarted the user_options are empty i.e. {} when submitting /hub/api/users request (before restart I’m getting user_options which are persisted in db due implemented in persist user_options (https://github.com/jupyterhub/jupyterhub/pull/2446) from looking at code it might be connected to the fact that in apihandler’s [server_model takes user_options from spawner and not spawner.orm_spawner] (https://github.com/jupyterhub/jupyterhub/blob/f5bb0a2622be51b02a64eaa23b10b5f66461ba2b/jupyterhub/apihandlers/base.py#L204) I've patched as suggested above our private jupyterhub, then tested manually that it indeed solves the problem #### Expected behaviour my expectation that user_options will be properly returned after jupyter hub restart #### Actual behaviour user_options are empty {} ### How to reproduce 1. create pod with user_options 2. make sure it's up 3. access jupyterhub api of users 4. make sure user_options are returned as part of response with custom values inside 4. restart jupyter hub 4. access jupyterhub api of users 5. make sure user_options are returned but empty {} ### Your personal set up zero-to-jupyterhub
Thank you for opening your first issue in this project! Engagement like this is essential for open source projects! :hugs: <br>If you haven't done so already, check out [Jupyter's Code of Conduct](https://github.com/jupyter/governance/blob/master/conduct/code_of_conduct.md). Also, please try to follow the issue template as it helps other other community members to contribute more effectively. ![welcome](https://raw.githubusercontent.com/jupyterhub/.github/master/images/welcome.jpg) You can meet the other [Jovyans](https://jupyter.readthedocs.io/en/latest/community/content-community.html?highlight=jovyan#what-is-a-jovyan) by joining our [Discourse forum](http://discourse.jupyter.org/). There is also an intro thread there where you can stop by and say Hi! :wave: <br>Welcome to the Jupyter community! :tada:
2022-01-19T19:48:16Z
[]
[]
jupyterhub/jupyterhub
3,802
jupyterhub__jupyterhub-3802
[ "3592" ]
4a1842bf8a42caf663bf3da7e43c33d6e6c7eb58
diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -515,7 +515,7 @@ async def post(self, user_name, server_name=''): user_name, self.named_server_limit_per_user ), ) - spawner = user.spawners[server_name] + spawner = user.get_spawner(server_name, replace_failed=True) pending = spawner.pending if pending == 'spawn': self.set_header('Content-Type', 'text/plain') diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -151,7 +151,7 @@ async def _get(self, user_name, server_name): self.redirect(url) return - spawner = user.spawners[server_name] + spawner = user.get_spawner(server_name, replace_failed=True) pending_url = self._get_pending_url(user, server_name) @@ -237,7 +237,7 @@ async def _post(self, user_name, server_name): if user is None: raise web.HTTPError(404, "No such user: %s" % for_user) - spawner = user.spawners[server_name] + spawner = user.get_spawner(server_name, replace_failed=True) if spawner.ready: raise web.HTTPError(400, "%s is already running" % (spawner._log_name)) @@ -369,13 +369,9 @@ async def get(self, user_name, server_name=''): auth_state = await user.get_auth_state() # First, check for previous failure. - if ( - not spawner.active - and spawner._spawn_future - and spawner._spawn_future.done() - and spawner._spawn_future.exception() - ): - # Condition: spawner not active and _spawn_future exists and contains an Exception + if not spawner.active and spawner._failed: + # Condition: spawner not active and last spawn failed + # (failure is available as spawner._spawn_future.exception()). # Implicit spawn on /user/:name is not allowed if the user's last spawn failed. # We should point the user to Home if the most recent spawn failed. exc = spawner._spawn_future.exception() diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -253,6 +253,22 @@ def authenticator(self): def spawner_class(self): return self.settings.get('spawner_class', LocalProcessSpawner) + def get_spawner(self, server_name="", replace_failed=False): + """Get a spawner by name + + replace_failed governs whether a failed spawner should be replaced + or returned (default: returned). + + .. versionadded:: 2.2 + """ + spawner = self.spawners[server_name] + if replace_failed and spawner._failed: + self.log.debug(f"Discarding failed spawner {spawner._log_name}") + # remove failed spawner, create a new one + self.spawners.pop(server_name) + spawner = self.spawners[server_name] + return spawner + def sync_groups(self, group_names): """Synchronize groups with database""" @@ -628,7 +644,7 @@ async def spawn(self, server_name='', options=None, handler=None): api_token = self.new_api_token(note=note, roles=['server']) db.commit() - spawner = self.spawners[server_name] + spawner = self.get_spawner(server_name, replace_failed=True) spawner.server = server = Server(orm_server=orm_server) assert spawner.orm_spawner.server is orm_server
diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -1030,7 +1030,7 @@ async def test_never_spawn(app, no_patience, never_spawn): assert not app_user.spawner._spawn_pending status = await app_user.spawner.poll() assert status is not None - # failed spawn should decrements pending count + # failed spawn should decrement pending count assert app.users.count_active_users()['pending'] == 0 @@ -1039,9 +1039,16 @@ async def test_bad_spawn(app, bad_spawn): name = 'prim' user = add_user(db, app=app, name=name) r = await api_request(app, 'users', name, 'server', method='post') + # check that we don't re-use spawners that failed + user.spawners[''].reused = True assert r.status_code == 500 assert app.users.count_active_users()['pending'] == 0 + r = await api_request(app, 'users', name, 'server', method='post') + # check that we don't re-use spawners that failed + spawner = user.spawners[''] + assert not getattr(spawner, 'reused', False) + async def test_spawn_nosuch_user(app): r = await api_request(app, 'users', "nosuchuser", 'server', method='post') diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -128,11 +128,20 @@ async def test_admin_sort(app, sort): assert r.status_code == 200 -async def test_spawn_redirect(app): [email protected]("last_failed", [True, False]) +async def test_spawn_redirect(app, last_failed): name = 'wash' cookies = await app.login_user(name) u = app.users[orm.User.find(app.db, name)] + if last_failed: + # mock a failed spawn + last_spawner = u.spawners[''] + last_spawner._spawn_future = asyncio.Future() + last_spawner._spawn_future.set_exception(RuntimeError("I failed!")) + else: + last_spawner = None + status = await u.spawner.poll() assert status is not None @@ -141,6 +150,10 @@ async def test_spawn_redirect(app): r.raise_for_status() print(urlparse(r.url)) path = urlparse(r.url).path + + # ensure we got a new spawner + assert u.spawners[''] is not last_spawner + # make sure we visited hub/spawn-pending after spawn # if spawn was really quick, we might get redirected all the way to the running server, # so check history instead of r.url @@ -258,6 +271,25 @@ async def test_spawn_page(app): assert FormSpawner.options_form in r.text +async def test_spawn_page_after_failed(app, user): + cookies = await app.login_user(user.name) + + # mock a failed spawn + last_spawner = user.spawners[''] + last_spawner._spawn_future = asyncio.Future() + last_spawner._spawn_future.set_exception(RuntimeError("I failed!")) + + with mock.patch.dict(app.users.settings, {'spawner_class': FormSpawner}): + r = await get_page('spawn', app, cookies=cookies) + spawner = user.spawners[''] + # make sure we didn't reuse last spawner + assert isinstance(spawner, FormSpawner) + assert spawner is not last_spawner + assert r.url.endswith('/spawn') + spawner = user.spawners[''] + assert FormSpawner.options_form in r.text + + async def test_spawn_page_falsy_callable(app): with mock.patch.dict( app.users.settings, {'spawner_class': FalsyCallableFormSpawner}
Spawner instance reused after a failed start If I'm not mistaken, each server starting should get a fresh Spawner instance for each spawn attempt. I made a spawn attempt that failed because start_timeout triggered after in this case, KubeSpawner, had failed to schedule a k8s pod on a k8s node. After this attempt, I tried to start another server with a different configuration via KubeSpawner's profile_list, but I ended up with a mixed configuration where one setting came from the first spawn attempt and the other came from the new spawn attempt. This to me indicated that the Spawner instance had been re-used.
Yes, indeed! I'm not sure how this can happen, but more details would help. Maybe logs. Each spawn should indeed create a new Spawner. Is it possible the spawner was stuck in 'pending' state instead of actually finished failing? I'm not sure about the spawner instance's state, but the k8s pod was stuck in a Pending state but must have been terminated between the attempts as otherwise the new pod couldn't startup I think. I have no logs to provide at this point. I think the reproduction procedure would be like this. Reproduction setup: 1. Configure a short start_timeout to avoid needing to wait for a long time. 2. Configure a pre_spawn_hook that updates the node_selector to include a node label that doesn't exist 3. Configure the pre_spawn_hook to make an assertion that the node_selector shouldn't be set before it sets it. If it is, that means that this logic has already run for this spawner instance. Reproduction steps: 1. Login to jupyterhub 2. Spawn a pod. This should fail with a timeout as the pod should be stuck in a pending state 3. Spawn a pod again. This should fail with the broken assertion if it reproduces. This seems like a potential cause of this issue @minrk. Any ideas of a suggested change comes to mind? https://github.com/jupyterhub/jupyterhub/blob/a3ea0f0449e9e19feff863b5f5cce4d8a4febf1f/jupyterhub/user.py#L945-L954 @consideRatio good eye! I think you're right that this is going to be the root cause. In most cases, failure to dispose of a previous spawner isn't an issue, but certain cases, especially with dynamic options, certainly will not fully reinitialize unless a new Spawner is instantiated. Should search Issues, I think this may be related to some other reports around spawners having 'stale' state. Will need to think carefully about exactly when to dispose of a failed Spawner vs create a fresh one. We probably want these same checks for `spawner._spawn_future` in User.spawn, but possibly elsewhere as well (when showing spawn form, for example).
2022-02-22T10:03:53Z
[]
[]
jupyterhub/jupyterhub
3,876
jupyterhub__jupyterhub-3876
[ "3014" ]
ec2c90c73fa39b8c240a0319ad3bf058c4a8a97a
diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -635,29 +635,32 @@ def get_next_url(self, user=None, default=None): next_url = next_url.replace('\\', '%5C') proto = get_browser_protocol(self.request) host = self.request.host + if next_url.startswith("///"): + # strip more than 2 leading // down to 2 + # because urlparse treats that as empty netloc, + # whereas browsers treat more than two leading // the same as //, + # so netloc is the first non-/ bit + next_url = "//" + next_url.lstrip("/") + parsed_next_url = urlparse(next_url) if (next_url + '/').startswith((f'{proto}://{host}/', f'//{host}/',)) or ( self.subdomain_host - and urlparse(next_url).netloc - and ("." + urlparse(next_url).netloc).endswith( + and parsed_next_url.netloc + and ("." + parsed_next_url.netloc).endswith( "." + urlparse(self.subdomain_host).netloc ) ): # treat absolute URLs for our host as absolute paths: - # below, redirects that aren't strictly paths - parsed = urlparse(next_url) - next_url = parsed.path - if parsed.query: - next_url = next_url + '?' + parsed.query - if parsed.fragment: - next_url = next_url + '#' + parsed.fragment + # below, redirects that aren't strictly paths are rejected + next_url = parsed_next_url.path + if parsed_next_url.query: + next_url = next_url + '?' + parsed_next_url.query + if parsed_next_url.fragment: + next_url = next_url + '#' + parsed_next_url.fragment + parsed_next_url = urlparse(next_url) # if it still has host info, it didn't match our above check for *this* host - if next_url and ( - '://' in next_url - or next_url.startswith('//') - or not next_url.startswith('/') - ): + if next_url and (parsed_next_url.netloc or not next_url.startswith('/')): self.log.warning("Disallowing redirect outside JupyterHub: %r", next_url) next_url = ''
diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -768,6 +768,10 @@ async def mock_authenticate(handler, data): (False, '/user/other', '/hub/user/other', None), (False, '/absolute', '/absolute', None), (False, '/has?query#andhash', '/has?query#andhash', None), + # :// in query string or fragment + (False, '/has?repo=https/host.git', '/has?repo=https/host.git', None), + (False, '/has?repo=https://host.git', '/has?repo=https://host.git', None), + (False, '/has#repo=https://host.git', '/has#repo=https://host.git', None), # next_url outside is not allowed (False, 'relative/path', '', None), (False, 'https://other.domain', '', None), @@ -807,7 +811,9 @@ async def test_login_redirect(app, running, next_url, location, params): if params: url = url_concat(url, params) if next_url: - if '//' not in next_url and next_url.startswith('/'): + if next_url.startswith('/') and not ( + next_url.startswith("//") or urlparse(next_url).netloc + ): next_url = ujoin(app.base_url, next_url, '') url = url_concat(url, dict(next=next_url))
nbgitpuller repo target triggers disallowed redirect ### Bug description We've been seeing a problem where users following nbgitpuller links would sometimes have to go through a two step process the repository would clone/pull (I think this jupyterhub/nbgitpuller#118 is the same problem). It looks like [next_url check](https://github.com/jupyterhub/jupyterhub/blob/1f515464fe2edf5d9d8a7617c22ebe67002e0ba0/jupyterhub/handlers/base.py#L620-L626) notices when the `repo=` part of the query string contains unencoded special characters (specifically the `://`) and triggers this warning from the hub `Disallowing redirect outside hub` and redirects the user to `/hub/home`, skipping nbgitpuller. **N.B. This only seems to happen when the user is not authenticated to start with, so visiting the nbgitpuller link a second time works** #### Expected behaviour Clicking an ngitpuller link should send the user through authentication then on to nbgitpuller as a single process without the user having to re-click the link. #### Actual behaviour If the user is not already logged in and follows an nbgitpuller link they are authenticated but nbgitpuller is not run. If they click the link a second time (now that they are logged in) nbgitpuller will do its thing and clone/pull. ### How to reproduce 1. Make sure you're not authenticated to the hub 2. Visit an nbgitpuller link where the repo target hasn't been encoded, e.g. ``` https://hub.example.com/hub/user-redirect/git-pull?repo=https://github.com/callysto/callysto-sample-notebooks ``` 3. Authenticate to the hub 4. You'll be taken to `/hub/home` and nbgitpuller will not run. ### Workaround Make sure the query string is properly encoded. The [nbgitpuller link generator](https://jupyterhub.github.io/nbgitpuller/link) does this for you automatically, but some URL shortening services (e.g. bit.ly) will undo the encoding and trigger the behaviour. ### Your personal set up I've reproduced this on a couple of different hubs both running JupyterHub 1.1 & using different browsers (Chrome & Firefox) on the client side. ### Notes * I'm not sure why this isn't triggered when the user is already authenticated * This might be the intended behaviour and the solution might be to remind people that those characters should be encoded, but it comes up _a lot_ so I thought I should file an issue.
2022-04-28T11:37:18Z
[]
[]
jupyterhub/jupyterhub
3,886
jupyterhub__jupyterhub-3886
[ "3881" ]
585b47051f246966c9c4db951adc4e0aa1eae698
diff --git a/jupyterhub/apihandlers/hub.py b/jupyterhub/apihandlers/hub.py --- a/jupyterhub/apihandlers/hub.py +++ b/jupyterhub/apihandlers/hub.py @@ -47,9 +47,8 @@ def post(self): self.set_status(202) self.finish(json.dumps({"message": "Shutting down Hub"})) - # stop the eventloop, which will trigger cleanup - loop = IOLoop.current() - loop.add_callback(loop.stop) + # instruct the app to stop, which will trigger cleanup + app.stop() class RootAPIHandler(APIHandler): diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -3234,9 +3234,15 @@ def atexit(self): loop.make_current() loop.run_sync(self.cleanup) - async def shutdown_cancel_tasks(self, sig): + async def shutdown_cancel_tasks(self, sig=None): """Cancel all other tasks of the event loop and initiate cleanup""" - self.log.critical("Received signal %s, initiating shutdown...", sig.name) + if sig is None: + self.log.critical("Initiating shutdown...") + else: + self.log.critical("Received signal %s, initiating shutdown...", sig.name) + + await self.cleanup() + tasks = [t for t in asyncio_all_tasks() if t is not asyncio_current_task()] if tasks: @@ -3253,7 +3259,6 @@ async def shutdown_cancel_tasks(self, sig): tasks = [t for t in asyncio_all_tasks()] for t in tasks: self.log.debug("Task status: %s", t) - await self.cleanup() asyncio.get_event_loop().stop() def stop(self): @@ -3261,7 +3266,7 @@ def stop(self): return if self.http_server: self.http_server.stop() - self.io_loop.add_callback(self.io_loop.stop) + self.io_loop.add_callback(self.shutdown_cancel_tasks) async def start_show_config(self): """Async wrapper around base start_show_config method"""
diff --git a/jupyterhub/tests/conftest.py b/jupyterhub/tests/conftest.py --- a/jupyterhub/tests/conftest.py +++ b/jupyterhub/tests/conftest.py @@ -188,6 +188,8 @@ def cleanup_after(request, io_loop): if not MockHub.initialized(): return app = MockHub.instance() + if app.db_file.closed: + return for uid, user in list(app.users.items()): for name, spawner in list(user.spawners.items()): if spawner.active: diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -325,26 +325,28 @@ async def initialize(self, argv=None): roles.assign_default_roles(self.db, entity=user) self.db.commit() - def stop(self): - super().stop() + _stop_called = False + def stop(self): + if self._stop_called: + return + self._stop_called = True # run cleanup in a background thread # to avoid multiple eventloops in the same thread errors from asyncio def cleanup(): - asyncio.set_event_loop(asyncio.new_event_loop()) - loop = IOLoop.current() - loop.run_sync(self.cleanup) + loop = asyncio.new_event_loop() + loop.run_until_complete(self.cleanup()) loop.close() - pool = ThreadPoolExecutor(1) - f = pool.submit(cleanup) - # wait for cleanup to finish - f.result() - pool.shutdown() + with ThreadPoolExecutor(1) as pool: + f = pool.submit(cleanup) + # wait for cleanup to finish + f.result() - # ignore the call that will fire in atexit - self.cleanup = lambda: None + # prevent redundant atexit from running + self._atexit_ran = True + super().stop() self.db_file.close() async def login_user(self, name): diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -2095,14 +2095,23 @@ async def shutdown(): ) return r - real_stop = loop.stop + real_stop = loop.asyncio_loop.stop def stop(): stop.called = True loop.call_later(1, real_stop) - with mock.patch.object(loop, 'stop', stop): + real_cleanup = app.cleanup + + def cleanup(): + cleanup.called = True + return real_cleanup() + + app.cleanup = cleanup + + with mock.patch.object(loop.asyncio_loop, 'stop', stop): r = loop.run_sync(shutdown, timeout=5) r.raise_for_status() reply = r.json() + assert cleanup.called assert stop.called
API shutdown doesn't call cleanup ### Bug description If a POST is sent to the shutdown API endpoint http://localhost:8000/hub/api/shutdown, either through the shutdown button on the admin page, or by making a request to the API with curl, `cleanup()`: https://github.com/jupyterhub/jupyterhub/blob/107dc02fd0698eaff11125829a947863275f32ef/jupyterhub/app.py#L2871-L2872 is not called #### Expected behaviour The hub should shut down gracefully by calling `cleanup()` #### Actual behaviour It seems to shutdown straightaway. ### How to reproduce Using the latest `main` Docker Hub image ```sh podman pull jupyterhub/jupyterhub:main podman run -it --rm -p 8000:8000 jupyterhub/jupyterhub:main bash ``` In the container run jupyterhub: ``` root@4a418a63bfba:/srv/jupyterhub# jupyterhub --JupyterHub.authenticator_class=dummy --Authenticator.admin_users=demo --debug ``` Go to http://localhost:8000/hub/admin#/ , login as `demo`, click `Shutdown Hub`. Logs: ``` [D 2022-04-30 17:14:01.292 JupyterHub scopes:792] Checking access via scope shutdown [D 2022-04-30 17:14:01.292 JupyterHub scopes:606] Unrestricted access to /hub/api/shutdown via shutdown [I 2022-04-30 17:14:01.293 JupyterHub log:186] 202 POST /hub/api/shutdown (demo@::ffff:10.0.2.100) 6.24ms root@4a418a63bfba:/srv/jupyterhub# ``` `configurable-http-proxy` is still running: ``` root@4a418a63bfba:/srv/jupyterhub# ps auwx USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 7244 3640 pts/0 Ss 17:13 0:00 bash root 8 1.4 0.2 585092 45988 ? Ssl 17:13 0:00 node /usr/local/bin/configurable-http-proxy --ip --port 8000 --api-ip 127.0.0.1 --api-port 8001 --error-target http://12 root 15 0.0 0.0 8884 3232 pts/0 R+ 17:14 0:00 ps auwx ``` In contrast if the hub is stopped with `<Ctrl-C>` in the terminal: ``` ^C[C 2022-04-30 17:16:34.920 JupyterHub app:3239] Received signal SIGINT, initiating shutdown... [I 2022-04-30 17:16:34.921 JupyterHub app:2883] Cleaning up single-user servers... [D 2022-04-30 17:16:34.922 JupyterHub app:2895] Stopping proxy [I 2022-04-30 17:16:34.922 JupyterHub proxy:750] Cleaning up proxy[8]... [D 2022-04-30 17:16:34.923 JupyterHub proxy:607] Removing proxy pid file jupyterhub-proxy.pid 17:16:34.924 [ConfigProxy] warn: Terminated [I 2022-04-30 17:16:34.925 JupyterHub app:2915] ...done root@9f02d163f208:/srv/jupyterhub# ``` ``` root@9f02d163f208:/srv/jupyterhub# ps auwx USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 7244 3788 pts/0 Ss 17:15 0:00 bash root 15 0.0 0.0 8884 3212 pts/0 R+ 17:16 0:00 ps auwx ``` This is the backend part of the bug in https://github.com/jupyterhub/jupyterhub/issues/3880
2022-05-05T10:56:13Z
[]
[]
jupyterhub/jupyterhub
3,909
jupyterhub__jupyterhub-3909
[ "3981" ]
d1706016782106cf451666a049c6048b358460c5
diff --git a/jupyterhub/apihandlers/base.py b/jupyterhub/apihandlers/base.py --- a/jupyterhub/apihandlers/base.py +++ b/jupyterhub/apihandlers/base.py @@ -187,22 +187,44 @@ def write_error(self, status_code, **kwargs): json.dumps({'status': status_code, 'message': message or status_message}) ) - def server_model(self, spawner): + def server_model(self, spawner, *, user=None): """Get the JSON model for a Spawner - Assume server permission already granted""" + Assume server permission already granted + """ + if isinstance(spawner, orm.Spawner): + # if an orm.Spawner is passed, + # create a model for a stopped Spawner + # not all info is available without the higher-level Spawner wrapper + orm_spawner = spawner + pending = None + ready = False + stopped = True + user = user + if user is None: + raise RuntimeError("Must specify User with orm.Spawner") + state = orm_spawner.state + else: + orm_spawner = spawner.orm_spawner + pending = spawner.pending + ready = spawner.ready + user = spawner.user + stopped = not spawner.active + state = spawner.get_state() + model = { - 'name': spawner.name, - 'last_activity': isoformat(spawner.orm_spawner.last_activity), - 'started': isoformat(spawner.orm_spawner.started), - 'pending': spawner.pending, - 'ready': spawner.ready, - 'url': url_path_join(spawner.user.url, url_escape_path(spawner.name), '/'), + 'name': orm_spawner.name, + 'last_activity': isoformat(orm_spawner.last_activity), + 'started': isoformat(orm_spawner.started), + 'pending': pending, + 'ready': ready, + 'stopped': stopped, + 'url': url_path_join(user.url, url_escape_path(spawner.name), '/'), 'user_options': spawner.user_options, - 'progress_url': spawner._progress_url, + 'progress_url': user.progress_url(spawner.name), } scope_filter = self.get_scope_filter('admin:server_state') if scope_filter(spawner, kind='server'): - model['state'] = spawner.get_state() + model['state'] = state return model def token_model(self, token): @@ -248,10 +270,22 @@ def _filter_model(self, model, access_map, entity, kind, keys=None): keys.update(allowed_keys) return model + _include_stopped_servers = None + + @property + def include_stopped_servers(self): + """Whether stopped servers should be included in user models""" + if self._include_stopped_servers is None: + self._include_stopped_servers = self.get_argument( + "include_stopped_servers", "0" + ).lower() not in {"0", "false"} + return self._include_stopped_servers + def user_model(self, user): """Get the JSON model for a User object""" if isinstance(user, orm.User): user = self.users[user.id] + include_stopped_servers = self.include_stopped_servers model = { 'kind': 'user', 'name': user.name, @@ -291,18 +325,29 @@ def user_model(self, user): if '' in user.spawners and 'pending' in allowed_keys: model['pending'] = user.spawners[''].pending - servers = model['servers'] = {} + servers = {} scope_filter = self.get_scope_filter('read:servers') for name, spawner in user.spawners.items(): # include 'active' servers, not just ready # (this includes pending events) - if spawner.active and scope_filter(spawner, kind='server'): + if (spawner.active or include_stopped_servers) and scope_filter( + spawner, kind='server' + ): servers[name] = self.server_model(spawner) - if not servers and 'servers' not in allowed_keys: + + if include_stopped_servers: + # add any stopped servers in the db + seen = set(servers.keys()) + for name, orm_spawner in user.orm_spawners.items(): + if name not in seen and scope_filter(orm_spawner, kind='server'): + servers[name] = self.server_model(orm_spawner, user=user) + + if "servers" in allowed_keys or servers: # omit servers if no access # leave present and empty # if request has access to read servers in general - model.pop('servers') + model["servers"] = servers + return model def group_model(self, group):
diff --git a/jupyterhub/tests/test_named_servers.py b/jupyterhub/tests/test_named_servers.py --- a/jupyterhub/tests/test_named_servers.py +++ b/jupyterhub/tests/test_named_servers.py @@ -1,6 +1,7 @@ """Tests for named servers""" import asyncio import json +import time from unittest import mock from urllib.parse import unquote, urlencode, urlparse @@ -61,6 +62,7 @@ async def test_default_server(app, named_servers): 'url': user.url, 'pending': None, 'ready': True, + 'stopped': False, 'progress_url': 'PREFIX/hub/api/users/{}/server/progress'.format( username ), @@ -148,6 +150,7 @@ async def test_create_named_server( 'url': url_path_join(user.url, escapedname, '/'), 'pending': None, 'ready': True, + 'stopped': False, 'progress_url': 'PREFIX/hub/api/users/{}/servers/{}/progress'.format( username, escapedname ), @@ -433,3 +436,61 @@ async def test_named_server_stop_server(app, username, named_servers): assert user.spawners[server_name].server is None assert user.spawners[''].server assert user.running + + [email protected]( + "include_stopped_servers", + [True, False], +) +async def test_stopped_servers(app, user, named_servers, include_stopped_servers): + r = await api_request(app, 'users', user.name, 'server', method='post') + r.raise_for_status() + r = await api_request(app, 'users', user.name, 'servers', "named", method='post') + r.raise_for_status() + + # wait for starts + for i in range(60): + r = await api_request(app, 'users', user.name) + r.raise_for_status() + user_model = r.json() + if not all(s["ready"] for s in user_model["servers"].values()): + time.sleep(1) + else: + break + else: + raise TimeoutError(f"User never stopped: {user_model}") + + r = await api_request(app, 'users', user.name, 'server', method='delete') + r.raise_for_status() + r = await api_request(app, 'users', user.name, 'servers', "named", method='delete') + r.raise_for_status() + + # wait for stops + for i in range(60): + r = await api_request(app, 'users', user.name) + r.raise_for_status() + user_model = r.json() + if not all(s["stopped"] for s in user_model["servers"].values()): + time.sleep(1) + else: + break + else: + raise TimeoutError(f"User never stopped: {user_model}") + + # we have two stopped servers + path = f"users/{user.name}" + if include_stopped_servers: + path = f"{path}?include_stopped_servers" + r = await api_request(app, path) + r.raise_for_status() + user_model = r.json() + servers = list(user_model["servers"].values()) + if include_stopped_servers: + assert len(servers) == 2 + assert all(s["last_activity"] for s in servers) + assert all(s["started"] is None for s in servers) + assert all(s["stopped"] for s in servers) + assert not any(s["ready"] for s in servers) + assert not any(s["pending"] for s in servers) + else: + assert user_model["servers"] == {}
Add "Last seen" column in admin page ### Proposed change <!-- Use this section to describe the feature you'd like to be added. --> I just updated jupyterhub. There used to be a Last seen column in the admin panel, and this was a feature I used a lot. Now there is a "Last activity" column instead, which show "Never" if no server is running. As I use the culling system anyway, this column is rarely of any use. I would like to have the "Last seen" column back. ### (Optional): Suggest a solution I'm not fluent enough with the jupyterhub project to test a solution. I understand that the file to modify is probably this one https://github.com/jupyterhub/jupyterhub/blob/main/jsx/src/components/ServerDashboard/ServerDashboard.jsx around the line 261. Maybe switching "server.last_activity" to "user.last_activity" would do ? I couldn't find out how to test this.
2022-05-25T13:17:07Z
[]
[]
jupyterhub/jupyterhub
3,976
jupyterhub__jupyterhub-3976
[ "3972" ]
6fdd0ff7c564266cd0b9048b16ee6d701f5d4c4f
diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -11,6 +11,7 @@ import secrets import signal import socket +import ssl import sys import time from concurrent.futures import ThreadPoolExecutor @@ -23,15 +24,6 @@ if sys.version_info[:2] < (3, 3): raise ValueError("Python < 3.3 not supported: %s" % sys.version) -# For compatibility with python versions 3.6 or earlier. -# asyncio.Task.all_tasks() is fully moved to asyncio.all_tasks() starting with 3.9. Also applies to current_task. -try: - asyncio_all_tasks = asyncio.all_tasks - asyncio_current_task = asyncio.current_task -except AttributeError as e: - asyncio_all_tasks = asyncio.Task.all_tasks - asyncio_current_task = asyncio.Task.current_task - import tornado.httpserver import tornado.options from dateutil.parser import parse as parse_date @@ -3056,7 +3048,7 @@ async def start(self): self.internal_ssl_key, self.internal_ssl_cert, cafile=self.internal_ssl_ca, - check_hostname=False, + purpose=ssl.Purpose.CLIENT_AUTH, ) # start the webserver @@ -3248,7 +3240,7 @@ async def shutdown_cancel_tasks(self, sig=None): await self.cleanup() - tasks = [t for t in asyncio_all_tasks() if t is not asyncio_current_task()] + tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()] if tasks: self.log.debug("Cancelling pending tasks") @@ -3261,7 +3253,7 @@ async def shutdown_cancel_tasks(self, sig=None): except StopAsyncIteration as e: self.log.error("Caught StopAsyncIteration Exception", exc_info=True) - tasks = [t for t in asyncio_all_tasks()] + tasks = [t for t in asyncio.all_tasks()] for t in tasks: self.log.debug("Task status: %s", t) asyncio.get_event_loop().stop() diff --git a/jupyterhub/singleuser/mixins.py b/jupyterhub/singleuser/mixins.py --- a/jupyterhub/singleuser/mixins.py +++ b/jupyterhub/singleuser/mixins.py @@ -14,6 +14,7 @@ import os import random import secrets +import ssl import sys import warnings from datetime import timezone diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -1,9 +1,11 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import json +import string import warnings from collections import defaultdict from datetime import datetime, timedelta +from functools import lru_cache from urllib.parse import quote, urlparse from sqlalchemy import inspect @@ -53,6 +55,42 @@ to a number of seconds that is enough for servers to become responsive. """ +# set of chars that are safe in dns labels +# (allow '.' because we don't mind multiple levels of subdomains) +_dns_safe = set(string.ascii_letters + string.digits + '-.') +# don't escape % because it's the escape char and we handle it separately +_dns_needs_replace = _dns_safe | {"%"} + + +@lru_cache() +def _dns_quote(name): + """Escape a name for use in a dns label + + this is _NOT_ fully domain-safe, but works often enough for realistic usernames. + Fully safe would be full IDNA encoding, + PLUS escaping non-IDNA-legal ascii, + PLUS some encoding of boundary conditions + """ + # escape name for subdomain label + label = quote(name, safe="").lower() + # some characters are not handled by quote, + # because they are legal in URLs but not domains, + # specifically _ and ~ (starting in 3.7). + # Escape these in the same way (%{hex_codepoint}). + unique_chars = set(label) + for c in unique_chars: + if c not in _dns_needs_replace: + label = label.replace(c, f"%{ord(c):x}") + + # underscore is our escape char - + # it's not officially legal in hostnames, + # but is valid in _domain_ names (?), + # and always works in practice. + # FIXME: We should consider switching to proper IDNA encoding + # for 3.0. + label = label.replace("%", "_") + return label + class UserDict(dict): """Like defaultdict, but for users @@ -520,10 +558,8 @@ def proxy_spec(self): @property def domain(self): """Get the domain for my server.""" - # use underscore as escape char for domains - return ( - quote(self.name).replace('%', '_').lower() + '.' + self.settings['domain'] - ) + + return _dns_quote(self.name) + '.' + self.settings['domain'] @property def host(self): diff --git a/jupyterhub/utils.py b/jupyterhub/utils.py --- a/jupyterhub/utils.py +++ b/jupyterhub/utils.py @@ -27,14 +27,26 @@ from tornado.httpclient import AsyncHTTPClient, HTTPError from tornado.log import app_log -# For compatibility with python versions 3.6 or earlier. -# asyncio.Task.all_tasks() is fully moved to asyncio.all_tasks() starting with 3.9. Also applies to current_task. -try: - asyncio_all_tasks = asyncio.all_tasks - asyncio_current_task = asyncio.current_task -except AttributeError as e: - asyncio_all_tasks = asyncio.Task.all_tasks - asyncio_current_task = asyncio.Task.current_task + +# Deprecated aliases: no longer needed now that we require 3.7 +def asyncio_all_tasks(loop=None): + warnings.warn( + "jupyterhub.utils.asyncio_all_tasks is deprecated in JupyterHub 2.4." + " Use asyncio.all_tasks().", + DeprecationWarning, + stacklevel=2, + ) + return asyncio.all_tasks(loop=loop) + + +def asyncio_current_task(loop=None): + warnings.warn( + "jupyterhub.utils.asyncio_current_task is deprecated in JupyterHub 2.4." + " Use asyncio.current_task().", + DeprecationWarning, + stacklevel=2, + ) + return asyncio.current_task(loop=loop) def random_port(): @@ -82,13 +94,51 @@ def can_connect(ip, port): return True -def make_ssl_context(keyfile, certfile, cafile=None, verify=True, check_hostname=True): - """Setup context for starting an https server or making requests over ssl.""" +def make_ssl_context( + keyfile, + certfile, + cafile=None, + verify=None, + check_hostname=None, + purpose=ssl.Purpose.SERVER_AUTH, +): + """Setup context for starting an https server or making requests over ssl. + + Used for verifying internal ssl connections. + Certificates are always verified in both directions. + Hostnames are checked for client sockets. + + Client sockets are created with `purpose=ssl.Purpose.SERVER_AUTH` (default), + Server sockets are created with `purpose=ssl.Purpose.CLIENT_AUTH`. + """ if not keyfile or not certfile: return None - purpose = ssl.Purpose.SERVER_AUTH if verify else ssl.Purpose.CLIENT_AUTH + if verify is not None: + purpose = ssl.Purpose.SERVER_AUTH if verify else ssl.Purpose.CLIENT_AUTH + warnings.warn( + f"make_ssl_context(verify={verify}) is deprecated in jupyterhub 2.4." + f" Use make_ssl_context(purpose={purpose!s}).", + DeprecationWarning, + stacklevel=2, + ) + if check_hostname is not None: + purpose = ssl.Purpose.SERVER_AUTH if check_hostname else ssl.Purpose.CLIENT_AUTH + warnings.warn( + f"make_ssl_context(check_hostname={check_hostname}) is deprecated in jupyterhub 2.4." + f" Use make_ssl_context(purpose={purpose!s}).", + DeprecationWarning, + stacklevel=2, + ) + ssl_context = ssl.create_default_context(purpose, cafile=cafile) + # always verify + ssl_context.verify_mode = ssl.CERT_REQUIRED + + if purpose == ssl.Purpose.SERVER_AUTH: + # SERVER_AUTH is authenticating servers (i.e. for a client) + ssl_context.check_hostname = True ssl_context.load_default_certs() + ssl_context.load_cert_chain(certfile, keyfile) ssl_context.check_hostname = check_hostname return ssl_context diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -14,12 +14,6 @@ from setuptools.command.build_py import build_py from setuptools.command.sdist import sdist -v = sys.version_info -if v[:2] < (3, 6): - error = "ERROR: JupyterHub requires Python version 3.6 or above." - print(error, file=sys.stderr) - sys.exit(1) - shell = False if os.name in ('nt', 'dos'): shell = True @@ -91,7 +85,7 @@ def get_package_data(): license="BSD", platforms="Linux, Mac OS X", keywords=['Interactive', 'Interpreter', 'Shell', 'Web'], - python_requires=">=3.6", + python_requires=">=3.7", entry_points={ 'jupyterhub.authenticators': [ 'default = jupyterhub.auth:PAMAuthenticator',
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -56,9 +56,9 @@ jobs: # Tests everything when JupyterHub works against a dedicated mysql or # postgresql server. # - # nbclassic: + # legacy_notebook: # Tests everything when the user instances are started with - # notebook instead of jupyter_server. + # the legacy notebook server instead of jupyter_server. # # ssl: # Tests everything using internal SSL connections instead of @@ -72,20 +72,24 @@ jobs: # GitHub UI when the workflow run, we avoid using true/false as # values by instead duplicating the name to signal true. include: - - python: "3.6" - oldest_dependencies: oldest_dependencies - nbclassic: nbclassic - - python: "3.6" - subdomain: subdomain - - python: "3.7" - db: mysql - python: "3.7" - ssl: ssl - - python: "3.8" - db: postgres + oldest_dependencies: oldest_dependencies + legacy_notebook: legacy_notebook - python: "3.8" - nbclassic: nbclassic + legacy_notebook: legacy_notebook - python: "3.9" + db: mysql + - python: "3.10" + db: postgres + - python: "3.10" + subdomain: subdomain + - python: "3.10" + ssl: ssl + # can't test 3.11.0-beta.4 until a greenlet release + # greenlet is a dependency of sqlalchemy on linux + # see https://github.com/gevent/gevent/issues/1867 + # - python: "3.11.0-beta.4" + - python: "3.10" main_dependencies: main_dependencies steps: @@ -148,9 +152,9 @@ jobs: if [ "${{ matrix.main_dependencies }}" != "" ]; then pip install git+https://github.com/ipython/traitlets#egg=traitlets --force fi - if [ "${{ matrix.nbclassic }}" != "" ]; then + if [ "${{ matrix.legacy_notebook }}" != "" ]; then pip uninstall jupyter_server --yes - pip install notebook + pip install 'notebook<7' fi if [ "${{ matrix.db }}" == "mysql" ]; then pip install mysql-connector-python diff --git a/jupyterhub/tests/conftest.py b/jupyterhub/tests/conftest.py --- a/jupyterhub/tests/conftest.py +++ b/jupyterhub/tests/conftest.py @@ -54,28 +54,6 @@ _db = None -def _pytest_collection_modifyitems(items): - """This function is automatically run by pytest passing all collected test - functions. - - We use it to add asyncio marker to all async tests and assert we don't use - test functions that are async generators which wouldn't make sense. - - It is no longer required with pytest-asyncio >= 0.17 - """ - for item in items: - if inspect.iscoroutinefunction(item.obj): - item.add_marker('asyncio') - assert not inspect.isasyncgenfunction(item.obj) - - -if sys.version_info < (3, 7): - # apply pytest-asyncio's 'auto' mode on Python 3.6. - # 'auto' mode is new in pytest-asyncio 0.17, - # which requires Python 3.7. - pytest_collection_modifyitems = _pytest_collection_modifyitems - - @fixture(scope='module') def ssl_tmpdir(tmpdir_factory): return tmpdir_factory.mktemp('ssl') diff --git a/jupyterhub/tests/mockservice.py b/jupyterhub/tests/mockservice.py --- a/jupyterhub/tests/mockservice.py +++ b/jupyterhub/tests/mockservice.py @@ -15,6 +15,7 @@ import json import os import pprint +import ssl import sys from urllib.parse import urlparse @@ -111,7 +112,9 @@ def main(): ca = os.environ.get('JUPYTERHUB_SSL_CLIENT_CA') or '' if key and cert and ca: - ssl_context = make_ssl_context(key, cert, cafile=ca, check_hostname=False) + ssl_context = make_ssl_context( + key, cert, cafile=ca, purpose=ssl.Purpose.CLIENT_AUTH + ) server = httpserver.HTTPServer(app, ssl_options=ssl_context) server.listen(url.port, url.hostname) diff --git a/jupyterhub/tests/mocksu.py b/jupyterhub/tests/mocksu.py --- a/jupyterhub/tests/mocksu.py +++ b/jupyterhub/tests/mocksu.py @@ -47,7 +47,11 @@ def main(): ca = os.environ.get('JUPYTERHUB_SSL_CLIENT_CA') or '' if key and cert and ca: - ssl_context = make_ssl_context(key, cert, cafile=ca, check_hostname=False) + import ssl + + ssl_context = make_ssl_context( + key, cert, cafile=ca, purpose=ssl.Purpose.CLIENT_AUTH + ) assert url.scheme == "https" server = httpserver.HTTPServer(app, ssl_options=ssl_context) diff --git a/jupyterhub/tests/test_singleuser.py b/jupyterhub/tests/test_singleuser.py --- a/jupyterhub/tests/test_singleuser.py +++ b/jupyterhub/tests/test_singleuser.py @@ -1,7 +1,7 @@ """Tests for jupyterhub.singleuser""" import os import sys -from contextlib import contextmanager +from contextlib import contextmanager, nullcontext from subprocess import CalledProcessError, check_output from unittest import mock from urllib.parse import urlencode, urlparse @@ -17,12 +17,6 @@ from .utils import AsyncSession, async_requests, get_page -@contextmanager -def nullcontext(): - """Python 3.7+ contextlib.nullcontext, backport for 3.6""" - yield - - @pytest.mark.parametrize( "access_scopes, server_name, expect_success", [
Test against python 3.10 Related to #3973 - if a decision is made about that, I'll keep moving on fixing things based on findings here and then finally marking this PR as non-draft when tests pass.
We should definitely add 3.10 and 3.11-beta, but we also _definitely_ shouldn't stop testing supported Python versions (back to 3.6, but should probably bump to 3.7 soon). Absolutely, we should test all versions. In this state, i wanted to ensure i caught all kinds of test errors if poython 3.10 is used before letting it run only for one test variation.
2022-07-14T16:05:10Z
[]
[]
jupyterhub/jupyterhub
4,011
jupyterhub__jupyterhub-4011
[ "4010" ]
2f1d340c424107483826efc8e50f8ac2e0b3e4b2
diff --git a/jupyterhub/auth.py b/jupyterhub/auth.py --- a/jupyterhub/auth.py +++ b/jupyterhub/auth.py @@ -256,6 +256,9 @@ def validate_username(self, username): if not username: # empty usernames are not allowed return False + if username != username.strip(): + # starting/ending with space is not allowed + return False if not self.username_regex: return True return bool(self.username_regex.match(username)) diff --git a/jupyterhub/handlers/login.py b/jupyterhub/handlers/login.py --- a/jupyterhub/handlers/login.py +++ b/jupyterhub/handlers/login.py @@ -145,7 +145,9 @@ async def post(self): # parse the arguments dict data = {} for arg in self.request.arguments: - data[arg] = self.get_argument(arg, strip=False) + # strip username, but not other fields like passwords, + # which should be allowed to start or end with space + data[arg] = self.get_argument(arg, strip=arg == "username") auth_timer = self.statsd.timer('login.authenticate').start() user = await self.login_user(data)
diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -740,9 +740,17 @@ async def test_login_fail(app): assert not r.cookies -async def test_login_strip(app): - """Test that login form doesn't strip whitespace from passwords""" - form_data = {'username': 'spiff', 'password': ' space man '} [email protected]( + "form_user, auth_user, form_password", + [ + ("spiff", "spiff", " space man "), + (" spiff ", "spiff", " space man "), + ], +) +async def test_login_strip(app, form_user, auth_user, form_password): + """Test that login form strips space form usernames, but not passwords""" + form_data = {"username": form_user, "password": form_password} + expected_auth = {"username": auth_user, "password": form_password} base_url = public_url(app) called_with = [] @@ -754,7 +762,7 @@ async def mock_authenticate(handler, data): base_url + 'hub/login', data=form_data, allow_redirects=False ) - assert called_with == [form_data] + assert called_with == [expected_auth] @pytest.mark.parametrize(
trim username to avoid creating of several notebook_dir volumes ### Proposed change I think it would be better if you do a `user.name.rstrip()` (maybe in the login form) in order to avoid the dummy authenticator to spawn several `notebook_dir` for the "same" username but with spaces in the end. I've recently accessed my jupyterhub via tablet and the keyboard automatically added a space after completing my username. To my surprise all my notebooks (ipynb files) were gone until I realize that the problem was that I was using a different username (containing a space in the end) . If using docker, several volumes would be created simply by adding a space or two in the username end. This can be avoided by trimming the username. Also you cannot delete a user (via webgui - hub control panel) created like this (without trimming). TIA.
Thank you for opening your first issue in this project! Engagement like this is essential for open source projects! :hugs: <br>If you haven't done so already, check out [Jupyter's Code of Conduct](https://github.com/jupyter/governance/blob/master/conduct/code_of_conduct.md). Also, please try to follow the issue template as it helps other other community members to contribute more effectively. ![welcome](https://raw.githubusercontent.com/jupyterhub/.github/master/images/welcome.jpg) You can meet the other [Jovyans](https://jupyter.readthedocs.io/en/latest/community/content-community.html?highlight=jovyan#what-is-a-jovyan) by joining our [Discourse forum](http://discourse.jupyter.org/). There is also an intro thread there where you can stop by and say Hi! :wave: <br>Welcome to the Jupyter community! :tada:
2022-08-10T06:49:19Z
[]
[]
jupyterhub/jupyterhub
4,013
jupyterhub__jupyterhub-4013
[ "3991" ]
f3d17eb77e43e548427bfee8a4291f519efe97c3
diff --git a/ci/mock-greenlet/greenlet.py b/ci/mock-greenlet/greenlet.py new file mode 100644 --- /dev/null +++ b/ci/mock-greenlet/greenlet.py @@ -0,0 +1,3 @@ +__version__ = "22.0.0.dev0" + +raise ImportError("Don't actually have greenlet")
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -71,6 +71,8 @@ jobs: # NOTE: Since only the value of these parameters are presented in the # GitHub UI when the workflow run, we avoid using true/false as # values by instead duplicating the name to signal true. + # Python versions available at: + # https://github.com/actions/python-versions/blob/HEAD/versions-manifest.json include: - python: "3.7" oldest_dependencies: oldest_dependencies @@ -85,10 +87,7 @@ jobs: subdomain: subdomain - python: "3.10" ssl: ssl - # can't test 3.11.0-beta.4 until a greenlet release - # greenlet is a dependency of sqlalchemy on linux - # see https://github.com/gevent/gevent/issues/1867 - # - python: "3.11.0-beta.4" + - python: "3.11.0-rc.1" - python: "3.10" main_dependencies: main_dependencies @@ -136,9 +135,19 @@ jobs: uses: actions/setup-python@v4 with: python-version: "${{ matrix.python }}" + - name: Install Python dependencies run: | pip install --upgrade pip + + if [[ "${{ matrix.python }}" == "3.11"* ]]; then + # greenlet is not actually required, + # but is an install dependency of sqlalchemy. + # It does not yet install on 3.11 + # see: see https://github.com/gevent/gevent/issues/1867 + pip install ./ci/mock-greenlet + fi + pip install --upgrade . -r dev-requirements.txt if [ "${{ matrix.oldest_dependencies }}" != "" ]; then
ci: test against python 3.11 As @minrk noted in https://github.com/jupyterhub/jupyterhub/pull/3976#issuecomment-1184975768, we can't yet do this > Can't test 3.11 on linux because sqlalchemy requires greenlet on linux (specifically because it's easy to install there), but greenlet can't be installed with Python 3.11 yet. Ref: https://github.com/gevent/gevent/issues/1867 > >sqlalchemy issue about how optional greenlet should be: https://github.com/sqlalchemy/sqlalchemy/issues/6136
Since gevent is technically optional, we could get tests running by producing a requirements.txt and omitting gevent, as [described here](https://stackoverflow.com/questions/52126116/prevent-pip-from-installing-some-dependencies): 1. `pip-compile requirements.txt > frozen.txt` (resolves all dependencies) 2. `grep -v gevent frozen.txt > without-gevent.txt` (remove gevent) 3. `pip install --no-deps -r without-gevent.txt` (install only listed packages, including dependencies, avoiding resolving dependencies a second time) We could also get it running by testing 3.11 on mac, where gevent is not listed as a default dependency of sqlalchemy
2022-08-10T08:09:00Z
[]
[]
jupyterhub/jupyterhub
4,019
jupyterhub__jupyterhub-4019
[ "4017" ]
71e86f30649be2c941e4c3af947e9315ce4d6c4a
diff --git a/jupyterhub/user.py b/jupyterhub/user.py --- a/jupyterhub/user.py +++ b/jupyterhub/user.py @@ -310,19 +310,19 @@ def sync_groups(self, group_names): return # log group changes - new_groups = set(group_names).difference(current_groups) + added_groups = new_groups.difference(current_groups) removed_groups = current_groups.difference(group_names) - if new_groups: - self.log.info(f"Adding user {self.name} to group(s): {new_groups}") + if added_groups: + self.log.info(f"Adding user {self.name} to group(s): {added_groups}") if removed_groups: self.log.info(f"Removing user {self.name} from group(s): {removed_groups}") if group_names: groups = ( - self.db.query(orm.Group).filter(orm.Group.name.in_(group_names)).all() + self.db.query(orm.Group).filter(orm.Group.name.in_(new_groups)).all() ) existing_groups = {g.name for g in groups} - for group_name in group_names: + for group_name in added_groups: if group_name not in existing_groups: # create groups that don't exist yet self.log.info( @@ -331,9 +331,9 @@ def sync_groups(self, group_names): group = orm.Group(name=group_name) self.db.add(group) groups.append(group) - self.groups = groups + self.orm_user.groups = groups else: - self.groups = [] + self.orm_user.groups = [] self.db.commit() async def save_auth_state(self, auth_state):
diff --git a/jupyterhub/tests/test_user.py b/jupyterhub/tests/test_user.py --- a/jupyterhub/tests/test_user.py +++ b/jupyterhub/tests/test_user.py @@ -29,12 +29,12 @@ async def test_userdict_get(db, attr): ["isin1", "isin2"], ["isin1"], ["notin", "isin1"], - ["new-group", "isin1"], + ["new-group", "new-group", "isin1"], [], ], ) def test_sync_groups(app, user, group_names): - expected = sorted(group_names) + expected = sorted(set(group_names)) db = app.db db.add(orm.Group(name="notin")) in_groups = [orm.Group(name="isin1"), orm.Group(name="isin2")]
Database error when hub tries to add existing group We enabled groups on a hub, and they seemed to be working fine for a little while, but users started to see 500 errors on logging in. One traceback indicated that the hub attempted to add an already existing group to the ORM database. The groups are based on course enrollments which we obtain from our Canvas LMS as users login. Unfortunately I don't have other tracebacks. Here is the traceback from one such instance: https://github.com/berkeley-dsep-infra/datahub/issues/3556#issuecomment-1212830090 The deployment is https://github.com/berkeley-dsep-infra/datahub and our authenticator is at https://github.com/berkeley-dsep-infra/datahub/tree/staging/images/hub/canvasauthenticator. Here is a condensed version of our `authenticate` method: ``` async def authenticate(self, handler, data=None): user = await super().authenticate(handler, data) courses = await self.get_courses(user['auth_state']['access_token']) user['groups'] = self.extract_course_groups(courses) return user ``` We've temporarily disabled the assignment to the `groups` key and that stopped the 500 errors. We [had set](https://github.com/berkeley-dsep-infra/datahub/blob/5096d43940768a3f33dca48b9c87f2c5d7fcbf91/hub/values.yaml#L194) `Authenticator.managed_groups = True` but that is also temporarily disabled. Our hub is `jupyterhub/k8s-hub:1.1.3-n554.hfa81c67f` and is using a customized KubeSpawner. Under /hub/admin we can see that 35 of the 37 groups were created during this time have only one user, while two groups have two. Our students tend to cluster in the same classes so I would normally expect higher group memberships. Some people were using the hub but hadn't yet been forced to reauthenticate due to the age of their login. I don't know how two groups managed to get two users added, given the behavior. The error from the traceback: ``` sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: groups.name [SQL: INSERT INTO groups (name) VALUES (?)] [parameters: ('canvas::1497305::student',)] ``` occurred with the group `canvas::1497305::student`, however I see no such existing group in the hub.
Is there any chance `user["groups"]` could have the same group name occurring twice? Looking at the code for sync_groups, I think it would try to create a group that doesn't exist once for each occurrence in `user["groups"]` The alternative is that the `orm.Group.name.in_` query isn't actually working. That would be harder to track down and deal with.
2022-08-19T08:59:33Z
[]
[]
jupyterhub/jupyterhub
4,032
jupyterhub__jupyterhub-4032
[ "4024" ]
c56583577349bef96b056449a5eaa7bf1645de08
diff --git a/jupyterhub/apihandlers/auth.py b/jupyterhub/apihandlers/auth.py --- a/jupyterhub/apihandlers/auth.py +++ b/jupyterhub/apihandlers/auth.py @@ -15,6 +15,11 @@ class TokenAPIHandler(APIHandler): + def check_xsrf_cookie(self): + # no xsrf check needed here + # post is just a 404 + return + @token_authenticated def get(self, token): # FIXME: deprecate this API for oauth token resolution, in favor of using /api/user @@ -378,32 +383,6 @@ async def get(self): @web.authenticated def post(self): uri, http_method, body, headers = self.extract_oauth_params() - referer = self.request.headers.get('Referer', 'no referer') - full_url = self.request.full_url() - # trim protocol, which cannot be trusted with multiple layers of proxies anyway - # Referer is set by browser, but full_url can be modified by proxy layers to appear as http - # when it is actually https - referer_proto, _, stripped_referer = referer.partition("://") - referer_proto = referer_proto.lower() - req_proto, _, stripped_full_url = full_url.partition("://") - req_proto = req_proto.lower() - if referer_proto != req_proto: - self.log.warning("Protocol mismatch: %s != %s", referer, full_url) - if req_proto == "https": - # insecure origin to secure target is not allowed - raise web.HTTPError( - 403, "Not allowing authorization form submitted from insecure page" - ) - if stripped_referer != stripped_full_url: - # OAuth post must be made to the URL it came from - self.log.error("Original OAuth POST from %s != %s", referer, full_url) - self.log.error( - "Stripped OAuth POST from %s != %s", stripped_referer, stripped_full_url - ) - raise web.HTTPError( - 403, "Authorization form must be sent from authorization page" - ) - # The scopes the user actually authorized, i.e. checkboxes # that were selected. scopes = self.get_arguments('scopes') diff --git a/jupyterhub/apihandlers/base.py b/jupyterhub/apihandlers/base.py --- a/jupyterhub/apihandlers/base.py +++ b/jupyterhub/apihandlers/base.py @@ -2,6 +2,7 @@ # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import json +import warnings from functools import lru_cache from http.client import responses from urllib.parse import parse_qs, urlencode, urlparse, urlunparse @@ -12,7 +13,7 @@ from .. import orm from ..handlers import BaseHandler from ..scopes import get_scopes_for -from ..utils import get_browser_protocol, isoformat, url_escape_path, url_path_join +from ..utils import isoformat, url_escape_path, url_path_join PAGINATION_MEDIA_TYPE = "application/jupyterhub-pagination+json" @@ -23,7 +24,6 @@ class APIHandler(BaseHandler): Differences from page handlers: - JSON responses and errors - - strict referer checking for Cookie-authenticated requests - strict content-security-policy - methods for REST API models """ @@ -49,48 +49,12 @@ def accepts_pagination(self): return PAGINATION_MEDIA_TYPE in accepts def check_referer(self): - """Check Origin for cross-site API requests. - - Copied from WebSocket with changes: - - - allow unspecified host/referer (e.g. scripts) - """ - host_header = self.app.forwarded_host_header or "Host" - host = self.request.headers.get(host_header) - if host and "," in host: - host = host.split(",", 1)[0].strip() - referer = self.request.headers.get("Referer") - - # If no header is provided, assume it comes from a script/curl. - # We are only concerned with cross-site browser stuff here. - if not host: - self.log.warning("Blocking API request with no host") - return False - if not referer: - self.log.warning("Blocking API request with no referer") - return False - - proto = get_browser_protocol(self.request) - - full_host = f"{proto}://{host}{self.hub.base_url}" - host_url = urlparse(full_host) - referer_url = urlparse(referer) - # resolve default ports for http[s] - referer_port = referer_url.port or ( - 443 if referer_url.scheme == 'https' else 80 + """DEPRECATED""" + warnings.warn( + "check_referer is deprecated in JupyterHub 3.2 and always returns True", + DeprecationWarning, + stacklevel=2, ) - host_port = host_url.port or (443 if host_url.scheme == 'https' else 80) - if ( - referer_url.scheme != host_url.scheme - or referer_url.hostname != host_url.hostname - or referer_port != host_port - or not (referer_url.path + "/").startswith(host_url.path) - ): - self.log.warning( - f"Blocking Cross Origin API request. Referer: {referer}," - f" {host_header}: {host}, Host URL: {full_host}", - ) - return False return True def check_post_content_type(self): @@ -111,6 +75,25 @@ def check_post_content_type(self): return True + async def prepare(self): + await super().prepare() + # tornado only checks xsrf on non-GET + # we also check xsrf on GETs to API endpoints + # make sure this runs after auth, which happens in super().prepare() + if self.request.method not in {"HEAD", "OPTIONS"} and self.settings.get( + "xsrf_cookies" + ): + self.check_xsrf_cookie() + + def check_xsrf_cookie(self): + if not hasattr(self, '_jupyterhub_user'): + # called too early to check if we're token-authenticated + return + if getattr(self, '_token_authenticated', False): + # if token-authenticated, ignore XSRF + return + return super().check_xsrf_cookie() + def get_current_user_cookie(self): """Extend get_user_cookie to add checks for CORS""" cookie_user = super().get_current_user_cookie() @@ -119,8 +102,6 @@ def get_current_user_cookie(self): # avoiding misleading "Blocking Cross Origin" messages # when there's no cookie set anyway. if cookie_user: - if not self.check_referer(): - return None if ( self.request.method.upper() == 'POST' and not self.check_post_content_type() @@ -518,6 +499,9 @@ class API404(APIHandler): Ensures JSON 404 errors for malformed URLs """ + def check_xsrf_cookie(self): + pass + async def prepare(self): await super().prepare() raise web.HTTPError(404) diff --git a/jupyterhub/apihandlers/hub.py b/jupyterhub/apihandlers/hub.py --- a/jupyterhub/apihandlers/hub.py +++ b/jupyterhub/apihandlers/hub.py @@ -51,6 +51,9 @@ def post(self): class RootAPIHandler(APIHandler): + def check_xsrf_cookie(self): + return + def get(self): """GET /api/ returns info about the Hub and its API. diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -337,6 +337,15 @@ async def patch(self, user_name): class UserTokenListAPIHandler(APIHandler): """API endpoint for listing/creating tokens""" + # defer check_xsrf_cookie so we can accept auth + # in the `auth` request field, which shouldn't require xsrf cookies + _skip_post_check_xsrf = True + + def check_xsrf_cookie(self): + if self.request.method == 'POST' and self._skip_post_check_xsrf: + return + return super().check_xsrf_cookie() + @needs_scope('read:tokens') def get(self, user_name): """Get tokens for a given user""" @@ -374,6 +383,7 @@ async def post(self, user_name): if isinstance(name, dict): # not a simple string so it has to be a dict name = name.get('name') + # don't check xsrf if we've authenticated via the request body except web.HTTPError as e: # turn any authentication error into 403 raise web.HTTPError(403) @@ -384,7 +394,14 @@ async def post(self, user_name): "Error authenticating request for %s: %s", self.request.uri, e ) raise web.HTTPError(403) + if name is None: + raise web.HTTPError(403) requester = self.find_user(name) + else: + # perform delayed xsrf check + # if we aren't authenticating via the request body + self._skip_post_check_xsrf = False + self.check_xsrf_cookie() if requester is None: # couldn't identify requester raise web.HTTPError(403) diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -2721,6 +2721,16 @@ def init_tornado_settings(self): ) oauth_no_confirm_list.add(service.oauth_client_id) + # configure xsrf cookie + # (user xsrf_cookie_kwargs works as override) + xsrf_cookie_kwargs = self.tornado_settings.setdefault("xsrf_cookie_kwargs", {}) + if not xsrf_cookie_kwargs: + # default to cookie_options + xsrf_cookie_kwargs.update(self.tornado_settings.get("cookie_options", {})) + + # restrict xsrf cookie to hub base path + xsrf_cookie_kwargs["path"] = self.hub.base_url + settings = dict( log_function=log_request, config=self.config, @@ -2774,6 +2784,7 @@ def init_tornado_settings(self): shutdown_on_logout=self.shutdown_on_logout, eventlog=self.eventlog, app=self, + xsrf_cookies=True, ) # allow configured settings to have priority settings.update(self.tornado_settings) diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -233,6 +233,16 @@ def set_default_headers(self): # Login and cookie-related # --------------------------------------------------------------- + def check_xsrf_cookie(self): + try: + return super().check_xsrf_cookie() + except Exception as e: + # ensure _juptyerhub_user is defined on rejected requests + if not hasattr(self, "_jupyterhub_user"): + self._jupyterhub_user = None + self._resolve_roles_and_scopes() + raise + @property def admin_users(self): return self.settings.setdefault('admin_users', set()) @@ -380,6 +390,10 @@ def get_current_user_token(self): if recorded: self.db.commit() + # record that we've been token-authenticated + # XSRF checks are skipped when using token auth + self._token_authenticated = True + if orm_token.service: return orm_token.service @@ -717,7 +731,7 @@ def get_next_url(self, user=None, default=None): if not next_url_from_param: # when a request made with ?next=... assume all the params have already been encoded # otherwise, preserve params from the current request across the redirect - next_url = self.append_query_parameters(next_url, exclude=['next']) + next_url = self.append_query_parameters(next_url, exclude=['next', '_xsrf']) return next_url def append_query_parameters(self, url, exclude=None): @@ -1257,6 +1271,7 @@ def render_template(self, name, sync=False, **ns): """ template_ns = {} template_ns.update(self.template_namespace) + template_ns["xsrf_token"] = self.xsrf_token.decode("ascii") template_ns.update(ns) template = self.get_template(name, sync) if sync: @@ -1279,6 +1294,7 @@ def template_namespace(self): services=self.get_accessible_services(user), parsed_scopes=self.parsed_scopes, expanded_scopes=self.expanded_scopes, + xsrf=self.xsrf_token.decode('ascii'), ) if self.settings['template_vars']: ns.update(self.settings['template_vars']) diff --git a/jupyterhub/handlers/login.py b/jupyterhub/handlers/login.py --- a/jupyterhub/handlers/login.py +++ b/jupyterhub/handlers/login.py @@ -101,7 +101,9 @@ def _render(self, login_error=None, username=None): "login_url": self.settings['login_url'], "authenticator_login_url": url_concat( self.authenticator.login_url(self.hub.base_url), - {'next': self.get_argument('next', '')}, + { + 'next': self.get_argument('next', ''), + }, ), } custom_html = Template( @@ -147,7 +149,10 @@ async def get(self): async def post(self): # parse the arguments dict data = {} - for arg in self.request.arguments: + for arg in self.request.body_arguments: + if arg == "_xsrf": + # don't include xsrf token in auth input + continue # strip username, but not other fields like passwords, # which should be allowed to start or end with space data[arg] = self.get_argument(arg, strip=arg == "username") diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -99,7 +99,9 @@ async def _render_form(self, for_user, spawner_options_form, message=''): auth_state=auth_state, spawner_options_form=spawner_options_form, error_message=message, - url=self.request.uri, + url=url_concat( + self.request.uri, {"_xsrf": self.xsrf_token.decode('ascii')} + ), spawner=for_user.spawner, ) @@ -404,7 +406,9 @@ async def get(self, user_name, server_name=''): page, user=user, spawner=spawner, - progress_url=spawner._progress_url, + progress_url=url_concat( + spawner._progress_url, {"_xsrf": self.xsrf_token.decode('ascii')} + ), auth_state=auth_state, ) self.finish(html) diff --git a/jupyterhub/log.py b/jupyterhub/log.py --- a/jupyterhub/log.py +++ b/jupyterhub/log.py @@ -66,7 +66,7 @@ def formatException(self, exc_info): # url params to be scrubbed if seen # any url param that *contains* one of these # will be scrubbed from logs -SCRUB_PARAM_KEYS = ('token', 'auth', 'key', 'code', 'state') +SCRUB_PARAM_KEYS = ('token', 'auth', 'key', 'code', 'state', '_xsrf') def _scrub_uri(uri):
diff --git a/jupyterhub/tests/mocking.py b/jupyterhub/tests/mocking.py --- a/jupyterhub/tests/mocking.py +++ b/jupyterhub/tests/mocking.py @@ -36,6 +36,7 @@ from urllib.parse import urlparse from pamela import PAMError +from tornado.httputil import url_concat from traitlets import Bool, Dict, default from .. import metrics, orm, roles @@ -354,14 +355,25 @@ async def login_user(self, name): external_ca = None if self.internal_ssl: external_ca = self.external_certs['files']['ca'] + login_url = base_url + 'hub/login' + r = await async_requests.get(login_url) + r.raise_for_status() + xsrf = r.cookies['_xsrf'] + r = await async_requests.post( - base_url + 'hub/login', + url_concat(login_url, {"_xsrf": xsrf}), + cookies=r.cookies, data={'username': name, 'password': name}, allow_redirects=False, verify=external_ca, ) r.raise_for_status() - assert r.cookies + r.cookies["_xsrf"] = xsrf + assert sorted(r.cookies.keys()) == [ + '_xsrf', + 'jupyterhub-hub-login', + 'jupyterhub-session-id', + ] return r.cookies diff --git a/jupyterhub/tests/test_api.py b/jupyterhub/tests/test_api.py --- a/jupyterhub/tests/test_api.py +++ b/jupyterhub/tests/test_api.py @@ -6,7 +6,7 @@ import uuid from datetime import datetime, timedelta from unittest import mock -from urllib.parse import quote, urlparse, urlunparse +from urllib.parse import quote, urlparse from pytest import fixture, mark from tornado.httputil import url_concat @@ -95,108 +95,31 @@ async def test_post_content_type(app, content_type, status): assert r.status_code == status [email protected]("xsrf_in_url", [True, False]) @mark.parametrize( - "host, referer, extraheaders, status", + "method, path", [ - ('$host', '$url', {}, 200), - (None, None, {}, 200), - (None, 'null', {}, 403), - (None, 'http://attack.com/csrf/vulnerability', {}, 403), - ('$host', {"path": "/user/someuser"}, {}, 403), - ('$host', {"path": "{path}/foo/bar/subpath"}, {}, 200), - # mismatch host - ("mismatch.com", "$url", {}, 403), - # explicit host, matches - ("fake.example", {"netloc": "fake.example"}, {}, 200), - # explicit port, matches implicit port - ("fake.example:80", {"netloc": "fake.example"}, {}, 200), - # explicit port, mismatch - ("fake.example:81", {"netloc": "fake.example"}, {}, 403), - # implicit ports, mismatch proto - ("fake.example", {"netloc": "fake.example", "scheme": "https"}, {}, 403), - # explicit ports, match - ("fake.example:81", {"netloc": "fake.example:81"}, {}, 200), - # Test proxy protocol defined headers taken into account by utils.get_browser_protocol - ( - "fake.example", - {"netloc": "fake.example", "scheme": "https"}, - {'X-Scheme': 'https'}, - 200, - ), - ( - "fake.example", - {"netloc": "fake.example", "scheme": "https"}, - {'X-Forwarded-Proto': 'https'}, - 200, - ), - ( - "fake.example", - {"netloc": "fake.example", "scheme": "https"}, - { - 'Forwarded': 'host=fake.example;proto=https,for=1.2.34;proto=http', - 'X-Scheme': 'http', - }, - 200, - ), - ( - "fake.example", - {"netloc": "fake.example", "scheme": "https"}, - { - 'Forwarded': 'host=fake.example;proto=http,for=1.2.34;proto=http', - 'X-Scheme': 'https', - }, - 403, - ), - ("fake.example", {"netloc": "fake.example"}, {'X-Scheme': 'https'}, 403), - ("fake.example", {"netloc": "fake.example"}, {'X-Scheme': 'https, http'}, 403), + ("GET", "user"), + ("POST", "users/{username}/tokens"), ], ) -async def test_cors_check(request, app, host, referer, extraheaders, status): - url = ujoin(public_host(app), app.hub.base_url) - real_host = urlparse(url).netloc - if host == "$host": - host = real_host - - if referer == '$url': - referer = url - elif isinstance(referer, dict): - parsed_url = urlparse(url) - # apply {} - url_ns = {key: getattr(parsed_url, key) for key in parsed_url._fields} - for key, value in referer.items(): - referer[key] = value.format(**url_ns) - referer = urlunparse(parsed_url._replace(**referer)) - - # disable default auth header, cors is for cookie auth - headers = {"Authorization": ""} - if host is not None: - headers['X-Forwarded-Host'] = host - if referer is not None: - headers['Referer'] = referer - headers.update(extraheaders) - - # add admin user - user = find_user(app.db, 'admin') - if user is None: - user = add_user(app.db, name='admin', admin=True) - cookies = await app.login_user('admin') - - # test custom forwarded_host_header behavior - app.forwarded_host_header = 'X-Forwarded-Host' - - # reset the config after the test to avoid leaking state - def reset_header(): - app.forwarded_host_header = "" - - request.addfinalizer(reset_header) +async def test_xsrf_check(app, username, method, path, xsrf_in_url): + cookies = await app.login_user(username) + xsrf = cookies['_xsrf'] + url = path.format(username=username) + if xsrf_in_url: + url = f"{url}?_xsrf={xsrf}" r = await api_request( app, - 'users', - headers=headers, + url, + noauth=True, cookies=cookies, ) - assert r.status_code == status + if xsrf_in_url: + assert r.status_code == 200 + else: + assert r.status_code == 403 # -------------- diff --git a/jupyterhub/tests/test_named_servers.py b/jupyterhub/tests/test_named_servers.py --- a/jupyterhub/tests/test_named_servers.py +++ b/jupyterhub/tests/test_named_servers.py @@ -6,6 +6,7 @@ from urllib.parse import unquote, urlencode, urlparse import pytest +from bs4 import BeautifulSoup from requests.exceptions import HTTPError from tornado.httputil import url_concat @@ -13,7 +14,7 @@ from ..utils import url_escape_path, url_path_join from .mocking import FormSpawner from .test_api import TIMESTAMP, add_user, api_request, fill_user, normalize_user -from .utils import async_requests, get_page, public_url +from .utils import async_requests, get_page, public_host, public_url @pytest.fixture @@ -372,6 +373,9 @@ async def test_named_server_spawn_form(app, username, named_servers): r.raise_for_status() assert r.url.endswith(f'/spawn/{username}/{server_name}') assert FormSpawner.options_form in r.text + spawn_page = BeautifulSoup(r.text, 'html.parser') + form = spawn_page.find("form") + action_url = public_host(app) + form["action"] # submit the form next_url = url_path_join( @@ -379,7 +383,7 @@ async def test_named_server_spawn_form(app, username, named_servers): ) r = await async_requests.post( url_concat( - url_path_join(base_url, 'hub/spawn', username, server_name), + action_url, {'next': next_url}, ), cookies=cookies, diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -6,7 +6,6 @@ import pytest from bs4 import BeautifulSoup -from tornado.escape import url_escape from tornado.httputil import url_concat from .. import orm, roles, scopes @@ -380,8 +379,15 @@ async def test_spawn_form(app): u = app.users[orm_u] await u.stop() next_url = ujoin(app.base_url, 'user/jones/tree') + r = await async_requests.get( + url_concat(ujoin(base_url, 'spawn'), {'next': next_url}), cookies=cookies + ) + r.raise_for_status() + spawn_page = BeautifulSoup(r.text, 'html.parser') + form = spawn_page.find("form") + action_url = public_host(app) + form["action"] r = await async_requests.post( - url_concat(ujoin(base_url, 'spawn'), {'next': next_url}), + action_url, cookies=cookies, data={'bounds': ['-1', '1'], 'energy': '511keV'}, ) @@ -419,8 +425,22 @@ async def test_spawn_form_other_user( base_url = ujoin(public_host(app), app.hub.base_url) next_url = ujoin(app.base_url, 'user', user.name, 'tree') + url = ujoin(base_url, 'spawn', user.name) + r = await async_requests.get( + url_concat(url, {'next': next_url}), + cookies=cookies, + ) + if has_access: + r.raise_for_status() + spawn_page = BeautifulSoup(r.text, 'html.parser') + form = spawn_page.find("form") + action_url = ujoin(public_host(app), form["action"]) + else: + assert r.status_code == 404 + action_url = url_concat(url, {"_xsrf": cookies['_xsrf']}) + r = await async_requests.post( - url_concat(ujoin(base_url, 'spawn', user.name), {'next': next_url}), + action_url, cookies=cookies, data={'bounds': ['-3', '3'], 'energy': '938MeV'}, ) @@ -450,9 +470,19 @@ async def test_spawn_form_with_file(app): orm_u = orm.User.find(app.db, 'jones') u = app.users[orm_u] await u.stop() + url = ujoin(base_url, 'spawn') + + r = await async_requests.get( + url, + cookies=cookies, + ) + r.raise_for_status() + spawn_page = BeautifulSoup(r.text, 'html.parser') + form = spawn_page.find("form") + action_url = public_host(app) + form["action"] r = await async_requests.post( - ujoin(base_url, 'spawn'), + action_url, cookies=cookies, data={'bounds': ['-1', '1'], 'energy': '511keV'}, files={'hello': ('hello.txt', b'hello world\n')}, @@ -642,58 +672,6 @@ async def test_other_user_url(app, username, user, group, create_temp_role, has_ ) [email protected]( - 'url, params, redirected_url, form_action', - [ - ( - # spawn?param=value - # will encode given parameters for an unauthenticated URL in the next url - # the next parameter will contain the app base URL (replaces BASE_URL in tests) - 'spawn', - [('param', 'value')], - '/hub/login?next={{BASE_URL}}hub%2Fspawn%3Fparam%3Dvalue', - '/hub/login?next={{BASE_URL}}hub%2Fspawn%3Fparam%3Dvalue', - ), - ( - # login?param=fromlogin&next=encoded(/hub/spawn?param=value) - # will drop parameters given to the login page, passing only the next url - 'login', - [('param', 'fromlogin'), ('next', '/hub/spawn?param=value')], - '/hub/login?param=fromlogin&next=%2Fhub%2Fspawn%3Fparam%3Dvalue', - '/hub/login?next=%2Fhub%2Fspawn%3Fparam%3Dvalue', - ), - ( - # login?param=value&anotherparam=anothervalue - # will drop parameters given to the login page, and use an empty next url - 'login', - [('param', 'value'), ('anotherparam', 'anothervalue')], - '/hub/login?param=value&anotherparam=anothervalue', - '/hub/login?next=', - ), - ( - # login - # simplest case, accessing the login URL, gives an empty next url - 'login', - [], - '/hub/login', - '/hub/login?next=', - ), - ], -) -async def test_login_page(app, url, params, redirected_url, form_action): - url = url_concat(url, params) - r = await get_page(url, app) - redirected_url = redirected_url.replace('{{BASE_URL}}', url_escape(app.base_url)) - assert r.url.endswith(redirected_url) - # now the login.html rendered template must include the given parameters in the form - # action URL, including the next URL - page = BeautifulSoup(r.text, "html.parser") - form = page.find("form", method="post") - action = form.attrs['action'] - form_action = form_action.replace('{{BASE_URL}}', url_escape(app.base_url)) - assert action.endswith(form_action) - - @pytest.mark.parametrize( "url, token_in", [ @@ -722,11 +700,13 @@ async def test_page_with_token(app, user, url, token_in): allow_redirects=False, ) if "/hub/login" in r.url: + cookies = {'_xsrf'} assert r.status_code == 200 else: + cookies = set() assert r.status_code == 302 assert r.headers["location"].partition("?")[0].endswith("/hub/login") - assert not r.cookies + assert {c.name for c in r.cookies} == cookies async def test_login_fail(app): @@ -737,7 +717,7 @@ async def test_login_fail(app): data={'username': name, 'password': 'wrong'}, allow_redirects=False, ) - assert not r.cookies + assert set(r.cookies.keys()).issubset({"_xsrf"}) @pytest.mark.parametrize( @@ -758,8 +738,16 @@ async def mock_authenticate(handler, data): called_with.append(data) with mock.patch.object(app.authenticator, 'authenticate', mock_authenticate): + r = await async_requests.get(base_url + 'hub/login') + r.raise_for_status() + cookies = r.cookies + xsrf = cookies['_xsrf'] + page = BeautifulSoup(r.text, "html.parser") + action_url = public_host(app) + page.find("form")["action"] + xsrf_input = page.find("form").find("input", attrs={"name": "_xsrf"}) + form_data["_xsrf"] = xsrf_input["value"] await async_requests.post( - base_url + 'hub/login', data=form_data, allow_redirects=False + action_url, data=form_data, allow_redirects=False, cookies=cookies ) assert called_with == [expected_auth] diff --git a/jupyterhub/tests/test_services_auth.py b/jupyterhub/tests/test_services_auth.py --- a/jupyterhub/tests/test_services_auth.py +++ b/jupyterhub/tests/test_services_auth.py @@ -339,7 +339,8 @@ async def test_oauth_service_roles( data = {} if scope_values: data["scopes"] = scope_values - r = await s.post(r.url, data=data, headers={'Referer': r.url}) + data["_xsrf"] = s.cookies["_xsrf"] + r = await s.post(r.url, data=data) r.raise_for_status() assert r.url == url # verify oauth cookie is set @@ -436,7 +437,7 @@ async def test_oauth_access_scopes( assert set(r.history[0].cookies.keys()) == {'service-%s-oauth-state' % service.name} # submit the oauth form to complete authorization - r = await s.post(r.url, headers={'Referer': r.url}) + r = await s.post(r.url, data={"_xsrf": s.cookies["_xsrf"]}) r.raise_for_status() assert r.url == url # verify oauth cookie is set @@ -549,7 +550,7 @@ async def test_oauth_cookie_collision(app, mockservice_url, create_user_with_sco # finish oauth 2 # submit the oauth form to complete authorization r = await s.post( - oauth_2.url, data={'scopes': ['identify']}, headers={'Referer': oauth_2.url} + oauth_2.url, data={'scopes': ['identify'], "_xsrf": s.cookies["_xsrf"]} ) r.raise_for_status() assert r.url == url @@ -561,7 +562,7 @@ async def test_oauth_cookie_collision(app, mockservice_url, create_user_with_sco # finish oauth 1 r = await s.post( - oauth_1.url, data={'scopes': ['identify']}, headers={'Referer': oauth_1.url} + oauth_1.url, data={'scopes': ['identify'], "_xsrf": s.cookies["_xsrf"]} ) r.raise_for_status() assert r.url == url @@ -606,7 +607,7 @@ def auth_tokens(): r.raise_for_status() assert urlparse(r.url).path.endswith('oauth2/authorize') # submit the oauth form to complete authorization - r = await s.post(r.url, data={'scopes': ['identify']}, headers={'Referer': r.url}) + r = await s.post(r.url, data={'scopes': ['identify'], "_xsrf": s.cookies["_xsrf"]}) r.raise_for_status() assert r.url == url @@ -631,7 +632,7 @@ def auth_tokens(): r = await s.get(public_url(app, path='hub/logout')) r.raise_for_status() # verify that all cookies other than the service cookie are cleared - assert list(s.cookies.keys()) == [service_cookie_name] + assert sorted(s.cookies.keys()) == ["_xsrf", service_cookie_name] # verify that clearing session id invalidates service cookie # i.e. redirect back to login page r = await s.get(url) diff --git a/jupyterhub/tests/test_singleuser.py b/jupyterhub/tests/test_singleuser.py --- a/jupyterhub/tests/test_singleuser.py +++ b/jupyterhub/tests/test_singleuser.py @@ -114,7 +114,7 @@ async def test_singleuser_auth( return r.raise_for_status() # submit the oauth form to complete authorization - r = await s.post(r.url, data={'scopes': ['identify']}, headers={'Referer': r.url}) + r = await s.post(r.url, data={'scopes': ['identify'], '_xsrf': s.cookies['_xsrf']}) final_url = urlparse(r.url).path.rstrip('/') final_path = url_path_join( '/user/', user.name, spawner.name, spawner.default_url or "/tree" diff --git a/jupyterhub/tests/utils.py b/jupyterhub/tests/utils.py --- a/jupyterhub/tests/utils.py +++ b/jupyterhub/tests/utils.py @@ -6,6 +6,7 @@ import pytest import requests from certipy import Certipy +from tornado.httputil import url_concat from jupyterhub import metrics, orm from jupyterhub.objects import Server @@ -161,13 +162,14 @@ async def api_request( h.update(headers) h.update(auth_header(app.db, kwargs.pop('name', 'admin'))) + url = ujoin(base_url, 'api', *api_path) + if 'cookies' in kwargs: # for cookie-authenticated requests, - # set Referer so it looks like the request originated - # from a Hub-served page - headers.setdefault('Referer', ujoin(base_url, 'test')) + # add _xsrf to url params + if "_xsrf" in kwargs['cookies'] and not noauth: + url = url_concat(url, {"_xsrf": kwargs['cookies']['_xsrf']}) - url = ujoin(base_url, 'api', *api_path) f = getattr(async_requests, method) if app.internal_ssl: kwargs['cert'] = (app.internal_ssl_cert, app.internal_ssl_key)
Users unable to restart their own server Hi, recently upgraded JupyterHub from 1.1.0 to 2.3.1. After upgrading our users are no longer able to use File -> Hub Control Panel -> Stop My Server the following error is shown ``` API request failed (403): Action is not authorized with current scopes; requires any of [delete:servers] ``` Looks like I might have to add a role to the jupyterhub_config.py to bestow "delete:servers" but I don't understand how to write one to apply to all users. Can you please help?
Thank you for opening your first issue in this project! Engagement like this is essential for open source projects! :hugs: <br>If you haven't done so already, check out [Jupyter's Code of Conduct](https://github.com/jupyter/governance/blob/master/conduct/code_of_conduct.md). Also, please try to follow the issue template as it helps other other community members to contribute more effectively. ![welcome](https://raw.githubusercontent.com/jupyterhub/.github/master/images/welcome.jpg) You can meet the other [Jovyans](https://jupyter.readthedocs.io/en/latest/community/content-community.html?highlight=jovyan#what-is-a-jovyan) by joining our [Discourse forum](http://discourse.jupyter.org/). There is also an intro thread there where you can stop by and say Hi! :wave: <br>Welcome to the Jupyter community! :tada: Hello, I am seeing the same on my deployment. There seems to be a change in the way certain bit of the UI query the backend. I am using helm to deploy my instances, and when comparing stable and beta deployments (roughly correspond to your hub versions) I see the web UI in the beta deployment does queries the API directly, whereas the previous stable webUI does not use the /API. I am not sure why users authenticated on the browser cannot use the API, but that seems to be the main issue I am facing. I cannot query anything other than the root /api/, with the admin user. Hello again, Okay I know what my trouble is. I set `hub.baseUrl` to a sub path for my instances. The API doesn't seem to like that, as when I deploy to a '/' path, it works happily. So my "/some_sub_path/" is causing my issues. Do you run your Jupyterhub instance on a sub path? Thanks for looking into this @ajcollett. I do not set `hub.baseUrl`. But you did give me an idea though. I run a CDN (CloudFront) in front of the jupyter server, it acts like a proxy and it handles https termination etc. I just tried accessing the jupyter server directly and when using the Hub Control Panel to restart the server the error does not appear. So something in the new jupyterhub/lab version must be conflicting with CloudFront. I will try analysing the http requests to see how the auth permissions are sent from the browser to the server as CloudFront must be interfering with it. @blair-anson this is actually the case with my situation too. I tested removing the path without going through out reverse proxy, Pomerium. When I test **with** the path, but bypassing Pomerium, then it works. So this is probably a headers thing. I'll also look into this. So, my issue seems to stem from here: https://github.com/jupyterhub/jupyterhub/blob/7a48da1916cad8668c8d9aa5f2019b236354cb94/jupyterhub/utils.py#L743 I see `Blocking Cross Origin API request. Referer: https://myhost/hub/admin, X-Forwarded-Host: myhost, Host URL: http://myhost/hub/` In the hub logs, but I don't know where to convince jhub it's actually https. The browser is at https, and so are all the reverse proxies in-between. Somehow, in that code, it concludes the "host url" proto is http. This then doesn't match the referrer scheme and blocks it. Okay, I managed to get things working in my case. I had to set the nginx ingress on K8s to use ssl as well as Jupyterhub, then my reverse proxy via Pomerium would work. So somewhere in the chain the wrong scheme was being passed down. For your case, maybe you need to use HTTPS between your server and CloudFlare? You may need to set CloudFlare SSL to strict, see here: https://stackoverflow.com/questions/23121800/nginx-redirect-loop-with-ssl
2022-09-09T11:43:21Z
[]
[]
jupyterhub/jupyterhub
4,053
jupyterhub__jupyterhub-4053
[ "4038" ]
666b3cb36eb57d0ed58f372561ed926abac9934b
diff --git a/jupyterhub/apihandlers/users.py b/jupyterhub/apihandlers/users.py --- a/jupyterhub/apihandlers/users.py +++ b/jupyterhub/apihandlers/users.py @@ -502,17 +502,19 @@ async def post(self, user_name, server_name=''): if server_name: if not self.allow_named_servers: raise web.HTTPError(400, "Named servers are not enabled.") - if ( - self.named_server_limit_per_user > 0 - and server_name not in user.orm_spawners - ): + + named_server_limit_per_user = ( + await self.get_current_user_named_server_limit() + ) + + if named_server_limit_per_user > 0 and server_name not in user.orm_spawners: named_spawners = list(user.all_spawners(include_default=False)) - if self.named_server_limit_per_user <= len(named_spawners): + if named_server_limit_per_user <= len(named_spawners): raise web.HTTPError( 400, "User {} already has the maximum of {} named servers." " One must be deleted before a new server can be created".format( - user_name, self.named_server_limit_per_user + user_name, named_server_limit_per_user ), ) spawner = user.get_spawner(server_name, replace_failed=True) diff --git a/jupyterhub/app.py b/jupyterhub/app.py --- a/jupyterhub/app.py +++ b/jupyterhub/app.py @@ -1150,14 +1150,27 @@ def _authenticator_default(self): False, help="Allow named single-user servers per user" ).tag(config=True) - named_server_limit_per_user = Integer( - 0, + named_server_limit_per_user = Union( + [Integer(), Callable()], + default_value=0, help=""" Maximum number of concurrent named servers that can be created by a user at a time. Setting this can limit the total resources a user can consume. If set to 0, no limit is enforced. + + Can be an integer or a callable/awaitable based on the handler object: + + :: + + def named_server_limit_per_user_fn(handler): + user = handler.current_user + if user and user.admin: + return 0 + return 5 + + c.JupyterHub.named_server_limit_per_user = named_server_limit_per_user_fn """, ).tag(config=True) diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -248,6 +248,17 @@ def redirect_to_server(self): def authenticate_prometheus(self): return self.settings.get('authenticate_prometheus', True) + async def get_current_user_named_server_limit(self): + """ + Return named server limit for current user. + """ + named_server_limit_per_user = self.named_server_limit_per_user + + if callable(named_server_limit_per_user): + return await maybe_future(named_server_limit_per_user(self)) + + return named_server_limit_per_user + def get_auth_token(self): """Get the authorization token from Authorization header""" auth_header = self.request.headers.get('Authorization', '') diff --git a/jupyterhub/handlers/pages.py b/jupyterhub/handlers/pages.py --- a/jupyterhub/handlers/pages.py +++ b/jupyterhub/handlers/pages.py @@ -72,7 +72,7 @@ async def get(self): user=user, url=url, allow_named_servers=self.allow_named_servers, - named_server_limit_per_user=self.named_server_limit_per_user, + named_server_limit_per_user=await self.get_current_user_named_server_limit(), url_path_join=url_path_join, # can't use user.spawners because the stop method of User pops named servers from user.spawners when they're stopped spawners=user.orm_user._orm_spawners, @@ -129,17 +129,19 @@ async def _get(self, user_name, server_name): if server_name: if not self.allow_named_servers: raise web.HTTPError(400, "Named servers are not enabled.") - if ( - self.named_server_limit_per_user > 0 - and server_name not in user.orm_spawners - ): + + named_server_limit_per_user = ( + await self.get_current_user_named_server_limit() + ) + + if named_server_limit_per_user > 0 and server_name not in user.orm_spawners: named_spawners = list(user.all_spawners(include_default=False)) - if self.named_server_limit_per_user <= len(named_spawners): + if named_server_limit_per_user <= len(named_spawners): raise web.HTTPError( 400, "User {} already has the maximum of {} named servers." " One must be deleted before a new server can be created".format( - user.name, self.named_server_limit_per_user + user.name, named_server_limit_per_user ), ) @@ -458,7 +460,7 @@ async def get(self): auth_state=auth_state, admin_access=True, allow_named_servers=self.allow_named_servers, - named_server_limit_per_user=self.named_server_limit_per_user, + named_server_limit_per_user=await self.get_current_user_named_server_limit(), server_version=f'{__version__} {self.version_hash}', api_page_limit=self.settings["api_page_default_limit"], base_url=self.settings["base_url"],
diff --git a/jupyterhub/tests/test_named_servers.py b/jupyterhub/tests/test_named_servers.py --- a/jupyterhub/tests/test_named_servers.py +++ b/jupyterhub/tests/test_named_servers.py @@ -25,6 +25,25 @@ def named_servers(app): yield [email protected] +def named_servers_with_callable_limit(app): + def named_server_limit_per_user_fn(handler): + """Limit number of named servers to `2` for non-admin users. No limit for admin users.""" + user = handler.current_user + if user and user.admin: + return 0 + return 2 + + with mock.patch.dict( + app.tornado_settings, + { + 'allow_named_servers': True, + 'named_server_limit_per_user': named_server_limit_per_user_fn, + }, + ): + yield + + @pytest.fixture def default_server_name(app, named_servers): """configure app to use a default server name""" @@ -292,6 +311,57 @@ async def test_named_server_limit(app, named_servers): assert r.text == '' [email protected]( + 'username,admin', + [ + ('nonsuperfoo', False), + ('superfoo', True), + ], +) +async def test_named_server_limit_as_callable( + app, named_servers_with_callable_limit, username, admin +): + """Test named server limit based on `named_server_limit_per_user_fn` callable""" + user = add_user(app.db, app, name=username, admin=admin) + cookies = await app.login_user(username) + + # Create 1st named server + servername1 = 'bar-1' + r = await api_request( + app, 'users', username, 'servers', servername1, method='post', cookies=cookies + ) + r.raise_for_status() + assert r.status_code == 201 + assert r.text == '' + + # Create 2nd named server + servername2 = 'bar-2' + r = await api_request( + app, 'users', username, 'servers', servername2, method='post', cookies=cookies + ) + r.raise_for_status() + assert r.status_code == 201 + assert r.text == '' + + # Create 3rd named server + servername3 = 'bar-3' + r = await api_request( + app, 'users', username, 'servers', servername3, method='post', cookies=cookies + ) + + # No named server limit for admin users as in `named_server_limit_per_user_fn` callable + if admin: + r.raise_for_status() + assert r.status_code == 201 + assert r.text == '' + else: + assert r.status_code == 400 + assert r.json() == { + "status": 400, + "message": f"User {username} already has the maximum of 2 named servers. One must be deleted before a new server can be created", + } + + async def test_named_server_spawn_form(app, username, named_servers): server_name = "myserver" base_url = public_url(app)
Named server limit per user indeed <!-- Thank you for contributing. These HTML comments will not render in the issue, but you can delete them once you've read them if you prefer! --> Would it be doable to set `named_server_limit_per_user` type as Callable as well? ```python def named_server_limit_per_user(user): if user.name == 'user': return 10 return 0 c.JupyterHub.named_server_limit_per_user = named_server_limit_per_user ``` ### Proposed change <!-- Use this section to describe the feature you'd like to be added. --> Open to discussion. ### Alternative options - Introduce `named_server_limit_hook` - Introduce `named_server_limit` attribute per user - Introduce general quota service ### Who would use this feature? Administrator needs to set how much server each user is limited to spawn simultaneously.
Thank you for opening your first issue in this project! Engagement like this is essential for open source projects! :hugs: <br>If you haven't done so already, check out [Jupyter's Code of Conduct](https://github.com/jupyter/governance/blob/master/conduct/code_of_conduct.md). Also, please try to follow the issue template as it helps other other community members to contribute more effectively. ![welcome](https://raw.githubusercontent.com/jupyterhub/.github/master/images/welcome.jpg) You can meet the other [Jovyans](https://jupyter.readthedocs.io/en/latest/community/content-community.html?highlight=jovyan#what-is-a-jovyan) by joining our [Discourse forum](http://discourse.jupyter.org/). There is also an intro thread there where you can stop by and say Hi! :wave: <br>Welcome to the Jupyter community! :tada: Yes, allowing a Callable here should be just fine.
2022-09-26T04:39:13Z
[]
[]
jupyterhub/jupyterhub
4,230
jupyterhub__jupyterhub-4230
[ "4202" ]
eac96acadd29efbcfa8b1552f898931c7ff2f8e3
diff --git a/jupyterhub/handlers/base.py b/jupyterhub/handlers/base.py --- a/jupyterhub/handlers/base.py +++ b/jupyterhub/handlers/base.py @@ -542,8 +542,6 @@ def clear_login_cookie(self, name=None): '_xsrf', **clear_xsrf_cookie_kwargs, ) - # Reset _jupyterhub_user - self._jupyterhub_user = None def _set_cookie(self, key, value, encrypted=True, **overrides): """Setting any cookie should go through here diff --git a/jupyterhub/handlers/login.py b/jupyterhub/handlers/login.py --- a/jupyterhub/handlers/login.py +++ b/jupyterhub/handlers/login.py @@ -84,6 +84,9 @@ async def get(self): """ await self.default_handle_logout() await self.handle_logout() + # clear jupyterhub user before rendering logout page + # ensures the login button is shown instead of logout + self._jupyterhub_user = None await self.render_logout_page()
diff --git a/jupyterhub/tests/test_pages.py b/jupyterhub/tests/test_pages.py --- a/jupyterhub/tests/test_pages.py +++ b/jupyterhub/tests/test_pages.py @@ -942,6 +942,14 @@ async def test_auto_login_logout(app): logout_url = public_host(app) + app.tornado_settings['logout_url'] assert r.url == logout_url assert r.cookies == {} + # don't include logged-out user in page: + try: + idx = r.text.index(name) + except ValueError: + # not found, good! + pass + else: + assert name not in r.text[idx - 100 : idx + 100] async def test_logout(app):
Added prehandle_logout This pull request is to allow subclasses the ability to perform some action before starting the logout process. Use cases include: calling `self.current_user` right before logout. For example, app may need to perform some action with the user object (like removing information from a cache) before its unset via `self.default_logout()`. `self.current_user` is not exposed to the override-able method `self.handle_logout()` if `self.shutdown_on_logout` is specified.
Thanks for submitting your first pull request! You are awesome! :hugs: <br>If you haven't done so already, check out [Jupyter's Code of Conduct](https://github.com/jupyter/governance/blob/master/conduct/code_of_conduct.md). Also, please make sure you followed the pull request template, as this will help us review your contribution more quickly. ![welcome](https://raw.githubusercontent.com/jupyterhub/.github/master/images/welcome.jpg) You can meet the other [Jovyans](https://jupyter.readthedocs.io/en/latest/community/content-community.html?highlight=jovyan#what-is-a-jovyan) by joining our [Discourse forum](http://discourse.jupyter.org/). There is also a intro thread there where you can stop by and say Hi! :wave: <br>Welcome to the Jupyter community! :tada: Thanks for the PR! Here's a question: if we fixed `self.current_user` so it's available in `handle_logout()`, would that solve your problem? If so, I might go for that rather than defining a new hook. @minrk Thanks for the feedback and I think that would solve the problem. How that would be implemented since `default_handle_logout()` sets `self.current_user` to `None`?
2022-11-29T09:04:42Z
[]
[]