-
Notifications
You must be signed in to change notification settings - Fork 52
fix: scrub Nostr keys from 14 more log lines + add a CI check (#836) #842
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ToRyVand
wants to merge
5
commits into
MostroP2P:main
Choose a base branch
from
ToRyVand:fix/836-log-redaction-lint
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
f5cbd2f
fix: scrub Nostr keys from 14 more log lines + add a CI check (#836)
ToRyVand 4c65802
fix(util): drop cleartext payload from send_dm log line
ToRyVand f485590
fix(scheduler): remove debug println! leaking order pubkeys
ToRyVand 3e682e9
test(check_log_redaction): match brace/bracket macros and identity_ke…
ToRyVand 4945eb8
test(check_log_redaction): assert the reported line and identifier
ToRyVand File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,3 +24,5 @@ CLAUDE.md | |
| # Mutation testing output | ||
| mutants.out/ | ||
| mutants.out.old/ | ||
|
|
||
| __pycache__/ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| #!/usr/bin/env python3 | ||
| """CI gate for AGENTS.md:48 ("Scrub logs that might leak invoices or Nostr | ||
| keys"). Flags any `tracing::{trace,debug,info,warn,error}!(...)` call whose | ||
| argument list interpolates an identifier that looks like a Nostr | ||
| key/identity, so a new log-scrubbing regression (issue #836's pattern) fails | ||
| CI instead of shipping quietly. | ||
|
|
||
| Not a Rust parser: string literals are skipped so a key-shaped *word* inside | ||
| a log message's own text doesn't trigger a false positive, but the paren | ||
| matching is a plain depth counter — a macro call containing a raw string | ||
| literal with unbalanced parens would confuse it. None of this codebase's | ||
| tracing calls do that today; if one ever needs to, exempt it inline (see | ||
| ALLOW_COMMENT below) rather than fighting the matcher. | ||
| """ | ||
|
|
||
| import re | ||
| import sys | ||
| from pathlib import Path | ||
|
|
||
| REPO_ROOT = Path(__file__).resolve().parent.parent | ||
| SRC_ROOT = REPO_ROOT / "src" | ||
|
|
||
| MACRO_RE = re.compile(r"\b(?:tracing::)?(?:trace|debug|info|warn|error)!\s*([({\[])") | ||
|
|
||
| # Rust macros accept any of these three delimiter pairs; the matcher must | ||
| # track whichever one was actually opened. | ||
| DELIMITER_PAIRS = {"(": ")", "{": "}", "[": "]"} | ||
|
|
||
| # Identifiers that name a Nostr key/identity in this codebase. Extend this | ||
| # list, don't loosen it to a bare `key` — that also matches innocuous things | ||
| # like HashMap iteration variables. | ||
| SUSPICIOUS_RE = re.compile( | ||
| r"\b(" | ||
| r"\w*pubkey\w*" | ||
| r"|identity\w*" | ||
| r"|sender\w*" | ||
| r"|master_key" | ||
| r"|trade_key" | ||
| r"|nsec\w*" | ||
| r"|priv(?:ate)?_?key\w*" | ||
| r")\b" | ||
| ) | ||
|
|
||
| # A `// pubkey-log-allow: <reason>` comment on the line right before a | ||
| # flagged macro call exempts it — for a documented, deliberate exception | ||
| # (e.g. an already-redacted/truncated value) rather than a silent miss. | ||
| ALLOW_COMMENT = "pubkey-log-allow:" | ||
|
|
||
|
|
||
| def find_call_span(text: str, open_delim: int) -> tuple[int, str]: | ||
| """Return (index just past the delimiter matching | ||
| `text[open_delim]`, the call's source with string-literal *contents* | ||
| blanked out). Handles all three Rust macro delimiter pairs: `()`, | ||
| `{}`, `[]`. | ||
|
|
||
| Blanking string contents (not just skipping them for delimiter-matching) | ||
| matters: a format string's own English prose can contain a key-shaped | ||
| word ("...pubkey in order...") that isn't an interpolated argument at | ||
| all — only the blanked version should be searched for suspicious | ||
| identifiers, or every message that merely *mentions* a pubkey false- | ||
| positives. | ||
| """ | ||
| open_ch = text[open_delim] | ||
| close_ch = DELIMITER_PAIRS[open_ch] | ||
| depth = 0 | ||
| i = open_delim | ||
| n = len(text) | ||
| out = [] | ||
| while i < n: | ||
| c = text[i] | ||
| if c == '"': | ||
| start = i | ||
| i += 1 | ||
| while i < n and text[i] != '"': | ||
| i += 2 if text[i] == "\\" else 1 | ||
| i += 1 | ||
| out.append('"' * (i - start)) | ||
| continue | ||
| out.append(c) | ||
| if c == open_ch: | ||
| depth += 1 | ||
| elif c == close_ch: | ||
| depth -= 1 | ||
| if depth == 0: | ||
| return i + 1, "".join(out) | ||
| i += 1 | ||
| return n, "".join(out) # unbalanced — best effort | ||
|
|
||
|
|
||
| def line_before(text: str, index: int) -> str: | ||
| line_start = text.rfind("\n", 0, index) | ||
| prev_start = text.rfind("\n", 0, line_start) + 1 if line_start != -1 else 0 | ||
| return text[prev_start:line_start] if line_start != -1 else "" | ||
|
|
||
|
|
||
| def check_file(path: Path) -> list[tuple[int, str]]: | ||
| text = path.read_text(encoding="utf-8") | ||
| violations = [] | ||
| for m in MACRO_RE.finditer(text): | ||
| open_delim = m.end() - 1 | ||
| _end, code_only = find_call_span(text, open_delim) | ||
| found = SUSPICIOUS_RE.search(code_only) | ||
| if not found: | ||
| continue | ||
| if ALLOW_COMMENT in line_before(text, m.start()): | ||
| continue | ||
| line_no = text.count("\n", 0, m.start()) + 1 | ||
| violations.append((line_no, found.group(0))) | ||
| return violations | ||
|
|
||
|
|
||
| def main() -> int: | ||
| total = 0 | ||
| for path in sorted(SRC_ROOT.rglob("*.rs")): | ||
| for line_no, ident in check_file(path): | ||
| rel = path.relative_to(REPO_ROOT) | ||
| print( | ||
| f"{rel}:{line_no}: tracing call interpolates `{ident}` — " | ||
| f"looks like a Nostr key/identity (AGENTS.md:48). Drop it from " | ||
| f"the log line, or mark a deliberate exception with a " | ||
| f"`// {ALLOW_COMMENT} <reason>` comment on the line above." | ||
| ) | ||
| total += 1 | ||
| if total: | ||
| print(f"\n{total} log-redaction violation(s) found.", file=sys.stderr) | ||
| return 1 | ||
| print("check_log_redaction: clean.") | ||
| return 0 | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| sys.exit(main()) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| #!/usr/bin/env python3 | ||
| """Regression coverage for check_log_redaction.py's macro/identifier | ||
| matching (delimiter forms and suspicious-identifier variants). Run via | ||
| `python3 scripts/check_log_redaction_test.py` — wired into the | ||
| `log-redaction` CI job alongside the checker itself. | ||
| """ | ||
|
|
||
| import tempfile | ||
| import unittest | ||
| from pathlib import Path | ||
|
|
||
| from check_log_redaction import check_file | ||
|
|
||
|
|
||
| class CheckLogRedactionTest(unittest.TestCase): | ||
| def _violations(self, rust_src: str) -> list[tuple[int, str]]: | ||
| with tempfile.NamedTemporaryFile( | ||
| "w", suffix=".rs", delete=False, encoding="utf-8" | ||
| ) as f: | ||
| f.write(rust_src) | ||
| path = Path(f.name) | ||
| try: | ||
| return check_file(path) | ||
| finally: | ||
| path.unlink() | ||
|
|
||
| def test_paren_call_flags_pubkey(self): | ||
| violations = self._violations('fn x() { tracing::info!("{}", pubkey); }') | ||
| self.assertEqual(len(violations), 1) | ||
|
|
||
| def test_brace_call_flags_pubkey(self): | ||
| violations = self._violations("fn x() { trace! {pubkey} }") | ||
| self.assertEqual(len(violations), 1) | ||
|
|
||
| def test_bracket_call_flags_pubkey(self): | ||
| violations = self._violations("fn x() { trace![pubkey] }") | ||
| self.assertEqual(len(violations), 1) | ||
|
|
||
| def test_identity_key_variant_is_flagged(self): | ||
| violations = self._violations('fn x() { info!("{}", identity_key); }') | ||
| self.assertEqual(len(violations), 1) | ||
|
|
||
| def test_sender_key_variant_is_flagged(self): | ||
| violations = self._violations('fn x() { info!("{}", sender_key); }') | ||
| self.assertEqual(len(violations), 1) | ||
|
coderabbitai[bot] marked this conversation as resolved.
Outdated
|
||
|
|
||
| def test_prose_mention_is_not_flagged(self): | ||
| violations = self._violations('fn x() { info!("logging pubkey redaction"); }') | ||
| self.assertEqual(violations, []) | ||
|
|
||
| def test_allow_comment_exempts_call(self): | ||
| violations = self._violations( | ||
| "fn x() {\n" | ||
| "// pubkey-log-allow: already truncated\n" | ||
| 'info!("{}", pubkey);\n' | ||
| "}" | ||
| ) | ||
| self.assertEqual(violations, []) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.