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
10 changes: 5 additions & 5 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ class Readiness:
_read_scope: ContextVar[tuple[float, str | None, bool] | None] = ContextVar("github_reads", default=None)
_api_error_diagnostics: ContextVar[bool] = ContextVar("github_api_error_diagnostics", default=False)
_HTTP_STATUS_RE = re.compile(r"^HTTP/\S+\s+(\d{3})(?:\s+(.*))?$", re.IGNORECASE)
_GITHUB_TOKEN_RE = re.compile(
r"\b(?:github_pat_[A-Za-z0-9_]+|gh[pousr]_[A-Za-z0-9_]{10,})\b"
_CREDENTIAL_TOKEN_RE = re.compile(
r"\b(?:github_pat_[A-Za-z0-9_]+\b|gh[pousr]_[A-Za-z0-9_]{10,}\b|sk-[A-Za-z0-9_-]{8,})"

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: The broader sk- pattern can redact ordinary hyphenated words in both prose and API error diagnostics

\bsk-[A-Za-z0-9_-]{8,} matches any standalone word that starts with sk- and has 8 or more following characters, including hyphens. Ordinary text like sk-learn-compatible or a branch name like sk-refactor-loader becomes [REDACTED]. This works against the acceptance item that explanatory text must survive. The regex is shared with _redact_tokens, so the same applies to GhError diagnostics. If false positives matter, require a longer body or a known prefix, for example sk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}. The tests use short fake values, so they would need longer ones.

)


Expand Down Expand Up @@ -220,7 +220,7 @@ def _redact_tokens(value: str, token: str = "") -> str:
value = re.sub(r"(?i)\b(authorization)\s*[:=]\s*"
r"(?:(?:basic|bearer|token)\s+)?[^\s,;]+", r"\1=[REDACTED]", value)
value = re.sub(r"(?i)\bBearer\s+[^\s,;]+", "Bearer [REDACTED]", value)
value = _GITHUB_TOKEN_RE.sub("[REDACTED]", value)
value = _CREDENTIAL_TOKEN_RE.sub("[REDACTED]", value)
value = re.sub(r"(?i)\b(access_token|auth_token|token)\s*[:=]\s*"
r"[^\s,;]+", r"\1=[REDACTED]", value)
value = re.sub(r"(?i)(https?://[^?\s]+)\?[^\s]+", r"\1?[REDACTED]", value)
Expand Down Expand Up @@ -780,7 +780,7 @@ def finding_marker(severity: str, head_sha: str, finding: Finding) -> str:


def _comment_body(f: Finding, head_sha: str, prefix: str = "") -> str:
text = f"{prefix}**{f.severity}: {f.title}**\n\n{f.body}".rstrip()
text = prefix + _CREDENTIAL_TOKEN_RE.sub("[REDACTED]", f"**{f.severity}: {f.title}**\n\n{f.body}").rstrip()

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: Finding prose uses a narrower credential recogniser than the shared _redact_tokens

The task says to apply the shared credential recognition to finding prose. _comment_body and _review_body only apply _CREDENTIAL_TOKEN_RE. They don't use the rest of _redact_tokens (github.py:199): exact matches for the live GH_TOKEN/GITHUB_TOKEN/app token, Authorization: ... values and Bearer <value>. So a finding that quotes Authorization: Bearer eyJ..., or a token whose format isn't gh*_, github_pat_ or sk-, is still published as written. The URL-query and token= rules in _redact_tokens would damage normal explanatory text like token: str, so I wouldn't use the whole function. Smallest fix: add one _redact_prose(text) helper that applies the exact-secret replacements, the Bearer/Authorization rules and _CREDENTIAL_TOKEN_RE. Call it from both places and from _redact_tokens, so the two recognisers can't drift apart.

if f.severity in BLOCKING:
return f"{finding_marker(f.severity, head_sha, f)}\n{text}"
return text
Expand Down Expand Up @@ -832,7 +832,7 @@ def _review_body(result: ReviewResult, unplaced: list[Finding], prefix: str = ""
lines.extend(_review_settings_lines(result, include_configured=settings_layout == "current"))
if unplaced:
lines.append("\nFindings without a file location:\n")
lines += [f"- **{f.severity}**: {f.title} — {f.body}".rstrip(" —") for f in unplaced]
lines += [_CREDENTIAL_TOKEN_RE.sub("[REDACTED]", f"- **{f.severity}**: {f.title} — {f.body}".rstrip(" —")) for f in unplaced]

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: The same inline redaction call is duplicated at two publication sites

_CREDENTIAL_TOKEN_RE.sub("[REDACTED]", ...) is written out at line 718 (inline comment) and line 770 (unplaced findings). If someone later adds a third place that renders finding prose, or changes the marker, these will drift. Line 770 is also now a long nested expression. Move it into a small named helper (for example _public_text(s)) and call it from both sites. This also gives later rendering paths, such as the cannot anchor '{f.title}' message at line 890, an obvious function to reuse.

return "\n".join(lines) + _review_transcript(result, legacy_display)


Expand Down
30 changes: 27 additions & 3 deletions tests/test_review_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,16 @@ def record_claude_runs(fake_bin):


def lost_reply(wt, gh, fake_bin, monkeypatch, *, kind, verdict, interrupted=False,
mutate=None, timeout=False):
mutate=None, timeout=False, findings=None):
history = []
if kind == "delta":
history = [rev(head_of(wt), "primary")]
(wt / "feature.py").write_text("print('fixed')\n")
git(wt, "commit", "-qam", "repair")
head = support.prepare_review(wt, gh, fake_bin, history=history, post_id=17,
payload=APPROVE if verdict == 0 else CHANGES)
payload = APPROVE if verdict == 0 else CHANGES
if findings is not None:
payload = {**payload, "findings": findings}
head = support.prepare_review(wt, gh, fake_bin, history=history, post_id=17, payload=payload)
record_claude_runs(fake_bin)
original = github._api

Expand Down Expand Up @@ -249,6 +251,28 @@ def read(endpoint):
assert len([c for c in gh.calls if "--input" in c]) == 1


def test_repost_recovers_review_with_redacted_findings(wt, gh, fake_bin, monkeypatch, capsys):
title = "Rotate sk-ant-FAKE0123"
findings = [
{"severity": "important", "path": "feature.py", "line": 1,
"title": title, "body": "Remove sk-proj-Fake_only-0123 from settings."},
{"severity": "suggestion", "path": None, "line": None,
"title": "Replace ghp_FAKE0123456789", "body": "See sk-FakeToken0123 in the log."},
]
head = lost_reply(wt, gh, fake_bin, monkeypatch, kind="primary", verdict=5,
interrupted=True, findings=findings)
assert run(capsys, "review")[0] == 130
payload = support.posted_review(gh)
assert "**suggestion**: Replace [REDACTED] — See [REDACTED] in the log." in payload["body"]
comment, = payload["comments"]
assert (comment["path"], comment["line"], comment["side"]) == ("feature.py", 1, "RIGHT")
stable_id = github.finding_id(head, "feature.py", 1, title)
assert comment["body"].splitlines()[0].endswith(f"severity=important head={head} id={stable_id} -->")
assert "**important: Rotate [REDACTED]**\n\nRemove [REDACTED] from settings." in comment["body"]
assert run(capsys, "review", "--repost")[0] == 5
assert_single_publication(gh, fake_bin)


def test_interrupted_explicit_repost_recovers_repost_body(wt, gh, fake_bin, monkeypatch, capsys):
head = lost_reply(wt, gh, fake_bin, monkeypatch, kind="primary", verdict=5, interrupted=True)
original = github._api
Expand Down
Loading