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
5 changes: 2 additions & 3 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,9 +421,8 @@ def _validation_section(wt: Path, head: str, config: Config) -> str:
lines = [f"Recorded for `{recorded[:12]}`" + ("" if recorded == head else " (not current head)")]
if _check_report_problem(loaded, wt, config, head, require_pass=False):
lines[0] += " (unverified, run `loopzero check`)"
lines += [
f"- `{r.command}`: exit {r.exit_code}" for r in results
] or ["- (no check commands configured)"]
lines += [f"- `{github.redact_credentials(r.command)}`: exit {r.exit_code}"
for r in results] or ["- (no check commands configured)"]
return "\n".join(lines)


Expand Down
9 changes: 9 additions & 0 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,15 @@ def _api_path(args: tuple[str, ...]) -> str:
return "/" + path.lstrip("/")


def redact_credentials(value: str) -> str:
value = re.sub(r"""(?i)(https?://)[^\s/?#'"<>`]+@""", r"\1[REDACTED]@", value)
value = re.sub(r"""(?i)(\bauthorization(?:\\?['"])?[ \t]*:[ \t]*)(\\?['"])(?:(?!\2)(?:\\.|[^\\\r\n]))+\2""",

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: Quoted-key values that use a string prefix or = are still published unredacted

The new first pass only matches when a quote comes straight after the colon, and the second pass is skipped because of the quote after the key. So {"Authorization": f"Bearer <literal>"}, a b"..." or r"..." value, and dict(Authorization="Bearer <literal>") / Authorization="..." kwargs all reach the Validation block unredacted. The existing 'Authorization': '...' and "Authorization": "..." cases are covered. A literal token inside an f-string is unusual, so this is not blocking. If you want it covered, allow an optional [rbfu]{0,2} prefix before group 2 and accept [:=] as the separator. Add one test case for each.

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: Two overlapping Authorization regexes need to be kept in sync by hand

Two passes now handle Authorization: one for a quoted key with a quoted value, and one for a quoted header string or an unquoted header. Each has its own escape and quote handling, so a future fix to one can easily miss the other. The ordering also matters: the second pass only avoids redacting "Authorization": "[REDACTED]" again because a quote sits between the key and the colon. Consider building both from one compiled, commented (re.X) pattern with named alternatives, or at least add a comment that explains why the order matters.

r"\1\2[REDACTED]\2", value)
return re.sub(r"""(?i)((?P<quote>['"])?\bauthorization[ \t]*:[ \t]*)"""
Comment thread
eowca marked this conversation as resolved.
Resolved
r"""(?(quote)(?:\\.|(?!(?P=quote))[^\\\r\n])+|(?:[a-z][\w-]*[ \t]+)?(?:\\.|[^\\\s'"`])+)""",

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: Broadened scheme prefix can over-redact ordinary command text

(?:[a-z][\w-]*[ \t]+)? now treats any word followed by a space as an auth scheme. For an unquoted Authorization:abc next-arg, both abc and next-arg (for example a following URL or flag) are swapped for [REDACTED]. Nothing leaks, but this works against the acceptance goal that ordinary command text stays readable. Low impact, because unquoted Authorization headers are rare in shell commands. You could keep the general scheme prefix only when another non-space token follows it on the same argument, or just accept the trade-off.

r"\1[REDACTED]", value)


def _redact_tokens(value: str, token: str = "") -> str:
for secret in (token, os.environ.get("GH_TOKEN", ""),
os.environ.get("GITHUB_TOKEN", "")):
Expand Down
44 changes: 44 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -952,6 +952,50 @@ def test_pr_pushes_and_creates_draft(
assert "- `echo ok`: exit 0" in body and "- `test -f README.md`: exit 0" in body


@pytest.mark.parametrize("refresh", [False, True])
def test_pr_validation_redacts_private_check_commands(wt, gh, capsys, tmp_path, refresh):
command = (
"git ls-remote 'https://x-access-token:ghs_FAKE0123@example.invalid/repo.git' "
"&& curl -H 'Authorization: Bearer opaque-fake-header' https://example.invalid/ "
r"&& curl -H Authorization:\ Bot\ opaque-fake-header https://example.invalid/ "
"""&& curl -d '{"Authorization": "Bearer opaque-fake-header"}' https://example.invalid/ """
r'''&& curl -d "{\"Authorization\": \"Bearer opaque-fake-header\"}" https://example.invalid/ '''
"""&& python -c "request(headers={'Authorization': 'Basic opaque-fake-header'})" """
"""&& curl -H 'Authorization: Digest username="fake-user", response="opaque-fake-header"' """
"https://example.invalid/"
)
private = tmp_path / "private.toml"
private.write_text(WORKFLOW.replace(json.dumps("echo ok"), json.dumps(command)))
cfg = config.load(private)
head = head_of(wt)
results = (CheckResult(command, 7, 0.1, ""), CheckResult("test -f README.md", 0, 0.1, ""))
cli._save_report(wt, CheckReport(head, False, results, cli.sandbox.settings_fingerprint(cfg, wt)))

if refresh:
git(wt, "push", "-q", "-u", "origin", "lz/t1")
gh.respond_pr_list([pr_json(headRefOid=head)])
gh.respond(f"api repos/{REPO}/pulls/7 --method PATCH", {})
cli._refresh_pr_checks(wt, cfg)
else:
gh.respond(branch_history_key(), [])
gh.respond_pr_list([])
gh.respond_pr_create(pr_json(headRefOid=head))
assert run(capsys, "--config", str(private), "pr")[0] == 0

body = json.loads(gh.calls[-1]["--input"])["body"]
assert "ghs_FAKE0123" not in body and "opaque-fake-header" not in body
assert "git ls-remote 'https://[REDACTED]@example.invalid/repo.git'" in body
assert "curl -H 'Authorization: [REDACTED]' https://example.invalid/" in body
assert "curl -H Authorization:[REDACTED] https://example.invalid/" in body
assert """curl -d '{"Authorization": "[REDACTED]"}' https://example.invalid/""" in body
assert r'''curl -d "{\"Authorization\": \"[REDACTED]\"}" https://example.invalid/''' in body
assert """python -c "request(headers={'Authorization': '[REDACTED]'})" """ in body
assert "'Authorization: [REDACTED]' https://example.invalid/`: exit 7" in body
assert f"Recorded for `{head[:12]}`" in body and "(unverified" not in body
assert "- `test -f README.md`: exit 0" in body
assert cli._load_report(wt).results == results


@pytest.mark.parametrize("duplicate", [None, "CLOSED", "OPEN"])
def test_pr_refuses_completed_branch_before_any_publication(
wt: Path, gh: FakeGh, fake_tool, tmp_path: Path, capsys, duplicate: str | None,
Expand Down
Loading