Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions docs/04_automation_and_utility.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
log:
2026-12-04: `colab auth` now answers the kernel's `input_request`: the stdin hook sends an `input_reply` on the stdin channel instead of only returning the typed value (which `jupyter_kernel_client` discards), prints `content.prompt` instead of the raw message, uses `getpass` for password prompts, and logs `***` in history for those. Added `tests/test_runtime_stdin.py`.
2026-11-30: `_run_with_timeout` in `auth.py` now sets a `cancel_event` on timeout so keyring worker threads that unblock from `_check_linux_keyring_locked` after timing out skip stale lock warnings and abort before calling `get_password`/`set_password`/`delete_password`. Unit tests now enforce `keyring.backends.null.Keyring` (and `PYTHON_KEYRING_BACKEND`) for the entire pytest process via `pytest_configure` in `tests/conftest.py` instead of restoring the host OS keyring between tests, and timeout tests in `tests/test_auth.py` join spawned daemon threads before fixture teardown.
2026-11-19: Added `colab logout` to clear stored OAuth2 credentials across all chained OS keyring backends (disambiguating missing entries from real keychain/KWallet failures and warning on `NoKeyringError`) and legacy `~/.config/colab-cli/token.json` without revoking Google Cloud SDK's shared OAuth client grant. Under `--auth=adc`, prints `gcloud auth application-default revoke`. Also invalidates cached runtime proxy tokens in `sessions.json` (warning if local sessions remain), resets cached API capability flags in `settings.json`, and suppresses the daily auto-update banner.
2026-11-13: `_get_adc_credentials` in `auth.py` now catches `DefaultCredentialsError` from `google.auth.default()` so missing local ADC prints the 4-scope `gcloud auth application-default login` command and exits 1 instead of surfacing `google-auth`'s stock unscoped setup message. Updated scope documentation to clarify that both `colaboratory` and `userinfo.email` are required by `colab.research.google.com`.
Expand Down Expand Up @@ -117,8 +118,10 @@ How each provider supplies the scopes:
google.colab import auth auth.authenticate_user()`
- **Handling**: Setting `USE_AUTH_EPHEM` to `'0'` forces the kernel to print a
standard `gcloud` verification URL and trigger an `input_request` message on
the `iopub` channel. The CLI intercepts this via a `stdin_hook` and prompts
the user locally, returning the code to unlock the kernel.
the `stdin` channel. `ColabRuntime.execute_code(allow_stdin=True)` wraps the
kernel client's `stdin_hook`, prints `content.prompt` locally (via `getpass`
for password prompts), and sends the typed value back as an `input_reply`
so the kernel's `input()` returns.

### 2. Package Installation (`colab install`)

Expand Down Expand Up @@ -340,6 +343,10 @@ TDD is mandatory for all automation features.
- **Test Case**: Verify `colab drivemount` correctly injects `drive.mount()`
commands and registers the `colab_request_hook` to intercept credential
propagation events.
- **Test Case**: Verify `ColabRuntime.execute_code(allow_stdin=True)` answers
each `input_request` with an `input_reply`: prompt text, `getpass` for
password prompts, `"\x04"` on EOF, no reply on Ctrl-C or when a channel
already has a queued message (`tests/test_runtime_stdin.py`).

### 2. History Capture

Expand Down
54 changes: 42 additions & 12 deletions src/colab_cli/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import getpass
import logging
import queue
import time
Expand Down Expand Up @@ -188,10 +189,17 @@ def execute_code(
self,
code: str,
allow_stdin: bool = False,
stdin_hook: Any = None,
stdin_hook: Optional[Callable[[Dict[str, Any]], Optional[str]]] = None,
output_hook: Optional[Callable[[Dict[str, Any]], None]] = None,
timeout: Optional[float] = None,
) -> List[Dict[str, Any]]:
"""Execute code and collect its outputs.

With ``allow_stdin``, ``stdin_hook`` is called with each
``input_request`` message. It must either send the ``input_reply``
itself and return ``None``, or return the value for this method to
send.
"""
if allow_stdin and output_hook is not None:
raise NotImplementedError(
"output_hook is not supported when allow_stdin is True"
Expand All @@ -209,24 +217,46 @@ def execute_code(
# explicitly.
if allow_stdin:
original_stdin_hook = stdin_hook

def wrapped_stdin_hook(prompt):
wsclient = self.kernel_client._manager.client

def wrapped_stdin_hook(request):
content = request.get("content") if isinstance(request, dict) else None
if not isinstance(content, dict):
content = {}
prompt = content.get("prompt", "")
password = bool(content.get("password", False))
if self.history and self.session_name:
self.history.log_event(
self.session_name, "stdin_request", {"prompt": prompt}
self.session_name,
"stdin_request",
{"prompt": prompt},
)

res = (
original_stdin_hook(prompt)
if original_stdin_hook
else input(prompt)
)

try:
if original_stdin_hook:
value = original_stdin_hook(request)
if value is None:
return
elif password:
value = getpass.getpass(prompt)
else:
value = input(prompt)
except EOFError:
value = "\x04"
except KeyboardInterrupt:
return

if not (
wsclient.stdin_channel.msg_ready()
or wsclient.shell_channel.msg_ready()
):
wsclient.input(value)
if self.history and self.session_name:
self.history.log_event(
self.session_name, "input_reply", {"value": res}
self.session_name,
"input_reply",
{"value": "***" if password else value},
)
return res

kwargs: Dict[str, Any] = {
"allow_stdin": True,
Expand Down
14 changes: 10 additions & 4 deletions tests/test_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,15 +228,21 @@ def test_colab_runtime_stdin_logging():
)
mock_kc = MagicMock()
runtime._kernel_client = mock_kc
mock_kc._manager.client.stdin_channel.msg_ready.return_value = False
mock_kc._manager.client.shell_channel.msg_ready.return_value = False
request = {"content": {"prompt": "Enter something: ", "password": False}}

mock_kc.execute.side_effect = lambda code, allow_stdin=False, stdin_hook=None: {
"outputs": [{"text": stdin_hook("Enter something: ")}]
}
def fake_execute(code, allow_stdin=False, stdin_hook=None):
stdin_hook(request)
return {"outputs": []}

mock_kc.execute.side_effect = fake_execute

with patch("colab_cli.runtime.input", return_value="user input"):
outputs = runtime.execute_code("code", allow_stdin=True)

assert outputs == [{"text": "user input"}]
assert outputs == []
mock_kc._manager.client.input.assert_called_once_with("user input")
mock_history.log_event.assert_any_call(
"test-s", "stdin_request", {"prompt": "Enter something: "}
)
Expand Down
187 changes: 187 additions & 0 deletions tests/test_runtime_stdin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""The stdin hook must answer the kernel's ``input_request``.

``jupyter_kernel_client`` calls ``stdin_hook(request)`` and discards the return
value, so the hook itself has to send the ``input_reply``. Before this suite the
hook returned the typed value without sending anything, and ``colab auth`` hung
forever on its first prompt.
"""

from types import SimpleNamespace
from unittest.mock import MagicMock

import pytest

from colab_cli.runtime import ColabRuntime


class FakeChannel:
"""A Jupyter channel whose queued-message state the test controls."""

def __init__(self, ready=False):
self.ready = ready

def msg_ready(self):
return self.ready


class FakeWsClient:
"""Records the replies that the runtime sends on the stdin channel."""

def __init__(self, stale=False):
self.replies = []
self.stdin_channel = FakeChannel(ready=stale)
self.shell_channel = FakeChannel()

def input(self, value):
self.replies.append(value)


class FakeKernelClient:
"""Calls the runtime's stdin hook with a canned ``input_request``."""

def __init__(self, request, stale=False):
self.request = request
self.ws = FakeWsClient(stale=stale)
self._manager = SimpleNamespace(client=self.ws)

def execute(self, code, **kwargs):
kwargs["stdin_hook"](self.request)
return {"status": "ok", "outputs": []}


def make_runtime(history=None):
return ColabRuntime(
"http://url",
"token",
session_name="session",
history=history,
)


def test_stdin_hook_shows_the_prompt_and_sends_the_reply(monkeypatch):
runtime = make_runtime()
runtime._kernel_client = FakeKernelClient(
{"content": {"prompt": "Enter code: ", "password": False}}
)
prompts = []

def fake_input(prompt):
prompts.append(prompt)
return "4/abc"

monkeypatch.setattr("builtins.input", fake_input)

runtime.execute_code("code", allow_stdin=True)

assert prompts == ["Enter code: "]
assert runtime._kernel_client.ws.replies == ["4/abc"]


def test_stdin_hook_uses_getpass_for_password_and_redacts_the_history(monkeypatch):
history = MagicMock()
runtime = make_runtime(history=history)
runtime._kernel_client = FakeKernelClient(
{"content": {"prompt": "Password: ", "password": True}}
)
prompts = []

def fake_getpass(prompt):
prompts.append(prompt)
return "s3cret"

monkeypatch.setattr("getpass.getpass", fake_getpass)
monkeypatch.setattr(
"builtins.input", lambda prompt: pytest.fail("input() used for a password")
)

runtime.execute_code("code", allow_stdin=True)

assert prompts == ["Password: "]
assert runtime._kernel_client.ws.replies == ["s3cret"]
assert "s3cret" not in str(history.log_event.call_args_list)


def test_stdin_hook_sends_eof_to_unblock_the_kernel(monkeypatch):
runtime = make_runtime()
runtime._kernel_client = FakeKernelClient({"content": {"prompt": "Enter: "}})

def raise_eof(prompt):
raise EOFError

monkeypatch.setattr("builtins.input", raise_eof)

runtime.execute_code("code", allow_stdin=True)

assert runtime._kernel_client.ws.replies == ["\x04"]


def test_stdin_hook_does_not_reply_after_ctrl_c(monkeypatch):
runtime = make_runtime()
runtime._kernel_client = FakeKernelClient({"content": {"prompt": "Enter: "}})

def raise_interrupt(prompt):
raise KeyboardInterrupt

monkeypatch.setattr("builtins.input", raise_interrupt)

runtime.execute_code("code", allow_stdin=True)

assert runtime._kernel_client.ws.replies == []


def test_stdin_hook_skips_a_stale_reply(monkeypatch):
runtime = make_runtime()
runtime._kernel_client = FakeKernelClient(
{"content": {"prompt": "Enter: "}}, stale=True
)
monkeypatch.setattr("builtins.input", lambda prompt: "late")

runtime.execute_code("code", allow_stdin=True)

assert runtime._kernel_client.ws.replies == []


def test_stdin_hook_sends_the_value_returned_by_a_custom_hook(monkeypatch):
runtime = make_runtime()
runtime._kernel_client = FakeKernelClient({"content": {"prompt": "Enter: "}})

runtime.execute_code("code", allow_stdin=True, stdin_hook=lambda request: "typed")

assert runtime._kernel_client.ws.replies == ["typed"]


def test_stdin_hook_assumes_a_custom_hook_replied_when_it_returns_none():
runtime = make_runtime()
runtime._kernel_client = FakeKernelClient({"content": {"prompt": "Enter: "}})

runtime.execute_code("code", allow_stdin=True, stdin_hook=lambda request: None)

assert runtime._kernel_client.ws.replies == []


def test_stdin_hook_tolerates_a_missing_content(monkeypatch):
runtime = make_runtime()
runtime._kernel_client = FakeKernelClient({"content": None})
prompts = []
monkeypatch.setattr(
"builtins.input", lambda prompt: prompts.append(prompt) or "value"
)

runtime.execute_code("code", allow_stdin=True)

assert prompts == [""]
assert runtime._kernel_client.ws.replies == ["value"]