|
| 1 | +"""Integration tests of authorization running under jupyter-server.""" |
| 2 | +import json |
| 3 | +import os |
| 4 | +import socket |
| 5 | +import subprocess |
| 6 | +import time |
| 7 | +import uuid |
| 8 | +from typing import Generator, Tuple |
| 9 | +from urllib.error import HTTPError, URLError |
| 10 | +from urllib.request import urlopen |
| 11 | + |
| 12 | +import pytest |
| 13 | + |
| 14 | +from .conftest import KNOWN_SERVERS |
| 15 | + |
| 16 | +LOCALHOST = "127.0.0.1" |
| 17 | +REST_ROUTES = ["/lsp/status"] |
| 18 | +WS_ROUTES = [f"/lsp/ws/{ls}" for ls in KNOWN_SERVERS] |
| 19 | + |
| 20 | + |
| 21 | +@pytest.mark.parametrize("route", REST_ROUTES) |
| 22 | +def test_auth_rest(route: str, a_server_url_and_token: Tuple[str, str]) -> None: |
| 23 | + """Verify a REST route only provides access to an authenticated user.""" |
| 24 | + base_url, token = a_server_url_and_token |
| 25 | + |
| 26 | + verify_response(base_url, route) |
| 27 | + |
| 28 | + url = f"{base_url}{route}" |
| 29 | + |
| 30 | + with urlopen(f"{url}?token={token}") as response: |
| 31 | + raw_body = response.read().decode("utf-8") |
| 32 | + |
| 33 | + decode_error = None |
| 34 | + |
| 35 | + try: |
| 36 | + json.loads(raw_body) |
| 37 | + except json.decoder.JSONDecodeError as err: |
| 38 | + decode_error = err |
| 39 | + assert not decode_error, f"the response for {url} was not JSON" |
| 40 | + |
| 41 | + |
| 42 | +@pytest.mark.parametrize("route", WS_ROUTES) |
| 43 | +def test_auth_websocket(route: str, a_server_url_and_token: Tuple[str, str]) -> None: |
| 44 | + """Verify a WebSocket does not provide access to an unauthenticated user.""" |
| 45 | + verify_response(a_server_url_and_token[0], route) |
| 46 | + |
| 47 | + |
| 48 | +@pytest.fixture(scope="module") |
| 49 | +def a_server_url_and_token( |
| 50 | + tmp_path_factory: pytest.TempPathFactory, |
| 51 | +) -> Generator[Tuple[str, str], None, None]: |
| 52 | + """Start a temporary, isolated jupyter server.""" |
| 53 | + token = str(uuid.uuid4()) |
| 54 | + port = get_unused_port() |
| 55 | + |
| 56 | + root_dir = tmp_path_factory.mktemp("root_dir") |
| 57 | + home = tmp_path_factory.mktemp("home") |
| 58 | + server_conf = home / "etc/jupyter/jupyter_config.json" |
| 59 | + |
| 60 | + server_conf.parent.mkdir(parents=True) |
| 61 | + extensions = {"jupyter_lsp": True, "jupyterlab": False, "nbclassic": False} |
| 62 | + app = {"jpserver_extensions": extensions, "token": token} |
| 63 | + config_data = {"ServerApp": app, "IdentityProvider": {"token": token}} |
| 64 | + |
| 65 | + server_conf.write_text(json.dumps(config_data), encoding="utf-8") |
| 66 | + args = ["jupyter-server", f"--port={port}", "--no-browser"] |
| 67 | + env = dict(os.environ) |
| 68 | + env.update( |
| 69 | + HOME=str(home), |
| 70 | + USERPROFILE=str(home), |
| 71 | + JUPYTER_CONFIG_DIR=str(server_conf.parent), |
| 72 | + ) |
| 73 | + proc = subprocess.Popen(args, cwd=str(root_dir), env=env, stdin=subprocess.PIPE) |
| 74 | + url = f"http://{LOCALHOST}:{port}" |
| 75 | + retries = 20 |
| 76 | + while retries: |
| 77 | + time.sleep(1) |
| 78 | + try: |
| 79 | + urlopen(f"{url}/favicon.ico") |
| 80 | + break |
| 81 | + except URLError: |
| 82 | + print(f"[{retries} / 20] ...", flush=True) |
| 83 | + retries -= 1 |
| 84 | + continue |
| 85 | + yield url, token |
| 86 | + proc.terminate() |
| 87 | + proc.communicate(b"y\n") |
| 88 | + proc.wait() |
| 89 | + assert proc.returncode is not None, "jupyter-server probably still running" |
| 90 | + |
| 91 | + |
| 92 | +def get_unused_port(): |
| 93 | + """Get an unused port by trying to listen to any random port. |
| 94 | +
|
| 95 | + Probably could introduce race conditions if inside a tight loop. |
| 96 | + """ |
| 97 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 98 | + sock.bind((LOCALHOST, 0)) |
| 99 | + sock.listen(1) |
| 100 | + port = sock.getsockname()[1] |
| 101 | + sock.close() |
| 102 | + return port |
| 103 | + |
| 104 | + |
| 105 | +def verify_response(base_url: str, route: str, expect: int = 403): |
| 106 | + """Verify that a response returns the expected error.""" |
| 107 | + error = None |
| 108 | + body = None |
| 109 | + url = f"{base_url}{route}" |
| 110 | + try: |
| 111 | + with urlopen(url) as res: |
| 112 | + body = res.read() |
| 113 | + except HTTPError as err: |
| 114 | + error = err |
| 115 | + assert error, f"no HTTP error for {url}: {body}" |
| 116 | + http_code = error.getcode() |
| 117 | + assert http_code == expect, f"{url} HTTP code was unexpected: {body}" |
0 commit comments