hub-client 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rolf Simoes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: hub-client
3
+ Version: 0.1.0
4
+ Summary: Small JupyterHub and Jupyter Server API client and command line
5
+ Author-email: Rolf Simoes <rolfsimoes@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/rolfsimoes/hub-client
8
+ Project-URL: Repository, https://github.com/rolfsimoes/hub-client
9
+ Project-URL: Issues, https://github.com/rolfsimoes/hub-client/issues
10
+ Project-URL: Changelog, https://github.com/rolfsimoes/hub-client/blob/main/CHANGELOG.md
11
+ Keywords: jupyter,jupyterhub,api,client,socks5,cli
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest; extra == "test"
26
+ Requires-Dist: pytest-asyncio; extra == "test"
27
+ Requires-Dist: pytest-cov; extra == "test"
28
+ Requires-Dist: pytest-timeout; extra == "test"
29
+ Requires-Dist: aiohttp; extra == "test"
30
+ Requires-Dist: trustme; extra == "test"
31
+ Requires-Dist: ruff; extra == "test"
32
+ Dynamic: license-file
33
+
34
+ # hub-client
35
+
36
+ A small client for the JupyterHub and Jupyter Server APIs, with the `hub` command.
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ pip install hub-client
42
+ ```
43
+
44
+ Python 3.11 or newer is needed.
45
+
46
+ ## Status
47
+
48
+ Early. The API client layer is in place. The command grammar comes later, so `hub` has no
49
+ subcommands yet.
50
+
51
+ ## Rule
52
+
53
+ The package uses the Python standard library only. It has no runtime dependencies.
54
+
55
+ ## Development
56
+
57
+ ```bash
58
+ pip install -e ".[test]"
59
+ python3 -m pytest -q
60
+ ```
61
+
62
+ Unit tests only: `python3 -m pytest -m unit -q`. They include `ruff check` and
63
+ `ruff format --check`.
@@ -0,0 +1,30 @@
1
+ # hub-client
2
+
3
+ A small client for the JupyterHub and Jupyter Server APIs, with the `hub` command.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install hub-client
9
+ ```
10
+
11
+ Python 3.11 or newer is needed.
12
+
13
+ ## Status
14
+
15
+ Early. The API client layer is in place. The command grammar comes later, so `hub` has no
16
+ subcommands yet.
17
+
18
+ ## Rule
19
+
20
+ The package uses the Python standard library only. It has no runtime dependencies.
21
+
22
+ ## Development
23
+
24
+ ```bash
25
+ pip install -e ".[test]"
26
+ python3 -m pytest -q
27
+ ```
28
+
29
+ Unit tests only: `python3 -m pytest -m unit -q`. They include `ruff check` and
30
+ `ruff format --check`.
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: hub-client
3
+ Version: 0.1.0
4
+ Summary: Small JupyterHub and Jupyter Server API client and command line
5
+ Author-email: Rolf Simoes <rolfsimoes@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/rolfsimoes/hub-client
8
+ Project-URL: Repository, https://github.com/rolfsimoes/hub-client
9
+ Project-URL: Issues, https://github.com/rolfsimoes/hub-client/issues
10
+ Project-URL: Changelog, https://github.com/rolfsimoes/hub-client/blob/main/CHANGELOG.md
11
+ Keywords: jupyter,jupyterhub,api,client,socks5,cli
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest; extra == "test"
26
+ Requires-Dist: pytest-asyncio; extra == "test"
27
+ Requires-Dist: pytest-cov; extra == "test"
28
+ Requires-Dist: pytest-timeout; extra == "test"
29
+ Requires-Dist: aiohttp; extra == "test"
30
+ Requires-Dist: trustme; extra == "test"
31
+ Requires-Dist: ruff; extra == "test"
32
+ Dynamic: license-file
33
+
34
+ # hub-client
35
+
36
+ A small client for the JupyterHub and Jupyter Server APIs, with the `hub` command.
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ pip install hub-client
42
+ ```
43
+
44
+ Python 3.11 or newer is needed.
45
+
46
+ ## Status
47
+
48
+ Early. The API client layer is in place. The command grammar comes later, so `hub` has no
49
+ subcommands yet.
50
+
51
+ ## Rule
52
+
53
+ The package uses the Python standard library only. It has no runtime dependencies.
54
+
55
+ ## Development
56
+
57
+ ```bash
58
+ pip install -e ".[test]"
59
+ python3 -m pytest -q
60
+ ```
61
+
62
+ Unit tests only: `python3 -m pytest -m unit -q`. They include `ruff check` and
63
+ `ruff format --check`.
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ hub_client.egg-info/PKG-INFO
5
+ hub_client.egg-info/SOURCES.txt
6
+ hub_client.egg-info/dependency_links.txt
7
+ hub_client.egg-info/entry_points.txt
8
+ hub_client.egg-info/requires.txt
9
+ hub_client.egg-info/top_level.txt
10
+ hubclient/__init__.py
11
+ hubclient/auth.py
12
+ hubclient/cli.py
13
+ hubclient/contents.py
14
+ hubclient/http.py
15
+ hubclient/transport.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ hub = hubclient.cli:main
@@ -0,0 +1,9 @@
1
+
2
+ [test]
3
+ pytest
4
+ pytest-asyncio
5
+ pytest-cov
6
+ pytest-timeout
7
+ aiohttp
8
+ trustme
9
+ ruff
@@ -0,0 +1 @@
1
+ hubclient
@@ -0,0 +1 @@
1
+ """hubclient: a small JupyterHub and Jupyter Server API client."""
@@ -0,0 +1,222 @@
1
+ """Jupyter Server token authentication and XSRF cookie handling."""
2
+
3
+ import json
4
+ import re
5
+ from urllib.parse import urljoin, urlsplit
6
+
7
+ from .http import HttpStatusError
8
+
9
+ # Jupyter Server answers a missing or invalid token with one of these.
10
+ REJECTED_STATUSES = (401, 403)
11
+
12
+
13
+ class TokenRejected(RuntimeError):
14
+ """Raised when the server rejects the token itself."""
15
+
16
+
17
+ class TokenValidationError(RuntimeError):
18
+ """Raised when the server response cannot prove token validity."""
19
+
20
+
21
+ class ServerStopped(RuntimeError):
22
+ """Raised when the user's server on the hub is not running."""
23
+
24
+
25
+ class ServerStarting(RuntimeError):
26
+ """Raised when the user's server on the hub is still starting."""
27
+
28
+
29
+ _REDIRECT_STATUSES = (301, 302, 303, 307, 308)
30
+ _USER_PATH = re.compile(r"^(.*)/user/([^/]+)/*$")
31
+
32
+
33
+ def _hub_user_url(base_url):
34
+ """Return the hub API URL of the user named in a `.../user/<name>` base URL."""
35
+ parts = urlsplit(base_url)
36
+ match = _USER_PATH.match(parts.path)
37
+ if not match:
38
+ raise TokenValidationError("base URL does not look like .../user/<name>")
39
+ prefix, name = match.groups()
40
+ return f"{parts.scheme}://{parts.netloc}{prefix}/hub/api/users/{name}"
41
+
42
+
43
+ async def _server_state(http, base_url, token):
44
+ """Ask the hub API whether the default server is starting or stopped."""
45
+ headers = {"Authorization": f"token {token}", "Accept": "application/json"}
46
+ try:
47
+ response = await http.request("GET", _hub_user_url(base_url), headers)
48
+ if response.status != 200:
49
+ return "stopped"
50
+ data = json.loads(response.body)
51
+ except Exception:
52
+ return "stopped"
53
+ if not isinstance(data, dict):
54
+ return "stopped"
55
+ servers = data.get("servers")
56
+ default = servers.get("") if isinstance(servers, dict) else None
57
+ pending = data.get("pending")
58
+ if isinstance(default, dict):
59
+ pending = pending or default.get("pending")
60
+ return "stopped" if pending == "stop" else "starting"
61
+ return "starting" if pending == "spawn" else "stopped"
62
+
63
+
64
+ def _hub_prefix(base_url):
65
+ match = _USER_PATH.match(urlsplit(base_url).path)
66
+ return match.group(1) if match else ""
67
+
68
+
69
+ async def _read_redirect(http, base_url, token, response):
70
+ location = response.headers.get("location", "")
71
+ parts = urlsplit(location)
72
+ path = parts.path
73
+ trusted = (not parts.scheme and not parts.netloc) or _same_host(base_url, location)
74
+ prefix = _hub_prefix(base_url)
75
+ plain = path.rstrip("/")
76
+ if trusted and plain in (prefix + "/hub/login", prefix + "/login"):
77
+ raise TokenRejected("GET /api/me redirected to the hub login")
78
+ if trusted and (
79
+ plain == prefix + "/hub/spawn"
80
+ or path.startswith(
81
+ (prefix + "/hub/spawn/", prefix + "/hub/spawn-pending/", prefix + "/hub/user/")
82
+ )
83
+ ):
84
+ if await _server_state(http, base_url, token) == "starting":
85
+ raise ServerStarting("the user's server on the hub is starting")
86
+ raise ServerStopped("the user's server on the hub is not running")
87
+ raise TokenValidationError(f"GET /api/me returned a redirect to {path or '(none)'}")
88
+
89
+
90
+ def _json_object(response):
91
+ content_type = response.headers.get("content-type", "")
92
+ media_type = content_type.split(";", 1)[0].strip().lower()
93
+ if media_type != "application/json":
94
+ raise TokenValidationError("GET /api/me did not return application/json")
95
+ try:
96
+ data = json.loads(response.body)
97
+ except (UnicodeDecodeError, json.JSONDecodeError) as error:
98
+ raise TokenValidationError("GET /api/me returned invalid JSON") from error
99
+ if not isinstance(data, dict):
100
+ raise TokenValidationError("GET /api/me JSON response is not an object")
101
+ return data
102
+
103
+
104
+ async def verify_token(http, base_url, token):
105
+ """Verify a token through Jupyter Server's authentication-only API.
106
+
107
+ Success proves validity, ``TokenRejected`` proves invalidity, and every
108
+ other outcome is deliberately inconclusive so callers retain the token.
109
+ """
110
+ url = base_url.rstrip("/") + "/api/me"
111
+ headers = {
112
+ "Authorization": f"token {token}",
113
+ "Accept": "application/json",
114
+ }
115
+ try:
116
+ response = await http.request("GET", url, headers)
117
+ except Exception as error:
118
+ raise TokenValidationError(f"GET /api/me failed: {error}") from error
119
+
120
+ if response.status in _REDIRECT_STATUSES:
121
+ await _read_redirect(http, base_url, token, response)
122
+ if response.status in (404, 405):
123
+ raise TokenValidationError("Jupyter Server 2.0 or newer with GET /api/me is required")
124
+ if response.status in REJECTED_STATUSES:
125
+ data = _json_object(response)
126
+ if not isinstance(data.get("message"), str) or not data["message"]:
127
+ raise TokenValidationError(
128
+ f"GET /api/me returned unrecognized HTTP {response.status} JSON"
129
+ )
130
+ raise TokenRejected(f"GET /api/me returned HTTP {response.status}")
131
+ if response.status != 200:
132
+ raise TokenValidationError(f"GET /api/me returned HTTP {response.status}")
133
+
134
+ data = _json_object(response)
135
+ identity = data.get("identity")
136
+ permissions = data.get("permissions")
137
+ if (
138
+ not isinstance(identity, dict)
139
+ or not isinstance(identity.get("username"), str)
140
+ or not identity["username"]
141
+ or not isinstance(permissions, dict)
142
+ or not all(
143
+ isinstance(resource, str)
144
+ and isinstance(actions, list)
145
+ and all(isinstance(action, str) for action in actions)
146
+ for resource, actions in permissions.items()
147
+ )
148
+ ):
149
+ raise TokenValidationError(
150
+ "GET /api/me did not return valid identity and permissions models"
151
+ )
152
+
153
+
154
+ async def start_server(http, base_url, token):
155
+ """Ask the hub to start the user's server; return "starting" or "running"."""
156
+ headers = {"Authorization": f"token {token}", "Accept": "application/json"}
157
+ try:
158
+ url = _hub_user_url(base_url) + "/server"
159
+ response = await http.request("POST", url, {**headers, "Content-Length": "0"})
160
+ except TokenValidationError:
161
+ raise
162
+ except Exception as error:
163
+ raise TokenValidationError(f"could not start the server: {error}") from error
164
+ if response.status in (201, 202):
165
+ return "starting"
166
+ if response.status in REJECTED_STATUSES:
167
+ raise TokenRejected(f"the hub returned HTTP {response.status}")
168
+ if response.status == 400 and b"already running" in response.body.lower():
169
+ return "running"
170
+ raise TokenValidationError(f"could not start the server: HTTP {response.status}")
171
+
172
+
173
+ def _default_port(scheme):
174
+ if scheme == "https":
175
+ return 443
176
+ if scheme == "http":
177
+ return 80
178
+ return None
179
+
180
+
181
+ def _same_host(origin, target):
182
+ base = urlsplit(origin)
183
+ nxt = urlsplit(target)
184
+ if not nxt.scheme or nxt.hostname is None or base.hostname is None:
185
+ return False
186
+ if nxt.scheme != base.scheme or nxt.hostname != base.hostname:
187
+ return False
188
+ return (nxt.port or _default_port(nxt.scheme)) == (base.port or _default_port(base.scheme))
189
+
190
+
191
+ async def xsrf_cookie(http, base_url, token):
192
+ url = base_url.rstrip("/") + "/"
193
+ redirect_statuses = (301, 302, 303, 307, 308)
194
+ for attempt in range(4):
195
+ response = await http.request("GET", url, {"Authorization": f"token {token}"})
196
+ if response.status >= 400:
197
+ raise HttpStatusError(
198
+ response.status,
199
+ f"Jupyter Server returned HTTP {response.status}",
200
+ )
201
+ for cookie in response.headers.get("set-cookie", []):
202
+ first = cookie.split(";", 1)[0]
203
+ if first.startswith("_xsrf="):
204
+ value = first.split("=", 1)[1]
205
+ if not value:
206
+ raise RuntimeError("Jupyter Server returned an empty _xsrf cookie")
207
+ return value
208
+ if response.status in redirect_statuses:
209
+ if "location" not in response.headers:
210
+ raise RuntimeError("redirect without Location")
211
+ if attempt == 3:
212
+ raise RuntimeError("redirect limit exceeded without an _xsrf cookie")
213
+ url = urljoin(url, response.headers["location"])
214
+ if not _same_host(base_url, url):
215
+ raise RuntimeError("refusing to follow a redirect to another host")
216
+ continue
217
+ break
218
+ raise RuntimeError("Jupyter Server did not return an _xsrf cookie")
219
+
220
+
221
+ def headers(token, xsrf):
222
+ return {"Authorization": f"token {token}", "Cookie": f"_xsrf={xsrf}"}
@@ -0,0 +1,15 @@
1
+ """The `hub` command line."""
2
+
3
+ import argparse
4
+ import sys
5
+
6
+
7
+ def main(argv=None):
8
+ """Entry point of the `hub` command."""
9
+ parser = argparse.ArgumentParser(
10
+ prog="hub",
11
+ description="Command line client for JupyterHub and Jupyter Server.",
12
+ )
13
+ parser.parse_args(argv)
14
+ parser.print_usage(sys.stderr)
15
+ return 2
@@ -0,0 +1,359 @@
1
+ """Jupyter contents and files HTTP client.
2
+
3
+ Owns the Contents API used by the SCP bridge: chunk planning, sequential
4
+ upload streaming, and path checks. No SSH types live here; `sftp_bridge`
5
+ maps these results onto asyncssh.
6
+ """
7
+
8
+ import asyncio
9
+ import base64
10
+ import json
11
+ import stat
12
+ import time
13
+ from dataclasses import dataclass
14
+ from datetime import datetime
15
+ from urllib.parse import quote
16
+
17
+ from .auth import headers as auth_headers
18
+ from .auth import xsrf_cookie
19
+ from .http import HttpClient
20
+ from .transport import ConnectionTransport, build_ssl_context
21
+
22
+ # Same size JupyterLab's file browser uses for Contents chunk uploads.
23
+ CHUNK_SIZE = 1024 * 1024
24
+
25
+
26
+ class ContentsError(Exception):
27
+ def __init__(self, status, message):
28
+ super().__init__(message)
29
+ self.status = status
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class FileAttrs:
34
+ """POSIX-shaped metadata derived from a Contents model (no SSH types)."""
35
+
36
+ kind: str
37
+ size: int
38
+ permissions: int
39
+ atime: int
40
+ mtime: int
41
+
42
+
43
+ def chunk_plan(size: int, chunk_size: int = CHUNK_SIZE) -> list[tuple[int, int, int | None]]:
44
+ """Plan Contents API uploads for `size` bytes.
45
+
46
+ Returns `(offset, length, chunk)` rows. `chunk` is `None` for a single
47
+ unchunked PUT (size <= chunk_size), matching JupyterLab. Larger files use
48
+ `1 .. n-1` then `-1` for the last piece, each at most `chunk_size` bytes.
49
+ """
50
+ if size < 0:
51
+ raise ValueError("size must be non-negative")
52
+ if chunk_size <= 0:
53
+ raise ValueError("chunk_size must be positive")
54
+ if size <= chunk_size:
55
+ return [(0, size, None)]
56
+ plan = []
57
+ offset = 0
58
+ index = 1
59
+ while offset < size:
60
+ length = min(chunk_size, size - offset)
61
+ last = offset + length >= size
62
+ plan.append((offset, length, -1 if last else index))
63
+ offset += length
64
+ index += 1
65
+ return plan
66
+
67
+
68
+ def api_path(path: str | bytes) -> str:
69
+ """Contents path with `.` and empty segments dropped; `..` is rejected."""
70
+ text = path.decode("utf-8") if isinstance(path, bytes) else path
71
+ parts = []
72
+ for part in text.split("/"):
73
+ if part in ("", "."):
74
+ continue
75
+ if part == "..":
76
+ raise ContentsError(404, "path leaves the Jupyter root")
77
+ parts.append(part)
78
+ return "/".join(parts)
79
+
80
+
81
+ def _unix_time(value, default: int) -> int:
82
+ if isinstance(value, str):
83
+ try:
84
+ return int(datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp())
85
+ except ValueError:
86
+ pass
87
+ return default
88
+
89
+
90
+ def file_attrs(model) -> FileAttrs:
91
+ """Map a Contents model to POSIX type bits plus Contents timestamps.
92
+
93
+ OpenSSH `scp` checks `S_ISREG` in the permission bits. Legacy `scp -O -p`
94
+ also needs atime/mtime. Mode bits are advisory; Contents does not store them.
95
+ """
96
+ now = int(time.time())
97
+ mtime = _unix_time(model.get("last_modified"), now)
98
+ atime = _unix_time(model.get("created"), mtime)
99
+ kind = model.get("type")
100
+ if kind == "directory":
101
+ return FileAttrs("directory", 0, stat.S_IFDIR | 0o755, atime, mtime)
102
+ if kind in ("file", "notebook"):
103
+ size = model.get("size")
104
+ return FileAttrs(
105
+ "file",
106
+ 0 if not isinstance(size, int) else size,
107
+ stat.S_IFREG | 0o644,
108
+ atime,
109
+ mtime,
110
+ )
111
+ raise ContentsError(400, f"unsupported contents type {kind!r}")
112
+
113
+
114
+ class StreamingUpload:
115
+ """Sequential upload that flushes 1 MiB Contents chunks as they fill.
116
+
117
+ Keeps at most `CHUNK_SIZE` bytes pending. A non-sequential write raises
118
+ `ContentsError` and aborts the upload (the SCP bridge only accepts the order
119
+ `scp` uses). A failed chunk PUT aborts the upload too: later writes and
120
+ `finish` raise and send nothing. An aborted upload deletes the partial file
121
+ only if a PUT was already sent; before that the file was never touched.
122
+
123
+ With `truncate=False` (an open without FXF_TRUNC), a `finish` with nothing
124
+ written leaves an existing file alone and only creates a missing one.
125
+ """
126
+
127
+ def __init__(self, api, path: str, *, truncate: bool = True):
128
+ self.path = path
129
+ self._api = api
130
+ self._truncate = truncate
131
+ self._put_sent = False
132
+ self._pending = bytearray()
133
+ self._offset = 0
134
+ self._next_index = 1
135
+ self._aborted = False
136
+ self._discarded = False
137
+ self._delete_error = None
138
+ # Clear while a write (and its chunk PUT) runs; `abort` waits for it.
139
+ self._idle = asyncio.Event()
140
+ self._idle.set()
141
+
142
+ async def write(self, offset: int, data: bytes) -> int:
143
+ if self._aborted:
144
+ raise ContentsError(409, "the upload was aborted")
145
+ if offset != self._offset:
146
+ # Appending to an existing file (`reput`, `put -a`) lands here. The
147
+ # upload is aborted; with nothing PUT yet no DELETE is sent, so an
148
+ # existing file stays as it was.
149
+ self._aborted = True
150
+ self._pending.clear()
151
+ try:
152
+ await self._discard()
153
+ except ContentsError:
154
+ pass
155
+ raise ContentsError(
156
+ 400,
157
+ f"non-sequential write at offset {offset} (expected {self._offset})",
158
+ )
159
+ self._pending.extend(data)
160
+ self._offset += len(data)
161
+ self._idle.clear()
162
+ try:
163
+ while len(self._pending) > CHUNK_SIZE and not self._aborted:
164
+ piece = bytes(self._pending[:CHUNK_SIZE])
165
+ del self._pending[:CHUNK_SIZE]
166
+ await self._put(piece, self._next_index)
167
+ self._next_index += 1
168
+ finally:
169
+ self._idle.set()
170
+ return len(data)
171
+
172
+ @property
173
+ def aborted(self) -> bool:
174
+ """Whether the upload was given up: aborted, or a chunk PUT failed."""
175
+ return self._aborted
176
+
177
+ async def _put(self, piece, chunk):
178
+ self._put_sent = True
179
+ try:
180
+ await self._api.put_chunk(self.path, piece, chunk)
181
+ except ContentsError:
182
+ # A failed chunk ends the upload: no PUT for this file after it.
183
+ # A failed delete is kept; `abort` raises it.
184
+ self._aborted = True
185
+ self._pending.clear()
186
+ try:
187
+ await self._discard()
188
+ except ContentsError:
189
+ pass
190
+ raise
191
+
192
+ async def _discard(self):
193
+ """Delete the partial file once; a failed delete raises now and on every later call.
194
+
195
+ With no PUT sent yet there is nothing to delete: no DELETE is sent.
196
+ """
197
+ if self._discarded:
198
+ if self._delete_error is not None:
199
+ raise self._delete_error
200
+ return
201
+ self._discarded = True
202
+ if not self._put_sent:
203
+ return
204
+ try:
205
+ await self._api.delete(self.path)
206
+ except ContentsError as error:
207
+ if error.status == 404:
208
+ return
209
+ self._delete_error = error
210
+ raise
211
+
212
+ async def abort(self) -> None:
213
+ """Give up: delete what was sent; no chunk is sent after this.
214
+
215
+ A chunk PUT already in flight is awaited first, so it cannot
216
+ re-create the file after the delete. Raises `ContentsError` if the
217
+ delete failed (now or after a failed chunk PUT); at most one DELETE
218
+ is ever sent, and none when no PUT was sent.
219
+ """
220
+ self._aborted = True
221
+ self._pending.clear()
222
+ await self._idle.wait()
223
+ await self._discard()
224
+
225
+ async def finish(self) -> None:
226
+ if self._aborted:
227
+ raise ContentsError(409, "the upload was aborted")
228
+ piece = bytes(self._pending)
229
+ self._pending.clear()
230
+ if self._offset == 0 and not self._truncate:
231
+ # Opened without FXF_TRUNC and nothing written: keep an existing file.
232
+ if await self._api.stat(self.path) is not None:
233
+ return
234
+ if self._next_index == 1:
235
+ await self._put(piece, None)
236
+ else:
237
+ await self._put(piece, -1)
238
+
239
+
240
+ class JupyterContents:
241
+ """The contents and files endpoints for one Jupyter Server."""
242
+
243
+ def __init__(self, http, base_url, token, xsrf):
244
+ self._http = http
245
+ self._base = base_url.rstrip("/")
246
+ self._token = token
247
+ self._xsrf = xsrf
248
+
249
+ def _headers(self, *, json_body=False):
250
+ fields = auth_headers(self._token, self._xsrf)
251
+ fields["X-XSRFToken"] = self._xsrf
252
+ fields["Accept"] = "application/json"
253
+ if json_body:
254
+ fields["Content-Type"] = "application/json"
255
+ return fields
256
+
257
+ def _url(self, prefix, path, query=""):
258
+ suffix = "" if path == "" else "/" + quote(path, safe="/")
259
+ return f"{self._base}{prefix}{suffix}{query}"
260
+
261
+ async def _request(self, method, url, body=b"", *, json_body=False):
262
+ try:
263
+ return await self._http.request(
264
+ method,
265
+ url,
266
+ self._headers(json_body=json_body),
267
+ body,
268
+ )
269
+ except Exception as error:
270
+ raise ContentsError(0, str(error)) from error
271
+
272
+ async def stat(self, path):
273
+ response = await self._request("GET", self._url("/api/contents", path, "?content=0"))
274
+ if response.status == 404:
275
+ return None
276
+ self._expect(response, 200, "GET /api/contents")
277
+ return json.loads(response.body)
278
+
279
+ async def listdir(self, path):
280
+ response = await self._request("GET", self._url("/api/contents", path, "?content=1"))
281
+ if response.status == 404:
282
+ raise ContentsError(404, "no such directory")
283
+ self._expect(response, 200, "GET /api/contents")
284
+ content = json.loads(response.body).get("content")
285
+ if not isinstance(content, list):
286
+ raise ContentsError(response.status, "directory listing is not a list")
287
+ return content
288
+
289
+ async def open_download(self, path):
290
+ """Stream `GET /files`. The caller reads and closes the body."""
291
+ try:
292
+ stream = await self._http.open_response(
293
+ "GET",
294
+ self._url("/files", path, "?download=1"),
295
+ self._headers(),
296
+ )
297
+ except Exception as error:
298
+ raise ContentsError(0, str(error)) from error
299
+ if stream.status == 404:
300
+ await stream.close()
301
+ raise ContentsError(404, "no such file")
302
+ if stream.status != 200:
303
+ await stream.close()
304
+ raise ContentsError(stream.status, f"GET /files returned HTTP {stream.status}")
305
+ return stream
306
+
307
+ async def put_chunk(self, path, piece: bytes, chunk: int | None):
308
+ model = {
309
+ "type": "file",
310
+ "format": "base64",
311
+ "content": base64.b64encode(piece).decode("ascii"),
312
+ }
313
+ if chunk is not None:
314
+ model["chunk"] = chunk
315
+ response = await self._request(
316
+ "PUT",
317
+ self._url("/api/contents", path),
318
+ json.dumps(model).encode(),
319
+ json_body=True,
320
+ )
321
+ self._expect(response, (200, 201), "PUT /api/contents")
322
+
323
+ async def mkdir(self, path):
324
+ body = json.dumps({"type": "directory"}).encode()
325
+ response = await self._request(
326
+ "PUT",
327
+ self._url("/api/contents", path),
328
+ body,
329
+ json_body=True,
330
+ )
331
+ self._expect(response, (200, 201), "PUT /api/contents")
332
+
333
+ async def delete(self, path):
334
+ response = await self._request("DELETE", self._url("/api/contents", path))
335
+ if response.status == 404:
336
+ raise ContentsError(404, "no such file")
337
+ self._expect(response, 204, "DELETE /api/contents")
338
+
339
+ @staticmethod
340
+ def _expect(response, statuses, what):
341
+ if isinstance(statuses, int):
342
+ statuses = (statuses,)
343
+ if response.status not in statuses:
344
+ raise ContentsError(response.status, f"{what} returned HTTP {response.status}")
345
+
346
+
347
+ async def connect(args, token):
348
+ """Open a contents client for `args.base_url` using the caller's token."""
349
+ context = build_ssl_context(args.insecure_tls)
350
+ http = HttpClient(
351
+ transport=ConnectionTransport(
352
+ args.socks_host,
353
+ args.socks_port,
354
+ context,
355
+ args.timeout,
356
+ )
357
+ )
358
+ xsrf = await xsrf_cookie(http, args.base_url, token)
359
+ return JupyterContents(http, args.base_url, token, xsrf)
@@ -0,0 +1,145 @@
1
+ """Minimal async HTTP client over TLS, optionally through SOCKS5."""
2
+
3
+ from dataclasses import dataclass
4
+ from urllib.parse import urlsplit
5
+
6
+ from .transport import ensure_transport, read_exactly
7
+
8
+
9
+ class HttpStatusError(RuntimeError):
10
+ """HTTP failure whose numeric status must survive exception wrapping."""
11
+
12
+ def __init__(self, status, message):
13
+ super().__init__(message)
14
+ self.status = status
15
+
16
+
17
+ @dataclass
18
+ class HttpResponse:
19
+ status: int
20
+ headers: dict
21
+ body: bytes
22
+
23
+
24
+ async def read_response(reader):
25
+ status, headers, pending, length = await _read_head(reader)
26
+ body = bytearray(pending)
27
+ if len(body) < length:
28
+ body.extend(await read_exactly(reader, length - len(body)))
29
+ return HttpResponse(status, headers, bytes(body))
30
+
31
+
32
+ def format_request_head(method, url, headers):
33
+ parsed = urlsplit(url)
34
+ target = parsed.path or "/"
35
+ if parsed.query:
36
+ target += f"?{parsed.query}"
37
+ head = f"{method} {target} HTTP/1.1\r\n"
38
+ head += "".join(f"{key}: {value}\r\n" for key, value in headers.items())
39
+ return (head + "\r\n").encode()
40
+
41
+
42
+ class HttpClient:
43
+ def __init__(self, proxy_host=None, proxy_port=None, transport=None):
44
+ self.proxy_host = proxy_host
45
+ self.proxy_port = proxy_port
46
+ self.transport = ensure_transport(transport, proxy_host, proxy_port)
47
+
48
+ async def request(self, method, url, headers=None, body=b""):
49
+ parsed = urlsplit(url)
50
+ reader, writer = await self.transport.open_tls(url)
51
+ request_headers = {"Host": parsed.netloc, "Connection": "close", **(headers or {})}
52
+ if body:
53
+ request_headers.setdefault("Content-Length", str(len(body)))
54
+ head = format_request_head(method, url, request_headers)
55
+ try:
56
+ writer.write(head + body)
57
+ await writer.drain()
58
+ return await read_response(reader)
59
+ finally:
60
+ writer.close()
61
+ try:
62
+ await writer.wait_closed()
63
+ except OSError:
64
+ pass
65
+
66
+ async def open_response(self, method, url, headers=None):
67
+ """Return a body stream. The caller closes it, which closes the socket."""
68
+ parsed = urlsplit(url)
69
+ reader, writer = await self.transport.open_tls(url)
70
+ request_headers = {"Host": parsed.netloc, "Connection": "close", **(headers or {})}
71
+ head = format_request_head(method, url, request_headers)
72
+ try:
73
+ writer.write(head)
74
+ await writer.drain()
75
+ status, headers_out, pending, length = await _read_head(reader)
76
+ except BaseException:
77
+ writer.close()
78
+ raise
79
+ return BodyStream(reader, writer, status, headers_out, pending, length)
80
+
81
+
82
+ class BodyStream:
83
+ """HTTP body read in pieces. Bytes already returned are not kept."""
84
+
85
+ def __init__(self, reader, writer, status, headers, pending, length):
86
+ self.status = status
87
+ self.headers = headers
88
+ self._reader = reader
89
+ self._writer = writer
90
+ self._pending = bytearray(pending)
91
+ self._left = length
92
+
93
+ async def read(self, size):
94
+ if size <= 0 or self._left <= 0:
95
+ return b""
96
+ want = min(size, self._left)
97
+ while len(self._pending) < want:
98
+ self._pending.extend(await read_exactly(self._reader, want - len(self._pending)))
99
+ data = bytes(self._pending[:want])
100
+ del self._pending[:want]
101
+ self._left -= want
102
+ return data
103
+
104
+ async def close(self):
105
+ self._writer.close()
106
+ try:
107
+ await self._writer.wait_closed()
108
+ except OSError:
109
+ pass
110
+
111
+
112
+ async def _read_head(reader):
113
+ data = bytearray()
114
+ while b"\r\n\r\n" not in data:
115
+ data.extend(await read_exactly(reader, 1))
116
+ if len(data) > 65536:
117
+ raise RuntimeError("HTTP header is too large")
118
+ headers_raw, pending = bytes(data).split(b"\r\n\r\n", 1)
119
+ lines = headers_raw.decode("iso-8859-1").split("\r\n")
120
+ status_parts = lines[0].split()
121
+ try:
122
+ status = int(status_parts[1])
123
+ except (IndexError, ValueError) as error:
124
+ raise RuntimeError("invalid HTTP status") from error
125
+ headers = {}
126
+ for line in lines[1:]:
127
+ if ":" not in line:
128
+ raise RuntimeError("invalid HTTP header")
129
+ key, value = line.split(":", 1)
130
+ key, value = key.lower(), value.strip()
131
+ if key == "set-cookie":
132
+ headers.setdefault(key, []).append(value)
133
+ else:
134
+ headers[key] = value
135
+ if "transfer-encoding" in headers:
136
+ raise RuntimeError("unsupported Transfer-Encoding")
137
+ try:
138
+ length = int(headers.get("content-length", "0"))
139
+ except ValueError as error:
140
+ raise RuntimeError("invalid Content-Length") from error
141
+ if length < 0:
142
+ raise RuntimeError("invalid Content-Length")
143
+ if len(pending) > length:
144
+ pending = pending[:length]
145
+ return status, headers, pending, length
@@ -0,0 +1,161 @@
1
+ """Async SOCKS5 and TLS transport for HTTP and WebSocket."""
2
+
3
+ import asyncio
4
+ import socket
5
+ import ssl
6
+ import struct
7
+ from dataclasses import dataclass
8
+ from urllib.parse import urlsplit
9
+
10
+
11
+ async def read_exactly(reader, size):
12
+ try:
13
+ return await reader.readexactly(size)
14
+ except asyncio.IncompleteReadError as error:
15
+ raise ConnectionError("connection closed") from error
16
+
17
+
18
+ async def socks5_connect(proxy_host, proxy_port, destination_host, destination_port, timeout=None):
19
+ reader, writer = await asyncio.wait_for(
20
+ asyncio.open_connection(proxy_host, proxy_port), timeout=timeout
21
+ )
22
+ try:
23
+ writer.write(b"\x05\x01\x00")
24
+ await writer.drain()
25
+ version, method = await asyncio.wait_for(read_exactly(reader, 2), timeout=timeout)
26
+ if version != 5:
27
+ raise RuntimeError("invalid SOCKS5 response version")
28
+ if method != 0:
29
+ raise RuntimeError("SOCKS5 proxy did not accept 'none' authentication")
30
+
31
+ host = destination_host.encode("idna")
32
+ if len(host) > 255:
33
+ raise ValueError("hostname is too long")
34
+ request = (
35
+ b"\x05\x01\x00\x03" + bytes([len(host)]) + host + struct.pack("!H", destination_port)
36
+ )
37
+ writer.write(request)
38
+ await writer.drain()
39
+ version, reply, reserved, address_type = await asyncio.wait_for(
40
+ read_exactly(reader, 4), timeout=timeout
41
+ )
42
+ if version != 5:
43
+ raise RuntimeError("invalid SOCKS5 CONNECT response version")
44
+ if reserved != 0:
45
+ raise RuntimeError("invalid reserved field in SOCKS5 response")
46
+ if reply != 0:
47
+ raise RuntimeError(f"SOCKS5 CONNECT rejected (code {reply})")
48
+ if address_type == 1:
49
+ await asyncio.wait_for(read_exactly(reader, 4), timeout=timeout)
50
+ elif address_type == 3:
51
+ length = (await asyncio.wait_for(read_exactly(reader, 1), timeout=timeout))[0]
52
+ await asyncio.wait_for(read_exactly(reader, length), timeout=timeout)
53
+ elif address_type == 4:
54
+ await asyncio.wait_for(read_exactly(reader, 16), timeout=timeout)
55
+ else:
56
+ raise RuntimeError("invalid address type in SOCKS5 response")
57
+ await asyncio.wait_for(read_exactly(reader, 2), timeout=timeout)
58
+ return reader, writer
59
+ except BaseException:
60
+ writer.close()
61
+ raise
62
+
63
+
64
+ def _enable_tcp_keepalive(writer) -> None:
65
+ """Without this, an idle websocket (e.g. a terminal session with
66
+ nothing typed for a while) can be silently dropped by a NAT gateway
67
+ or firewall between here and the Jupyter Server, since no traffic
68
+ ever crosses it to keep its connection-tracking entry alive. It also
69
+ means a genuinely dead connection surfaces as an error within a few
70
+ probes instead of hanging forever. Best-effort: not every platform
71
+ exposes every option, and failures here shouldn't break the caller."""
72
+ sock = writer.get_extra_info("socket") if hasattr(writer, "get_extra_info") else None
73
+ if sock is None:
74
+ return
75
+ try:
76
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
77
+ if hasattr(socket, "TCP_KEEPIDLE"):
78
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60)
79
+ if hasattr(socket, "TCP_KEEPINTVL"):
80
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 15)
81
+ if hasattr(socket, "TCP_KEEPCNT"):
82
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 4)
83
+ except OSError:
84
+ pass
85
+
86
+
87
+ @dataclass
88
+ class ConnectionTransport:
89
+ socks_host: str | None = None
90
+ socks_port: int | None = None
91
+ ssl_context: ssl.SSLContext | None = None
92
+ timeout: float = 15.0
93
+
94
+ async def open_tls(self, url: str):
95
+ parsed = urlsplit(url)
96
+ if parsed.scheme != "https" or not parsed.hostname:
97
+ raise ValueError("URL must use https://")
98
+ if (self.socks_host is None) != (self.socks_port is None):
99
+ raise ValueError("SOCKS5 proxy host or port is missing")
100
+ destination_host = parsed.hostname.encode("idna").decode("ascii")
101
+ destination_port = parsed.port or 443
102
+ context = self.ssl_context or ssl.create_default_context()
103
+ if self.socks_host is None:
104
+ reader, writer = await asyncio.wait_for(
105
+ asyncio.open_connection(
106
+ destination_host,
107
+ destination_port,
108
+ ssl=context,
109
+ server_hostname=destination_host,
110
+ ),
111
+ timeout=self.timeout,
112
+ )
113
+ _enable_tcp_keepalive(writer)
114
+ return reader, writer
115
+ reader, writer = await socks5_connect(
116
+ self.socks_host,
117
+ self.socks_port,
118
+ destination_host,
119
+ destination_port,
120
+ self.timeout,
121
+ )
122
+ try:
123
+ loop = asyncio.get_running_loop()
124
+ transport = writer.transport
125
+ protocol = transport.get_protocol()
126
+ new_transport = await loop.start_tls(
127
+ transport,
128
+ protocol,
129
+ context,
130
+ server_hostname=destination_host,
131
+ ssl_handshake_timeout=self.timeout,
132
+ )
133
+ new_writer = asyncio.StreamWriter(new_transport, protocol, reader, loop)
134
+ # asyncio.StreamWriter.__del__ closes its transport. Once this
135
+ # coroutine returns, `writer` (the pre-TLS wrapper around the
136
+ # SOCKS-tunneled socket) would otherwise become unreferenced and
137
+ # get garbage-collected, closing the underlying socket out from
138
+ # under the new TLS transport that still needs it. Keep it alive
139
+ # for as long as the TLS writer is.
140
+ new_writer._raw_writer = writer
141
+ _enable_tcp_keepalive(new_writer)
142
+ return reader, new_writer
143
+ except BaseException:
144
+ writer.close()
145
+ raise
146
+
147
+
148
+ def build_ssl_context(insecure: bool):
149
+ if not insecure:
150
+ return None
151
+ context = ssl.create_default_context()
152
+ context.check_hostname = False
153
+ context.verify_mode = ssl.CERT_NONE
154
+ return context
155
+
156
+
157
+ def ensure_transport(transport, socks_host, socks_port):
158
+ """Return the given transport, or a default ConnectionTransport."""
159
+ if transport is not None:
160
+ return transport
161
+ return ConnectionTransport(socks_host, socks_port)
@@ -0,0 +1,73 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "hub-client"
7
+ version = "0.1.0"
8
+ description = "Small JupyterHub and Jupyter Server API client and command line"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Rolf Simoes", email = "rolfsimoes@gmail.com" }]
14
+ keywords = ["jupyter", "jupyterhub", "api", "client", "socks5", "cli"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Environment :: Console",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: POSIX :: Linux",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/rolfsimoes/hub-client"
29
+ Repository = "https://github.com/rolfsimoes/hub-client"
30
+ Issues = "https://github.com/rolfsimoes/hub-client/issues"
31
+ Changelog = "https://github.com/rolfsimoes/hub-client/blob/main/CHANGELOG.md"
32
+
33
+ [project.scripts]
34
+ hub = "hubclient.cli:main"
35
+
36
+ [project.optional-dependencies]
37
+ test = [
38
+ "pytest",
39
+ "pytest-asyncio",
40
+ "pytest-cov",
41
+ "pytest-timeout",
42
+ "aiohttp",
43
+ "trustme",
44
+ "ruff",
45
+ ]
46
+
47
+ [tool.pytest.ini_options]
48
+ testpaths = ["tests"]
49
+ addopts = [
50
+ "--strict-markers",
51
+ "--strict-config",
52
+ "--timeout=10",
53
+ ]
54
+ asyncio_mode = "auto"
55
+ markers = [
56
+ "unit: isolated hubclient tests",
57
+ "integration: loopback integration tests",
58
+ ]
59
+
60
+ [tool.setuptools.packages.find]
61
+ include = ["hubclient*"]
62
+
63
+ [tool.commit-check]
64
+ # run by the global commit-check before a commit block is given
65
+ command = "python3 -m pytest -m unit -q -p no:cacheprovider"
66
+
67
+ [tool.ruff]
68
+ line-length = 100
69
+ target-version = "py311"
70
+ extend-exclude = ["build", "dist", "*.egg-info"]
71
+
72
+ [tool.ruff.lint]
73
+ select = ["E", "F", "W", "I", "B", "UP"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+