diff --git a/README.md b/README.md index e6c48d0..a701220 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,7 @@ CLI tool for using the CSA Test Harness Commands: abort-testing Abort the current test execution available-tests Get a list of available tests + doctor Diagnose problems reaching the backend project Manage the application projects rescan-tests Rescan available test collections run-tests Create a new test run from selected tests @@ -68,6 +69,30 @@ Options: Run `th-cli test-runner-status` to get the current state of the Matter test runner. For JSON respond, add `--json`. +### doctor + +Run `th-cli doctor` when the CLI cannot talk to the backend. It checks, and reports as pass / warn / fail / skip: + +- **config**: which `config.json` is used (or that the example file or defaults were used) and the backend host. A + broken `config.json` is reported here instead of aborting the command. +- **backend reachable**: `GET /api/v1/version` with a 5 s timeout, reported as connection refused, DNS failure, + timeout or the HTTP status. +- **versions**: the CLI version and SHA next to the backend version, SHA, SDK tag and database revision. +- **test runner** and **database**: the runner state and a database-backed call (`/projects/`). A failure here is a + warning. +- **Docker containers** (backend, frontend, db, proxy): skipped when `docker` is not installed. + +The command exits with a non-zero status if a check fails. + +Options: +- `--json`: Print the results as JSON. +- `--no-docker`: Skip the Docker container checks. +- `--log-lines `: Include the last N lines of the backend container log. +- `--no-redact`: Do not mask IP and MAC addresses. + +The output is meant to be pasted into issues. Values of keys such as passwords, network keys, datasets, tokens and +setup codes, and credentials in URLs, are always masked. IP and MAC addresses are masked unless `--no-redact` is given. + ### abort-testing Run `th-cli abort-testing` to abort the test run execution that is currently running. diff --git a/tests/test_available_tests.py b/tests/test_available_tests.py index ab41384..aa1c0c5 100644 --- a/tests/test_available_tests.py +++ b/tests/test_available_tests.py @@ -166,6 +166,25 @@ def test_available_tests_generic_exception( assert "Please check if the API server is running and accessible" in result.output mock_api_client.close.assert_called_once() + def test_available_tests_transport_error_suggests_doctor( + self, cli_runner: CliRunner, mock_sync_apis: Mock, mock_api_client: Mock + ) -> None: + """An empty-text transport error names its type and points at `th-cli doctor`.""" + from httpx import ConnectError + + from th_cli.api_lib_autogen.exceptions import ResponseHandlingException + from th_cli.exceptions import BACKEND_HINT + + api = mock_sync_apis.test_collections_api.read_test_collections_api_v1_test_collections__get + api.side_effect = ResponseHandlingException(ConnectError("")) + with patch("th_cli.commands.available_tests.get_client", return_value=mock_api_client): + with patch("th_cli.commands.available_tests.SyncApis", return_value=mock_sync_apis): + result = cli_runner.invoke(available_tests) + + assert result.exit_code == 1 + assert "ConnectError" in result.output + assert BACKEND_HINT in result.output + def test_available_tests_client_cleanup_on_exception(self, cli_runner: CliRunner, mock_api_client: Mock) -> None: """Test that client is properly cleaned up even when an exception occurs.""" # Arrange diff --git a/tests/test_doctor.py b/tests/test_doctor.py new file mode 100644 index 0000000..2e6826d --- /dev/null +++ b/tests/test_doctor.py @@ -0,0 +1,400 @@ +# +# Copyright (c) 2026 Project CHIP Authors +# +# 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. +# +"""Tests for the doctor command.""" + +import importlib +import json +import socket +import subprocess +from pathlib import Path +from unittest.mock import Mock, patch + +import pytest +from click.testing import CliRunner +from httpx import ConnectError, ConnectTimeout, ReadTimeout + +from th_cli.api_lib_autogen import models as api_models +from th_cli.api_lib_autogen.exceptions import ResponseHandlingException, UnexpectedResponse +from th_cli.commands.doctor import CheckResult, Status, check_config, check_docker, classify_error, doctor +from th_cli.config import Config +from th_cli.exceptions import ConfigurationError + +# th_cli.commands.doctor is shadowed by the command object in the package namespace +doctor_module = importlib.import_module("th_cli.commands.doctor") + +VERSION = api_models.TestHarnessBackendVersion( + version="2.16", sha="abcdef123456", sdk_sha="s", sdk_docker_tag="tag", db_revision="rev1" +) + + +def _wrapped(error: Exception) -> ResponseHandlingException: + return ResponseHandlingException(error) + + +def _gaierror_connect_error() -> ConnectError: + error = ConnectError("") + error.__cause__ = socket.gaierror(-2, "Name or service not known") + return error + + +def _refused_connect_error() -> ConnectError: + error = ConnectError("") + error.__cause__ = ConnectionRefusedError(111, "Connection refused") + return error + + +@pytest.mark.unit +@pytest.mark.cli +class TestClassifyError: + def test_http_status(self) -> None: + assert classify_error(UnexpectedResponse(502, b"")) == "HTTP 502 from the backend" + + def test_connection_refused(self) -> None: + assert classify_error(_wrapped(_refused_connect_error())) == "connection refused" + + def test_dns(self) -> None: + assert classify_error(_wrapped(_gaierror_connect_error())).startswith("DNS lookup failed") + + @pytest.mark.parametrize("error", [ReadTimeout(""), ConnectTimeout("")]) + def test_timeout(self, error: Exception) -> None: + assert classify_error(_wrapped(error)).startswith("timeout") + + def test_plain_connect_error_is_never_empty(self) -> None: + assert classify_error(_wrapped(ConnectError(""))) == "cannot connect (ConnectError)" + + def test_unknown_error_uses_its_description(self) -> None: + assert classify_error(_wrapped(ValueError("bad body"))) == "ValueError: bad body" + + +@pytest.mark.unit +@pytest.mark.cli +class TestCheckConfig: + def test_valid_config(self, tmp_path: Path) -> None: + (tmp_path / "config.json").write_text('{"hostname": "th.local"}') + with ( + patch("th_cli.commands.doctor.get_config_search_paths", return_value=[tmp_path]), + patch("th_cli.config.get_config_search_paths", return_value=[tmp_path]), + ): + result, config = check_config() + assert result.status == Status.PASS + assert config is not None and config.hostname == "th.local" + assert str(tmp_path / "config.json") in result.detail + + def test_invalid_config_reported_not_raised(self, tmp_path: Path) -> None: + (tmp_path / "config.json").write_text("{bad") + with ( + patch("th_cli.commands.doctor.get_config_search_paths", return_value=[tmp_path]), + patch("th_cli.config.get_config_search_paths", return_value=[tmp_path]), + ): + result, config = check_config() + assert result.status == Status.FAIL + assert config is None + assert "config.json" in result.detail + + def test_defaults_used_is_a_warning_and_output_is_captured(self, tmp_path: Path, capsys) -> None: + with ( + patch("th_cli.commands.doctor.get_config_search_paths", return_value=[tmp_path]), + patch("th_cli.config.get_config_search_paths", return_value=[tmp_path]), + ): + result, config = check_config() + assert result.status == Status.WARN + assert config is not None and config.hostname == "localhost" + assert "defaults" in result.detail + assert capsys.readouterr().out == "" + + def test_broken_example_falls_back_with_warning(self, tmp_path: Path) -> None: + (tmp_path / "config.json.example").write_text("{bad") + with ( + patch("th_cli.commands.doctor.get_config_search_paths", return_value=[tmp_path]), + patch("th_cli.config.get_config_search_paths", return_value=[tmp_path]), + ): + result, _ = check_config() + assert result.status == Status.WARN + assert "Could not load example config" in result.detail + + +@pytest.fixture +def backend(mock_api_client: Mock): + """Patch get_client and SyncApis so each probe's response can be set per test.""" + apis = Mock() + apis.version_api.get_test_harness_backend_version_api_v1_version_get.return_value = VERSION + status = Mock() + status.state = Mock(value="idle") + apis.test_run_executions_api.get_test_runner_status_api_v1_test_run_executions_status_get.return_value = status + apis.projects_api.read_projects_api_v1_projects__get.return_value = [] + with ( + patch("th_cli.commands.doctor.get_client", return_value=mock_api_client), + patch("th_cli.commands.doctor.SyncApis", return_value=apis), + ): + yield apis + + +@pytest.mark.unit +@pytest.mark.cli +class TestCheckBackend: + def test_all_healthy(self, backend: Mock) -> None: + results = doctor_module.check_backend() + assert [r.status for r in results] == [Status.PASS] * 4 + assert "backend 2.16 (abcdef12)" in results[1].detail + + def test_unreachable_skips_the_rest_with_reason(self, backend: Mock) -> None: + backend.version_api.get_test_harness_backend_version_api_v1_version_get.side_effect = _wrapped( + _refused_connect_error() + ) + results = doctor_module.check_backend() + assert results[0].status == Status.FAIL + assert results[0].detail == "connection refused" + assert all(r.status == Status.SKIP for r in results[1:]) + + def test_database_failure_is_a_warning(self, backend: Mock) -> None: + backend.projects_api.read_projects_api_v1_projects__get.side_effect = UnexpectedResponse(500, b"") + results = doctor_module.check_backend() + assert results[0].status == Status.PASS + assert results[-1].name == "database" and results[-1].status == Status.WARN + assert "HTTP 500" in results[-1].detail + + def test_runner_status_failure_is_a_warning(self, backend: Mock) -> None: + runner = backend.test_run_executions_api.get_test_runner_status_api_v1_test_run_executions_status_get + runner.side_effect = _wrapped(ReadTimeout("")) + results = doctor_module.check_backend() + assert results[2].status == Status.WARN + + def test_unexpected_exception_in_probe_is_reported(self, backend: Mock) -> None: + backend.version_api.get_test_harness_backend_version_api_v1_version_get.side_effect = RuntimeError("boom") + assert doctor_module.check_backend()[0].detail == "boom" + + def test_client_construction_failure(self) -> None: + with patch("th_cli.commands.doctor.get_client", side_effect=ConfigurationError("no host")): + results = doctor_module.check_backend() + assert results[0].status == Status.FAIL and results[0].detail == "no host" + + +@pytest.mark.unit +@pytest.mark.cli +class TestCheckDocker: + def test_skipped_without_docker(self) -> None: + with patch("th_cli.commands.doctor.shutil.which", return_value=None): + results = check_docker(0) + assert [r.status for r in results] == [Status.SKIP] + + def test_states(self) -> None: + def fake(args: list[str]) -> subprocess.CompletedProcess: + name = args[-1] + if name.endswith("backend-1"): + return subprocess.CompletedProcess(args, 0, "running\n", "") + if name.endswith("db-1"): + return subprocess.CompletedProcess(args, 0, "exited\n", "") + return subprocess.CompletedProcess(args, 1, "", "No such object") + + with ( + patch("th_cli.commands.doctor.shutil.which", return_value="/usr/bin/docker"), + patch("th_cli.commands.doctor._run_docker", side_effect=fake), + ): + results = {r.name: r.status for r in check_docker(0)} + assert results["certification-tool-backend-1"] == Status.PASS + assert results["certification-tool-db-1"] == Status.FAIL + assert results["certification-tool-proxy-1"] == Status.WARN + + def test_docker_failing_to_run_is_skipped(self) -> None: + with ( + patch("th_cli.commands.doctor.shutil.which", return_value="/usr/bin/docker"), + patch("th_cli.commands.doctor._run_docker", side_effect=subprocess.TimeoutExpired("docker", 10)), + ): + results = check_docker(0) + assert [r.status for r in results] == [Status.SKIP] + + def test_log_tail_included_on_request(self) -> None: + def fake(args: list[str]) -> subprocess.CompletedProcess: + if args[0] == "logs": + return subprocess.CompletedProcess(args, 0, "line1\n", "line2 password=x\n") + return subprocess.CompletedProcess(args, 0, "running\n", "") + + with ( + patch("th_cli.commands.doctor.shutil.which", return_value="/usr/bin/docker"), + patch("th_cli.commands.doctor._run_docker", side_effect=fake), + ): + results = check_docker(5) + assert results[-1].name == "backend logs" + assert "line2" in results[-1].data["log_tail"] + + def test_log_command_failure_is_a_warning_not_a_pass(self) -> None: + def fake(args: list[str]) -> subprocess.CompletedProcess: + if args[0] == "logs": + return subprocess.CompletedProcess(args, 1, "", "Error: No such container") + return subprocess.CompletedProcess(args, 0, "running\n", "") + + with ( + patch("th_cli.commands.doctor.shutil.which", return_value="/usr/bin/docker"), + patch("th_cli.commands.doctor._run_docker", side_effect=fake), + ): + result = check_docker(5)[-1] + assert result.status == Status.WARN + assert "No such container" in result.detail + assert result.data is None + + def test_empty_log_is_still_a_pass(self) -> None: + def fake(args: list[str]) -> subprocess.CompletedProcess: + return subprocess.CompletedProcess(args, 0, "" if args[0] == "logs" else "running\n", "") + + with ( + patch("th_cli.commands.doctor.shutil.which", return_value="/usr/bin/docker"), + patch("th_cli.commands.doctor._run_docker", side_effect=fake), + ): + assert check_docker(5)[-1].status == Status.PASS + + def test_log_failure_is_a_warning(self) -> None: + def fake(args: list[str]) -> subprocess.CompletedProcess: + if args[0] == "logs": + raise OSError("denied") + return subprocess.CompletedProcess(args, 0, "running\n", "") + + with ( + patch("th_cli.commands.doctor.shutil.which", return_value="/usr/bin/docker"), + patch("th_cli.commands.doctor._run_docker", side_effect=fake), + ): + assert check_docker(5)[-1].status == Status.WARN + + +@pytest.mark.unit +@pytest.mark.cli +class TestDoctorCommand: + def _run(self, cli_runner: CliRunner, results: list[CheckResult], *args: str): + with patch("th_cli.commands.doctor.run_checks", return_value=results) as run_checks: + result = cli_runner.invoke(doctor, list(args)) + return result, run_checks + + def test_success_exit_zero(self, cli_runner: CliRunner) -> None: + result, _ = self._run(cli_runner, [CheckResult("config", Status.PASS, "ok")]) + assert result.exit_code == 0 + assert "No problems found" in result.output + + def test_warning_does_not_fail(self, cli_runner: CliRunner) -> None: + result, _ = self._run(cli_runner, [CheckResult("config", Status.WARN, "defaults")]) + assert result.exit_code == 0 + + def test_failure_exit_nonzero(self, cli_runner: CliRunner) -> None: + result, _ = self._run(cli_runner, [CheckResult("backend reachable", Status.FAIL, "connection refused")]) + assert result.exit_code == 1 + assert "connection refused" in result.output + assert "1 check(s) failed" in result.output + + def test_json_output(self, cli_runner: CliRunner) -> None: + results = [ + CheckResult("config", Status.PASS, "ok", {"hostname": "10.1.2.3", "wifi_password": "pw"}), + CheckResult("backend reachable", Status.FAIL, "timeout"), + ] + result, _ = self._run(cli_runner, results, "--json") + payload = json.loads(result.output) + assert payload["ok"] is False + assert [c["status"] for c in payload["checks"]] == ["pass", "fail"] + assert payload["checks"][0]["data"] == {"hostname": "[ip]", "wifi_password": "[redacted]"} + assert result.exit_code == 1 + + def test_no_redact_keeps_ips_but_not_secrets(self, cli_runner: CliRunner) -> None: + results = [CheckResult("config", Status.PASS, "host 10.1.2.3", {"hostname": "10.1.2.3", "token": "t"})] + result, _ = self._run(cli_runner, results, "--json", "--no-redact") + data = json.loads(result.output)["checks"][0]["data"] + assert data == {"hostname": "10.1.2.3", "token": "[redacted]"} + + def test_human_output_masks_ips_by_default(self, cli_runner: CliRunner) -> None: + result, _ = self._run(cli_runner, [CheckResult("config", Status.PASS, "host 10.1.2.3")]) + assert "10.1.2.3" not in result.output + + def test_options_forwarded(self, cli_runner: CliRunner) -> None: + _, run_checks = self._run(cli_runner, [], "--no-docker", "--log-lines", "7") + run_checks.assert_called_once_with(docker=False, log_lines=7) + + def test_log_tail_printed_and_redacted(self, cli_runner: CliRunner) -> None: + results = [CheckResult("backend logs", Status.PASS, "last 2 lines", {"log_tail": "a password=x 10.0.0.9"})] + result, _ = self._run(cli_runner, results) + assert "password=x" not in result.output and "10.0.0.9" not in result.output + + +@pytest.mark.unit +@pytest.mark.cli +class TestRunChecks: + def test_invalid_config_skips_backend(self) -> None: + with ( + patch( + "th_cli.commands.doctor.check_config", return_value=(CheckResult("config", Status.FAIL, "bad"), None) + ), + patch("th_cli.commands.doctor.check_backend") as check_backend, + ): + results = doctor_module.run_checks(docker=False, log_lines=0) + check_backend.assert_not_called() + assert [r.status for r in results] == [Status.FAIL, Status.SKIP] + + def test_docker_section_is_optional(self) -> None: + ok = (CheckResult("config", Status.PASS, "ok"), Config()) + with ( + patch("th_cli.commands.doctor.check_config", return_value=ok), + patch("th_cli.commands.doctor.check_backend", return_value=[]), + patch("th_cli.commands.doctor.check_docker", return_value=[CheckResult("docker", Status.SKIP, "x")]) as d, + ): + assert len(doctor_module.run_checks(docker=True, log_lines=3)) == 2 + d.assert_called_once_with(3) + assert len(doctor_module.run_checks(docker=False, log_lines=3)) == 1 + + +@pytest.mark.unit +@pytest.mark.cli +class TestDoctorInvocationDetection: + """A bad config.json normally exits at import; `doctor` must be allowed to report it instead.""" + + @pytest.mark.parametrize( + "argv, expected", + [ + (["th-cli", "doctor"], True), + (["th-cli", "doctor", "--json"], True), + (["th-cli", "--version", "doctor"], True), + (["th-cli", "project", "list"], False), + (["th-cli", "project", "doctor"], False), + (["th-cli"], False), + ], + ) + def test_is_doctor_invocation(self, argv: list[str], expected: bool) -> None: + from th_cli import config as config_module + + with patch.object(config_module.sys, "argv", argv): + assert config_module._is_doctor_invocation() is expected + + +@pytest.mark.unit +@pytest.mark.cli +class TestImportTimeConfigWarnings: + """`doctor --json` output must stay valid JSON even when no config file exists.""" + + @staticmethod + def _import_config_stdout(tmp_path: Path, command: str) -> str: + import os + import subprocess as sp + import sys + + code = f"import sys; sys.argv = ['th-cli', {command!r}]; import th_cli.config" + # Drop pytest-cov's variables: older versions (4.x, used in CI) start coverage inside the child + # process, and its data from a temp cwd corrupts the parent's report. + env = {k: v for k, v in os.environ.items() if not k.startswith(("COV_CORE", "COVERAGE"))} + env.update(HOME=str(tmp_path), PYTHONPATH=str(Path(__file__).resolve().parent.parent)) + proc = sp.run([sys.executable, "-c", code], capture_output=True, text=True, cwd=tmp_path, env=env, check=False) + assert proc.returncode == 0, proc.stderr + return proc.stdout + + def test_warning_is_printed_for_other_commands(self, tmp_path: Path) -> None: + """Positive control: without this, the doctor test below could pass trivially.""" + assert "Using default configuration" in self._import_config_stdout(tmp_path, "project") + + def test_warning_is_not_printed_for_doctor(self, tmp_path: Path) -> None: + assert "Using default configuration" not in self._import_config_stdout(tmp_path, "doctor") diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 40dc0b3..6d0dc4d 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -19,9 +19,19 @@ import click import pytest - -from th_cli.api_lib_autogen.exceptions import UnexpectedResponse -from th_cli.exceptions import APIError, CLIError, ConfigurationError, handle_api_error, handle_file_error +from httpx import ConnectError, ReadTimeout + +from th_cli.api_lib_autogen.exceptions import ResponseHandlingException, UnexpectedResponse, describe_error +from th_cli.exceptions import ( + BACKEND_HINT, + APIError, + CLIError, + ConfigurationError, + backend_hint_for, + handle_api_error, + handle_file_error, + unexpected_error, +) # --------------------------------------------------------------------------- # CLIError @@ -280,3 +290,49 @@ def test_default_file_type_is_file(self): handle_file_error(e) # "file" title-cased → "File" assert "File" in exc_info.value.format_message() + + +# --------------------------------------------------------------------------- +# Empty error text (#1224) +# --------------------------------------------------------------------------- + + +class TestDescribeError: + @pytest.mark.parametrize("error", [ConnectError(""), ReadTimeout("")]) + def test_empty_transport_error_falls_back_to_class_name(self, error): + assert describe_error(error) == type(error).__name__ + + def test_response_handling_exception_is_unwrapped_with_class_name(self): + assert describe_error(ResponseHandlingException(ConnectError("refused"))) == "ConnectError: refused" + + def test_plain_exception_text_is_unchanged(self): + assert describe_error(ValueError("bad value")) == "bad value" + + def test_response_handling_str_is_never_empty(self): + assert str(ResponseHandlingException(ConnectError(""))) == "Error handling response: ConnectError" + + +class TestUnexpectedError: + def test_transport_error_keeps_type_and_adds_hint(self): + err = unexpected_error("Unexpected error in list operation", ResponseHandlingException(ConnectError(""))) + assert err.message == f"Unexpected error in list operation: ConnectError\n{BACKEND_HINT}" + + def test_other_error_has_no_backend_hint(self): + err = unexpected_error("Unexpected error in list operation", ValueError("boom")) + assert err.message == "Unexpected error in list operation: boom" + + +class TestBackendHintFor: + def test_transport_error_gets_hint(self): + assert backend_hint_for(ResponseHandlingException(ConnectError(""))) == f"\n{BACKEND_HINT}" + + def test_other_error_gets_nothing(self): + assert backend_hint_for(ValueError("x")) == "" + + def test_shared_transport_formatter_includes_hint_but_not_for_timeouts(self): + from th_cli.commands.test_run_execution import _timeout_or_connection_error + + refused = _timeout_or_connection_error(ResponseHandlingException(ConnectError("")), "repeat run") + assert BACKEND_HINT in refused + timed_out = _timeout_or_connection_error(ResponseHandlingException(ReadTimeout("")), "repeat run") + assert BACKEND_HINT not in timed_out diff --git a/tests/test_main.py b/tests/test_main.py index 6bc8c76..d817f0c 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -24,7 +24,9 @@ import pytest from click.testing import CliRunner +from httpx import ConnectError +from th_cli.api_lib_autogen.exceptions import ResponseHandlingException from th_cli.main import root @@ -63,4 +65,13 @@ def test_version_exits_cleanly_when_server_unreachable(self, cli_runner: CliRunn result = cli_runner.invoke(root, ["--version"]) assert result.exit_code == 0 - assert "Not able to retrieve versions from server." in result.output + assert "Not able to retrieve versions from server: unreachable" in result.output + + def test_version_reports_reason_when_transport_error_has_empty_text(self, cli_runner: CliRunner) -> None: + """An httpx error with an empty str() must still say what failed.""" + error = ResponseHandlingException(ConnectError("")) + with patch("th_cli.main.get_versions", side_effect=error): + result = cli_runner.invoke(root, ["--version"]) + + assert result.exit_code == 0 + assert "Not able to retrieve versions from server: ConnectError" in result.output diff --git a/tests/test_redaction.py b/tests/test_redaction.py new file mode 100644 index 0000000..ee9605d --- /dev/null +++ b/tests/test_redaction.py @@ -0,0 +1,113 @@ +# +# Copyright (c) 2026 Project CHIP Authors +# +# 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. +# +"""Tests for the diagnostic output redaction helpers.""" + +import pytest + +from th_cli.th_utils.redaction import REDACTED, is_sensitive_key, redact_data, redact_text + + +@pytest.mark.unit +class TestIsSensitiveKey: + @pytest.mark.parametrize( + "key", + [ + "password", + "wifi_password", + "Passphrase", + "network_key", + "networkKey", + "operational_dataset_hex", + "psk", + "pskc", + "auth_token", + "client-secret", + "setup_code", + "qr", + "qr_code", + "manual_code", + ], + ) + def test_sensitive(self, key: str) -> None: + assert is_sensitive_key(key) + + @pytest.mark.parametrize("key", ["hostname", "query", "version", "ssid", "state", "sdk_docker_tag"]) + def test_not_sensitive(self, key: str) -> None: + assert not is_sensitive_key(key) + + +@pytest.mark.unit +class TestRedactText: + def test_masks_key_value_pairs(self) -> None: + out = redact_text('ssid=home password=hunter2 "network_key": "00112233"') + assert "hunter2" not in out + assert "00112233" not in out + assert "ssid=home" in out + + @pytest.mark.parametrize( + "text", ["pin=20202021", "setup_pin: 20202021", '{"pin": "20202021"}', "wifi_pin=20202021"] + ) + def test_masks_pin_values(self, text: str) -> None: + assert "20202021" not in redact_text(text) + assert "20202021" not in redact_text(text, mask_network=False) + + def test_does_not_mask_words_merely_containing_pin(self) -> None: + assert redact_text("spinning=fast") == "spinning=fast" + + def test_masks_whole_value_with_escaped_quotes(self) -> None: + out = redact_text(r'{"password": "ab\"secret-suffix", "ssid": "home"}') + assert "secret-suffix" not in out + assert '"ssid": "home"' in out + + def test_strips_url_userinfo(self) -> None: + assert redact_text("https://user:tok@github.com/o/r.git") == "https://github.com/o/r.git" + + def test_masks_ips_and_macs(self) -> None: + out = redact_text("host 192.168.1.20 mac aa:bb:cc:dd:ee:ff v6 fe80::1:2:3:4") + assert "192.168.1.20" not in out + assert "aa:bb:cc:dd:ee:ff" not in out + assert "fe80" not in out + + def test_keeps_timestamps_and_scoped_names(self) -> None: + assert redact_text("at 12:34:56 in std::string") == "at 12:34:56 in std::string" + + def test_masks_full_and_loopback_ipv6_forms(self) -> None: + assert redact_text("a 2001:db8:0:0:0:0:0:1 b ::1 c fd00::1") == "a [ip] b [ip] c [ip]" + + def test_keeps_loopback(self) -> None: + assert redact_text("localhost 127.0.0.1") == "localhost 127.0.0.1" + + def test_network_masking_can_be_disabled_but_secrets_stay_masked(self) -> None: + out = redact_text("192.168.1.20 password=x", mask_network=False) + assert "192.168.1.20" in out + assert "password=x" not in out + + +@pytest.mark.unit +class TestRedactData: + def test_masks_by_key_recursively(self) -> None: + data = {"a": {"wifi": {"ssid": "home", "password": "pw"}}, "list": [{"token": "t"}, "ok"]} + assert redact_data(data) == { + "a": {"wifi": {"ssid": "home", "password": REDACTED}}, + "list": [{"token": REDACTED}, "ok"], + } + + def test_masks_ips_in_string_values(self) -> None: + assert redact_data({"host": "10.0.0.5"}) == {"host": "[ip]"} + assert redact_data({"host": "10.0.0.5"}, mask_network=False) == {"host": "10.0.0.5"} + + def test_non_strings_pass_through(self) -> None: + assert redact_data({"n": 3, "b": True, "x": None}) == {"n": 3, "b": True, "x": None} diff --git a/tests/test_rescan_tests.py b/tests/test_rescan_tests.py index d7dd5a0..f411512 100644 --- a/tests/test_rescan_tests.py +++ b/tests/test_rescan_tests.py @@ -24,7 +24,7 @@ from th_cli.api_lib_autogen import models as api_models from th_cli.api_lib_autogen.exceptions import ResponseHandlingException, UnexpectedResponse from th_cli.commands.rescan_tests import rescan_tests -from th_cli.exceptions import ConfigurationError +from th_cli.exceptions import BACKEND_HINT, ConfigurationError def _rescan_response(test_collections: api_models.TestCollections, **changes: object) -> api_models.TestCollections: @@ -320,6 +320,7 @@ def test_rescan_tests_response_handling_error_non_timeout( assert result.exit_code == 1 assert "Could not rescan test collections" in result.output + assert BACKEND_HINT in result.output mock_api_client.close.assert_called_once() def test_rescan_tests_generic_exception( diff --git a/th_cli/api_lib_autogen/exceptions.py b/th_cli/api_lib_autogen/exceptions.py index ca3e7d7..6077008 100644 --- a/th_cli/api_lib_autogen/exceptions.py +++ b/th_cli/api_lib_autogen/exceptions.py @@ -24,12 +24,31 @@ class ApiException(Exception): pass +def describe_error(error: BaseException) -> str: + """Describe an exception so the result is never empty. + + Several httpx transport errors (ConnectError, ReadTimeout, ...) have an + empty str(), which used to leave messages ending in a bare colon. When + there is text it is kept as is, except for errors wrapped in a + ResponseHandlingException, where the class name is added so users can + tell a refused connection from a timeout. + """ + wrapped = isinstance(error, ResponseHandlingException) + if wrapped: + error = error.error + text = str(error).strip() + name = type(error).__name__ + if not text: + return name + return f"{name}: {text}" if wrapped else text + + class ResponseHandlingException(ApiException): """Exception raised when response handling fails.""" def __init__(self, error: Exception): self.error = error - super().__init__(f"Error handling response: {error}") + super().__init__(f"Error handling response: {describe_error(error)}") class UnexpectedResponse(ApiException): diff --git a/th_cli/commands/__init__.py b/th_cli/commands/__init__.py index 1c6f3b9..2d6c61d 100644 --- a/th_cli/commands/__init__.py +++ b/th_cli/commands/__init__.py @@ -15,6 +15,7 @@ # from .abort_testing import abort_testing from .available_tests import available_tests +from .doctor import doctor from .project import project from .rescan_tests import rescan_tests from .run_tests import run_tests @@ -24,6 +25,7 @@ __all__ = [ "abort_testing", "available_tests", + "doctor", "project", "rescan_tests", "run_tests", diff --git a/th_cli/commands/available_tests.py b/th_cli/commands/available_tests.py index a057be3..5ad1054 100644 --- a/th_cli/commands/available_tests.py +++ b/th_cli/commands/available_tests.py @@ -22,10 +22,10 @@ import yaml from th_cli.api_lib_autogen.api_client import SyncApis -from th_cli.api_lib_autogen.exceptions import UnexpectedResponse +from th_cli.api_lib_autogen.exceptions import UnexpectedResponse, describe_error from th_cli.client import get_client from th_cli.colorize import colorize_cmd_help, colorize_help -from th_cli.exceptions import CLIError, handle_api_error +from th_cli.exceptions import CLIError, backend_hint_for, handle_api_error from th_cli.utils import __json_string # Constants @@ -133,7 +133,9 @@ def available_tests( handle_api_error(e, "get available tests") except Exception as e: raise CLIError( - f"Could not fetch the available tests: {e}. Please check if the API server is running and accessible." + f"Could not fetch the available tests: {describe_error(e)}. " + "Please check if the API server is running and accessible." + f"{backend_hint_for(e)}" ) finally: if client: diff --git a/th_cli/commands/doctor.py b/th_cli/commands/doctor.py new file mode 100644 index 0000000..749fd80 --- /dev/null +++ b/th_cli/commands/doctor.py @@ -0,0 +1,317 @@ +# +# Copyright (c) 2026 Project CHIP Authors +# +# 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. +# +"""`th-cli doctor`: diagnose why the CLI cannot talk to the backend.""" + +import contextlib +import io +import json as jsonlib +import shutil +import socket +import subprocess +from dataclasses import asdict, dataclass +from enum import Enum +from typing import Any, Callable + +import click +import httpx + +from th_cli.api_lib_autogen.api_client import SyncApis +from th_cli.api_lib_autogen.exceptions import ResponseHandlingException, UnexpectedResponse, describe_error +from th_cli.client import get_client +from th_cli.colorize import ( + colorize_cmd_help, + colorize_error, + colorize_header, + colorize_help, + colorize_success, + colorize_warning, +) +from th_cli.config import Config, get_config_search_paths, load_config +from th_cli.exceptions import ConfigurationError +from th_cli.th_utils.redaction import redact_data, redact_text +from th_cli.utils import get_cli_sha, get_cli_version + +PROBE_TIMEOUT_SECONDS = 5.0 +DOCKER_TIMEOUT_SECONDS = 10 +DOCKER_CONTAINERS = ( + "certification-tool-backend-1", + "certification-tool-frontend-1", + "certification-tool-db-1", + "certification-tool-proxy-1", +) +BACKEND_CONTAINER = DOCKER_CONTAINERS[0] + + +class Status(str, Enum): + PASS = "pass" + WARN = "warn" + FAIL = "fail" + SKIP = "skip" + + +@dataclass +class CheckResult: + name: str + status: Status + detail: str + data: dict[str, Any] | None = None + + +def classify_error(e: Exception) -> str: + """Say what kind of failure a request error was (refused, DNS, timeout, HTTP status).""" + if isinstance(e, UnexpectedResponse): + return f"HTTP {e.status_code} from the backend" + + inner = e.error if isinstance(e, ResponseHandlingException) else e + chain: list[BaseException] = [] + current: BaseException | None = inner + while current is not None and current not in chain: + chain.append(current) + current = current.__cause__ or current.__context__ + + if any(isinstance(x, socket.gaierror) for x in chain): + return f"DNS lookup failed ({describe_error(inner)})" + if any(isinstance(x, ConnectionRefusedError) for x in chain): + return "connection refused" + if isinstance(inner, httpx.TimeoutException): + return f"timeout ({describe_error(inner)})" + if isinstance(inner, httpx.ConnectError): + return f"cannot connect ({describe_error(inner)})" + return describe_error(e) + + +def _config_source() -> str: + paths = get_config_search_paths() + for path in paths: + if (path / "config.json").exists(): + return str(path / "config.json") + for path in paths: + if (path / "config.json.example").exists(): + return f"{path / 'config.json.example'} (no config.json found)" + return "built-in defaults (no config.json found)" + + +def check_config() -> tuple[CheckResult, Config | None]: + """Load the config the way the CLI does, reporting problems instead of exiting.""" + source = _config_source() + captured = io.StringIO() + try: + # load_config() prints warnings on fallback; capture them so --json stays valid. + with contextlib.redirect_stdout(captured): + config = load_config() + except ConfigurationError as e: + return CheckResult("config", Status.FAIL, e.message, {"source": source}), None + + warnings = [line.strip() for line in captured.getvalue().splitlines() if line.strip()] + data = {"source": source, "hostname": config.hostname} + detail = f"{source}; backend host: {config.hostname}" + if warnings or "no config.json found" in source: + return CheckResult("config", Status.WARN, "; ".join([detail, *warnings]), data), config + return CheckResult("config", Status.PASS, detail, data), config + + +def _probe(name: str, fn: Callable[[], Any], failure: Status) -> tuple[CheckResult | None, Any]: + """Run an API call; return (failure result, None) or (None, response).""" + try: + return None, fn() + except (ResponseHandlingException, UnexpectedResponse) as e: + return CheckResult(name, failure, classify_error(e)), None + except Exception as e: # noqa: BLE001 - a diagnostic must report, not crash + return CheckResult(name, failure, describe_error(e)), None + + +def check_backend() -> list[CheckResult]: + """Reachability, version and a few cheap deeper probes.""" + try: + client = get_client(timeout=httpx.Timeout(PROBE_TIMEOUT_SECONDS)) + except ConfigurationError as e: + return [CheckResult("backend reachable", Status.FAIL, e.message)] + + try: + apis = SyncApis(client) + failure, version = _probe( + "backend reachable", + apis.version_api.get_test_harness_backend_version_api_v1_version_get, + Status.FAIL, + ) + if failure: + return [ + failure, + CheckResult("versions", Status.SKIP, "backend not reachable"), + CheckResult("test runner", Status.SKIP, "backend not reachable"), + CheckResult("database", Status.SKIP, "backend not reachable"), + ] + + backend = version.model_dump(mode="json") + results = [ + CheckResult("backend reachable", Status.PASS, "GET /api/v1/version answered"), + CheckResult( + "versions", + Status.PASS, + f"CLI {get_cli_version()} ({get_cli_sha()[:8]}); backend {backend['version']} " + f"({backend['sha'][:8]}), SDK {backend['sdk_docker_tag']}, db revision {backend['db_revision']}", + {"cli": {"version": get_cli_version(), "sha": get_cli_sha()}, "backend": backend}, + ), + ] + + failure, status = _probe( + "test runner", + apis.test_run_executions_api.get_test_runner_status_api_v1_test_run_executions_status_get, + Status.WARN, + ) + if failure: + results.append(failure) + else: + state = getattr(status.state, "value", status.state) + results.append(CheckResult("test runner", Status.PASS, f"state: {state}", {"state": str(state)})) + + # A DB-backed endpoint: /version touches no database, so this tells them apart. + failure, projects = _probe("database", apis.projects_api.read_projects_api_v1_projects__get, Status.WARN) + results.append( + failure or CheckResult("database", Status.PASS, f"/projects/ answered ({len(projects)} projects)") + ) + return results + finally: + client.close() + + +def _run_docker(args: list[str]) -> subprocess.CompletedProcess: + return subprocess.run( + ["docker", *args], + capture_output=True, + text=True, + timeout=DOCKER_TIMEOUT_SECONDS, + check=False, + ) + + +def check_docker(log_lines: int) -> list[CheckResult]: + """State of the TH containers; skipped cleanly when docker is unavailable.""" + if shutil.which("docker") is None: + return [CheckResult("docker", Status.SKIP, "docker not found on this host")] + + results = [] + for container in DOCKER_CONTAINERS: + try: + proc = _run_docker(["inspect", "-f", "{{.State.Status}}", container]) + except (OSError, subprocess.SubprocessError) as e: + return [CheckResult("docker", Status.SKIP, f"docker not usable: {describe_error(e)}")] + state = proc.stdout.strip() + if proc.returncode != 0: + results.append(CheckResult(container, Status.WARN, "container not found")) + elif state == "running": + results.append(CheckResult(container, Status.PASS, "running")) + else: + results.append(CheckResult(container, Status.FAIL, state or "unknown state")) + + if log_lines > 0: + try: + proc = _run_docker(["logs", "--tail", str(log_lines), BACKEND_CONTAINER]) + output = (proc.stdout + proc.stderr).strip() + if proc.returncode != 0: + results.append(CheckResult("backend logs", Status.WARN, output or f"docker exited {proc.returncode}")) + else: + results.append( + CheckResult("backend logs", Status.PASS, f"last {log_lines} lines", {"log_tail": output}) + ) + except (OSError, subprocess.SubprocessError) as e: + results.append(CheckResult("backend logs", Status.WARN, describe_error(e))) + return results + + +def run_checks(docker: bool, log_lines: int) -> list[CheckResult]: + config_result, config = check_config() + results = [config_result] + if config is None: + results += [CheckResult("backend reachable", Status.SKIP, "configuration is invalid")] + else: + results += check_backend() + if docker: + results += check_docker(log_lines) + return results + + +_STATUS_LABEL = { + Status.PASS: (" OK ", colorize_success), + Status.WARN: ("WARN", colorize_warning), + Status.FAIL: ("FAIL", colorize_error), + Status.SKIP: ("SKIP", lambda s: s), +} + + +def _print_report(results: list[CheckResult], mask_network: bool) -> None: + click.echo("") + click.echo(colorize_header("Test Harness CLI Doctor")) + for result in results: + label, paint = _STATUS_LABEL[result.status] + detail = redact_text(result.detail, mask_network) + click.echo(f"[{paint(label)}] {result.name}: {detail}") + log_tail = (result.data or {}).get("log_tail") + if log_tail: + click.echo(redact_text(log_tail, mask_network)) + failed = [r for r in results if r.status == Status.FAIL] + click.echo("") + if failed: + click.echo(colorize_error(f"{len(failed)} check(s) failed")) + else: + click.echo(colorize_success("No problems found")) + + +@click.command( + short_help=colorize_help("Diagnose problems reaching the backend"), + help=colorize_cmd_help( + "doctor", + "Check the CLI configuration, backend reachability and versions, and (if available) the " + "Docker containers. Exits non-zero if a check fails. Secrets, IPs and MACs are masked " + "unless --no-redact is given.", + ), +) +@click.option("--json", "as_json", is_flag=True, default=False, help=colorize_help("Print results as JSON")) +@click.option( + "--no-docker", + is_flag=True, + default=False, + help=colorize_help("Skip the Docker container checks"), +) +@click.option( + "--log-lines", + type=click.IntRange(min=0), + default=0, + show_default=True, + help=colorize_help("Include the last N lines of the backend container log (redacted)"), +) +@click.option( + "--no-redact", + is_flag=True, + default=False, + help=colorize_help("Do not mask IP/MAC addresses (secrets by key name and in logs are always masked)"), +) +@click.pass_context +def doctor(ctx: click.Context, as_json: bool, no_docker: bool, log_lines: int, no_redact: bool) -> None: + results = run_checks(docker=not no_docker, log_lines=log_lines) + mask_network = not no_redact + + if as_json: + payload = { + "ok": all(r.status != Status.FAIL for r in results), + "checks": [{**asdict(r), "status": r.status.value} for r in results], + } + click.echo(jsonlib.dumps(redact_data(payload, mask_network), indent=2)) + else: + _print_report(results, mask_network) + + if any(r.status == Status.FAIL for r in results): + ctx.exit(1) diff --git a/th_cli/commands/project.py b/th_cli/commands/project.py index 283846d..a9c9907 100644 --- a/th_cli/commands/project.py +++ b/th_cli/commands/project.py @@ -40,7 +40,7 @@ colorize_warning, italic, ) -from th_cli.exceptions import CLIError, handle_api_error, handle_file_error +from th_cli.exceptions import CLIError, handle_api_error, handle_file_error, unexpected_error from th_cli.utils import __print_config, __print_json, read_pics_config from th_cli.validation import validate_directory_path @@ -67,7 +67,7 @@ def get_sync_apis(operation: str): except CLIError: raise except Exception as e: - raise CLIError(f"Unexpected error in {operation} operation: {e}") + raise unexpected_error(f"Unexpected error in {operation} operation", e) from e finally: if client: client.close() diff --git a/th_cli/commands/rescan_tests.py b/th_cli/commands/rescan_tests.py index 12a7fb6..4d9733e 100644 --- a/th_cli/commands/rescan_tests.py +++ b/th_cli/commands/rescan_tests.py @@ -19,10 +19,10 @@ from th_cli.api_lib_autogen import models as api_models from th_cli.api_lib_autogen.api_client import SyncApis -from th_cli.api_lib_autogen.exceptions import ResponseHandlingException, UnexpectedResponse +from th_cli.api_lib_autogen.exceptions import ResponseHandlingException, UnexpectedResponse, describe_error from th_cli.client import get_client from th_cli.colorize import colorize_change, colorize_cmd_help, colorize_help, colorize_success, colorize_warning -from th_cli.exceptions import CLIError, handle_api_error +from th_cli.exceptions import CLIError, backend_hint_for, handle_api_error # Rescanning regenerates the Python test JSON files via the SDK container, # which can take significantly longer than httpx's 5s default read timeout. @@ -141,13 +141,17 @@ def rescan_tests() -> None: click.echo(colorize_success("Rescan request sent (backend may still be processing)")) else: raise CLIError( - f"Could not rescan test collections: {e}. Please check if the API server is running and accessible." + f"Could not rescan test collections: {describe_error(e)}. " + "Please check if the API server is running and accessible." + f"{backend_hint_for(e)}" ) except UnexpectedResponse as e: handle_api_error(e, "rescan test collections") except Exception as e: raise CLIError( - f"Could not rescan test collections: {e}. Please check if the API server is running and accessible." + f"Could not rescan test collections: {describe_error(e)}. " + "Please check if the API server is running and accessible." + f"{backend_hint_for(e)}" ) finally: if client: diff --git a/th_cli/commands/run_tests.py b/th_cli/commands/run_tests.py index 21f39c4..ad441ee 100644 --- a/th_cli/commands/run_tests.py +++ b/th_cli/commands/run_tests.py @@ -42,7 +42,7 @@ set_colors_enabled, ) from th_cli.config import config as th_config -from th_cli.exceptions import CLIError, handle_api_error +from th_cli.exceptions import CLIError, handle_api_error, unexpected_error from th_cli.test_run.camera.two_way_talk_handler import TwoWayTalkHandler from th_cli.test_run.websocket import IncompleteTestRunError, TestRunSocket from th_cli.utils import ( @@ -431,7 +431,7 @@ async def run_tests( except CLIError: raise # Re-raise CLI errors except Exception as e: - raise CLIError(f"Unexpected error during test execution: {e}") + raise unexpected_error("Unexpected error during test execution", e) from e finally: # Stop log streaming test_logging.stop_log_streaming() diff --git a/th_cli/commands/test_run_execution.py b/th_cli/commands/test_run_execution.py index 2cb710b..1ae7eed 100644 --- a/th_cli/commands/test_run_execution.py +++ b/th_cli/commands/test_run_execution.py @@ -41,7 +41,7 @@ ) from th_cli.commands.run_tests import TWO_WAY_TALK_TEST_IDS, _print_webrtc_banner_and_wait from th_cli.config import config as th_config -from th_cli.exceptions import CLIError, handle_api_error, handle_file_error +from th_cli.exceptions import CLIError, backend_hint_for, handle_api_error, handle_file_error, unexpected_error from th_cli.test_run import logging as test_logging from th_cli.test_run.camera.two_way_talk_handler import TwoWayTalkHandler from th_cli.test_run.websocket import TestRunSocket @@ -481,7 +481,7 @@ async def repeat(id: int, title: str | None, no_color: bool, no_streaming: bool) except CLIError: raise # Re-raise CLI Errors as-is except Exception as e: - raise CLIError(f"Unexpected error during repeated test execution: {e}") + raise unexpected_error("Unexpected error during repeated test execution", e) from e finally: if client: await client.aclose() @@ -778,7 +778,10 @@ def _timeout_or_connection_error(e: ResponseHandlingException, operation: str) - f"(waited {int(TEST_RUN_EXECUTION_IO_TIMEOUT.read)}s). Executions with a lot of " "log data can take longer than that to transfer; please try again." ) - return f"Could not {operation}: {e}. Please check if the API server is running and accessible." + return ( + f"Could not {operation}: {e}. Please check if the API server is running and accessible." + f"{backend_hint_for(e)}" + ) async def __repeat_test_run_execution( @@ -862,8 +865,7 @@ async def __start_and_stream_repeated_execution( await _cancel_socket_task(socket_task) if e.status_code == 409: raise CLIError( - f"Execution {new_execution.id} was created but could not be started: " - f"{_extract_error_detail(e)}" + f"Execution {new_execution.id} was created but could not be started: " f"{_extract_error_detail(e)}" ) from e handle_api_error(e, f"start repeated test run execution '{new_execution.id}'") except ResponseHandlingException as e: diff --git a/th_cli/config.py b/th_cli/config.py index f9bda62..e56de75 100644 --- a/th_cli/config.py +++ b/th_cli/config.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +import contextlib +import io import json import sys from enum import Enum @@ -147,12 +149,26 @@ def load_config(): # Load the configuration +def _is_doctor_invocation() -> bool: + """True when the first non-option argument is `doctor`.""" + args = [arg for arg in sys.argv[1:] if not arg.startswith("-")] + return bool(args) and args[0] == "doctor" + + try: - config = load_config() + if _is_doctor_invocation(): + # Fallback warnings would corrupt `doctor --json`; check_config() reports them instead. + with contextlib.redirect_stdout(io.StringIO()): + config = load_config() + else: + config = load_config() except ConfigurationError as e: - # Raised at import time, before click is running, so report it like click would - e.show() - sys.exit(e.exit_code) + if not _is_doctor_invocation(): + # Raised at import time, before click is running, so report it like click would + e.show() + sys.exit(e.exit_code) + # `th-cli doctor` loads the config itself so it can report this error. + config = Config(**get_default_config()) class PairingMode(str, Enum): diff --git a/th_cli/exceptions.py b/th_cli/exceptions.py index 70ff5d1..4963d71 100644 --- a/th_cli/exceptions.py +++ b/th_cli/exceptions.py @@ -19,7 +19,7 @@ import click -from th_cli.api_lib_autogen.exceptions import UnexpectedResponse +from th_cli.api_lib_autogen.exceptions import ResponseHandlingException, UnexpectedResponse, describe_error from th_cli.colorize import colorize_error @@ -63,6 +63,23 @@ class ConfigurationError(CLIError): pass +BACKEND_HINT = "Is the backend running? Try `th-cli doctor` to diagnose." + + +def backend_hint_for(e: BaseException) -> str: + """Return the newline-prefixed backend hint for transport errors, else an empty string.""" + return f"\n{BACKEND_HINT}" if isinstance(e, ResponseHandlingException) else "" + + +def unexpected_error(message: str, e: BaseException) -> CLIError: + """Build a CLIError for an unexpected failure that never has an empty reason. + + Adds a hint to check the backend when the failure was a transport error. + Callers should `raise unexpected_error(...) from e` so the cause is chained. + """ + return CLIError(f"{message}: {describe_error(e)}{backend_hint_for(e)}") + + def _format_api_error_content(content: Any) -> Any: """Turn a decoded API error response body into a human-readable string. diff --git a/th_cli/main.py b/th_cli/main.py index 9b5e6bc..37eb00f 100644 --- a/th_cli/main.py +++ b/th_cli/main.py @@ -17,10 +17,12 @@ import click +from th_cli.api_lib_autogen.exceptions import describe_error from th_cli.colorize import colorize_cmd_help, colorize_error, colorize_key_value from th_cli.commands import ( abort_testing, available_tests, + doctor, project, rescan_tests, run_tests, @@ -45,8 +47,8 @@ def get_extended_help() -> str: if versions_data: for key, value in versions_data.items(): help_text += f"\n{colorize_key_value(key, value)}" - except Exception: - help_text += colorize_error("\nNot able to retrieve versions from server.") + except Exception as e: + help_text += colorize_error(f"\nNot able to retrieve versions from server: {describe_error(e)}") return help_text @@ -79,6 +81,7 @@ def root() -> None: root.add_command(abort_testing) root.add_command(available_tests) +root.add_command(doctor) root.add_command(project) root.add_command(rescan_tests) root.add_command(run_tests) diff --git a/th_cli/th_utils/redaction.py b/th_cli/th_utils/redaction.py new file mode 100644 index 0000000..20d7ea9 --- /dev/null +++ b/th_cli/th_utils/redaction.py @@ -0,0 +1,94 @@ +# +# Copyright (c) 2026 Project CHIP Authors +# +# 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. +# +"""Redaction of sensitive values from diagnostic output. + +`th-cli doctor` output is meant to be pasted into issues and chats, so secrets +(Wi-Fi passwords, Thread network keys, DUT setup codes) and network identifiers +(IPs, MACs) are masked by default. +""" + +import re +from typing import Any + +REDACTED = "[redacted]" + +# Matched as substrings of the key with separators removed ("network_key" -> "networkkey"). +_SENSITIVE_SUBSTRINGS = ( + "password", + "passphrase", + "networkkey", + "dataset", + "token", + "secret", + "setupcode", + "setuppin", + "manualcode", +) +# Too short to match as substrings ("qr" is inside "query"); matched as whole words only. +_SENSITIVE_WORDS = {"psk", "pskc", "qr", "pin", "passcode"} + +_KEY_WORD_PATTERN = ( + r"password|passphrase|network[_-]?key|(?:[a-z_]*_)?dataset(?:_hex)?|psk|pskc|token|secret|" + r"setup[_-]?(?:code|pin)|(? bool: + """True if a field with this name is expected to hold a secret.""" + lowered = key.lower() + if _SENSITIVE_WORDS & set(re.split(r"[^a-z0-9]+", lowered)): + return True + squashed = re.sub(r"[^a-z0-9]", "", lowered) + return any(word in squashed for word in _SENSITIVE_SUBSTRINGS) + + +def redact_text(text: str, mask_network: bool = True) -> str: + """Mask secrets, URL credentials and (optionally) IP/MAC addresses in free text.""" + text = _URL_USERINFO_RE.sub(r"\1", text) + text = _KEY_VALUE_RE.sub(lambda m: f"{m.group(1)}{REDACTED}", text) + if mask_network: + text = _MAC_RE.sub("[mac]", text) + text = _IPV6_RE.sub("[ip]", text) + text = _IPV4_RE.sub(lambda m: m.group(0) if m.group(0) in _LOOPBACK else "[ip]", text) + return text + + +def redact_data(data: Any, mask_network: bool = True) -> Any: + """Recursively redact a JSON-like structure: by key name, then by text content.""" + if isinstance(data, dict): + return { + key: REDACTED if is_sensitive_key(str(key)) else redact_data(value, mask_network) + for key, value in data.items() + } + if isinstance(data, (list, tuple)): + return [redact_data(item, mask_network) for item in data] + if isinstance(data, str): + return redact_text(data, mask_network) + return data