Skip to content
Merged
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
16 changes: 13 additions & 3 deletions src/loopzero/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,16 @@ def _tail(text: str) -> str:
return text[-TAIL_CHARS:]


def _auth_failure(family: str, diagnostic: str) -> RunnerAuthFailed:
names = CLAUDE_AUTH_ENV if family == "claude" else CODEX_AUTH_ENV
env = _proc.build_env(names)
values = {variant for value in env.values() if value for variant in (value, json.dumps(value)[1:-1])}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Very short forwarded env values redact unrelated text

Every non-empty forwarded value becomes a literal redaction pattern. If someone sets ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN to a placeholder such as 1, x or test, every occurrence of that substring is replaced. This can mangle the failure text the acceptance criteria say must be preserved, e.g. Not logged in becomes No[REDACTED] logged in when the value is t. Smallest fix: skip values below a minimum length, e.g. len(value) >= 8. The provider-shaped sk-/JWT patterns still cover real credentials.

patterns = [*map(re.escape, sorted(values, key=len, reverse=True)), r"\bsk-[A-Za-z0-9_-]{8,}",
r"\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+"]
diagnostic = re.sub("|".join(patterns), "[REDACTED]", diagnostic)
return RunnerAuthFailed(f"{family}: CLI is not authenticated\n{_tail(diagnostic)}")


def _looks_like_auth_failure(text: str) -> bool:
return _AUTH_FAILURE.search(text) is not None

Expand Down Expand Up @@ -270,7 +280,7 @@ def _run(
with contextlib.suppress(json.JSONDecodeError, ValueError):
envelope = _extract_json_object(done.stdout)
if _claude_envelope_auth_failure(envelope) or _looks_like_auth_failure(combined):
raise RunnerAuthFailed(f"{family}: CLI is not authenticated\n{_tail(combined)}")
raise _auth_failure(family, combined)
if _subscription_exhausted(combined, envelope):
raise RunnerUsageLimit(f"{family}: usage limit reached", _tail(combined))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Native diagnostics on non-auth failure paths are still forwarded without redaction

Only the RunnerAuthFailed paths go through _auth_failure. A provider can echo the same forwarded key in output that the auth check misses. For example, a message like Invalid x-api-key does not match _AUTH_PATTERNS. That output then reaches stderr unredacted through RunnerUsageLimit/RunnerPromptTooLong/RunnerBadOutput tails here: runners.py:286 (timeout tail), 296, 298, 299 in _run, and 1164, 1170, 1171 in _review_claude. The task scopes acceptance to auth failures, so this does not block. The goal, though, is to keep credentials out of logs. Smallest fix: split the scrubbing out of _auth_failure into a _redact(family, text) helper and apply it inside _tail for runner diagnostics, or at least in the RunnerBadOutput constructor. Then every runner tail is scrubbed once at a single boundary instead of only at the auth call sites.

if _looks_too_long(combined):
Expand Down Expand Up @@ -1050,13 +1060,13 @@ def _review_claude(
if not isinstance(envelope, dict):
raise RunnerMalformedOutput("claude: result envelope is not an object", _tail(raw))
if _claude_envelope_auth_failure(envelope):
raise RunnerAuthFailed(f"claude: CLI is not authenticated\n{_tail(raw)}")
raise _auth_failure("claude", raw)
if envelope.get("is_error") and _subscription_exhausted(raw, envelope):
raise RunnerUsageLimit("claude: usage limit reached", _tail(raw))
if envelope.get("is_error") or envelope.get("subtype", "success") != "success":
text = str(envelope.get("result", ""))
if _looks_like_auth_failure(text):
raise RunnerAuthFailed(f"claude: CLI is not authenticated\n{_tail(text)}")
raise _auth_failure("claude", text)
if _looks_too_long(text) or _looks_too_long(raw):
raise RunnerPromptTooLong("claude: prompt is too long", _tail(raw))
raise RunnerBadOutput(f"claude: {envelope.get('subtype', 'error')}", _tail(raw))
Expand Down
15 changes: 15 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2230,6 +2230,21 @@ def test_review_observes_new_codex_version_in_saved_receipt(
assert result.provenance["cli_version"] == version


def test_review_redacts_native_authentication_diagnostics(wt, gh, fake_tool, capsys, monkeypatch, head):
arm_empty_primary_review_history(gh, head)
for family, env in (("claude", "ANTHROPIC_API_KEY"), ("codex", "OPENAI_API_KEY")):
monkeypatch.setenv(env, f"opaque-fake-{family}-credential")
fake_tool(family, "if [ \"$1\" = --version ]; then echo 'codex-cli 0.161.0'; exit 0; fi\n"
f'printf "Not logged in with %s (server echoed sk-FakeToken0123)\\n" "${env}" >&2\nexit 1\n')
code, _, err = run(capsys, "review")
assert code == 4
assert err.count("Not logged in with [REDACTED] (server echoed [REDACTED])") == 2
assert "opaque-fake-" not in err and "sk-FakeToken0123" not in err
for family, remedy in (("claude", "claude auth login"), ("codex", "codex login")):
assert f"{family}: CLI is not authenticated" in err
assert f"Fix: run `{remedy}`." in err


@pytest.mark.parametrize("save", [True, False])
def test_review_malformed_fragments_stay_out_of_terminal(wt, gh, fake_bin, monkeypatch, capsys, save):
prepare_review(wt, gh, fake_bin)
Expand Down
4 changes: 3 additions & 1 deletion tests/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -625,7 +625,7 @@ def test_claude_bad_severity(fake_bin: Path, tmp_path: Path) -> None:

CLAUDE_EXPIRED_OAUTH = {
"is_error": True, "api_error_status": 401, "terminal_reason": "api_error",
"result": "Failed to authenticate. API Error: 401 OAuth access token has expired. Re-authenticate to continue.",
"result": "Failed to authenticate. API Error: 401 OAuth access token has expired. Re-authenticate to continue. Token sk-ant-FAKE0123.",
}


Expand Down Expand Up @@ -653,6 +653,8 @@ def test_claude_classifies_error_envelopes(fake_bin, tmp_path, exit_code, output
_review("claude", tmp_path)
if error is RunnerBadOutput:
assert not isinstance(raised.value, RunnerUsageLimit)
if output is CLAUDE_EXPIRED_OAUTH:
assert "Token [REDACTED]." in str(raised.value)


@pytest.mark.parametrize("family,message", [
Expand Down
Loading