From 68c8a95003848d5c39aaa1636f701d01bdd48196 Mon Sep 17 00:00:00 2001 From: Zhong-fan <17373302683@163.com> Date: Fri, 4 Dec 2026 16:21:32 +0800 Subject: [PATCH 1/2] fix(auth): answer the kernel's input_request on the stdin channel jupyter_kernel_client calls stdin_hook(request) and discards the return value, so the hook must send the input_reply itself. The wrapper returned the typed value without sending anything, which left colab auth waiting forever on its first prompt, and it passed the whole message dict to input(), so the raw dict was printed instead of the prompt. Send the reply through the websocket client, print content.prompt, use getpass for password prompts, and redact those values in session history. --- docs/04_automation_and_utility.md | 7 ++- src/colab_cli/runtime.py | 30 ++++++--- tests/test_runtime.py | 12 ++-- tests/test_runtime_stdin.py | 101 ++++++++++++++++++++++++++++++ 4 files changed, 135 insertions(+), 15 deletions(-) create mode 100644 tests/test_runtime_stdin.py diff --git a/docs/04_automation_and_utility.md b/docs/04_automation_and_utility.md index fb91ddcd..0951af74 100644 --- a/docs/04_automation_and_utility.md +++ b/docs/04_automation_and_utility.md @@ -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`. @@ -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`) diff --git a/src/colab_cli/runtime.py b/src/colab_cli/runtime.py index 96cd442b..69c2fbda 100644 --- a/src/colab_cli/runtime.py +++ b/src/colab_cli/runtime.py @@ -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 @@ -209,24 +210,35 @@ def execute_code( # explicitly. if allow_stdin: original_stdin_hook = stdin_hook + wsclient = self.kernel_client._manager.client - def wrapped_stdin_hook(prompt): + def wrapped_stdin_hook(request): + content = request.get("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) - ) + if original_stdin_hook: + value = original_stdin_hook(request) + if value is None: + return + elif password: + value = getpass.getpass(prompt) + else: + value = input(prompt) 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 + wsclient.input(value) kwargs: Dict[str, Any] = { "allow_stdin": True, diff --git a/tests/test_runtime.py b/tests/test_runtime.py index 00f00dde..c64b6655 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -228,15 +228,19 @@ def test_colab_runtime_stdin_logging(): ) mock_kc = MagicMock() runtime._kernel_client = mock_kc + 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: "} ) diff --git a/tests/test_runtime_stdin.py b/tests/test_runtime_stdin.py new file mode 100644 index 00000000..e7f4adee --- /dev/null +++ b/tests/test_runtime_stdin.py @@ -0,0 +1,101 @@ +# 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 FakeWsClient: + """Records the replies that the runtime sends on the stdin channel.""" + + def __init__(self): + self.replies = [] + + 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): + self.request = request + self.ws = FakeWsClient() + 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}} + ) + monkeypatch.setattr("getpass.getpass", lambda prompt: "s3cret") + monkeypatch.setattr( + "builtins.input", lambda prompt: pytest.fail("input() used for a password") + ) + + runtime.execute_code("code", allow_stdin=True) + + assert runtime._kernel_client.ws.replies == ["s3cret"] + replies = [ + call.args + for call in history.log_event.call_args_list + if call.args[1] == "input_reply" + ] + assert replies[-1][2] == {"value": "***"} From 64d4716d0225bb19070713c36a81ccc4dfcdbb6a Mon Sep 17 00:00:00 2001 From: Zhong-fan <17373302683@163.com> Date: Fri, 4 Dec 2026 16:41:35 +0800 Subject: [PATCH 2/2] fix(auth): harden the stdin reply path Mirror jupyter_kernel_client's default stdin hook: send an EOF marker on EOF, stay silent on Ctrl-C, and skip the reply when a channel already has a queued message. Send the reply before writing history so a logging failure cannot strand the kernel, tolerate a request without a content mapping, and document the custom stdin_hook contract. --- docs/04_automation_and_utility.md | 4 ++ src/colab_cli/runtime.py | 42 ++++++++---- tests/test_runtime.py | 2 + tests/test_runtime_stdin.py | 106 +++++++++++++++++++++++++++--- 4 files changed, 132 insertions(+), 22 deletions(-) diff --git a/docs/04_automation_and_utility.md b/docs/04_automation_and_utility.md index 0951af74..b86a25d8 100644 --- a/docs/04_automation_and_utility.md +++ b/docs/04_automation_and_utility.md @@ -343,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 diff --git a/src/colab_cli/runtime.py b/src/colab_cli/runtime.py index 69c2fbda..0b5657d1 100644 --- a/src/colab_cli/runtime.py +++ b/src/colab_cli/runtime.py @@ -189,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" @@ -213,7 +220,9 @@ def execute_code( wsclient = self.kernel_client._manager.client def wrapped_stdin_hook(request): - content = request.get("content", {}) + 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: @@ -223,22 +232,31 @@ def wrapped_stdin_hook(request): {"prompt": prompt}, ) - if original_stdin_hook: - value = original_stdin_hook(request) - if value is None: - return - elif password: - value = getpass.getpass(prompt) - else: - value = 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": "***" if password else value}, ) - wsclient.input(value) kwargs: Dict[str, Any] = { "allow_stdin": True, diff --git a/tests/test_runtime.py b/tests/test_runtime.py index c64b6655..e9bbc2ee 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -228,6 +228,8 @@ 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}} def fake_execute(code, allow_stdin=False, stdin_hook=None): diff --git a/tests/test_runtime_stdin.py b/tests/test_runtime_stdin.py index e7f4adee..341852c6 100644 --- a/tests/test_runtime_stdin.py +++ b/tests/test_runtime_stdin.py @@ -28,11 +28,23 @@ 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): + 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) @@ -41,9 +53,9 @@ def input(self, value): class FakeKernelClient: """Calls the runtime's stdin hook with a canned ``input_request``.""" - def __init__(self, request): + def __init__(self, request, stale=False): self.request = request - self.ws = FakeWsClient() + self.ws = FakeWsClient(stale=stale) self._manager = SimpleNamespace(client=self.ws) def execute(self, code, **kwargs): @@ -85,17 +97,91 @@ def test_stdin_hook_uses_getpass_for_password_and_redacts_the_history(monkeypatc runtime._kernel_client = FakeKernelClient( {"content": {"prompt": "Password: ", "password": True}} ) - monkeypatch.setattr("getpass.getpass", lambda prompt: "s3cret") + 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"] - replies = [ - call.args - for call in history.log_event.call_args_list - if call.args[1] == "input_reply" - ] - assert replies[-1][2] == {"value": "***"} + 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"]