diff --git a/CHANGELOG.md b/CHANGELOG.md index 8633acd9..af48fc98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,10 @@ below corresponds to a tag of the same name. ### Added - **ssh:** `colab ssh [-s NAME] -- CMD` runs one command on an existing runtime and exits with its status. Output is byte-exact when piped (a PTY only when stdin and stdout are terminals), and it never creates a runtime. Its handshake is tagged `ssh-mode-cmd`. +- **ssh:** `colab ssh` uses `~/.ssh/colab_cli_ed25519` when it exists, ahead of `id_ed25519` and `id_ecdsa`, for the interactive shell, `-- CMD` and `--proxy-mode`. +- **ssh:** Without `--identity` or a usable key, `colab ssh` creates `~/.ssh/colab_cli_ed25519` on first use and reuses it, and tells users with only an RSA key why it did not use that key. +- **ssh:** `colab ssh` names the `IdentityFile` line to add to `~/.ssh/config` + whenever it creates or, in `--proxy-mode`, picks `~/.ssh/colab_cli_ed25519`. ### Removed @@ -44,6 +48,12 @@ below corresponds to a tag of the same name. older versions may contain credentials and can be deleted; if other users could read an old log, revoke the CLI's access in your Google Account and sign in again. +- **ssh:** `colab ssh` now checks its key before creating a runtime: a missing + `--identity` file, an empty `--identity` value, or an empty `.pub` with no + private key, or a blocked default key write, exits 2 before creating a + runtime. +- **ssh:** Parallel first runs, such as several ProxyCommands started at once, + share one generated key instead of failing. ## [0.7.1] - 2026-09-14 diff --git a/docs/06_ssh_access.md b/docs/06_ssh_access.md index b659c5ab..0385402a 100644 --- a/docs/06_ssh_access.md +++ b/docs/06_ssh_access.md @@ -1,5 +1,6 @@ --- log: +2026-12-03: `colab ssh` now checks its key before resolving or creating a session (exiting 2 on a missing `--identity` file, accepting either `.pub` or private paths), prefers `~/.ssh/colab_cli_ed25519` ahead of `id_ed25519` and `id_ecdsa`, and generates it on first use when no usable key exists (sharing one key across parallel runs, explaining why `id_rsa` is skipped, and noting the `IdentityFile` line for `~/.ssh/config` users). 2026-11-27: Fixed `colab ssh` under Git for Windows' MSYS `ssh` (`/usr/bin/ssh` in Git Bash): ProxyCommand path arguments now use forward slashes on Windows (bash stripped the backslashes, failing with `D:Projects...python.exe: not found`), and `UserKnownHostsFile` is `/dev/null` when `ssh.exe` is an MSYS/Cygwin build (it wrote the host key to a `./nul` file). Native Windows OpenSSH keeps `nul`. Verified live from Git Bash and PowerShell (OpenSSH_for_Windows 9.5), and `integration/repro_windows_ssh/test.py` passed. 2026-11-23: Updated `integration/repro_windows_ssh/test.py` to check cached OAuth2 credentials via the OS `keyring` (`KEYRING_SERVICE_NAME` / `KEYRING_USERNAME`) instead of the removed `TOKEN_CONFIG_PATH`, and added portable import and prerequisite-skip regression tests in `tests/test_windows_ssh.py`. 2026-11-09: `--identity/-i` now accepts either a `.pub` public key or a private key path: `_resolve_pubkey` reads the `.pub` file directly when present before falling back to `_pubkey_from_identity` (`ssh-keygen -y -f`), and `_ssh_base_args` strips `.pub` for `ssh -i` when the sibling private key exists on disk. @@ -38,7 +39,7 @@ colab ssh [OPTIONS] [-- CMD [ARGS]...] |---|---|---|---| | `-s`, `--session` | str | auto | Session to connect to. If omitted, uses your only active session, auto-creates one when you have none (not with `-- CMD`), or errors when you have several. | | `--proxy-mode` | bool | False | Act as an OpenSSH `ProxyCommand`-compatible WebSocket↔stdio bridge (reads stdin, writes stdout) for `~/.ssh/config`. Every other flag still applies. | -| `-i`, `--identity` | str | auto | SSH key (`.pub` public key or private key path) for the public key sent to Colab. Default: first of `~/.ssh/id_ed25519.pub`, `id_ecdsa.pub`. | +| `-i`, `--identity` | str | auto | SSH key (`.pub` public key or private key path) for the public key sent to Colab. Default: first of `~/.ssh/colab_cli_ed25519`, `id_ed25519`, `id_ecdsa` (else `~/.ssh/colab_cli_ed25519` is generated). | | `--gpu` | str | None | GPU accelerator for a runtime this command creates (T4, L4, G4, H100, A100). | | `--tpu` | str | None | TPU accelerator for a runtime this command creates (v5e1, v6e1). | | `--high-mem` | bool | False | Request high-RAM when this command auto-creates a runtime (ignored when connecting to an existing session). | @@ -62,6 +63,12 @@ where a bare `colab` may not be on `PATH`. External SSH tools run their own remote command, so to also land in `/content` add `RequestTTY yes` and `RemoteCommand cd /content 2>/dev/null; exec bash -l`. +If `colab ssh` created `~/.ssh/colab_cli_ed25519` for you, also add +`IdentityFile ~/.ssh/colab_cli_ed25519`. A config `IdentityFile` works even on +the first connect, when the ProxyCommand creates the key; `ssh -i` with a +missing file does not. `--proxy-mode` prints this line when it picks that key; +adding `--identity ~/.ssh/colab_cli_ed25519` to the ProxyCommand silences it. + ### Remote command `colab ssh [-s NAME] -- CMD [ARGS]...` runs CMD in `/content` on an existing session (never creating one); every word from CMD on goes to CMD, flags too. @@ -88,7 +95,10 @@ session (never creating one); every word from CMD on goes to CMD, flags too. `colab ssh` uses your only active session; with **no** session it auto-creates one (mirrors `colab new`: assign → persist `SessionState`; never with `-- CMD`); with **multiple** - it errors and asks you to pick one with `-s`. + it errors and asks you to pick one with `-s`. Before that, it checks the + key: a missing `--identity` file, an empty `--identity` value, or an empty `.pub` with no private key, or an unusable or uncreatable + default key (such as a stray path or missing `ssh-keygen`), exits 2 before + any session is resolved or created. 2. **Connect**: Opens the WebSocket to `wss:///colab/ssh?colab-runtime-proxy-token=` and sends the resolved public key verbatim in the `X-Colab-Ssh-Pubkey` header (no transformation -- the bytes the user controls are exactly what the server @@ -97,6 +107,11 @@ session (never creating one); every word from CMD on goes to CMD, flags too. `&colab-client-agent=colab-cli&colab-client-agent=ssh-mode-`: `interactive` for plain `colab ssh`, `cmd` for `colab ssh -- CMD`, `proxy` for a user-written `ProxyCommand` or an IDE. + Without `--identity`, the key is `~/.ssh/colab_cli_ed25519` (with + its `.pub`), then `id_ed25519`, then `id_ecdsa` (each with its `.pub`). The + first is passed to `ssh` as `-i`; the other two leave `ssh` its own key choice. + With none of them, `colab ssh` generates `~/.ssh/colab_cli_ed25519`; + parallel first runs share one key. 3. **Interactive shell**: Spawns the system `ssh` binary with the CLI re-invoked as its own `ProxyCommand` (`python -m colab_cli.cli ssh --proxy-mode --colab-internal-mode interactive`), so the WebSocket bridge and the interactive shell share one code path. It forces a @@ -149,10 +164,12 @@ session (never creating one); every word from CMD on goes to CMD, flags too. ### Unit tests (`tests/test_ssh.py`) 1. WebSocket URL construction (`wss` for https, `ws` for http; token query param). -2. Pubkey resolution — `--identity` (reads the matching `.pub` file first, - whether passed with or without `.pub`, before falling back to `ssh-keygen -y - -f`) and the `~/.ssh` default scan; missing-key and missing-identity exit - paths. +2. Pubkey resolution & key setup — `--identity` (reads the matching `.pub` file + first, whether passed with or without `.pub`, before falling back to + `ssh-keygen -y -f`), `resolve_default_identity()` (`~/.ssh/colab_cli_ed25519` + -> `id_ed25519` -> `id_ecdsa`), automatic generation and reuse of + `~/.ssh/colab_cli_ed25519` (with RSA notice, `IdentityFile` hint, write-error + cleanup, and parallel first-run sharing), and missing-identity early exits. 3. The full status→message map (400/401/403/404/429/502/other/none). 4. Shell quoting for the `ProxyCommand` string. 5. Session resolution (existing vs missing). diff --git a/integration/repro_ssh/test.sh b/integration/repro_ssh/test.sh index 82c467e9..7b16739d 100644 --- a/integration/repro_ssh/test.sh +++ b/integration/repro_ssh/test.sh @@ -46,15 +46,18 @@ done echo "== A2: an unknown session exits 2 with an actionable message (offline) ==" OFFLINE_CFG="$(mktemp -d)/sessions.json" -A2_OUT="$(uv run colab --config "$OFFLINE_CFG" ssh -s ghost-no-such-session 2>&1)" +A2_KEY="$(mktemp)" +A2_OUT="$(uv run colab --config "${OFFLINE_CFG}" ssh -s ghost-no-such-session \ + -i "${A2_KEY}" 2>&1)" A2_RC=$? +rm -f "${A2_KEY}" echo "$A2_OUT" if [ "$A2_RC" -ne 2 ]; then echo "FAIL: expected exit 2 for an unknown session, got $A2_RC" fail=1 fi -if ! printf '%s' "$A2_OUT" | grep -q "not found"; then - echo "FAIL: expected a 'not found' message for an unknown session" +if ! printf '%s' "${A2_OUT}" | grep -q "session 'ghost-no-such-session' not found"; then + echo "FAIL: expected the unknown-session message" fail=1 fi diff --git a/skills/colab-operator/SKILL.md b/skills/colab-operator/SKILL.md index c0c770fd..6fedf9f4 100644 --- a/skills/colab-operator/SKILL.md +++ b/skills/colab-operator/SKILL.md @@ -51,7 +51,7 @@ by running `uv tool install google-colab-cli` or `pip install google-colab-cli`. - **Notebooks**: `colab exec -s -f nb.ipynb` runs each code cell and writes results to `_output.ipynb` next to the input. A `# @title Foo` first line labels the cell in progress output. - **Exit status**: `colab exec` propagates exit codes with CPython semantics, matching `colab run`: uncaught exceptions exit `1`, `sys.exit()`/`sys.exit(0)` exit `0` silently, `sys.exit(N)` exits `N`, and `sys.exit("msg")` prints `msg` to `stderr` and exits `1` (the persistent IPython kernel reports `SystemExit` as an error message to stay alive, so the CLI translates it back rather than failing `sys.exit(0)` scripts like `argparse`/`unittest`). For `.ipynb` notebooks, execution stops at the first non-zero cell and still writes `_output.ipynb`. IPython `!cmd` shell escapes do **not** emit a kernel error on a non-zero shell exit — use `colab ssh -s -- ` or `subprocess.run(..., check=True)` when shell exit status matters. - **Plots/images**: PNG/JPEG outputs are intercepted. Use `--output-image ` on `exec`/`repl` to save to a known location (otherwise a temp path is printed). Inline terminal-image escapes are auto-suppressed when stdout isn't a TTY, so piped/captured output stays clean. -- **Shell**: run a one-shot shell command with `colab ssh -s -- `: it runs in `/content` and exits with the command's status. Output is byte-exact when stdout is piped or redirected; ssh allocates a PTY only when stdin and stdout are both terminals, so a shell tool that runs commands in a terminal should add ` -- 'nvidia-smi | head -5'`); several arguments are an exact argv, so pass untrusted values as separate arguments after `--` where the program accepts it (e.g. `colab ssh -s -- ls -- "$f"`), never inside a shell line or a piped script. Pipe a multi-line script to `colab ssh -s -- bash`. Use `colab exec` for Python code. When ssh can't work (no local `ssh` client, no `~/.ssh/id_ed25519` or `id_ecdsa` key and no `-i KEY`, a tool not on the minimal ssh environment's `PATH` such as `gcloud` or `node`, or the runtime's limited concurrent SSH connections in use, which the server answers with 429, e.g. while a person or an IDE is connected), fall back to `exec` with IPython's `!` prefix: `echo '!df -h /content' | colab exec -s ` (single quotes stop your local shell expanding `!`). Each `!` line runs in its own shell with no input (a command that prompts hangs), and IPython evaluates `{expr}` as Python even inside quotes and expands `$name` outside single quotes. Start a multi-line script with a `%%bash` line (not with `--env`, which prepends Python lines), use non-interactive flags such as `apt-get -y`, and never put untrusted text in a `%%bash` script or a `!` line (even via `{var}` or `$var`): pass it with `--env NAME=VALUE` and run `subprocess.run(["cmd", "--", os.environ["NAME"]])` from Python. For an interactive shell on the VM, a human runs `colab ssh -s `. +- **Shell**: run a one-shot shell command with `colab ssh -s -- `: it runs in `/content` and exits with the command's status. Output is byte-exact when stdout is piped or redirected; ssh allocates a PTY only when stdin and stdout are both terminals, so a shell tool that runs commands in a terminal should add ` -- 'nvidia-smi | head -5'`); several arguments are an exact argv, so pass untrusted values as separate arguments after `--` where the program accepts it (e.g. `colab ssh -s -- ls -- "$f"`), never inside a shell line or a piped script. Pipe a multi-line script to `colab ssh -s -- bash`. Use `colab exec` for Python code. When ssh can't work (no local `ssh` client (or `ssh-keygen` when no usable key exists), a tool not on the minimal ssh environment's `PATH` such as `gcloud` or `node`, or the runtime's limited concurrent SSH connections in use, which the server answers with 429, e.g. while a person or an IDE is connected), fall back to `exec` with IPython's `!` prefix: `echo '!df -h /content' | colab exec -s ` (single quotes stop your local shell expanding `!`). Each `!` line runs in its own shell with no input (a command that prompts hangs), and IPython evaluates `{expr}` as Python even inside quotes and expands `$name` outside single quotes. Start a multi-line script with a `%%bash` line (not with `--env`, which prepends Python lines), use non-interactive flags such as `apt-get -y`, and never put untrusted text in a `%%bash` script or a `!` line (even via `{var}` or `$var`): pass it with `--env NAME=VALUE` and run `subprocess.run(["cmd", "--", os.environ["NAME"]])` from Python. For an interactive shell on the VM, a human runs `colab ssh -s `. - **Never run `colab repl`, `colab ssh` without `-- CMD`, `colab auth`, or `colab drivemount` interactively from an agent** — `repl`, `auth` and `drivemount` expect a TTY and will hang or fail, and bare `colab ssh` with no saved session creates a billable runtime; an interactive shell is for a human. `repl` accepts piped stdin and exits on EOF; `auth`/`drivemount` genuinely require a human at the terminal. ### Ephemeral one-shot jobs (`colab run`) diff --git a/src/colab_cli/commands/ssh.py b/src/colab_cli/commands/ssh.py index cbf6a42b..3c038e66 100644 --- a/src/colab_cli/commands/ssh.py +++ b/src/colab_cli/commands/ssh.py @@ -30,11 +30,13 @@ connect), ``--gpu/--tpu`` pick the accelerator for that auto-created runtime, and ``--rm`` stops the runtime when you disconnect. -``--identity/-i`` overrides the default key order (``~/.ssh/id_ed25519`` -> -``id_ecdsa``); it accepts either a public key (``.pub``) or a private key path, -reading the ``.pub`` file directly when present and falling back to -``ssh-keygen -y -f`` to populate the ``X-Colab-Ssh-Pubkey`` header. RSA keys are -rejected by the server, so ``id_rsa`` is not auto-selected. +``--identity/-i`` overrides the default key order (``~/.ssh/colab_cli_ed25519`` +-> ``id_ed25519`` -> ``id_ecdsa``); it accepts either a public key (``.pub``) +or a private key path, reading the ``.pub`` file directly when present and +falling back to ``ssh-keygen -y -f`` to populate the ``X-Colab-Ssh-Pubkey`` +header. RSA keys may be rejected by Colab runtimes, so ``id_rsa`` is not +auto-selected. With none of these keys, ``colab ssh`` generates +``~/.ssh/colab_cli_ed25519``. """ import contextlib @@ -46,8 +48,10 @@ import signal import subprocess import sys +import tempfile import threading -from typing import Callable, Optional +import time +from typing import Callable, NoReturn, Optional from urllib.parse import urlparse import uuid @@ -60,8 +64,11 @@ import websocket _SSH_PATH = "/colab/ssh" -# ssh-rsa keys are rejected server-side, so they are not auto-selected. +# ssh-rsa keys may be rejected by runtimes, so they are not auto-selected. _KEY_TYPES = ["id_ed25519.pub", "id_ecdsa.pub"] +_COLAB_KEY = "~/.ssh/colab_cli_ed25519" +_KEY_WAIT_POLLS = 30 +_KEY_POLL_S = 0.1 _PUBKEY_HEADER = "X-Colab-Ssh-Pubkey" _SSH_HOST = "root@colab-runtime" # Colab's standard working directory; land here instead of root's home. @@ -72,6 +79,56 @@ _MAX_SSH_SESSIONS = 5 +def _identity_paths(identity: str) -> tuple[Path, Path]: + """Returns ``(priv_path, pub_path)`` for a public or private key path. + + Args: + identity: Path to a public (``.pub``) or private key (``~`` is expanded). + + Returns: + A ``(priv_path, pub_path)`` tuple. + """ + expanded = Path(os.path.expanduser(identity)) + if expanded.suffix == ".pub": + return expanded.with_suffix(""), expanded + return expanded, expanded.with_suffix(".pub") + + +def _require_identity_file(identity: str) -> None: + """Exits 2 unless ``identity`` has a private key or non-empty ``.pub``. + + Args: + identity: Path to a public or private key (``~`` is expanded). + + Raises: + typer.Exit: If neither a private key file nor a non-empty ``.pub`` file + exists (exit code 2). + """ + if not identity: + typer.echo("[colab] --identity : file not found.", err=True) + raise typer.Exit(code=2) + priv_path, pub_path = _identity_paths(identity) + if priv_path.exists() and not priv_path.is_dir(): + return + if pub_path.is_file(): + try: + if pub_path.read_bytes().strip(): + return + except OSError as e: + typer.echo( + f"[colab] --identity {pub_path}: {e.strerror or e}.", + err=True, + ) + raise typer.Exit(code=2) + elif pub_path.exists() and not pub_path.is_dir(): + return + typer.echo( + f"[colab] --identity {os.path.expanduser(identity)}: file not found.", + err=True, + ) + raise typer.Exit(code=2) + + def _pubkey_from_identity(identity: str) -> str: """Derives the public key from a private key via ``ssh-keygen -y -f``. @@ -86,17 +143,19 @@ def _pubkey_from_identity(identity: str) -> str: (exit code 2). """ identity = os.path.expanduser(identity) - if not os.path.exists(identity): + if not os.path.exists(identity) or os.path.isdir(identity): typer.echo(f"[colab] --identity {identity}: file not found.", err=True) raise typer.Exit(code=2) try: res = subprocess.run( ["ssh-keygen", "-y", "-f", identity], check=True, + stdin=subprocess.DEVNULL, capture_output=True, text=True, + timeout=30, ) - except (subprocess.CalledProcessError, FileNotFoundError) as e: + except (FileNotFoundError, subprocess.SubprocessError) as e: typer.echo( f"[colab] failed to derive public key from {identity}: {e}", err=True, @@ -109,17 +168,257 @@ def _pubkey_from_identity(identity: str) -> str: return pubkey +def resolve_default_identity() -> str | None: + """Returns the key ``colab ssh`` uses without ``--identity``. + + Checks existing files only and creates nothing. First + ``~/.ssh/colab_cli_ed25519``, when both it and its non-empty ``.pub`` are + regular files; then ``~/.ssh/id_ed25519`` if ``id_ed25519.pub`` exists, else + ``~/.ssh/id_ecdsa`` likewise. For those two the private key itself is not + required, since it may live only in an ssh-agent. + + Returns: + The absolute private key path, or None if there is no such key. + """ + colab_key = os.path.expanduser(_COLAB_KEY) + colab_pub = f"{colab_key}.pub" + if ( + os.path.isfile(colab_key) + and os.path.isfile(colab_pub) + and os.path.getsize(colab_pub) > 0 + ): + return colab_key + ssh_dir = os.path.expanduser("~/.ssh") + for name in _KEY_TYPES: + pub = os.path.join(ssh_dir, name) + if os.path.exists(pub): + return pub.removesuffix(".pub") + return None + + +def _wait_for_colab_key(key: str) -> None: + """Returns once ``key`` is a usable key pair, else exits 2. + + A private key without its ``.pub`` may be a parallel run's key mid-write, + so it gets ``_KEY_WAIT_POLLS`` polls to finish; anything else at ``key`` + is refused at once. + + Args: + key: The expanded private key path. + + Raises: + typer.Exit: If ``key`` is still not a usable key pair (exit code 2). + """ + polls = _KEY_WAIT_POLLS if os.path.isfile(key) else 0 + for _ in range(polls): + if resolve_default_identity() == key: + return + time.sleep(_KEY_POLL_S) + if resolve_default_identity() == key: + return + if os.path.isfile(key): + why = f"{_COLAB_KEY} is incomplete;" + elif os.path.lexists(key): + why = f"{_COLAB_KEY} exists but is not a usable key;" + elif os.path.lexists(f"{key}.pub"): + why = f"{_COLAB_KEY}.pub exists without a private key;" + else: + typer.echo( + f"[colab] {_COLAB_KEY} was removed while waiting; " + "retry or pass --identity.", + err=True, + ) + raise typer.Exit(code=2) + typer.echo(f"[colab] {why} remove it or pass --identity.", err=True) + raise typer.Exit(code=2) + + +def _exit_write_failed(error: OSError) -> NoReturn: + """Exits 2 because writing under ``~/.ssh`` failed with ``error``. + + Args: + error: The OS error raised while creating or writing the key files. + + Raises: + typer.Exit: Always (exit code 2). + """ + typer.echo( + f"[colab] could not write to ~/.ssh ({error.strerror or error}); pass " + "--identity to use another key.", + err=True, + ) + raise typer.Exit(code=2) + + +def _publish(src: str, dst: str, mode: int) -> None: + """Copies ``src`` to ``dst``, creating ``dst`` exclusively with ``mode``. + + Args: + src: Source file path to copy from. + dst: Destination file path to create exclusively. + mode: File permission mode for ``dst``. + + Raises: + FileExistsError: If ``dst`` already exists. + OSError: If linking, opening, writing, or removing on cleanup fails. + """ + if sys.platform == "win32": + os.link(src, dst) + return + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0) + fd = os.open(dst, flags, mode) + try: + with os.fdopen(fd, "wb") as f: + f.write(Path(src).read_bytes()) + except OSError: + with contextlib.suppress(OSError): + os.remove(dst) + raise + + +def _run_ssh_keygen(key: str) -> None: + """Writes an ed25519 key pair at ``key`` with ssh-keygen, or exits 2. + + Args: + key: Temporary private key file path passed to ``ssh-keygen -f``. + + Raises: + typer.Exit: If ``ssh-keygen`` is missing or exits non-zero (exit code 2). + """ + try: + subprocess.run( + ["ssh-keygen", "-t", "ed25519", "-N", "", "-C", "colab-cli", "-f", key], + check=True, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=30, + ) + except (FileNotFoundError, subprocess.SubprocessError) as e: + msg = f"[colab] ssh-keygen failed for {_COLAB_KEY}; pass --identity." + typer.echo(msg, err=True) + if isinstance(e, subprocess.CalledProcessError) and e.stderr: + typer.echo(f"[colab] ssh-keygen: {e.stderr.strip()}", err=True) + raise typer.Exit(code=2) + + +def _generate_colab_key(key: str) -> bool: + """Generates the dedicated key ``key``, or waits for a parallel run's key. + + Runs ``ssh-keygen`` in a temporary directory inside ``~/.ssh``, then + publishes the pair with exclusive creates, private key first, so it never + overwrites a file. Checks for a file in the way and for ``ssh-keygen`` + first. A run that loses to a parallel one waits for that key and uses it. + + Args: + key: The expanded private key path. + + Returns: + True if this run created the key, False if a parallel run did. + + Raises: + typer.Exit: If a file is in the way, ``~/.ssh`` cannot be created or + written, or ``ssh-keygen`` is missing or fails (exit code 2). + """ + pub = f"{key}.pub" + if os.path.lexists(key) or os.path.lexists(pub): + _wait_for_colab_key(key) + return False + if not shutil.which("ssh-keygen"): + msg = "[colab] ssh-keygen not found; install OpenSSH or pass --identity." + typer.echo(msg, err=True) + raise typer.Exit(code=2) + try: + os.makedirs(os.path.dirname(key), mode=0o700, exist_ok=True) + tmp_dir = tempfile.mkdtemp(dir=os.path.dirname(key)) + except OSError as e: + _exit_write_failed(e) + try: + tmp_key = os.path.join(tmp_dir, "key") + _run_ssh_keygen(tmp_key) + try: + _publish(tmp_key, key, 0o600) + except FileExistsError: + _wait_for_colab_key(key) + return False + except OSError as e: + _exit_write_failed(e) + try: + _publish(f"{tmp_key}.pub", pub, 0o644) + except OSError as e: + with contextlib.suppress(OSError): + os.remove(key) + _exit_write_failed(e) + finally: + shutil.rmtree(tmp_dir, ignore_errors=True) + rsa = os.path.join(os.path.dirname(key), "id_rsa") + if os.path.exists(rsa) or os.path.exists(f"{rsa}.pub"): + typer.echo( + "[colab] `colab ssh` does not pick RSA keys automatically because " + "Colab runtimes may reject them, so it created a dedicated " + "ed25519 key.", + err=True, + ) + typer.echo( + f"[colab] created {_COLAB_KEY} for Colab SSH; to use it from " + f"~/.ssh/config, add `IdentityFile {_COLAB_KEY}` to the host.", + err=True, + ) + return True + + +def _resolve_identity(identity: str | None, *, proxy_mode: bool = False) -> str | None: + """Returns the key ``ssh()`` passes to ssh and the pubkey header. + + An explicit ``identity`` (public ``.pub`` or private key path) must exist + and wins. An ``id_ed25519`` or ``id_ecdsa`` default returns None, which + keeps ssh's own key choice. Otherwise returns ``~/.ssh/colab_cli_ed25519``, + generating it if needed. + + Args: + identity: The ``--identity`` value, or None. + proxy_mode: Whether to print the ``IdentityFile`` hint a ProxyCommand + user needs when the dedicated key is picked but not created now. + + Returns: + The key path to pass through, or None to keep ssh's defaults. + + Raises: + typer.Exit: If the ``--identity`` file is missing or no usable key exists + or can be generated (exit code 2). + """ + if identity is not None: + _require_identity_file(identity) + return identity + key = os.path.expanduser(_COLAB_KEY) + default = resolve_default_identity() + if default is None: + generated = _generate_colab_key(key) + elif default == key: + generated = False + else: + return None + if proxy_mode and not generated: + typer.echo( + f"[colab] using {_COLAB_KEY}; if ssh reports Permission denied, " + f"add `IdentityFile {_COLAB_KEY}` for this host in ~/.ssh/config. " + f"Pass --identity {_COLAB_KEY} to silence this.", + err=True, + ) + return key + + def _resolve_pubkey(identity: Optional[str]) -> str: """Returns the public key for the ``X-Colab-Ssh-Pubkey`` header. With ``identity``, reads the matching ``.pub`` file directly if present (whether ``identity`` was passed with or without ``.pub``), falling back to deriving it from the private key via ``_pubkey_from_identity``; otherwise - scans ``~/.ssh`` for the first existing ``id_.pub`` in preference - order. + reads the ``.pub`` of ``resolve_default_identity()``. Args: - identity: Path to a public or private key, or None to scan ``~/.ssh``. + identity: Path to a public or private key, or None to use + ``resolve_default_identity()``. Returns: The public key text to send verbatim in the header. @@ -127,25 +426,20 @@ def _resolve_pubkey(identity: Optional[str]) -> str: Raises: typer.Exit: If no usable key is found (exit code 2). """ - if identity: - expanded = Path(os.path.expanduser(identity)) - if expanded.suffix == ".pub": - pub_path = expanded - priv_path = expanded.with_suffix("") - else: - priv_path = expanded - pub_path = expanded.with_suffix(".pub") - if pub_path.exists(): - if pubkey := pub_path.read_text().strip(): - return pubkey + if identity is not None: + if not identity: + return _pubkey_from_identity(identity) + priv_path, pub_path = _identity_paths(identity) + if pub_path.exists() and not pub_path.is_dir(): + with contextlib.suppress(OSError): + if pubkey := pub_path.read_text().strip(): + return pubkey target = str(priv_path) if priv_path.exists() else identity return _pubkey_from_identity(target) - ssh_dir = Path(os.path.expanduser("~/.ssh")) - for name in _KEY_TYPES: - candidate = ssh_dir / name - if candidate.exists(): - return candidate.read_text().strip() + default = resolve_default_identity() + if default is not None: + return Path(f"{default}.pub").read_text().strip() typer.echo( "[colab] no SSH public key found in ~/.ssh/. Run " "`ssh-keygen -t ed25519` to generate one, or pass --identity.", @@ -787,7 +1081,8 @@ def ssh( help=( "SSH key (public `.pub` or private key path) whose public key " "is sent in the X-Colab-Ssh-Pubkey header (default: first of " - "~/.ssh/id_ed25519.pub, id_ecdsa.pub)." + "~/.ssh/colab_cli_ed25519, id_ed25519, id_ecdsa; else " + "~/.ssh/colab_cli_ed25519 is generated)." ), ), ] = None, @@ -869,6 +1164,7 @@ def ssh( if proxy_mode and cmd: typer.echo("[colab] --proxy-mode takes no command.", err=True) raise typer.Exit(code=2) + identity = _resolve_identity(identity, proxy_mode=proxy_mode) if cmd: with contextlib.redirect_stdout(sys.stderr): s = _resolve_session(session) diff --git a/tests/conftest.py b/tests/conftest.py index 0f5eda5a..66407300 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -72,3 +72,20 @@ def get_session(name, ignore_missing_session=False): mocker.patch("colab_cli.commands.run.ColabRuntime") return mock_state + + +@pytest.fixture(autouse=True) +def isolated_home(monkeypatch, tmp_path): + """Keeps tests out of the real ~/.ssh (USERPROFILE is read on Windows). + + The seeded id_ed25519.pub keeps existing tests on the existing-key path; + the config dir exists for tests that patch os.path.exists. + """ + home = tmp_path / "user-home" + (home / ".ssh").mkdir(parents=True) + (home / ".config" / "colab-cli").mkdir(parents=True) + (home / ".ssh" / "id_ed25519.pub").write_text("ssh-ed25519 AAAAtest t@h\n") + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) + assert os.path.expanduser("~").startswith(str(tmp_path)) + return home diff --git a/tests/test_ssh.py b/tests/test_ssh.py index 1c57e5ea..7e0ef18c 100644 --- a/tests/test_ssh.py +++ b/tests/test_ssh.py @@ -21,17 +21,22 @@ vs --proxy-mode). """ +import errno import io import os +from pathlib import Path import shlex +import shutil +import stat import subprocess import sys import threading -from unittest.mock import MagicMock +import time +from unittest.mock import MagicMock, patch from colab_cli.auth import AuthProvider from colab_cli.cli import app -from colab_cli.commands import ssh as ssh_module +from colab_cli.commands import session as session_cmd, ssh as ssh_module import pytest import typer from typer.testing import CliRunner @@ -39,6 +44,21 @@ runner = CliRunner() +ENTRY_MODES = pytest.mark.parametrize( + "args", + [[], ["--proxy-mode", "-s", "new"], ["-s", "s1", "--", "true"]], + ids=["interactive", "proxy", "cmd"], +) +KEY = "colab_cli_ed25519" +PARALLEL_RUNS = 6 +POSIX_ONLY = pytest.mark.skipif(sys.platform == "win32", reason="requires POSIX") +NON_ROOT = pytest.mark.skipif( + getattr(os, "geteuid", lambda: 1)() == 0, reason="requires a non-root user" +) +NO_SPACE = os.strerror(errno.ENOSPC) +DENIED = os.strerror(errno.EACCES) +WRITE_FAILED = "could not write to ~/.ssh ({}); pass" + def _make_session( name: str = "s1", @@ -128,9 +148,10 @@ def test_resolve_pubkey_with_identity_calls_ssh_keygen_when_no_pub_file( arg = f"{key}.pub" if pass_pub_suffix else str(key) out = ssh_module._resolve_pubkey(arg) assert out == fake_pub - args, _ = mock_run.call_args + args, kwargs = mock_run.call_args assert args[0][:3] == ["ssh-keygen", "-y", "-f"] assert args[0][3] == str(key) + assert kwargs["stdin"] == subprocess.DEVNULL @pytest.mark.parametrize( @@ -705,3 +726,909 @@ def test_kill_stale_sshd_body(mock_common_state, mocker): rtCls.assert_called_once_with(sess.url, sess.token, kernel_id="k123") mockRt.execute_code.assert_called_once() mockRt.stop.assert_called_once() + + +def _home(monkeypatch, tmp_path, *names, mkdir_ssh=True): + home = tmp_path / "h" + home.mkdir() + if mkdir_ssh: + (home / ".ssh").mkdir() + for name in names: + (home / ".ssh" / name).write_text(f"{name}\n") + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) + return home + + +def _snapshot(root): + return { + p: (p.stat().st_mode, p.is_file() and (p.stat().st_mtime_ns, p.read_bytes())) + for p in root.rglob("*") + } + + +def _invoke(mock_common_state, *args): + mock_common_state.resolve_session.return_value = "s1" + mock_common_state.store.get.return_value = _make_session() + with ( + patch.object(subprocess, "call", autospec=True, return_value=0) as call, + patch.object(websocket.WebSocket, "connect", autospec=True) as connect, + patch.object(ssh_module, "_bridge_proxy_mode", autospec=True, return_value=0), + ): + result = runner.invoke(app, ["ssh", "-s", "s1", *args]) + return result, call, connect + + +@pytest.fixture +def keygen(mocker): + def fake_run(argv, **kwargs): + key = argv[argv.index("-f") + 1] + if "-y" not in argv: + Path(key).write_text("private") + Path(f"{key}.pub").write_text("ssh-ed25519 AAAAgenerated colab-cli\n") + pub = Path(f"{key}.pub").read_text() + return subprocess.CompletedProcess(argv, 0, stdout=pub, stderr="") + + mocker.patch.object(shutil, "which", autospec=True, return_value="ssh-keygen") + return mocker.patch.object(subprocess, "run", autospec=True, side_effect=fake_run) + + +def _generate_calls(keygen): + return [c for c in keygen.call_args_list if "-t" in c.args[0]] + + +def _ssh_identity(mock_common_state, call): + argv = call.call_args.args[0] + key = argv[argv.index("-i") + 1] + session = mock_common_state.store.get.return_value + proxy = ssh_module._proxy_command(session, key, "interactive") + assert argv[argv.index("-o") + 1] == f"ProxyCommand={proxy}" + return key + + +def _header(connect): + return connect.call_args.kwargs["header"][0].removeprefix( + f"{ssh_module._PUBKEY_HEADER}: " + ) + + +def _exit_before_session(mock_common_state, mocker, *args): + mock_common_state.store.list.return_value = {} + mock_common_state.store.get.return_value = None + new = mocker.patch.object(session_cmd, "new", autospec=True) + call = mocker.patch.object(subprocess, "call", autospec=True, return_value=0) + result = runner.invoke(app, ["ssh", *args]) + assert result.exit_code == 2, result.output + new.assert_not_called() + call.assert_not_called() + return result.stderr + + +def _short_write(mocker, ok_writes=0): + real_fdopen = os.fdopen + writes = [] + + def fdopen(fd, mode): + writes.append(fd) + if len(writes) <= ok_writes: + return real_fdopen(fd, mode) + with real_fdopen(fd, mode) as f: + f.write(b"partial") + raise OSError(errno.ENOSPC, NO_SPACE) + + mocker.patch.object(os, "fdopen", autospec=True, side_effect=fdopen) + + +@ENTRY_MODES +@pytest.mark.parametrize("arg_name", ["missing", "missing.pub"], ids=["priv", "pub"]) +def test_ssh_missing_identity_exits_before_creating_a_session( + mock_common_state, mocker, tmp_path, args, arg_name +): + missing = tmp_path / arg_name + + stderr = _exit_before_session(mock_common_state, mocker, "-i", str(missing), *args) + + assert f"[colab] --identity {missing}: file not found." in stderr + + +@pytest.mark.parametrize( + "arg_name", ["k", "k.pub"], ids=["priv-empty-pub", "pub-empty"] +) +def test_ssh_unusable_explicit_identity_exits_before_creating_a_session( + mock_common_state, mocker, tmp_path, arg_name +): + (tmp_path / "k.pub").write_text(" \n") + target = tmp_path / arg_name + + stderr = _exit_before_session(mock_common_state, mocker, "-i", str(target)) + + assert f"[colab] --identity {target}: file not found." in stderr + + +def test_ssh_empty_identity_exits_before_creating_a_session( + mock_common_state, mocker, monkeypatch, tmp_path +): + ssh_dir = _home(monkeypatch, tmp_path) / ".ssh" + before = _snapshot(ssh_dir) + + stderr = _exit_before_session(mock_common_state, mocker, "-i", "") + + assert "[colab] --identity : file not found." in stderr + assert _snapshot(ssh_dir) == before + + +def test_ssh_directory_identity_exits_before_creating_a_session( + mock_common_state, mocker, tmp_path +): + target = tmp_path / "dir" + target.mkdir() + + stderr = _exit_before_session(mock_common_state, mocker, "-i", str(target)) + + assert f"[colab] --identity {target}: file not found." in stderr + + +def test_resolve_pubkey_empty_pub_without_private_key_exits_without_keygen( + mocker, tmp_path, capsys +): + key = tmp_path / "k" + (tmp_path / "k.pub").write_text(" \n") + mock_run = mocker.patch.object(subprocess, "run", autospec=True) + + with pytest.raises(typer.Exit) as exc_info: + ssh_module._resolve_pubkey(str(key)) + + assert exc_info.value.exit_code == 2 + mock_run.assert_not_called() + assert f"[colab] --identity {key}: file not found." in capsys.readouterr().err + + +def test_resolve_pubkey_empty_identity_exits_without_keygen(mocker, capsys): + mock_run = mocker.patch.object(subprocess, "run", autospec=True) + + with pytest.raises(typer.Exit) as exc_info: + ssh_module._resolve_pubkey("") + + assert exc_info.value.exit_code == 2 + mock_run.assert_not_called() + assert "[colab] --identity : file not found." in capsys.readouterr().err + + +def test_pubkey_from_identity_directory_exits_without_keygen(mocker, tmp_path, capsys): + mock_run = mocker.patch.object(subprocess, "run", autospec=True) + + with pytest.raises(typer.Exit) as exc_info: + ssh_module._pubkey_from_identity(str(tmp_path)) + + assert exc_info.value.exit_code == 2 + mock_run.assert_not_called() + assert f"[colab] --identity {tmp_path}: file not found." in capsys.readouterr().err + + +@pytest.mark.parametrize( + ("filename", "arg_name"), + [("agent.pub", "agent.pub"), ("pub_only.pub", "pub_only")], + ids=["pub-only", "pub-only-via-priv-arg"], +) +def test_ssh_identity_reads_pub_directly_without_keygen( + mock_common_state, mocker, tmp_path, filename, arg_name +): + (tmp_path / filename).write_text("ssh-ed25519 AAAApub user@host\n") + mock_run = mocker.patch.object(subprocess, "run", autospec=True) + arg = str(tmp_path / arg_name) + + result, call, _ = _invoke(mock_common_state, "-i", arg) + proxy_result, _, connect = _invoke(mock_common_state, "--proxy-mode", "-i", arg) + + assert (result.exit_code, proxy_result.exit_code) == (0, 0) + argv = call.call_args.args[0] + assert argv[argv.index("-i") + 1] == arg + assert _header(connect) == "ssh-ed25519 AAAApub user@host" + mock_run.assert_not_called() + + +@pytest.mark.parametrize( + ("files", "arg_name", "priv_name"), + [ + ({"only_priv": "priv"}, "only_priv.pub", "only_priv"), + ( + {"priv_empty_pub": "priv", "priv_empty_pub.pub": " \n"}, + "priv_empty_pub", + "priv_empty_pub", + ), + ], + ids=["priv-only-via-pub-arg", "priv-with-empty-pub"], +) +def test_ssh_identity_derives_pubkey_via_ssh_keygen( + mock_common_state, mocker, tmp_path, files, arg_name, priv_name +): + for name, content in files.items(): + (tmp_path / name).write_text(content) + mock_run = mocker.patch.object( + subprocess, + "run", + autospec=True, + return_value=subprocess.CompletedProcess( + ["ssh-keygen"], 0, stdout="ssh-ed25519 AAAAderived user@host\n", stderr="" + ), + ) + arg = str(tmp_path / arg_name) + + result, call, _ = _invoke(mock_common_state, "-i", arg) + proxy_result, _, connect = _invoke(mock_common_state, "--proxy-mode", "-i", arg) + + assert (result.exit_code, proxy_result.exit_code) == (0, 0) + argv = call.call_args.args[0] + assert argv[argv.index("-i") + 1] == str(tmp_path / priv_name) + assert _header(connect) == "ssh-ed25519 AAAAderived user@host" + mock_run.assert_called_once_with( + ["ssh-keygen", "-y", "-f", str(tmp_path / priv_name)], + check=True, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=30, + ) + + +@POSIX_ONLY +def test_ssh_fifo_identity_derives_pubkey_and_succeeds( + mock_common_state, mocker, tmp_path +): + fifo = tmp_path / "fifo_key" + os.mkfifo(fifo, 0o600) + mock_run = mocker.patch.object( + subprocess, + "run", + autospec=True, + return_value=subprocess.CompletedProcess( + ["ssh-keygen"], 0, stdout="ssh-ed25519 AAAAfifo user@host\n", stderr="" + ), + ) + + result, _, connect = _invoke(mock_common_state, "--proxy-mode", "-i", str(fifo)) + + assert result.exit_code == 0, result.output + assert _header(connect) == "ssh-ed25519 AAAAfifo user@host" + assert mock_run.call_args.args[0] == ["ssh-keygen", "-y", "-f", str(fifo)] + + +@POSIX_ONLY +def test_ssh_pub_fifo_identity_reads_once_in_proxy_mode(mock_common_state, tmp_path): + fifo = tmp_path / "k.pub" + os.mkfifo(fifo, 0o600) + + def write_once(): + with open(fifo, "w", encoding="utf-8") as f: + f.write("ssh-ed25519 AAAAfifopub user@host\n") + + writer = threading.Thread(target=write_once, daemon=True) + writer.start() + result, _, connect = _invoke(mock_common_state, "--proxy-mode", "-i", str(fifo)) + writer.join(timeout=5) + + assert result.exit_code == 0, result.output + assert _header(connect) == "ssh-ed25519 AAAAfifopub user@host" + + +@POSIX_ONLY +@NON_ROOT +def test_ssh_unreadable_pub_with_private_key_derives_pubkey( + mock_common_state, mocker, tmp_path +): + key = tmp_path / "id_test" + pub = tmp_path / "id_test.pub" + key.write_text("priv") + pub.write_text("ssh-ed25519 AAAAunreadable user@host\n") + pub.chmod(0o000) + mock_run = mocker.patch.object( + subprocess, + "run", + autospec=True, + return_value=subprocess.CompletedProcess( + ["ssh-keygen"], 0, stdout="ssh-ed25519 AAAAderived user@host\n", stderr="" + ), + ) + try: + result, _, _ = _invoke(mock_common_state, "-i", str(key)) + proxy_result, _, connect = _invoke( + mock_common_state, "--proxy-mode", "-i", str(key) + ) + finally: + pub.chmod(0o644) + + assert (result.exit_code, proxy_result.exit_code) == (0, 0) + assert _header(connect) == "ssh-ed25519 AAAAderived user@host" + assert mock_run.call_args.args[0] == ["ssh-keygen", "-y", "-f", str(key)] + + +@POSIX_ONLY +@NON_ROOT +def test_ssh_unreadable_pub_without_private_key_exits_cleanly( + mock_common_state, mocker, tmp_path +): + pub = tmp_path / "id_test.pub" + pub.write_text("ssh-ed25519 AAAAunreadable user@host\n") + pub.chmod(0o000) + try: + stderr = _exit_before_session(mock_common_state, mocker, "-i", str(pub)) + finally: + pub.chmod(0o644) + + assert f"[colab] --identity {pub}: {DENIED}." in stderr + + +def test_publish_on_windows_uses_hard_link(mocker, tmp_path): + src = str(tmp_path / "src") + dst = str(tmp_path / "dst") + mocker.patch.object(ssh_module.sys, "platform", "win32") + link = mocker.patch.object(os, "link", autospec=True) + open_mock = mocker.patch.object(os, "open", autospec=True) + + ssh_module._publish(src, dst, 0o600) + + link.assert_called_once_with(src, dst) + open_mock.assert_not_called() + + +@pytest.mark.parametrize( + ("names", "mkdir_ssh", "expect_rsa_notice"), + [ + ((), False, False), + ((), True, False), + (("id_rsa", "id_rsa.pub", "config"), True, True), + ], + ids=["missing-ssh-dir", "empty-ssh-dir", "rsa-only"], +) +def test_ssh_without_ed25519_key_generates_one_then_reuses_it( + mock_common_state, + monkeypatch, + tmp_path, + keygen, + names, + mkdir_ssh, + expect_rsa_notice, +): + home = _home(monkeypatch, tmp_path, *names, mkdir_ssh=mkdir_ssh) + before = _snapshot(home / ".ssh") + + result, call, _ = _invoke(mock_common_state) + after = _snapshot(home / ".ssh") + reuse, reuse_call, _ = _invoke(mock_common_state) + + key = str(home / ".ssh" / KEY) + assert (result.exit_code, reuse.exit_code) == (0, 0), result.output + assert {_ssh_identity(mock_common_state, c) for c in (call, reuse_call)} == {key} + assert [c.kwargs["stdin"] for c in _generate_calls(keygen)] == [subprocess.DEVNULL] + assert {p: v for p, v in after.items() if p in before} == before + assert sorted(p.name for p in set(after) - set(before)) == [KEY, f"{KEY}.pub"] + assert _snapshot(home / ".ssh") == after + assert ("RSA keys" in result.stderr) is expect_rsa_notice + assert result.stderr.count(f"IdentityFile {ssh_module._COLAB_KEY}") == 1 + assert str(home) not in result.stderr + assert result.stdout == reuse.stdout == reuse.stderr == "" + + +@POSIX_ONLY +def test_ssh_created_ssh_dir_and_key_modes( + mock_common_state, monkeypatch, tmp_path, keygen +): + home = _home(monkeypatch, tmp_path, mkdir_ssh=False) + + result, _, _ = _invoke(mock_common_state) + + assert result.exit_code == 0, result.output + assert stat.S_IMODE((home / ".ssh").stat().st_mode) == 0o700 + assert stat.S_IMODE((home / ".ssh" / KEY).stat().st_mode) == 0o600 + + +@POSIX_ONLY +def test_ssh_preserves_existing_ssh_dir_mode( + mock_common_state, monkeypatch, tmp_path, keygen +): + home = _home(monkeypatch, tmp_path) + (home / ".ssh").chmod(0o750) + + result, _, _ = _invoke(mock_common_state) + + assert result.exit_code == 0, result.output + assert stat.S_IMODE((home / ".ssh").stat().st_mode) == 0o750 + assert stat.S_IMODE((home / ".ssh" / KEY).stat().st_mode) == 0o600 + + +def test_ssh_no_keygen_exits_before_creating_a_session( + mock_common_state, mocker, monkeypatch, tmp_path +): + ssh_dir = _home(monkeypatch, tmp_path) / ".ssh" + before = _snapshot(ssh_dir) + mocker.patch.object(shutil, "which", autospec=True, return_value=None) + + stderr = _exit_before_session(mock_common_state, mocker) + + assert "ssh-keygen not found; install OpenSSH or pass --identity." in stderr + assert _snapshot(ssh_dir) == before + + +def test_ssh_keygen_failure_exits_before_creating_a_session( + mock_common_state, mocker, monkeypatch, tmp_path, keygen +): + ssh_dir = _home(monkeypatch, tmp_path) / ".ssh" + before = _snapshot(ssh_dir) + keygen.side_effect = subprocess.CalledProcessError( + 1, "ssh-keygen", stderr="Saving key failed\n" + ) + + stderr = _exit_before_session(mock_common_state, mocker) + + assert ( + "failed for ~/.ssh/colab_cli_ed25519; pass --identity.\n" + "[colab] ssh-keygen: Saving key failed" + ) in stderr + assert _snapshot(ssh_dir) == before + + +def test_ssh_keygen_timeout_exits_before_creating_a_session( + mock_common_state, mocker, monkeypatch, tmp_path, keygen +): + ssh_dir = _home(monkeypatch, tmp_path) / ".ssh" + before = _snapshot(ssh_dir) + keygen.side_effect = subprocess.TimeoutExpired(["ssh-keygen"], 30) + + stderr = _exit_before_session(mock_common_state, mocker) + + assert "failed for ~/.ssh/colab_cli_ed25519; pass --identity." in stderr + assert _snapshot(ssh_dir) == before + + +def test_ssh_pub_write_failure_exits_and_cleans_up( + mock_common_state, mocker, monkeypatch, tmp_path, keygen +): + ssh_dir = _home(monkeypatch, tmp_path) / ".ssh" + before = _snapshot(ssh_dir) + publish = ssh_module._publish + + def pub_fails(src, dst, mode): + if dst.endswith(".pub"): + raise OSError(errno.ENOSPC, NO_SPACE) + publish(src, dst, mode) + + mocker.patch.object(ssh_module, "_publish", autospec=True, side_effect=pub_fails) + + stderr = _exit_before_session(mock_common_state, mocker) + + assert WRITE_FAILED.format(NO_SPACE) in stderr + assert _snapshot(ssh_dir) == before + + +@pytest.mark.parametrize( + ("setup_fn", "expected_message"), + [ + ( + lambda ssh_dir: (ssh_dir / KEY).mkdir(), + f"~/.ssh/{KEY} exists but is not a usable key; remove it", + ), + ( + lambda ssh_dir: (ssh_dir / f"{KEY}.pub").write_text("x"), + f"~/.ssh/{KEY}.pub exists without a private key; remove it", + ), + ( + lambda ssh_dir: (ssh_dir / KEY).write_text("x"), + f"~/.ssh/{KEY} is incomplete; remove it or pass --identity.", + ), + ( + lambda ssh_dir: ( + (ssh_dir / KEY).write_text("x"), + (ssh_dir / f"{KEY}.pub").write_text(""), + ), + f"~/.ssh/{KEY} is incomplete; remove it or pass --identity.", + ), + ], + ids=["stray-dir", "stray-pub", "incomplete", "zero-byte-pub"], +) +def test_ssh_unusable_colab_key_exits_before_creating_a_session( + mock_common_state, mocker, monkeypatch, tmp_path, setup_fn, expected_message +): + ssh_dir = _home(monkeypatch, tmp_path) / ".ssh" + setup_fn(ssh_dir) + mocker.patch.object(time, "sleep", autospec=True) + before = _snapshot(ssh_dir) + + stderr = _exit_before_session(mock_common_state, mocker) + + assert expected_message in stderr + assert _snapshot(ssh_dir) == before + + +@POSIX_ONLY +@NON_ROOT +def test_ssh_unwritable_home_exits_before_creating_a_session( + mock_common_state, mocker, monkeypatch, tmp_path +): + home = _home(monkeypatch, tmp_path) + (home / ".ssh").rmdir() + (home / ".config" / "colab-cli").mkdir(parents=True) + home.chmod(0o500) + try: + stderr = _exit_before_session(mock_common_state, mocker) + entries = [p.name for p in home.iterdir()] + finally: + home.chmod(0o700) + + assert WRITE_FAILED.format(DENIED) in stderr + assert entries == [".config"] + + +@POSIX_ONLY +@NON_ROOT +def test_ssh_readonly_ssh_dir_exits_before_creating_a_session( + mock_common_state, mocker, monkeypatch, tmp_path +): + ssh_dir = _home(monkeypatch, tmp_path) / ".ssh" + ssh_dir.chmod(0o500) + before = _snapshot(ssh_dir) + try: + stderr = _exit_before_session(mock_common_state, mocker) + after = _snapshot(ssh_dir) + finally: + ssh_dir.chmod(0o700) + + assert WRITE_FAILED.format(DENIED) in stderr + assert after == before + + +def _parallel_run_writes(keygen, *paths): + fake = keygen.side_effect + + def run(argv, **kwargs): + for path in paths: + path.write_text("other") + return fake(argv, **kwargs) + + keygen.side_effect = run + + +def test_parallel_run_uses_key_completed_before_check( + mock_common_state, mocker, monkeypatch, tmp_path, keygen +): + ssh_dir = _home(monkeypatch, tmp_path) / ".ssh" + key, pub = ssh_dir / KEY, ssh_dir / f"{KEY}.pub" + key.write_text("other") + pub.write_text("other") + mocker.patch.object(time, "sleep", autospec=True) + mocker.patch.object( + ssh_module, + "resolve_default_identity", + autospec=True, + side_effect=[None, str(key)], + ) + + result, call, _ = _invoke(mock_common_state) + + assert result.exit_code == 0, result.output + assert _ssh_identity(mock_common_state, call) == str(key) + keygen.assert_not_called() + assert result.stderr == "" + assert key.read_text() == "other" + assert sorted(p.name for p in ssh_dir.iterdir()) == [KEY, f"{KEY}.pub"] + + +def test_parallel_run_uses_key_when_race_loses_to_complete_pair( + mock_common_state, mocker, monkeypatch, tmp_path, keygen +): + ssh_dir = _home(monkeypatch, tmp_path) / ".ssh" + key, pub = ssh_dir / KEY, ssh_dir / f"{KEY}.pub" + mocker.patch.object(time, "sleep", autospec=True) + _parallel_run_writes(keygen, key, pub) + + result, call, _ = _invoke(mock_common_state) + + assert result.exit_code == 0, result.output + assert _ssh_identity(mock_common_state, call) == str(key) + assert result.stderr == "" + assert key.read_text() == "other" + assert sorted(p.name for p in ssh_dir.iterdir()) == [KEY, f"{KEY}.pub"] + + +def test_parallel_run_uses_key_when_pub_appears_while_waiting( + mock_common_state, mocker, monkeypatch, tmp_path, keygen +): + ssh_dir = _home(monkeypatch, tmp_path) / ".ssh" + key, pub = ssh_dir / KEY, ssh_dir / f"{KEY}.pub" + sleep = mocker.patch.object(time, "sleep", autospec=True) + sleep.side_effect = lambda _: pub.write_text("other") + _parallel_run_writes(keygen, key) + + result, call, _ = _invoke(mock_common_state) + + assert result.exit_code == 0, result.output + assert _ssh_identity(mock_common_state, call) == str(key) + assert result.stderr == "" + assert key.read_text() == "other" + assert sorted(p.name for p in ssh_dir.iterdir()) == [KEY, f"{KEY}.pub"] + + +def test_parallel_runs_partial_key_is_refused( + mock_common_state, mocker, monkeypatch, tmp_path, keygen +): + key = _home(monkeypatch, tmp_path) / ".ssh" / KEY + sleep = mocker.patch.object(time, "sleep", autospec=True) + _parallel_run_writes(keygen, key) + + stderr = _exit_before_session(mock_common_state, mocker) + + assert "is incomplete; remove it" in stderr + assert [p.name for p in key.parent.iterdir()] == [KEY] + assert sleep.call_count == ssh_module._KEY_WAIT_POLLS + + +def test_parallel_run_key_vanished_while_waiting_exits( + mock_common_state, mocker, monkeypatch, tmp_path +): + ssh_dir = _home(monkeypatch, tmp_path) / ".ssh" + key = ssh_dir / KEY + key.write_text("x") + sleep = mocker.patch.object(time, "sleep", autospec=True) + sleep.side_effect = lambda _: key.unlink(missing_ok=True) + + stderr = _exit_before_session(mock_common_state, mocker) + + assert "was removed while waiting; retry or pass --identity." in stderr + + +@POSIX_ONLY +def test_failed_key_write_leaves_nothing( + mock_common_state, mocker, monkeypatch, tmp_path, keygen +): + ssh_dir = _home(monkeypatch, tmp_path) / ".ssh" + _short_write(mocker) + + stderr = _exit_before_session(mock_common_state, mocker, "--proxy-mode", "-s", "x") + + assert WRITE_FAILED.format(NO_SPACE) in stderr + assert list(ssh_dir.iterdir()) == [] + + +@POSIX_ONLY +@pytest.mark.parametrize("ok_writes", [0, 1], ids=["key", "pub"]) +def test_failed_cleanup_keeps_the_write_error( + mock_common_state, mocker, monkeypatch, tmp_path, keygen, ok_writes +): + _home(monkeypatch, tmp_path) + _short_write(mocker, ok_writes) + denied = PermissionError(errno.EACCES, DENIED) + mocker.patch.object(os, "remove", autospec=True, side_effect=denied) + + stderr = _exit_before_session(mock_common_state, mocker, "--proxy-mode", "-s", "x") + + assert WRITE_FAILED.format(NO_SPACE) in stderr + assert DENIED not in stderr + + +@POSIX_ONLY +def test_failing_ssh_keygen_surfaces_its_stderr( + mock_common_state, mocker, monkeypatch, tmp_path +): + fake = _home(monkeypatch, tmp_path) / "ssh-keygen" + fake.write_text('#!/bin/sh\necho "$@" >&2\nexit 1\n') + fake.chmod(0o700) + monkeypatch.setenv("PATH", str(fake.parent)) + + stderr = _exit_before_session(mock_common_state, mocker) + + assert "[colab] ssh-keygen: -t ed25519 " in stderr + assert f" -f {fake.parent / '.ssh'}{os.sep}" in stderr + + +@POSIX_ONLY +def test_failing_ssh_keygen_ignores_cleanup_error( + mock_common_state, mocker, monkeypatch, tmp_path, keygen +): + _home(monkeypatch, tmp_path) + keygen.side_effect = subprocess.CalledProcessError(1, "ssh-keygen", stderr="err") + mocker.patch.object(os, "rmdir", autospec=True, side_effect=PermissionError) + + stderr = _exit_before_session(mock_common_state, mocker) + + assert "failed for ~/.ssh/colab_cli_ed25519" in stderr + + +@pytest.mark.parametrize( + "names", + [("id_ed25519.pub",), ("id_ecdsa.pub",), ("id_ecdsa.pub", KEY)], + ids=["ed25519", "ecdsa", "ecdsa-with-incomplete-colab-key"], +) +def test_ssh_existing_key_keeps_default_argv_and_header( + mock_common_state, monkeypatch, tmp_path, names +): + home = _home(monkeypatch, tmp_path, *names) + before = _snapshot(home / ".ssh") + + result, call, _ = _invoke(mock_common_state) + proxy_result, _, connect = _invoke(mock_common_state, "--proxy-mode") + + assert (result.exit_code, proxy_result.exit_code) == (0, 0) + assert "-i" not in call.call_args.args[0] + assert _header(connect) == names[0] + assert result.stderr == proxy_result.stderr == "" + assert _snapshot(home / ".ssh") == before + + +@pytest.mark.parametrize( + ("names", "expected"), + [ + ((KEY, f"{KEY}.pub", "id_ed25519.pub"), KEY), + ((KEY, "id_ed25519.pub"), "id_ed25519"), + ((f"{KEY}.pub", "id_ecdsa.pub"), "id_ecdsa"), + (("id_ed25519.pub", "id_ecdsa.pub"), "id_ed25519"), + (("id_ecdsa.pub",), "id_ecdsa"), + (("id_ed25519", "id_rsa", "id_rsa.pub"), None), + ((), None), + ], + ids=[ + "colab-key-first", + "colab-key-without-pub", + "colab-pub-without-key", + "ed25519-first", + "ecdsa", + "no-pub-or-rsa", + "nothing", + ], +) +def test_resolve_default_identity_order(mocker, monkeypatch, tmp_path, names, expected): + home = _home(monkeypatch, tmp_path, *names) + before = _snapshot(home) + mocker.patch.object( + subprocess, "run", autospec=True, side_effect=AssertionError("ran a command") + ) + + found = ssh_module.resolve_default_identity() + + assert found == (str(home / ".ssh" / expected) if expected else None) + assert _snapshot(home) == before + + +def test_resolve_default_identity_skips_empty_colab_pub(mocker, monkeypatch, tmp_path): + home = _home(monkeypatch, tmp_path, KEY, "id_ed25519.pub") + (home / ".ssh" / f"{KEY}.pub").write_text("") + mocker.patch.object( + subprocess, "run", autospec=True, side_effect=AssertionError("ran a command") + ) + + assert ssh_module.resolve_default_identity() == str(home / ".ssh" / "id_ed25519") + + +def test_ssh_colab_key_reaches_ssh_and_header( + mock_common_state, monkeypatch, tmp_path, keygen +): + home = _home(monkeypatch, tmp_path, KEY, "id_ed25519.pub") + (home / ".ssh" / f"{KEY}.pub").write_text("ssh-ed25519 AAAAcolab colab-cli\n") + + result, call, _ = _invoke(mock_common_state) + key = _ssh_identity(mock_common_state, call) + child, _, connect = _invoke(mock_common_state, "--proxy-mode", "-i", key) + + assert (result.exit_code, child.exit_code) == (0, 0) + assert key == str(home / ".ssh" / KEY) + assert _header(connect) == "ssh-ed25519 AAAAcolab colab-cli" + keygen.assert_not_called() + assert result.stderr == child.stderr == "" + + +def test_ssh_cmd_uses_the_colab_key(mock_common_state, mocker, monkeypatch, tmp_path): + home = _home(monkeypatch, tmp_path, KEY, f"{KEY}.pub", "id_ed25519.pub") + mocker.patch.object(ssh_module.sys, "platform", "linux") + + result, call, _ = _invoke(mock_common_state, "--", "true") + + key = str(home / ".ssh" / KEY) + argv = call.call_args.args[0] + child = shlex.split(argv[argv.index("-o") + 1].removeprefix("ProxyCommand=")) + assert result.exit_code == 0, result.output + assert ("-i", key) in zip(argv, argv[1:]) + assert ("--identity", key) in zip(child, child[1:]) + + +def _run_parallel_first_runs(tmp_path): + home = tmp_path / "race" + env = {**os.environ, "HOME": str(home), "USERPROFILE": str(home)} + code = "from colab_cli.commands import ssh; print(ssh._resolve_identity(None))" + runs = [ + subprocess.Popen( + [sys.executable, "-c", code], env=env, stdout=subprocess.PIPE, text=True + ) + for _ in range(PARALLEL_RUNS) + ] + try: + outputs = [run.communicate(timeout=30)[0].strip() for run in runs] + finally: + for run in runs: + if run.returncode is None: + run.kill() + run.wait() + if run.stdout is not None and not run.stdout.closed: + run.stdout.close() + return home / ".ssh" / KEY, runs, outputs + + +@pytest.mark.skipif(shutil.which("ssh-keygen") is None, reason="requires ssh-keygen") +def test_parallel_first_runs_share_one_real_key(tmp_path): + key, runs, outputs = _run_parallel_first_runs(tmp_path) + + assert [run.returncode for run in runs] == [0 for _ in runs] + assert outputs == [str(key) for _ in runs] + assert sorted(p.name for p in key.parent.iterdir()) == [KEY, f"{KEY}.pub"] + pub = Path(f"{key}.pub").read_text().split() + derived = subprocess.run( + ["ssh-keygen", "-y", "-f", str(key)], check=True, capture_output=True, text=True + ) + assert derived.stdout.split()[:2] == pub[:2] + assert pub[0] == "ssh-ed25519" and pub[2] == "colab-cli" + + +@POSIX_ONLY +@pytest.mark.skipif(shutil.which("ssh-keygen") is None, reason="requires ssh-keygen") +def test_parallel_first_runs_posix_modes(tmp_path): + key, runs, _ = _run_parallel_first_runs(tmp_path) + + assert [run.returncode for run in runs] == [0 for _ in runs] + assert stat.S_IMODE(key.stat().st_mode) == 0o600 + assert stat.S_IMODE(key.parent.stat().st_mode) == 0o700 + + +@POSIX_ONLY +def test_proxy_mode_generation_keeps_stdout_clean( + mock_common_state, monkeypatch, tmp_path, capfd +): + home = _home(monkeypatch, tmp_path) + fake = tmp_path / "bin" / "ssh-keygen" + fake.parent.mkdir() + fake.write_text( + f"#!{sys.executable}\n" + "import sys\n" + "from pathlib import Path\n" + "key = Path(sys.argv[sys.argv.index('-f') + 1])\n" + "pub = key.with_name(key.name + '.pub')\n" + "if '-y' in sys.argv:\n" + " print(pub.read_text().strip())\n" + " sys.exit()\n" + "print('keygen-noise')\n" + "key.write_text('private')\n" + "pub.write_text('ssh-ed25519 AAAAnoisy colab-cli')\n" + ) + fake.chmod(0o700) + monkeypatch.setenv("PATH", f"{fake.parent}{os.pathsep}{os.environ['PATH']}") + + result, _, connect = _invoke(mock_common_state, "--proxy-mode") + + assert result.exit_code == 0, result.output + assert result.stdout == "" + assert "keygen-noise" not in capfd.readouterr().out + assert _header(connect) == "ssh-ed25519 AAAAnoisy colab-cli" + assert result.stderr.count(f"IdentityFile {ssh_module._COLAB_KEY}") == 1 + assert str(home) not in result.stderr + + +def test_proxy_mode_hints_when_it_reuses_the_colab_key( + mock_common_state, monkeypatch, tmp_path, keygen +): + _home(monkeypatch, tmp_path, KEY, f"{KEY}.pub") + + result, _, _ = _invoke(mock_common_state, "--proxy-mode") + + assert result.exit_code == 0, result.output + assert _generate_calls(keygen) == [] + assert result.stderr.count("\n") == 1 + assert f"IdentityFile {ssh_module._COLAB_KEY}" in result.stderr + assert f"--identity {ssh_module._COLAB_KEY} to silence" in result.stderr + + +def test_proxy_mode_with_explicit_colab_key_prints_no_hint( + mock_common_state, monkeypatch, tmp_path, keygen +): + key = str(_home(monkeypatch, tmp_path, KEY, f"{KEY}.pub") / ".ssh" / KEY) + + result, _, _ = _invoke(mock_common_state, "--proxy-mode", "--identity", key) + + assert result.exit_code == 0, result.output + assert _generate_calls(keygen) == [] + assert result.stderr == ""