diff --git a/README.md b/README.md index 48423a5..0bd3d27 100644 --- a/README.md +++ b/README.md @@ -136,8 +136,8 @@ Run `colab --help` to view specific options, defaults, and detailed he | Command | Description | | --- | --- | | `colab ls [-s NAME] [PATH]` | List remote files on the VM | -| `colab upload [-s NAME] LOCAL REMOTE` | Upload a local file to the VM filesystem | -| `colab download [-s NAME] REMOTE LOCAL` | Download a remote file from the VM filesystem | +| `colab upload [-s NAME] [-r] LOCAL REMOTE` | Upload a local file or directory (`-r`) to the VM filesystem | +| `colab download [-s NAME] [-r] REMOTE LOCAL` | Download a remote file or directory (`-r`) from the VM filesystem | | `colab rm [-s NAME] PATH` | Delete a remote file on the VM filesystem | | `colab edit [-s NAME] PATH` | Edit a remote file in-place using your local `$EDITOR` | diff --git a/docs/03_file_management.md b/docs/03_file_management.md index 785644e..2ed7939 100644 --- a/docs/03_file_management.md +++ b/docs/03_file_management.md @@ -1,5 +1,7 @@ --- log: +2026-11-20: Took upstream PR #267 (`colab upload -r` / `colab download -r`, by Koji Shukawa) before Google merged it, with its review comments applied: no `ntpath` import (a drive-prefixed entry name is still refused on Windows, through `os.path.splitdrive`), simpler `posixpath.join` calls, `_is_local_symlink` so a destination given as `link/` is still seen as a symlink on POSIX, and HTTP errors without the URL (the fork's message, which hides the runtime proxy token). Tested live on a Colab web UI runtime: a tree with subfolders and an empty folder uploaded and downloaded back identical. +2026-11-19: Added `-r`/`--recursive` support to `colab upload` and `colab download` via `ContentsClient.mkdir`, `_ensure_dir`, `upload_dir`, and `download_dir` (preserving empty directories, skipping symlinks on upload, handling single-file `download -r` targets, normalizing remote paths, and enforcing entry-name, canonical local-symlink/containment, and recursion-depth checks). Reused a persistent `requests.Session` in `ContentsClient` with `close()`/context-manager cleanup (reopening a fresh client after `$EDITOR` in `colab edit`) for HTTP keep-alive, and redacted `colab-runtime-proxy-token` query params from `HTTPError` messages. 2026-11-12: Errors no longer show the runtime proxy token: `ContentsClient` reports an HTTP error as status and path (requests put the full URL, token included, in its message) and the file commands print errors through `common.redact_secrets`. Under Git Bash on Windows, remote paths that MSYS rewrote (`/content` -> `C:/Program Files/Git/content`) are turned back by `utils.undo_msys_path`. A failing editor in `colab edit` prints `[colab] ...: Editing failed` and exits 1 instead of a traceback (Typer vendors its own Click and does not handle `click.ClickException`). --- @@ -32,11 +34,13 @@ File management on the Colab VM will be implemented using the Jupyter Contents A ``` - **Base64 Encoding**: Use `format: base64` for binary files. - **Progress**: Implement a simple progress bar for large uploads by chunking or providing status updates. +- **Recursive (`-r` / `--recursive`)**: Walks a local directory top-down (`followlinks=False`), creates the remote directory (and any missing parent directories) with `PUT /api/contents/` (`{"type": "directory"}`), and uploads files using POSIX `/` paths. Uploading a directory without `-r` exits non-zero with a `-r/--recursive` hint. ### 3. Downloading Files (`colab download`) - **API**: `GET /api/contents/?content=1` (as seen in HAR). - **Response**: JSON with `content` field. - **Handling**: Decodes content based on `format` (`base64`, `json`, or plain `text`) and saves it locally. +- **Recursive (`-r` / `--recursive`)**: Walks remote directories returned by the Contents API, creates matching local directories (including empty directories), validates entry names against path traversal, and downloads nested files/notebooks (or falls back to downloading a single file if `remote_path` is not a directory). Non-recursive `download` raises `IsADirectoryError` with a `-r/--recursive` hint when targeting a directory. ### 4. Deleting Files (`colab rm`) - **API**: `DELETE /api/contents/`. diff --git a/src/colab_cli/commands/files.py b/src/colab_cli/commands/files.py index 51098e9..beb3503 100644 --- a/src/colab_cli/commands/files.py +++ b/src/colab_cli/commands/files.py @@ -56,6 +56,8 @@ def ls( except Exception as e: typer.echo(f"[colab] Error: {redact_secrets(str(e))}") raise typer.Exit(1) + finally: + contents.close() def rm( @@ -78,36 +80,70 @@ def rm( except Exception as e: typer.echo(f"[colab] Error: {redact_secrets(str(e))}") raise typer.Exit(1) + finally: + contents.close() def upload( session: Annotated[ Optional[str], typer.Option("-s", "--session", help="Session name") ] = None, - local_path: Annotated[str, typer.Argument(help="Local file to upload")] = ..., + local_path: Annotated[ + str, typer.Argument(help="Local file or directory to upload") + ] = ..., remote_path: Annotated[str, typer.Argument(help="Remote path to upload to")] = ..., + recursive: Annotated[ + bool, + typer.Option("-r", "--recursive", help="Recursively upload a directory"), + ] = False, ): - """Upload a file to a session""" + """Upload a file or directory to a session""" from colab_cli.common import state name = state.resolve_session(session) remote_path = undo_msys_path(remote_path) s = state.get_session(name) - if not os.path.isfile(local_path): - typer.echo(f"[colab] Local file '{local_path}' not found.") + is_dir = os.path.isdir(local_path) + if is_dir and not recursive: + typer.echo( + f"[colab] '{local_path}' is a directory. Use -r/--recursive to upload directories." + ) + raise typer.Exit(1) + if not is_dir and not os.path.isfile(local_path): + label = "path" if recursive else "file" + typer.echo(f"[colab] Local {label} '{local_path}' not found.") raise typer.Exit(1) contents = ContentsClient(s) try: - contents.upload(local_path, remote_path) - state.history.log_event( - name, - "file_operation", - {"op": "upload", "local": local_path, "remote": remote_path}, - ) - typer.echo(f"[colab] Uploaded '{local_path}' to '{remote_path}'") + if is_dir: + count = contents.upload_dir(local_path, remote_path) + state.history.log_event( + name, + "file_operation", + { + "op": "upload", + "local": local_path, + "remote": remote_path, + "recursive": True, + "count": count, + }, + ) + typer.echo( + f"[colab] Uploaded directory '{local_path}' ({count} file(s)) to '{remote_path}'" + ) + else: + contents.upload(local_path, remote_path) + state.history.log_event( + name, + "file_operation", + {"op": "upload", "local": local_path, "remote": remote_path}, + ) + typer.echo(f"[colab] Uploaded '{local_path}' to '{remote_path}'") except Exception as e: typer.echo(f"[colab] Upload failed: {redact_secrets(str(e))}") raise typer.Exit(1) + finally: + contents.close() def download( @@ -118,10 +154,14 @@ def download( str, typer.Argument(help="Remote path to download from") ] = ..., local_path: Annotated[ - str, typer.Argument(help="Local path to save the file") + str, typer.Argument(help="Local path to save the file or directory") ] = ..., + recursive: Annotated[ + bool, + typer.Option("-r", "--recursive", help="Recursively download a directory"), + ] = False, ): - """Download a file from a session""" + """Download a file or directory from a session""" from colab_cli.common import state name = state.resolve_session(session) @@ -129,16 +169,35 @@ def download( s = state.get_session(name) contents = ContentsClient(s) try: - contents.download(remote_path, local_path) - state.history.log_event( - name, - "file_operation", - {"op": "download", "remote": remote_path, "local": local_path}, - ) - typer.echo(f"[colab] Downloaded '{remote_path}' to '{local_path}'") + if recursive: + count = contents.download_dir(remote_path, local_path) + state.history.log_event( + name, + "file_operation", + { + "op": "download", + "remote": remote_path, + "local": local_path, + "recursive": True, + "count": count, + }, + ) + typer.echo( + f"[colab] Downloaded '{remote_path}' ({count} file(s)) to '{local_path}'" + ) + else: + contents.download(remote_path, local_path) + state.history.log_event( + name, + "file_operation", + {"op": "download", "remote": remote_path, "local": local_path}, + ) + typer.echo(f"[colab] Downloaded '{remote_path}' to '{local_path}'") except Exception as e: typer.echo(f"[colab] Download failed: {redact_secrets(str(e))}") raise typer.Exit(1) + finally: + contents.close() def _launch_editor(path: str) -> None: @@ -184,8 +243,6 @@ def edit( remote_path = undo_msys_path(remote_path) s = state.get_session(name) - contents = ContentsClient(s) - def get_file_hash(path): if not os.path.exists(path): return None @@ -201,11 +258,14 @@ def get_file_hash(path): tmpdir, os.path.basename(remote_path.rstrip("/")) or "file" ) + dl_client = ContentsClient(s) try: - contents.download(remote_path, local_path) + dl_client.download(remote_path, local_path) except Exception: # If download fails, assume file doesn't exist and start empty pass + finally: + dl_client.close() if not os.path.exists(local_path): open(local_path, "wb").close() @@ -222,7 +282,11 @@ def get_file_hash(path): hash_after = get_file_hash(local_path) if hash_after != hash_before: - contents.upload(local_path, remote_path) + ul_client = ContentsClient(s) + try: + ul_client.upload(local_path, remote_path) + finally: + ul_client.close() state.history.log_event( name, "file_operation", diff --git a/src/colab_cli/contents.py b/src/colab_cli/contents.py index 2e8367a..b5739bb 100644 --- a/src/colab_cli/contents.py +++ b/src/colab_cli/contents.py @@ -14,6 +14,8 @@ import base64 import json +import os +import posixpath from urllib.parse import quote import requests @@ -22,10 +24,80 @@ from colab_cli.utils import get_status_code +def _write_file_content(data: dict, local_path: str) -> None: + content = data.get("content") + if content is None: + raise ValueError("Missing file content in server response") + fmt = data.get("format") + + if fmt == "base64": + content_bytes = base64.b64decode(content) + elif fmt == "json": + content_bytes = json.dumps(content, indent=2).encode("utf-8") + else: + content_bytes = str(content).encode("utf-8") + + with open(local_path, "wb") as f: + f.write(content_bytes) + + +def _normalize_remote_path(remote_path: str) -> str: + cleaned = remote_path.strip("/") + if not cleaned: + return "" + normalized = posixpath.normpath(cleaned) + if normalized == ".": + return "" + if normalized == ".." or normalized.startswith("../"): + raise ValueError(f"Unsafe remote path: {remote_path!r}") + return normalized + + +def _validate_entry_name(name: object) -> str: + if ( + not isinstance(name, str) + or not name + or name in (".", "..") + or "/" in name + or "\\" in name + or "\x00" in name + or os.path.splitdrive(name)[0] + ): + raise ValueError(f"Unsafe entry name in remote directory: {name!r}") + return name + + +def _is_local_symlink(path: str) -> bool: + """islink() is False for "link/" on POSIX: the trailing slash resolves it.""" + return os.path.islink(path.rstrip("/" + os.sep) or path) + + +def _assert_safe_local_child(real_root: str, child_local: str) -> None: + if _is_local_symlink(child_local): + raise ValueError(f"Refusing to overwrite local symlink: {child_local}") + real_child = os.path.realpath(child_local) + try: + common = os.path.commonpath([real_root, real_child]) + except ValueError as e: + raise ValueError(f"Unsafe destination path: {child_local}") from e + if common != real_root or real_child == real_root: + raise ValueError(f"Unsafe destination path: {child_local}") + + class ContentsClient: def __init__(self, session_state: SessionState): self.base_url = session_state.url.rstrip("/") self.token = session_state.token + self._session = requests.Session() + + def close(self) -> None: + self._session.close() + + def __enter__(self): + return self + + def __exit__(self, *args) -> None: + self.close() def _request( self, method: str, path: str, params: dict = None, json_data: dict = None @@ -38,7 +110,7 @@ def _request( if params: req_params.update(params) - response = requests.request(method, url, params=req_params, json=json_data) + response = self._session.request(method, url, params=req_params, json=json_data) if get_status_code(response) == 404: raise FileNotFoundError(f"File or directory not found: {path}") @@ -48,10 +120,11 @@ def _request( except requests.HTTPError as e: # requests names the full URL, and the runtime proxy token is a # query parameter of it: report the status and path only. + resp = e.response or response + reason = getattr(resp, "reason", None) or "Error" raise requests.HTTPError( - f"{e.response.status_code} {e.response.reason} for " - f"/api/contents/{quoted_path}", - response=e.response, + f"{resp.status_code} {reason} for /api/contents/{quoted_path}", + response=resp, ) from None # DELETE doesn't return JSON @@ -81,25 +154,117 @@ def upload(self, local_path: str, remote_path: str): return self._request("PUT", remote_path, json_data=payload) + def mkdir(self, remote_path: str): + return self._request("PUT", remote_path, json_data={"type": "directory"}) + + def _ensure_dir(self, remote_path: str) -> None: + try: + self.mkdir(remote_path) + except (FileNotFoundError, requests.HTTPError) as e: + if isinstance(e, requests.HTTPError) and get_status_code(e) != 500: + raise + parent = posixpath.dirname(remote_path) + if not parent or parent == remote_path or parent == "content": + raise + self._ensure_dir(parent) + self.mkdir(remote_path) + + def upload_dir(self, local_dir: str, remote_dir: str) -> int: + if not os.path.isdir(local_dir): + raise NotADirectoryError(f"Not a directory: {local_dir}") + base_remote = _normalize_remote_path(remote_dir) + if base_remote: + self._ensure_dir(base_remote) + + def _raise_walk_error(err: OSError) -> None: + raise err + + count = 0 + for root, dirs, files in os.walk( + local_dir, followlinks=False, onerror=_raise_walk_error + ): + dirs[:] = sorted( + d for d in dirs if not os.path.islink(os.path.join(root, d)) + ) + files.sort() + rel = os.path.relpath(root, local_dir) + rel_posix = "" if rel == "." else rel.replace(os.sep, "/") + current_remote = posixpath.join(base_remote, rel_posix) + for d in dirs: + self.mkdir(posixpath.join(current_remote, d)) + for f in files: + local_file = os.path.join(root, f) + if not os.path.islink(local_file) and os.path.isfile(local_file): + self.upload(local_file, posixpath.join(current_remote, f)) + count += 1 + return count + def download(self, remote_path: str, local_path: str): data = self._request("GET", remote_path, params={"content": "1"}) if data.get("type") == "directory": - raise IsADirectoryError(f"Cannot download a directory: {remote_path}") + raise IsADirectoryError( + f"Cannot download a directory: {remote_path}. " + "Use -r/--recursive to download directories." + ) - content = data.get("content", "") - fmt = data.get("format") - - if fmt == "base64": - content_bytes = base64.b64decode(content) - elif fmt == "json": - content_bytes = json.dumps(content, indent=2).encode("utf-8") - else: - # Assume text if it's not base64 explicitly encoded - content_bytes = str(content).encode("utf-8") - - with open(local_path, "wb") as f: - f.write(content_bytes) + _write_file_content(data, local_path) + + def download_dir( + self, + remote_path: str, + local_path: str, + *, + _depth: int = 0, + _max_depth: int = 64, + ) -> int: + if _depth > _max_depth: + raise RecursionError( + f"Maximum directory depth ({_max_depth}) exceeded while downloading {remote_path!r}" + ) + base_remote = _normalize_remote_path(remote_path) + data = self._request("GET", base_remote, params={"content": "1"}) + if data.get("type") != "directory": + if _is_local_symlink(local_path): + raise ValueError(f"Refusing to overwrite local symlink: {local_path}") + if os.path.isdir(local_path) or local_path.endswith(("/", os.sep)): + target_name = _validate_entry_name( + data.get("name") or posixpath.basename(base_remote) + ) + os.makedirs(local_path, exist_ok=True) + target = os.path.join(local_path, target_name) + _assert_safe_local_child(os.path.realpath(local_path), target) + _write_file_content(data, target) + else: + parent = os.path.dirname(local_path) + if parent: + os.makedirs(parent, exist_ok=True) + _write_file_content(data, local_path) + return 1 + + if _is_local_symlink(local_path): + raise ValueError(f"Refusing to traverse local symlink: {local_path}") + os.makedirs(local_path, exist_ok=True) + real_root = os.path.realpath(local_path) + count = 0 + for item in data.get("content") or []: + item_name = _validate_entry_name(item.get("name", "")) + child_remote = ( + posixpath.join(base_remote, item_name) if base_remote else item_name + ) + child_local = os.path.join(local_path, item_name) + _assert_safe_local_child(real_root, child_local) + if item.get("type") == "directory": + count += self.download_dir( + child_remote, + child_local, + _depth=_depth + 1, + _max_depth=_max_depth, + ) + else: + self.download(child_remote, child_local) + count += 1 + return count def read_text(self, remote_path: str) -> str: """The content of a remote file as text (UTF-8).""" diff --git a/tests/test_cli.py b/tests/test_cli.py index 0242368..d26ecce 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1005,3 +1005,143 @@ def test_cli_test_public_api_hidden_and_reports_status(mock_common_state): assert res.exit_code == 0 assert "Public API" in res.output assert "Tunnel API" in res.output + + +@patch("colab_cli.commands.files.ContentsClient") +def test_cli_upload_directory_requires_recursive( + mock_contents_class, mock_store, mock_common_state, tmp_path +): + mock_store.get.return_value = MagicMock() + mock_common_state.resolve_session.return_value = "s1" + local_dir = tmp_path / "mydir" + local_dir.mkdir() + + result = runner.invoke(app, ["upload", "-s", "s1", str(local_dir), "content/mydir"]) + + assert result.exit_code == 1 + assert "-r/--recursive" in result.output + mock_contents_class.return_value.upload.assert_not_called() + mock_contents_class.return_value.upload_dir.assert_not_called() + + +@patch("colab_cli.commands.files.ContentsClient") +def test_cli_upload_recursive_directory( + mock_contents_class, mock_store, mock_common_state, tmp_path +): + mock_store.get.return_value = MagicMock() + mock_common_state.resolve_session.return_value = "s1" + mock_contents_class.return_value.upload_dir.return_value = 3 + local_dir = tmp_path / "mydir" + local_dir.mkdir() + + result = runner.invoke( + app, ["upload", "-r", "-s", "s1", str(local_dir), "content/mydir"] + ) + + assert result.exit_code == 0 + mock_contents_class.return_value.upload_dir.assert_called_once_with( + str(local_dir), "content/mydir" + ) + assert "3 file(s)" in result.output + + +@patch("colab_cli.commands.files.ContentsClient") +def test_cli_upload_recursive_single_file( + mock_contents_class, mock_store, mock_common_state, tmp_path +): + mock_store.get.return_value = MagicMock() + mock_common_state.resolve_session.return_value = "s1" + local_file = tmp_path / "a.txt" + local_file.write_text("hi", encoding="utf-8") + + result = runner.invoke( + app, ["upload", "-r", "-s", "s1", str(local_file), "content/a.txt"] + ) + + assert result.exit_code == 0 + mock_contents_class.return_value.upload.assert_called_once_with( + str(local_file), "content/a.txt" + ) + mock_contents_class.return_value.upload_dir.assert_not_called() + + +@patch("colab_cli.commands.files.ContentsClient") +def test_cli_download_recursive( + mock_contents_class, mock_store, mock_common_state, tmp_path +): + mock_store.get.return_value = MagicMock() + mock_common_state.resolve_session.return_value = "s1" + mock_contents_class.return_value.download_dir.return_value = 4 + dest = tmp_path / "out" + + result = runner.invoke( + app, ["download", "-r", "-s", "s1", "content/mydir", str(dest)] + ) + + assert result.exit_code == 0 + mock_contents_class.return_value.download_dir.assert_called_once_with( + "content/mydir", str(dest) + ) + assert "4 file(s)" in result.output + + +@patch("colab_cli.commands.files.ContentsClient") +@patch("click.edit") +def test_cli_edit_uses_fresh_client_for_upload( + mock_edit, mock_contents_class, mock_store, mock_common_state +): + mock_store.get.return_value = MagicMock() + mock_common_state.resolve_session.return_value = "s1" + dl_client = MagicMock() + ul_client = MagicMock() + mock_contents_class.side_effect = [dl_client, ul_client] + + def modify(filename, **kwargs): + with open(filename, "a") as f: + f.write("edited") + + mock_edit.side_effect = modify + + result = runner.invoke(app, ["edit", "-s", "s1", "remote.txt"]) + + assert result.exit_code == 0 + dl_client.download.assert_called_once() + dl_client.close.assert_called_once() + ul_client.upload.assert_called_once() + ul_client.close.assert_called_once() + + +@patch("colab_cli.commands.files.ContentsClient") +def test_cli_download_directory_without_recursive( + mock_contents_class, mock_store, mock_common_state, tmp_path +): + mock_store.get.return_value = MagicMock() + mock_common_state.resolve_session.return_value = "s1" + mock_contents_class.return_value.download.side_effect = IsADirectoryError( + "Cannot download a directory: content/mydir. " + "Use -r/--recursive to download directories." + ) + + result = runner.invoke( + app, ["download", "-s", "s1", "content/mydir", str(tmp_path / "out")] + ) + + assert result.exit_code == 1 + assert "-r/--recursive" in result.output + mock_contents_class.return_value.close.assert_called_once() + + +@patch("colab_cli.commands.files.ContentsClient") +def test_cli_upload_recursive_missing_path( + mock_contents_class, mock_store, mock_common_state, tmp_path +): + mock_store.get.return_value = MagicMock() + mock_common_state.resolve_session.return_value = "s1" + + result = runner.invoke( + app, ["upload", "-r", "-s", "s1", str(tmp_path / "nope"), "content/nope"] + ) + + assert result.exit_code == 1 + assert "Local path" in result.output + mock_contents_class.assert_not_called() diff --git a/tests/test_contents.py b/tests/test_contents.py index 0160c05..e893629 100644 --- a/tests/test_contents.py +++ b/tests/test_contents.py @@ -14,9 +14,11 @@ import base64 import json +import sys from unittest.mock import MagicMock, patch import pytest +import requests from colab_cli.contents import ContentsClient from requests import Response @@ -38,7 +40,7 @@ def client(session): return ContentsClient(session) -@patch("colab_cli.contents.requests.request") +@patch("colab_cli.contents.requests.Session.request") def test_list_dir(mock_request, client): mock_resp = MagicMock(spec=Response) mock_resp.status_code = 200 @@ -64,7 +66,7 @@ def test_list_dir(mock_request, client): assert len(res["content"]) == 2 -@patch("colab_cli.contents.requests.request") +@patch("colab_cli.contents.requests.Session.request") def test_rm_file(mock_request, client): mock_resp = MagicMock(spec=Response) mock_resp.status_code = 204 @@ -80,7 +82,7 @@ def test_rm_file(mock_request, client): ) -@patch("colab_cli.contents.requests.request") +@patch("colab_cli.contents.requests.Session.request") def test_404_error(mock_request, client): mock_resp = MagicMock(spec=Response) mock_resp.status_code = 404 @@ -90,7 +92,7 @@ def test_404_error(mock_request, client): client.list_dir("nonexistent") -@patch("colab_cli.contents.requests.request") +@patch("colab_cli.contents.requests.Session.request") def test_download_file(mock_request, client, tmp_path): mock_resp = MagicMock(spec=Response) mock_resp.status_code = 200 @@ -124,7 +126,7 @@ def test_download_file(mock_request, client, tmp_path): assert local_file.read_bytes() == content_bytes -@patch("colab_cli.contents.requests.request") +@patch("colab_cli.contents.requests.Session.request") def test_download_notebook_json_format(mock_request, client, tmp_path): """Downloading a format=json payload serializes valid 2-space indented JSON.""" notebook_doc = { @@ -160,7 +162,7 @@ def test_download_notebook_json_format(mock_request, client, tmp_path): assert raw == json.dumps(notebook_doc, indent=2) -@patch("colab_cli.contents.requests.request") +@patch("colab_cli.contents.requests.Session.request") def test_upload_file(mock_request, client, tmp_path): mock_resp = MagicMock(spec=Response) mock_resp.status_code = 200 @@ -202,7 +204,7 @@ def _http_error_response(status, reason): return resp -@patch("colab_cli.contents.requests.request") +@patch("colab_cli.contents.requests.Session.request") def test_http_error_message_hides_the_proxy_token(mock_request, client): """requests puts the full URL, query string included, in HTTPError. The runtime proxy token is a query parameter, so it must not reach the @@ -219,7 +221,7 @@ def test_http_error_message_hides_the_proxy_token(mock_request, client): assert "up.txt" in message -@patch("colab_cli.contents.requests.request") +@patch("colab_cli.contents.requests.Session.request") def test_read_text_handles_text_and_base64(mock_request, client): resp = MagicMock(spec=Response) resp.status_code = 200 @@ -234,7 +236,7 @@ def test_read_text_handles_text_and_base64(mock_request, client): assert client.read_text("/content/x.bin") == "ünnep" -@patch("colab_cli.contents.requests.request") +@patch("colab_cli.contents.requests.Session.request") def test_write_text_puts_a_text_file(mock_request, client): resp = MagicMock(spec=Response) resp.status_code = 200 @@ -247,3 +249,555 @@ def test_write_text_puts_a_text_file(mock_request, client): assert method == "PUT" and url.endswith("/api/contents/content/.colab-jobs/j/stop") payload = mock_request.call_args.kwargs["json"] assert payload["format"] == "text" and payload["content"] == "" and payload["name"] == "stop" + + +@patch("colab_cli.contents.requests.Session.request") +def test_mkdir(mock_request, client): + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 201 + mock_request.return_value = mock_resp + + client.mkdir("content/new_dir") + + mock_request.assert_called_once_with( + "PUT", + "https://fake-endpoint.colab.dev/api/contents/content/new_dir", + params={"authuser": "0", "colab-runtime-proxy-token": "test-token"}, + json={"type": "directory"}, + ) + + +@patch("colab_cli.contents.requests.Session.request") +def test_upload_dir(mock_request, client, tmp_path): + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 200 + mock_request.return_value = mock_resp + + src = tmp_path / "proj" + (src / "sub").mkdir(parents=True) + (src / "empty").mkdir() + (src / "root.txt").write_text("root", encoding="utf-8") + (src / "sub" / "bin.dat").write_bytes(b"\x00\x01\xff") + + count = client.upload_dir(str(src), "content/proj") + + assert count == 2 + urls = [c.args[1] for c in mock_request.call_args_list] + assert urls == [ + "https://fake-endpoint.colab.dev/api/contents/content/proj", + "https://fake-endpoint.colab.dev/api/contents/content/proj/empty", + "https://fake-endpoint.colab.dev/api/contents/content/proj/sub", + "https://fake-endpoint.colab.dev/api/contents/content/proj/root.txt", + "https://fake-endpoint.colab.dev/api/contents/content/proj/sub/bin.dat", + ] + assert mock_request.call_args_list[0].kwargs["json"] == {"type": "directory"} + assert mock_request.call_args_list[1].kwargs["json"] == {"type": "directory"} + assert mock_request.call_args_list[2].kwargs["json"] == {"type": "directory"} + assert ( + mock_request.call_args_list[4].kwargs["json"]["path"] + == "content/proj/sub/bin.dat" + ) + + +@patch("colab_cli.contents.requests.Session.request") +def test_download_directory_raises_with_hint(mock_request, client, tmp_path): + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 200 + mock_resp.json.return_value = {"name": "mydir", "type": "directory", "content": []} + mock_request.return_value = mock_resp + + with pytest.raises(IsADirectoryError, match="-r/--recursive"): + client.download("content/mydir", str(tmp_path / "mydir")) + + +@patch("colab_cli.contents.requests.Session.request") +def test_download_dir(mock_request, client, tmp_path): + responses = { + "https://fake-endpoint.colab.dev/api/contents/content/proj": { + "name": "proj", + "type": "directory", + "content": [ + {"name": "root.txt", "path": "content/proj/root.txt", "type": "file"}, + { + "name": "nb.ipynb", + "path": "content/proj/nb.ipynb", + "type": "notebook", + }, + {"name": "sub", "path": "content/proj/sub", "type": "directory"}, + {"name": "empty", "path": "content/proj/empty", "type": "directory"}, + ], + }, + "https://fake-endpoint.colab.dev/api/contents/content/proj/root.txt": { + "name": "root.txt", + "type": "file", + "format": "text", + "content": "hello", + }, + "https://fake-endpoint.colab.dev/api/contents/content/proj/nb.ipynb": { + "name": "nb.ipynb", + "type": "notebook", + "format": "json", + "content": {"cells": [], "nbformat": 4}, + }, + "https://fake-endpoint.colab.dev/api/contents/content/proj/sub": { + "name": "sub", + "type": "directory", + "content": [ + {"name": "bin.dat", "path": "content/proj/sub/bin.dat", "type": "file"} + ], + }, + "https://fake-endpoint.colab.dev/api/contents/content/proj/sub/bin.dat": { + "name": "bin.dat", + "type": "file", + "format": "base64", + "content": base64.b64encode(b"\x00\x02").decode("ascii"), + }, + "https://fake-endpoint.colab.dev/api/contents/content/proj/empty": { + "name": "empty", + "type": "directory", + "content": [], + }, + } + + def side_effect(method, url, **kwargs): + resp = MagicMock(spec=Response) + resp.status_code = 200 + resp.json.return_value = responses[url] + return resp + + mock_request.side_effect = side_effect + + dest = tmp_path / "out" + count = client.download_dir("content/proj", str(dest)) + + assert count == 3 + assert (dest / "root.txt").read_text(encoding="utf-8") == "hello" + assert json.loads((dest / "nb.ipynb").read_text(encoding="utf-8")) == { + "cells": [], + "nbformat": 4, + } + assert (dest / "sub" / "bin.dat").read_bytes() == b"\x00\x02" + assert (dest / "empty").is_dir() + + +@patch("colab_cli.contents.requests.Session.request") +def test_download_dir_single_file(mock_request, client, tmp_path): + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 200 + mock_resp.json.return_value = { + "name": "solo.txt", + "type": "file", + "format": "text", + "content": "solo", + } + mock_request.return_value = mock_resp + + dest = tmp_path / "nested" / "solo.txt" + count = client.download_dir("content/solo.txt", str(dest)) + + assert count == 1 + assert dest.read_text(encoding="utf-8") == "solo" + + +@patch("colab_cli.contents.requests.Session.request") +def test_download_dir_rejects_unsafe_entry_name(mock_request, client, tmp_path): + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 200 + mock_resp.json.return_value = { + "name": "dir", + "type": "directory", + "content": [{"name": "../escape", "path": "content/escape", "type": "file"}], + } + mock_request.return_value = mock_resp + + with pytest.raises(ValueError, match="Unsafe"): + client.download_dir("content/dir", str(tmp_path / "out")) + + +@patch("colab_cli.contents.requests.Session.request") +def test_upload_dir_creates_missing_remote_parents(mock_request, client, tmp_path): + src = tmp_path / "proj" + src.mkdir() + (src / "a.txt").write_text("hi", encoding="utf-8") + + attempts = {} + + def side_effect(method, url, **kwargs): + attempts[url] = attempts.get(url, 0) + 1 + resp = MagicMock(spec=Response) + if url.endswith("/content/a/b/proj") and attempts[url] == 1: + resp.status_code = 500 + resp.raise_for_status.side_effect = requests.HTTPError("500", response=resp) + return resp + if url.endswith("/content/a/b") and attempts[url] == 1: + resp.status_code = 500 + resp.raise_for_status.side_effect = requests.HTTPError("500", response=resp) + return resp + resp.status_code = 200 + return resp + + mock_request.side_effect = side_effect + + count = client.upload_dir(str(src), "content/a/b/proj") + + assert count == 1 + urls = [c.args[1] for c in mock_request.call_args_list] + assert urls == [ + "https://fake-endpoint.colab.dev/api/contents/content/a/b/proj", + "https://fake-endpoint.colab.dev/api/contents/content/a/b", + "https://fake-endpoint.colab.dev/api/contents/content/a", + "https://fake-endpoint.colab.dev/api/contents/content/a/b", + "https://fake-endpoint.colab.dev/api/contents/content/a/b/proj", + "https://fake-endpoint.colab.dev/api/contents/content/a/b/proj/a.txt", + ] + + +@patch("colab_cli.contents.requests.Session.request") +def test_upload_dir_does_not_recurse_on_403(mock_request, client, tmp_path): + src = tmp_path / "proj" + src.mkdir() + (src / "a.txt").write_text("hi", encoding="utf-8") + + resp = MagicMock(spec=Response) + resp.status_code = 403 + resp.raise_for_status.side_effect = requests.HTTPError("403", response=resp) + mock_request.return_value = resp + + with pytest.raises(requests.HTTPError): + client.upload_dir(str(src), "content/a/proj") + + assert mock_request.call_count == 1 + + +@patch("colab_cli.contents.requests.Session.request") +def test_upload_dir_does_not_mkdir_content_root_on_500(mock_request, client, tmp_path): + src = tmp_path / "proj" + src.mkdir() + (src / "a.txt").write_text("hi", encoding="utf-8") + + resp = MagicMock(spec=Response) + resp.status_code = 500 + resp.raise_for_status.side_effect = requests.HTTPError("500", response=resp) + mock_request.return_value = resp + + with pytest.raises(requests.HTTPError): + client.upload_dir(str(src), "content/proj") + + assert mock_request.call_count == 1 + + +@patch("colab_cli.contents.requests.Session.request") +def test_upload_dir_skips_symlinked_directories(mock_request, client, tmp_path): + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 200 + mock_request.return_value = mock_resp + + ext = tmp_path / "ext_dir" + ext.mkdir() + (ext / "secret.txt").write_text("secret", encoding="utf-8") + + src = tmp_path / "proj" + src.mkdir() + (src / "a.txt").write_text("hi", encoding="utf-8") + (src / "linked_dir").symlink_to(ext, target_is_directory=True) + + count = client.upload_dir(str(src), "content/proj") + + assert count == 1 + urls = [c.args[1] for c in mock_request.call_args_list] + assert urls == [ + "https://fake-endpoint.colab.dev/api/contents/content/proj", + "https://fake-endpoint.colab.dev/api/contents/content/proj/a.txt", + ] + + +@patch("colab_cli.contents.requests.Session.request") +def test_download_dir_ignores_untrusted_item_path(mock_request, client, tmp_path): + responses = { + "https://fake-endpoint.colab.dev/api/contents/content/proj": { + "name": "proj", + "type": "directory", + "content": [ + { + "name": "safe.txt", + "path": "other/untrusted.txt", + "type": "file", + } + ], + }, + "https://fake-endpoint.colab.dev/api/contents/content/proj/safe.txt": { + "name": "safe.txt", + "type": "file", + "format": "text", + "content": "trusted", + }, + } + + def side_effect(method, url, **kwargs): + resp = MagicMock(spec=Response) + resp.status_code = 200 + resp.json.return_value = responses[url] + return resp + + mock_request.side_effect = side_effect + + dest = tmp_path / "out" + count = client.download_dir("content/proj", str(dest)) + + assert count == 1 + assert (dest / "safe.txt").read_text(encoding="utf-8") == "trusted" + + +def test_reuses_http_session_across_requests(client, tmp_path): + assert isinstance(client._session, requests.Session) + local_file = tmp_path / "a.txt" + local_file.write_text("hi", encoding="utf-8") + + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 200 + with patch.object(client._session, "request", return_value=mock_resp) as m_req: + client.mkdir("content/proj") + client.upload(str(local_file), "content/proj/a.txt") + + assert m_req.call_count == 2 + assert m_req.call_args_list[0].args[0] == "PUT" + assert m_req.call_args_list[1].args[0] == "PUT" + + +@patch("colab_cli.contents.requests.Session.request") +def test_http_error_omits_runtime_proxy_token(mock_request, client): + resp = Response() + resp.status_code = 400 + resp.reason = "Bad Request" + resp.url = ( + "https://fake-endpoint.colab.dev/api/contents/content/x" + "?authuser=0&colab-runtime-proxy-token=SECRET-JWT" + ) + mock_request.return_value = resp + + with pytest.raises(requests.HTTPError) as exc_info: + client.list_dir("content/x") + + assert exc_info.value.response.status_code == 400 + assert "SECRET-JWT" not in str(exc_info.value) + assert "colab-runtime-proxy-token" not in str(exc_info.value) + + +@patch("colab_cli.contents.requests.Session.request") +def test_upload_dir_skips_symlinked_files_and_broken_symlinks( + mock_request, client, tmp_path +): + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 200 + mock_request.return_value = mock_resp + + secret = tmp_path / "secret.txt" + secret.write_text("secret", encoding="utf-8") + + src = tmp_path / "proj" + src.mkdir() + (src / "real.txt").write_text("ok", encoding="utf-8") + (src / "link.txt").symlink_to(secret) + (src / "broken.txt").symlink_to(tmp_path / "missing.txt") + + count = client.upload_dir(str(src), "content/proj") + + assert count == 1 + urls = [c.args[1] for c in mock_request.call_args_list] + assert urls == [ + "https://fake-endpoint.colab.dev/api/contents/content/proj", + "https://fake-endpoint.colab.dev/api/contents/content/proj/real.txt", + ] + + +@patch("colab_cli.contents.requests.Session.request") +def test_upload_dir_raises_on_non_directory_or_walk_error( + mock_request, client, tmp_path, mocker +): + not_a_dir = tmp_path / "file.txt" + not_a_dir.write_text("hi", encoding="utf-8") + + with pytest.raises(NotADirectoryError): + client.upload_dir(str(not_a_dir), "content/proj") + mock_request.assert_not_called() + + src = tmp_path / "proj" + src.mkdir() + + def failing_walk(*args, onerror=None, **kwargs): + onerror(PermissionError("denied")) + return iter([]) + + mocker.patch("colab_cli.contents.os.walk", side_effect=failing_walk) + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 200 + mock_request.return_value = mock_resp + + with pytest.raises(PermissionError, match="denied"): + client.upload_dir(str(src), "content/proj") + + +@patch("colab_cli.contents.requests.Session.request") +def test_upload_dir_normalizes_remote_dir(mock_request, client, tmp_path): + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 200 + mock_request.return_value = mock_resp + + src = tmp_path / "proj" + src.mkdir() + (src / "a.txt").write_text("hi", encoding="utf-8") + + client.upload_dir(str(src), "./content//proj/") + urls = [c.args[1] for c in mock_request.call_args_list] + assert urls == [ + "https://fake-endpoint.colab.dev/api/contents/content/proj", + "https://fake-endpoint.colab.dev/api/contents/content/proj/a.txt", + ] + + with pytest.raises(ValueError, match="Unsafe"): + client.upload_dir(str(src), "../escape") + + +@pytest.mark.parametrize( + "bad_name", + [ + pytest.param( + name, + marks=pytest.mark.skipif( + sys.platform != "win32", + reason="a drive prefix only means something on Windows", + ), + ) + for name in ("C:evil.txt", "D:evil.txt") + ] + + [123, "bad\x00name", "", ".", "..", "a\\b", "a/b"], +) +@patch("colab_cli.contents.requests.Session.request") +def test_download_dir_rejects_unsafe_entry_variants( + mock_request, client, tmp_path, bad_name +): + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 200 + mock_resp.json.return_value = { + "name": "dir", + "type": "directory", + "content": [{"name": bad_name, "type": "file"}], + } + mock_request.return_value = mock_resp + + with pytest.raises(ValueError, match="Unsafe"): + client.download_dir("content/dir", str(tmp_path / "out")) + + +@patch("colab_cli.contents.requests.Session.request") +def test_download_dir_rejects_local_symlink(mock_request, client, tmp_path): + outside = tmp_path / "outside.txt" + outside.write_text("keep", encoding="utf-8") + + dest = tmp_path / "out" + dest.mkdir() + (dest / "file.txt").symlink_to(outside) + + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 200 + mock_resp.json.return_value = { + "name": "dir", + "type": "directory", + "content": [{"name": "file.txt", "type": "file"}], + } + mock_request.return_value = mock_resp + + with pytest.raises(ValueError, match="symlink"): + client.download_dir("content/dir", str(dest)) + + assert outside.read_text(encoding="utf-8") == "keep" + + +@patch("colab_cli.contents.requests.Session.request") +def test_download_dir_single_file_into_existing_or_trailing_slash_dir( + mock_request, client, tmp_path +): + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 200 + mock_resp.json.return_value = { + "name": "solo.txt", + "type": "file", + "format": "text", + "content": "solo", + } + mock_request.return_value = mock_resp + + existing = tmp_path / "existing" + existing.mkdir() + assert client.download_dir("content/solo.txt", str(existing)) == 1 + assert (existing / "solo.txt").read_text(encoding="utf-8") == "solo" + + trailing = tmp_path / "new_dir" + assert client.download_dir("content/solo.txt", f"{trailing}/") == 1 + assert (trailing / "solo.txt").read_text(encoding="utf-8") == "solo" + + +@patch("colab_cli.contents.requests.Session.request") +def test_download_dir_max_depth_guard(mock_request, client, tmp_path): + def side_effect(method, url, **kwargs): + resp = MagicMock(spec=Response) + resp.status_code = 200 + resp.json.return_value = { + "name": "loop", + "type": "directory", + "content": [{"name": "loop", "type": "directory"}], + } + return resp + + mock_request.side_effect = side_effect + + with pytest.raises(RecursionError, match="Maximum directory depth"): + client.download_dir("content/loop", str(tmp_path / "out"), _max_depth=3) + + +@patch("colab_cli.contents.requests.Session.request") +def test_download_none_content_raises(mock_request, client, tmp_path): + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 200 + mock_resp.json.return_value = { + "name": "f.txt", + "type": "file", + "format": "text", + "content": None, + } + mock_request.return_value = mock_resp + + with pytest.raises(ValueError, match="Missing file content"): + client.download("content/f.txt", str(tmp_path / "f.txt")) + + +def test_context_manager_closes_session(session): + c = ContentsClient(session) + with patch.object(c._session, "close") as m_close: + with c as entered: + assert entered is c + m_close.assert_called_once_with() + + +@patch("colab_cli.contents.requests.Session.request") +def test_download_dir_refuses_a_symlinked_destination_with_a_trailing_slash( + mock_request, client, tmp_path +): + """os.path.islink("link/") is False: the slash resolves the link.""" + outside = tmp_path / "outside" + outside.mkdir() + link = tmp_path / "link" + try: + link.symlink_to(outside, target_is_directory=True) + except OSError: + pytest.skip("symlinks need extra rights here") + mock_resp = MagicMock(spec=Response) + mock_resp.status_code = 200 + mock_resp.json.return_value = { + "name": "solo.txt", "type": "file", "format": "text", "content": "x", + } + mock_request.return_value = mock_resp + + with pytest.raises(ValueError, match="symlink"): + client.download_dir("content/solo.txt", f"{link}/") + assert not (outside / "solo.txt").exists()