diff --git a/src/kiro_crew/cli_server.py b/src/kiro_crew/cli_server.py index 136844dfefae..bbf877f70689 100644 --- a/src/kiro_crew/cli_server.py +++ b/src/kiro_crew/cli_server.py @@ -819,6 +819,7 @@ def _tail_log_file(path: Path, lines: int, follow: bool) -> None: _replacement_is_serving, _resolve_restart_ready_timeout, _restart, + _signing_key_refusal_lines, _spawn_detached_gateway, _wait_for_pids_exit, _wait_gateway_ready, diff --git a/src/kiro_crew/cli_server_restart.py b/src/kiro_crew/cli_server_restart.py index 1d049813c20e..2b00b3aab004 100644 --- a/src/kiro_crew/cli_server_restart.py +++ b/src/kiro_crew/cli_server_restart.py @@ -676,6 +676,46 @@ def _died_replacement_message(pid: int, exit_status: int | None, port: int) -> s ) +def _signing_key_refusal_lines() -> list[str]: + """Repair steps to print when a gateway that just failed to start sits on a truncated key. + + The gateway's own refusal (``slack.gateway.signing_key_preflight``) prints these + steps to its stderr, which a detached or service-managed gateway sends to a log + the person running ``kirocrew restart`` has not opened. Repeating them here puts + the fix in the terminal that asked for the restart. + + Same read-only ``lstat`` look ``kirocrew doctor`` takes, with the same sandbox + evidence and the same ``open_is_denied`` guard, so a sandbox mask over a + healthy key never gets the file-removing steps. Any + error answers ``[]``: this only adds a hint to a failure already reported. + """ + try: + from kiro_crew import sandbox + from kiro_crew.dashboard import token_secret + from kiro_crew.service.common import restart_command_hint + + # Same two bits doctor and the boot preflight pass: a foreign macOS + # Seatbelt sandbox can leave the real key readable, so the open-refusal + # cross-check applies only when that verdict is the sole signal. + confined = sandbox.agent_confinement_evidence() is not None + state, key_path = token_secret.signing_key_health( + confined=confined, + require_denied_open=confined and not sandbox.agent_confinement_is_kirocrew_own(), + ) + # A short key this process cannot open may be the sandbox's mode-0 mask + # over a healthy key; doctor withholds the removal steps there too. + if state != "short" or token_secret.open_is_denied(key_path): + return [] + steps = token_secret.signing_key_remedy(key_path, restart_command_hint()) + except Exception: # noqa: BLE001 - a hint on an already-reported failure + return [] + return [ + f" The token signing key at {key_path} is shorter than 32 bytes, so the " + "gateway refuses to start. Repair it by hand:", + *(f" {step}" for step in steps), + ] + + def _print_token_url(port: int) -> None: """Wait for the gateway to come up, then print a fresh token URL.""" deadline = time.monotonic() + _RESTART_TOKEN_WAIT @@ -871,6 +911,9 @@ def _restart(cli_port: int | None = None) -> None: lines.append( " The service manager restarted nothing; run `kirocrew restart` again." ) + if any(f.kind == RESTART_NOT_UP for f in failures): + # A unit that is not up after a restart may be refusing to boot. + lines.extend(_signing_key_refusal_lines()) print("\n".join(lines)) sys.exit(1) @@ -1055,6 +1098,12 @@ def _restart(cli_port: int | None = None) -> None: print(" Its last lines in gateway.log:") for line in tail: print(f" {line}") + else: + # The relayed lines already carry the gateway's own refusal and + # its repair steps; only an empty relay needs them restated. + refusal = _signing_key_refusal_lines() + if refusal: + print("\n".join(refusal)) else: print( f"❌ Replacement gateway (pid {pid}) did not become ready within " diff --git a/test/test_cli_restart.py b/test/test_cli_restart.py index b5845ef80bd1..1f348972a6d0 100644 --- a/test/test_cli_restart.py +++ b/test/test_cli_restart.py @@ -255,6 +255,93 @@ def test_user_unit_that_does_not_stay_up_names_its_state_not_a_sudo_hint(self, c assert audit["outcome"] == "denied" assert "reason=service_restart_not_up" in audit["resources"] + def test_unit_not_up_on_a_truncated_key_prints_the_repair_steps(self, capsys, tmp_path): + # A service gateway's refusal lands in the journal. The restart names + # the journal command and, when the key is short, the steps themselves. + from kiro_crew import cli_server + from kiro_crew.service.common import RESTART_NOT_UP, RestartReport, ScopeRestart + + key = tmp_path / "token_signing.key" + not_up = RestartReport( + ( + ScopeRestart( + "user", + False, + reason="kirocrew.service is activating (auto-restart)", + kind=RESTART_NOT_UP, + hint="journalctl --user -u kirocrew.service -n 50 --no-pager", + ), + ) + ) + with ( + patch("kiro_crew.cli_server.sel", return_value=MagicMock()), + patch( + "kiro_crew.cli_server.service_controller.restart_service", + return_value=not_up, + ), + patch( + "kiro_crew.cli_server.service_controller.is_service_active", + return_value=True, + ), + patch("kiro_crew.cli_server._spawn_detached_gateway") as mock_spawn, + patch("kiro_crew.sandbox.agent_confinement_evidence", return_value=None), + patch( + "kiro_crew.dashboard.token_secret.signing_key_health", + return_value=("short", key), + ), + patch( + "kiro_crew.service.common.restart_command_hint", + return_value="systemctl --user restart kirocrew", + ), + ): + with pytest.raises(SystemExit) as exc: + cli_server._restart(None) + + assert exc.value.code == 1 + mock_spawn.assert_not_called() + out = capsys.readouterr().out + assert "Read why it exits: journalctl --user -u kirocrew.service" in out + assert f"token signing key at {key} is shorter than 32 bytes" in out + assert "systemctl --user restart kirocrew" in out + + def test_unit_the_manager_refused_to_restart_gets_no_key_steps(self, capsys, tmp_path): + # A refused verb never ran the gateway, so its boot cannot be the cause. + from kiro_crew import cli_server + from kiro_crew.service.common import RESTART_REFUSED, RestartReport, ScopeRestart + + refused = RestartReport( + ( + ScopeRestart( + "system", + False, + reason="Interactive authentication required", + kind=RESTART_REFUSED, + hint="sudo systemctl restart kirocrew", + ), + ) + ) + with ( + patch("kiro_crew.cli_server.sel", return_value=MagicMock()), + patch( + "kiro_crew.cli_server.service_controller.restart_service", + return_value=refused, + ), + patch( + "kiro_crew.cli_server.service_controller.is_service_active", + return_value=True, + ), + patch("kiro_crew.cli_server._spawn_detached_gateway"), + patch( + "kiro_crew.dashboard.token_secret.signing_key_health", + return_value=("short", tmp_path / "token_signing.key"), + ) as mock_health, + ): + with pytest.raises(SystemExit): + cli_server._restart(None) + + assert "Repair it by hand" not in capsys.readouterr().out + mock_health.assert_not_called() + def test_attempted_restart_that_left_the_unit_failed_never_spawns_a_foreground_gateway( self, capsys ): diff --git a/test/test_cli_restart_readiness.py b/test/test_cli_restart_readiness.py index 67996655dd05..affecce884d3 100644 --- a/test/test_cli_restart_readiness.py +++ b/test/test_cli_restart_readiness.py @@ -167,6 +167,145 @@ def test_replacement_that_never_becomes_ready_relays_no_log_lines(self, tmp_path assert "did not become ready" in out assert "still booting" not in out + def test_replacement_that_dies_on_a_truncated_key_prints_the_repair_steps( + self, capsys, tmp_path + ): + """The gateway's refusal goes to gateway.log; the restart terminal gets the steps too.""" + key = tmp_path / "token_signing.key" + with ( + patch("kiro_crew.sandbox.agent_confinement_evidence", return_value=None), + patch( + "kiro_crew.dashboard.token_secret.signing_key_health", + return_value=("short", key), + ), + patch( + "kiro_crew.service.common.restart_command_hint", + return_value="kirocrew restart", + ), + ): + code, _sel, _url = self._drive(poll=1, ready_status=0, marker_pid=[None, None]) + + assert code == 1 + out = capsys.readouterr().out + assert "died immediately" in out + assert f"token signing key at {key} is shorter than 32 bytes" in out + assert "Repair it by hand:" in out + # Every step the gateway prints, in order, ending on the restart. + from kiro_crew.dashboard import token_secret + + steps = token_secret.signing_key_remedy(key, "kirocrew restart") + positions = [out.index(step) for step in steps] + assert positions == sorted(positions) + assert "kirocrew restart" in steps[-1] + + @pytest.mark.parametrize("state", ["ok", "absent", "masked", "other", "unstatable"]) + def test_replacement_that_dies_on_a_healthy_key_prints_no_repair_steps( + self, capsys, tmp_path, state + ): + # Only a truncated key gets the remedy: the steps delete the file, so a + # sandbox mask or a healthy key must never be handed them. + with ( + patch("kiro_crew.sandbox.agent_confinement_evidence", return_value=None), + patch( + "kiro_crew.dashboard.token_secret.signing_key_health", + return_value=(state, tmp_path / "token_signing.key"), + ), + ): + code, _sel, _url = self._drive(poll=1, ready_status=0, marker_pid=[None, None]) + + assert code == 1 + out = capsys.readouterr().out + assert "died immediately" in out + assert "Repair it by hand" not in out + + @pytest.mark.parametrize( + ("kirocrew_own", "expect_steps"), + [ + # A foreign Seatbelt (kiro-cli's, an operator wrapper) can leave the + # real key readable: the boot preflight refuses it as short, so the + # restart must print the steps too, as doctor does. + (False, True), + # Kiro Crew's own sandbox masks the leaf whatever its readability. + (True, False), + ], + ) + def test_a_readable_short_key_under_a_seatbelt_follows_doctor( + self, capsys, tmp_path, kirocrew_own, expect_steps + ): + key = tmp_path / "token_signing.key" + key.write_bytes(b"short") + key.chmod(0o600) + with ( + patch("kiro_crew.config.loader.config_dir", return_value=tmp_path), + patch("kiro_crew.sandbox.agent_confinement_evidence", return_value="seatbelt"), + patch( + "kiro_crew.sandbox.agent_confinement_is_kirocrew_own", + return_value=kirocrew_own, + ), + patch( + "kiro_crew.service.common.restart_command_hint", + return_value="kirocrew restart", + ), + ): + code, _sel, _url = self._drive(poll=1, ready_status=0, marker_pid=[None, None]) + + assert code == 1 + out = capsys.readouterr().out + assert "died immediately" in out + assert ("Repair it by hand:" in out) is expect_steps + + def test_a_short_key_this_process_cannot_open_gets_no_removal_steps(self, capsys, tmp_path): + # Inside an agent sandbox whose confinement signals both missed, the + # mode-0 mask over a healthy key reads as short; doctor withholds the + # steps that delete the file, and so must restart. + with ( + patch("kiro_crew.sandbox.agent_confinement_evidence", return_value=None), + patch( + "kiro_crew.dashboard.token_secret.signing_key_health", + return_value=("short", tmp_path / "token_signing.key"), + ), + patch("kiro_crew.dashboard.token_secret.open_is_denied", return_value=True), + ): + code, _sel, _url = self._drive(poll=1, ready_status=0, marker_pid=[None, None]) + + assert code == 1 + out = capsys.readouterr().out + assert "died immediately" in out + assert "Repair it by hand" not in out + + def test_relayed_refusal_is_not_followed_by_a_second_copy_of_the_steps(self, capsys, tmp_path): + # The relayed gateway.log lines already hold the gateway's refusal and its + # repair steps, so the restart does not print them again under the relay. + relayed = ["ERROR Refusing to start: token signing key is shorter than 32 bytes"] + with ( + patch("kiro_crew.sandbox.agent_confinement_evidence", return_value=None), + patch( + "kiro_crew.dashboard.token_secret.signing_key_health", + return_value=("short", tmp_path / "token_signing.key"), + ), + patch("kiro_crew.cli_server._gateway_log_lines_since", return_value=relayed), + ): + code, _sel, _url = self._drive(poll=1, ready_status=0, marker_pid=[None, None]) + + assert code == 1 + out = capsys.readouterr().out + assert "Its last lines in gateway.log:" in out + assert relayed[0] in out + assert "Repair it by hand" not in out + + def test_a_failing_key_probe_leaves_the_died_report_unchanged(self, capsys): + with patch( + "kiro_crew.dashboard.token_secret.signing_key_health", + side_effect=OSError("stale file handle"), + ): + code, _sel, _url = self._drive(poll=1, ready_status=0, marker_pid=[None, None]) + + assert code == 1 + out = capsys.readouterr().out + assert "died immediately" in out + assert "kirocrew logs -f" in out + assert "Repair it by hand" not in out + def test_replacement_that_never_becomes_ready_is_reported_as_a_failure(self, capsys): """A live-but-not-serving replacement must exit non-zero with timeout wording.""" code, mock_sel, mock_token_url = self._drive(