From 5a35ab212b1c105e6f5d2525f49cae6edb321d27 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:08:59 +0100 Subject: [PATCH 1/3] Use suspend-aware elapsed time for GitHub App token reuse Architecture-Review: unchanged; GitHub identities and credential sources stay the same while cache expiry uses elapsed boot time. Co-Authored-By: Codex --- src/loopzero/github.py | 19 +++++++++++++++---- tests/test_gh_contract.py | 18 ++++++++++++++++++ tests/test_github.py | 10 +++++----- 3 files changed, 38 insertions(+), 9 deletions(-) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 4415b796..c572b88d 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -255,10 +255,18 @@ def _read_only(args: tuple[str, ...]) -> bool: return False +def _app_token_clock() -> float | None: + """Read elapsed time including suspend, when the OS provides it.""" + if (clock := getattr(time, "CLOCK_BOOTTIME", None)) is not None: + with suppress(OSError): + return time.clock_gettime(clock) + return None + + def _cached_app_token() -> str: - # Installation tokens expire one hour after minting by wall clock, suspend included. token, minted = _app_token_cache - return token if token and 0 <= time.time() - minted < 3000 else "" + now = _app_token_clock() if token else None + return token if now is not None and 0 <= now - minted < 3000 else "" def app_token() -> str: @@ -267,14 +275,17 @@ def app_token() -> str: return token if not APP_TOKEN_HELPER.is_file() or not os.access(APP_TOKEN_HELPER, os.X_OK): return "" - minted = time.time() # before the helper runs: a suspend mid-call still ages the token + minted = _app_token_clock() # before minting so a suspend mid-call ages the token try: result = run([str(APP_TOKEN_HELPER)], cwd=Path("/"), env_allowlist=GH_ENV, timeout=_read_timeout(10)) except (ToolMissing, ProcTimeout, ReadDeadline, OSError): return "" if result.exit_code or not result.stdout.strip(): return "" - _app_token_cache = (result.stdout.strip(), minted) + token = result.stdout.strip() + if minted is None: + return token # no suspend-aware clock, so use this token only for this call + _app_token_cache = (token, minted) return _cached_app_token() diff --git a/tests/test_gh_contract.py b/tests/test_gh_contract.py index f9d8b19b..45a8daa2 100644 --- a/tests/test_gh_contract.py +++ b/tests/test_gh_contract.py @@ -179,3 +179,21 @@ def test_strict_fake_matches_input_contents(fake_bin: Path, tmp_path: Path) -> N ) github.update_body(REPO, 7, "new body") fake.assert_complete() + + +def test_app_token_expires_after_wall_clock_rollback(tmp_path, monkeypatch): + helper = tmp_path / "app-token" + counter = tmp_path / "helper-calls" + helper.write_text(f'#!/bin/sh\necho called >> "{counter}"\nwc -l < "{counter}"\n') + helper.chmod(0o755) + monkeypatch.setattr(github, "APP_TOKEN_HELPER", helper) + wall_time = 10_000.0 + boot_time = 10_000.0 + monkeypatch.setattr(github.time, "time", lambda: wall_time) + monkeypatch.setattr(github.time, "CLOCK_BOOTTIME", 7, raising=False) + monkeypatch.setattr(github.time, "clock_gettime", lambda _clock_id: boot_time) + assert github.app_token() == "1" + assert github.app_token() == "1" + wall_time += 2_620 + boot_time += 3_620 + assert github.app_token() == "2" diff --git a/tests/test_github.py b/tests/test_github.py index 5189977b..e82e5733 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -690,7 +690,7 @@ def test_app_identity_selection_and_cache(gh: FakeGh, tmp_path: Path, monkeypatc helper.chmod(0o755) monkeypatch.setattr(github, "APP_TOKEN_HELPER", helper) clock = [0.0] - monkeypatch.setattr(github.time, "time", lambda: clock[0]) + monkeypatch.setattr(github, "_app_token_clock", lambda: clock[0]) monkeypatch.setattr(github.time, "monotonic", lambda: 100.0) # stopped during host suspend monkeypatch.setenv("GH_TOKEN", "operator-token") gh.respond("api repos/acme/widgets", {}) @@ -721,10 +721,10 @@ def test_app_token_age_counts_suspend_during_mint_and_retry(gh: FakeGh, tmp_path helper.write_text(f"#!/bin/sh\necho called >> {counter}\necho synthetic-token-$(wc -l < {counter})\n") helper.chmod(0o755) monkeypatch.setattr(github, "APP_TOKEN_HELPER", helper) - wall, real_run = [1_000_000.0], github.run - suspend = lambda: wall.append(wall.pop() + 3601) # noqa: E731 - monkeypatch.setattr(github.time, "time", lambda: wall[0]) - monkeypatch.setattr(github, "run", lambda argv, **k: (real_run(argv, **k), wall[0] == 1e6 and suspend())[0]) + boot, real_run = [1_000_000.0], github.run + suspend = lambda: boot.append(boot.pop() + 3601) # noqa: E731 + monkeypatch.setattr(github, "_app_token_clock", lambda: boot[0]) + monkeypatch.setattr(github, "run", lambda argv, **k: (real_run(argv, **k), boot[0] == 1e6 and suspend())[0]) monkeypatch.setattr(github, "_retry_sleep", lambda delay: suspend()) monkeypatch.setenv("GH_TOKEN", "operator-token") gh.expect(["api", "repos/acme/widgets", "--include"], {}) From e0558633dcae7ac61da5323913a01dcf1d32cc47 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:23:24 +0100 Subject: [PATCH 2/3] Drive review token remint tests with elapsed boot time Co-Authored-By: Codex --- tests/test_cli.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 356ca373..75c78ff7 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1678,9 +1678,9 @@ def test_review_reminted_app_token_keeps_publisher( helper.write_text(f"#!/bin/sh\necho called >> {counter}\n{fail}echo synthetic-token-$(wc -l < {counter})\n") helper.chmod(0o755) monkeypatch.setattr(github, "APP_TOKEN_HELPER", helper) - wall, run_review = [1_000_000.0], cli._run_review - monkeypatch.setattr(github.time, "time", lambda: wall[0]) - monkeypatch.setattr(cli, "_run_review", lambda *a, **k: (run_review(*a, **k), wall.append(wall.pop() + 3601))[0]) + boot, run_review = [1_000_000.0], cli._run_review + monkeypatch.setattr(github, "_app_token_clock", lambda: boot[0]) + monkeypatch.setattr(cli, "_run_review", lambda *a, **k: (run_review(*a, **k), boot.append(boot.pop() + 3601))[0]) (wt / "workflow.toml").write_text(WORKFLOW + '\nreview_publishers = ["app[bot]"]\n') git(wt, "commit", "-qam", "configure publisher") git(wt, "update-ref", "refs/remotes/origin/main", "HEAD") From ffdcdbf34d3e1937ac6baec071b26ed5bb283078 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:25:42 +0100 Subject: [PATCH 3/3] Redact credential-shaped values in public review findings Architecture-Review: unchanged; publication and recovery still use the same GitHub payload and original finding identities. Co-Authored-By: Codex --- src/loopzero/github.py | 10 +++++----- tests/test_review_recovery.py | 30 +++++++++++++++++++++++++++--- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 9ecaffd1..66723735 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -119,8 +119,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,})" ) @@ -204,7 +204,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) @@ -715,7 +715,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() if f.severity in BLOCKING: return f"{finding_marker(f.severity, head_sha, f)}\n{text}" return text @@ -767,7 +767,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] return "\n".join(lines) + _review_transcript(result, legacy_display) diff --git a/tests/test_review_recovery.py b/tests/test_review_recovery.py index 40e02dba..2ac8f0e8 100644 --- a/tests/test_review_recovery.py +++ b/tests/test_review_recovery.py @@ -24,14 +24,16 @@ 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) reviewer = fake_bin / "claude" reviewer.write_text(reviewer.read_text().replace( "#!/bin/sh\n", f'#!/bin/sh\nprintf "run\\n" >> "{fake_bin}/claude.runs"\n')) @@ -199,6 +201,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