You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tooling.apache.org by ak...@apache.org on 2026/06/07 22:05:25 UTC
(tooling-agents) 01/02: Remove report redaction/carve-out; publish single unredacted report
This is an automated email from the ASF dual-hosted git repository.
andrewmusselman pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tooling-agents.git
commit cd1f174af3cc63fc4959f1cfe8b75c270e4583d8
Author: Andrew Musselman <ak...@apache.org>
AuthorDate: Sun Jun 7 15:04:51 2026 -0700
Remove report redaction/carve-out; publish single unredacted report
Collapse the dual-destination carve-out into one publish target. Reports
now go to outputRepo/outputToken only; the previous split (full report to
a private repo, redacted report to a public repo) is removed.
Deletes Step 5 (redact-and-publish), the redact_consolidated and
redact_issues helpers, _redact_and_push, the leak-quarantine path, and the
email notification — ~1600 lines of now-dead redaction machinery. The
consolidate agent already pushes the full report to the push target, which
is now unconditionally outputRepo/outputToken.
Drops the privateRepo, privateToken, and notifyEmail inputs. Hardcodes
clearCache and cleanStaleReports to True (previously UI-toggleable). Note
cleanStaleReports' default flips false -> true: a fully successful run now
prunes prior-run reports in the output directory.
WARNING: reports are now published UNREDACTED to outputRepo. Point it at a
private repo — redaction was the only thing that made the old public
output safe to share.
---
ASVS/agents/asvs_orchestrate.py | 1637 +--------------------------------------
1 file changed, 24 insertions(+), 1613 deletions(-)
diff --git a/ASVS/agents/asvs_orchestrate.py b/ASVS/agents/asvs_orchestrate.py
index 10fae85..9820a2d 100644
--- a/ASVS/agents/asvs_orchestrate.py
+++ b/ASVS/agents/asvs_orchestrate.py
@@ -185,70 +185,6 @@ async def run(input_dict, tools):
)
return out
- # DEPRECATED: this helper is no longer called. Per-section reports
- # used to be pushed to GitHub (private repo) and then redacted-and-
- # re-pushed (public repo) per file. They now live in CouchDB only,
- # so neither push happens. The function is kept here intentionally
- # in case per-section public reports are ever revived. If you're
- # certain they won't be, this whole def can be deleted.
- async def _redact_and_push(gofannon_client, http_client, private_repo, private_token,
- output_repo, output_token, pass_output_dir, filename,
- redact_fn, source_id):
- import json
- import base64
- # Throttle through the shared github_push_sem so the redaction
- # phase doesn't bypass the global concurrency budget. Note: this
- # closure captures github_push_sem from the outer run() scope.
- async with github_push_sem:
- headers = {"Authorization": f"token {private_token}", "Accept": "application/vnd.github.v3+json"}
- resp = await http_client.get(
- f"https://api.github.com/repos/{private_repo}/contents/{pass_output_dir}/{filename}",
- headers=headers,
- )
- if resp.status_code != 200:
- # Surface this — previously returned silently and we'd never
- # know the private-repo read failed. Common causes: wrong
- # private repo, wrong path, or insufficient token scope.
- print(f" Read redacted {pass_output_dir}/{filename} from {private_repo} FAILED: HTTP {resp.status_code}", flush=True)
- return
- file_data = resp.json()
- file_content = base64.b64decode(file_data["content"]).decode("utf-8", errors="replace")
- redacted_section, _ = redact_fn(file_content)
- try:
- push_result = await gofannon_client.call(
- agent_name="asvs_push_github",
- input_dict={
- "inputText": json.dumps({
- "repo": output_repo, "token": output_token,
- "directory": pass_output_dir, "filename": filename,
- }),
- "commitMessage": f"ASVS audit: {filename} (redacted) [source: {source_id}]",
- "fileContents": redacted_section,
- }
- )
- # asvs_push_github doesn't raise on GitHub errors — it
- # returns the error body in outputText. Inspect for
- # success markers (content + commit) the same way push_one
- # does for the audit phase.
- output_text = ""
- if isinstance(push_result, dict):
- output_text = push_result.get("outputText", "") or ""
- if not output_text or "\"content\"" not in output_text or "\"commit\"" not in output_text:
- # Try to extract a clean error message
- err_msg = output_text[:300] if output_text else "(no outputText)"
- try:
- parsed = json.loads(output_text) if output_text else {}
- if isinstance(parsed, dict) and "message" in parsed:
- err_msg = parsed["message"]
- except Exception:
- pass
- print(f" Push redacted {filename} to {output_repo} FAILED: {err_msg}", flush=True)
- except Exception as e:
- typed = type(e).__name__
- detail = str(e) or f"{typed} (no detail)"
- print(f" Push redacted {filename} to {output_repo} FAILED: {detail}", flush=True)
-
-
import os
import json
import re
@@ -281,20 +217,18 @@ async def run(input_dict, tools):
consolidate = input_dict.get("consolidate", "true")
level = input_dict.get("level", "")
- private_repo = input_dict.get("privateRepo", "")
- private_token = input_dict.get("privateToken", "")
- notify_email = input_dict.get("notifyEmail", "")
- clear_cache = input_dict.get("clearCache", "true")
- clean_stale_reports = input_dict.get("cleanStaleReports", "false")
+ # clearCache and cleanStaleReports are no longer UI inputs — both
+ # default to True. clearCache=True means every run wipes the cached
+ # source namespace and re-downloads fresh. cleanStaleReports=True
+ # means a fully successful run prunes stale reports from prior runs
+ # in the same output directory (only when there are no failures).
+ clear_cache = True
+ clean_stale_reports = True
if isinstance(discover, str):
discover = discover.lower() in ("true", "1", "yes")
if isinstance(consolidate, str):
consolidate = consolidate.lower() in ("true", "1", "yes")
- if isinstance(clear_cache, str):
- clear_cache = clear_cache.lower() in ("true", "1", "yes")
- if isinstance(clean_stale_reports, str):
- clean_stale_reports = clean_stale_reports.lower() in ("true", "1", "yes")
level = level.strip().upper()
if level and not level.startswith("L"):
@@ -305,12 +239,11 @@ async def run(input_dict, tools):
if not source_repo:
return {"outputText": "Error: sourceRepo is required (e.g., 'apache/airflow')"}
- carve_out = bool(private_repo)
- if carve_out and not private_token:
- return {"outputText": "Error: privateToken is required when privateRepo is set"}
-
- push_repo = private_repo if carve_out else output_repo
- push_token = private_token if carve_out else output_token
+ # Reports are published unredacted to a single destination:
+ # outputRepo/outputToken. The former private-repo carve-out (full →
+ # private, redacted → public) has been removed.
+ push_repo = output_repo
+ push_token = output_token
# Derive repo name, path prefix, and namespace from sourceRepo
_source = source_repo.strip().strip("/")
@@ -395,1251 +328,13 @@ async def run(input_dict, tools):
print(f" Reports namespace: {reports_namespace}", flush=True)
print(f" Pass concurrency: {PASS_CONCURRENCY}", flush=True)
print(f" Bundling: max={BUNDLE_MAX_SECTIONS} sections/call, min={BUNDLE_MIN_SECTIONS}", flush=True)
- if carve_out:
- print(f" Carve-out enabled: full → {private_repo}, redacted → {output_repo}", flush=True)
+ print(f" Publishing (unredacted) to: {output_repo}", flush=True)
all_outputs = []
successes = []
failures = []
report_directories = []
- # =============================================================
- # Redaction helpers (unchanged from original)
- # =============================================================
- def redact_consolidated(content):
- """Strip Critical findings from the consolidated report.
-
- Robustness: a finding block is only treated as Critical when its
- STRUCTURED severity token says Critical — not when the word
- "critical" appears anywhere in prose. Audit reports legitimately
- use "critical" in descriptions, gap classifications, and impact
- language; matching on bare keywords drops innocent findings.
-
- Detection precedence (first match wins, per finding):
- 1. Finding ID token: `ASVS-{section}-CRIT-NNN` or `-CRITICAL-NNN`
- 2. Severity heading: `#### CRITICAL` / `### [CRITICAL]` (any depth)
- 3. Severity field: `**Severity:** Critical` / `**Severity**: Critical`
- 4. Old consolidated emoji marker at start of block: `🔴 Critical`
-
- Block matching covers BOTH formats produced by the pipeline:
- - Old consolidated: `#### FINDING-NNN: ...`
- - New bundled: `#### CRITICAL` / `#### MEDIUM` / etc., with
- `**Finding ID:** ASVS-NNN-SEV-NNN` inside
- """
- critical_findings = []
- leaks_detected = []
- redacted = content
-
- # Match a finding block: starts with `#### <header>` and runs until
- # the next `####`, `##`, horizontal rule, or end of doc.
- finding_pattern = re.compile(
- r'(####\s+[^\n]+\n[\s\S]*?)(?=####\s|##\s|\n---\n|\Z)',
- re.MULTILINE,
- )
-
- def is_critical_block(block):
- # 1. Finding ID severity token (most reliable)
- if re.search(r'ASVS-\d+-CRIT(?:ICAL)?-\d+', block, re.IGNORECASE):
- return True
- # 2. Severity heading at any depth
- first_line = block.split('\n', 1)[0]
- if re.match(r'#{1,6}\s*\[?\s*CRITICAL\s*\]?\s*$', first_line, re.IGNORECASE):
- return True
- # 3. Explicit Severity field
- if re.search(r'\*\*Severity:?\*\*:?\s*Critical\b', block, re.IGNORECASE):
- return True
- # 4. Old emoji-prefixed header
- if re.search(r'🔴\s*Critical\b', block, re.IGNORECASE):
- return True
- return False
-
- def extract_finding_id(block):
- # Try the new ASVS-{section}-{SEV}-NNN format first
- m = re.search(r'\*\*Finding ID:?\*\*:?\s*(ASVS-\d+-[A-Z]+-\d+)',
- block, re.IGNORECASE)
- if m:
- return m.group(1)
- # Fall back to the old FINDING-NNN format
- m = re.match(r'####\s+(FINDING-\d+)', block)
- if m:
- return m.group(1)
- # Last resort: a stable hash of the block's first line
- first_line = block.split('\n', 1)[0].strip()
- return f"UNKNOWN-{hash(first_line) & 0xFFFF:04X}"
-
- # Walk every finding block, deciding redaction structurally.
- for match in finding_pattern.finditer(content):
- block = match.group(1)
- if is_critical_block(block):
- finding_id = extract_finding_id(block)
- # Extract the title from the block's first heading line
- # — used later by the title-based leak scrub (3d).
- # Patterns to handle:
- # #### FINDING-NNN: Title goes here
- # #### Title goes here
- # #### CRITICAL (no title — title comes from a later
- # "**Title:** Foo" or "**Finding:** Foo" field)
- title = ""
- first_line = block.split("\n", 1)[0]
- # case A: heading has the title after a colon
- m_title = re.match(
- r'#{1,6}\s+(?:FINDING-\d+:\s*)?(.+?)\s*$',
- first_line,
- )
- if m_title:
- candidate = m_title.group(1).strip()
- # heading may be just "CRITICAL" / "[CRITICAL]" / "Critical"
- if not re.match(r'^\[?\s*CRITICAL\s*\]?$', candidate, re.IGNORECASE):
- title = candidate
- # case B: title in an inline field
- if not title:
- m_field = re.search(
- r'\*\*(?:Title|Finding)\*\*:?\s*(.+?)\s*(?:\n|$)',
- block,
- re.IGNORECASE,
- )
- if m_field:
- title = m_field.group(1).strip()
- # strip trailing punctuation/decorations
- title = re.sub(r'\s*\*+\s*$', '', title).strip()
- title = re.sub(r'\s*\([^)]*\)\s*$', '', title).strip()
- critical_findings.append({
- "id": finding_id,
- "title": title,
- "block": block.strip(),
- })
- redacted = redacted.replace(match.group(1), "")
-
- # Strip the Critical-severity section in the report body
- # (e.g., "### 3.1 Critical Findings" or "## Critical Severity")
- redacted = re.sub(
- r'###?\s+\d+\.\d+\s+Critical[^\n]*\n.*?(?=###?\s+\d+\.\d+\s+\w|##\s+\d|\Z)',
- '', redacted, flags=re.DOTALL,
- )
- redacted = re.sub(
- r'##\s+Critical\s+Severity\b.*?(?=##\s+\w|\Z)',
- '', redacted, flags=re.DOTALL,
- )
-
- if critical_findings:
- # Build a set of redacted Finding IDs for cross-reference scrubbing
- redacted_ids = set()
- for cf in critical_findings:
- fid = cf["id"]
- redacted_ids.add(fid)
- # Also add the FINDING-NNN form if it's an ASVS-style ID
- # (consolidated.md cross-refs always use the FINDING-NNN form
- # regardless of which form appears in the per-section reports)
- m = re.match(r'FINDING-(\d+)', fid)
- if m:
- redacted_ids.add(fid)
-
- # 1. Recompute the Severity Distribution table.
- # Two formats observed in practice:
- #
- # Horizontal (one row, columns by severity):
- # | Critical | High | Medium | Low | Info | Total |
- # |----------|------|--------|-----|------|-------|
- # | 6 | 16 | 34 | 21 | 0 | **77**|
- #
- # Vertical (one row per severity):
- # | Severity | Count | Percentage |
- # |--------------|------:|-----------:|
- # | **Critical** | 6 | 7.8% |
- # | **High** | 16 | 20.8% |
- # ...
- # | **Total** | **77**| **100%** |
- #
- # Both need to zero the Critical count and decrement Total.
- redacted_count = len(critical_findings)
-
- def _zero_critical_count(m):
- # Horizontal-format helper. Replace the Critical count
- # (first numeric cell after `|`) with 0, leaving the
- # other counts and Total intact.
- row = m.group(0)
- new_row = re.sub(r'(\|\s*)\d+(\s*\|)', r'\g<1>0\g<2>', row, count=1)
- total_m = re.search(r'\*\*(\d+)\*\*', new_row)
- if total_m:
- old_total = int(total_m.group(1))
- new_total = max(0, old_total - redacted_count)
- new_row = new_row.replace(f'**{old_total}**', f'**{new_total}**')
- return new_row
-
- # Horizontal format: header row + alignment row + data row.
- sev_table_pattern_horizontal = re.compile(
- r'(\|\s*Critical\s*\|\s*High\s*\|\s*Medium\s*\|\s*Low\s*\|\s*Info[^\n]*\|\n'
- r'\|[\s:|-]+\|\n)'
- r'(\|[^\n]+\|)',
- re.IGNORECASE,
- )
- def _sev_table_replace(m):
- return m.group(1) + _zero_critical_count(re.match(r'.*', m.group(2)))
- redacted = sev_table_pattern_horizontal.sub(_sev_table_replace, redacted)
-
- # Vertical format: zero the Critical row's count cell, and
- # decrement the Total row. Match the row pattern:
- # | (optional formatting) Critical (optional formatting) | <count> | ... |
- # Critical cell may be wrapped in **...** or contain emoji.
- def _zero_vertical_critical_row(m):
- row = m.group(0)
- # Replace first numeric or **N** cell after the
- # Critical label with 0.
- new_row = re.sub(
- r'(\|\s*\**\s*(?:🔴\s*)?Critical\s*\**\s*\|\s*)'
- r'(?:\*\*)?\d+(?:\*\*)?(\s*\|)',
- r'\g<1>0\g<2>',
- row,
- count=1,
- flags=re.IGNORECASE,
- )
- return new_row
- redacted = re.sub(
- r'\|\s*\**\s*(?:🔴\s*)?Critical\s*\**\s*\|[^\n]+\|',
- _zero_vertical_critical_row,
- redacted,
- flags=re.IGNORECASE,
- )
-
- # Vertical format: decrement Total row.
- def _decrement_vertical_total_row(m):
- row = m.group(0)
- # Find first numeric cell (possibly **N**) after Total
- num_m = re.search(
- r'(\|\s*\**\s*Total\s*\**\s*\|\s*\**)(\d+)(\**\s*\|)',
- row,
- flags=re.IGNORECASE,
- )
- if num_m:
- old = int(num_m.group(2))
- new = max(0, old - redacted_count)
- row = row[:num_m.start(2)] + str(new) + row[num_m.end(2):]
- return row
- redacted = re.sub(
- r'\|\s*\**\s*Total\s*\**\s*\|[^\n]+\|',
- _decrement_vertical_total_row,
- redacted,
- flags=re.IGNORECASE,
- )
-
- # 2. Strip ASCII bar chart Critical line if present (e.g.
- # "Critical ████░░ 6 ( 7.8%)")
- redacted = re.sub(
- r'^[ \t]*Critical[ \t]+[█░▓▒]+[^\n]*\n',
- '',
- redacted,
- flags=re.MULTILINE | re.IGNORECASE,
- )
-
- # 3. Scrub references to redacted Finding IDs in Top Risks /
- # Cross-Reference Matrix tables. These appear in cells like:
- # "FINDING-001 through FINDING-004, FINDING-010, ..."
- # Drop only the redacted IDs, preserving the rest.
- # Do not touch tables in code blocks or per-finding blocks
- # (those have already been removed).
- if redacted_ids:
- # Drop entire table rows whose severity column says
- # Critical. This catches Top 5 Risks rows (which have
- # full risk descriptions and titles in adjacent cells —
- # leaving only the IDs to strip but keeping the rest
- # leaks the redacted finding's content via title and
- # description), Cross-Reference Matrix rows, and any
- # other table that includes severity per row.
- #
- # The match is intentionally broad: any line that
- # starts with `|`, contains `Critical` in any cell
- # (with or without ** wrapping or 🔴 emoji), and ends
- # with `|`. False positives are theoretically possible
- # if a non-redacted finding's title contains the word
- # "Critical", but in practice severity columns are
- # the dominant source of the word in tables and we
- # accept this risk as the cost of full redaction.
- #
- # Safety: don't touch lines inside code fences. Code
- # fences are rendered as-is, so lines starting with
- # `|` inside ```...``` blocks aren't tables.
- def _strip_critical_table_rows(text):
- out = []
- in_fence = False
- for line in text.split('\n'):
- stripped = line.lstrip()
- if stripped.startswith('```'):
- in_fence = not in_fence
- out.append(line)
- continue
- if in_fence:
- out.append(line)
- continue
- # Detect table row with Critical in a cell.
- # Pattern: starts with |, ends with |, contains
- # Critical (with optional ** or 🔴 wrapping).
- if (
- stripped.startswith('|')
- and stripped.rstrip().endswith('|')
- and re.search(
- r'\|\s*\**\s*(?:🔴\s*)?Critical\s*\**\s*\|',
- line,
- re.IGNORECASE,
- )
- ):
- # Skip the row (don't append to output)
- continue
- out.append(line)
- return '\n'.join(out)
- redacted = _strip_critical_table_rows(redacted)
-
- # 3b. Drop heading-based Critical risk blocks. The
- # consolidate Sonnet sometimes produces Top 5 Risks as
- # `#### N. 🔴 Title (Critical)` headings followed by
- # paragraph content rather than as table rows. The
- # table-row stripper above doesn't see these. Walk the
- # document and drop any `#### ...` heading that
- # contains 🔴 or "(Critical)" along with everything
- # under it until the next heading at depth ≤ 4 (next
- # risk or end of section).
- #
- # Detection is intentionally narrow — we require
- # either the 🔴 emoji or the literal token `(Critical)`
- # in parens. We do NOT match a bare word "Critical"
- # in the heading because legitimate non-Critical
- # headings could mention the word in their title
- # ("Critical Path Analysis", etc.).
- #
- # Safety: code fences are skipped exactly as in the
- # table-row pass.
- def _strip_critical_heading_blocks(text):
- lines = text.split('\n')
- out = []
- in_fence = False
- i = 0
- crit_heading_re = re.compile(
- r'^####\s.*(?:🔴|\(\s*Critical\s*\))',
- re.IGNORECASE,
- )
- boundary_re = re.compile(r'^#{1,4}(\s|$)')
- while i < len(lines):
- line = lines[i]
- stripped = line.lstrip()
- if stripped.startswith('```'):
- in_fence = not in_fence
- out.append(line)
- i += 1
- continue
- if in_fence:
- out.append(line)
- i += 1
- continue
- if crit_heading_re.match(line):
- # Skip this heading + all content under it
- # until the next heading at depth ≤ 4.
- i += 1
- while i < len(lines):
- nxt = lines[i]
- nxt_stripped = nxt.lstrip()
- if nxt_stripped.startswith('```'):
- in_fence = not in_fence
- i += 1
- continue
- if (not in_fence) and boundary_re.match(nxt_stripped):
- break # don't consume the boundary line
- i += 1
- continue
- out.append(line)
- i += 1
- return '\n'.join(out)
- redacted = _strip_critical_heading_blocks(redacted)
-
- # 3c. Drop flat list-item Critical risks. Consolidate
- # sometimes renders Top 5 Risks as plain numbered or
- # bulleted list lines with a severity prefix:
- #
- # 1. [Critical] Title: full risk description...
- # - [Critical] Title: full risk description...
- # 2. **Critical** Title: ...
- #
- # Neither the table-row stripper (3a) nor the heading
- # stripper (3b) catches these — they're just markdown
- # prose lines. This stripper drops any line that starts
- # with a list marker (`N.`, `-`, or `*`) and contains
- # one of the unambiguous Critical severity tokens
- # before continuing into the title/description.
- #
- # Detection is narrow on purpose: we require [Critical],
- # (Critical), **Critical**, or the 🔴 emoji. A bare
- # mention of the word "critical" in a list item's
- # prose does NOT match (e.g., "1. Critical Path
- # Analysis: ..." in a non-Critical risk would be
- # preserved). Severity tokens with brackets/parens/
- # bold/emoji are the dominant way severity gets
- # rendered into list-item leaders, and we accept the
- # rare false-negative case in exchange for not
- # over-redacting innocent list items.
- def _strip_critical_list_items(text):
- out = []
- in_fence = False
- crit_list_re = re.compile(
- r'^\s*(?:\d+\.|[-*])\s+.*?'
- r'(?:\[\s*Critical\s*\]'
- r'|\(\s*Critical\s*\)'
- r'|\*\*\s*Critical\s*\*\*'
- r'|🔴)',
- re.IGNORECASE,
- )
- for line in text.split('\n'):
- stripped = line.lstrip()
- if stripped.startswith('```'):
- in_fence = not in_fence
- out.append(line)
- continue
- if in_fence:
- out.append(line)
- continue
- if crit_list_re.match(line):
- continue # drop the entire list item line
- out.append(line)
- return '\n'.join(out)
- redacted = _strip_critical_list_items(redacted)
-
- # 3c.0. SECTION-SCOPED Top N Risks redaction. The
- # global list-item stripper above (3c) has been
- # observed to miss items in real public reports
- # even when the per-line regex matches in
- # isolation. This redundant section-scoped pass
- # finds the "Top N Risks" heading, scans the
- # numbered list under it (until the next heading),
- # and drops any item whose body mentions Critical
- # severity in any recognizable form — including
- # forms 3c does not match. It also removes any
- # blank lines left by dropped items so the
- # surviving items pack cleanly for the renumber
- # pass that follows.
- #
- # Detection within an item's body:
- # - (Critical) / (CRITICAL) / (Severity Critical) anywhere
- # - [Critical] / [CRITICAL]
- # - **Critical** / **CRITICAL**
- # - 🔴 (Critical emoji marker)
- # - "Severity: Critical" or "Severity Critical"
- # - "ASVS-NNN-CRIT(ICAL)-NNN" finding-id token
- #
- # An item spans from its `N.` line to the next
- # `N.`-prefixed line or the next heading (#…).
- # Multi-paragraph items (rare in Top N Risks
- # output but possible) are dropped in full.
- def _strip_critical_items_in_top_risks(text):
- lines = text.split('\n')
- out = []
- in_fence = False
- top_heading_re = re.compile(
- r'^#{2,6}\s+Top\s+\d+\s+Risks?\s*$',
- re.IGNORECASE,
- )
- # Boundary: any next heading at any depth ends
- # the Top N Risks section.
- boundary_re = re.compile(r'^#{1,6}(\s|$)')
- list_start_re = re.compile(r'^\s*\d+\.\s')
- crit_token_re = re.compile(
- r'(?:'
- r'\(\s*(?:Severity\s+)?Critical\s*\)'
- r'|\[\s*Critical\s*\]'
- r'|\*\*\s*Critical\s*\*\*'
- r'|🔴'
- r'|Severity\s*:?\s*Critical\b'
- r'|ASVS-\d+-CRIT(?:ICAL)?-\d+'
- r')',
- re.IGNORECASE,
- )
- i = 0
- while i < len(lines):
- line = lines[i]
- stripped = line.lstrip()
- if stripped.startswith('```'):
- in_fence = not in_fence
- out.append(line)
- i += 1
- continue
- if in_fence:
- out.append(line)
- i += 1
- continue
- if not top_heading_re.match(line):
- out.append(line)
- i += 1
- continue
- # Enter Top N Risks section.
- out.append(line)
- i += 1
- # Process the list under this heading.
- while i < len(lines):
- nxt = lines[i]
- nxt_stripped = nxt.lstrip()
- if nxt_stripped.startswith('```'):
- in_fence = not in_fence
- out.append(nxt)
- i += 1
- continue
- if (not in_fence) and boundary_re.match(
- nxt_stripped
- ):
- break # next heading ends the section
- if (not in_fence) and list_start_re.match(nxt):
- # Found a top-level numbered item. Read
- # its body up to the next top-level
- # numbered item or the next heading.
- item_lines = [nxt]
- j = i + 1
- while j < len(lines):
- nn = lines[j]
- nn_stripped = nn.lstrip()
- if nn_stripped.startswith('```'):
- in_fence = not in_fence
- if (not in_fence) and (
- boundary_re.match(nn_stripped)
- or list_start_re.match(nn)
- ):
- break
- item_lines.append(nn)
- j += 1
- body = '\n'.join(item_lines)
- if crit_token_re.search(body):
- # Drop the entire item.
- i = j
- continue
- out.extend(item_lines)
- i = j
- continue
- out.append(nxt)
- i += 1
- return '\n'.join(out)
- redacted = _strip_critical_items_in_top_risks(redacted)
-
- # 3d. DEFENSIVE percentage-table normalization.
- # If the consolidator's executive summary slipped
- # into the vertical | Severity | Count | Percentage |
- # format anyway (older runs, prompt drift, model
- # nondeterminism), rewrite it in place to the
- # count-only | Severity | Count | shape. This
- # avoids two failure modes:
- # - Percentages computed against the pre-redaction
- # total that fail to sum to 100 after Critical
- # is zeroed.
- # - Percentages that DO sum to 100 (because the
- # consolidator silently dropped Critical from
- # the denominator) but create the false
- # impression that "0.0% Critical" means the
- # project has no critical findings.
- # The replacement is bytewise minimal: strip the
- # third column from the header, alignment, and
- # every severity-or-total data row that follows.
- def _normalize_severity_table(text):
- # Match the table block: header + alignment +
- # one or more rows whose first cell is a
- # severity label (or Total). Stop at the first
- # non-table line.
- header_re = re.compile(
- r'(\|\s*Severity\s*\|\s*Count\s*\|\s*Percentage\s*\|\s*\n'
- r'\|[\s:|\-]+\|[\s:|\-]+\|[\s:|\-]+\|\s*\n)'
- r'((?:\|[^\n]*\|\s*\n)+)',
- re.IGNORECASE,
- )
- def repl(m):
- new_header = (
- "| Severity | Count |\n"
- "|----------|-------|\n"
- )
- new_rows = []
- for row in m.group(2).splitlines():
- if not row.strip().startswith('|'):
- new_rows.append(row)
- continue
- cells = [c.strip() for c in row.split('|')]
- # cells = ['', sev, count, pct, ''] for a 3-col row
- if len(cells) >= 4:
- sev = cells[1]
- count = cells[2]
- new_rows.append(f"| {sev} | {count} |")
- else:
- new_rows.append(row)
- return new_header + '\n'.join(new_rows) + '\n'
- return header_re.sub(repl, text)
- redacted = _normalize_severity_table(redacted)
-
- # 3e. TRIPWIRE — fail loud rather than publish a
- # report with surviving Critical references. After
- # all redaction passes, scan the redacted output
- # for unambiguous Critical leak shapes. If any
- # survive, raise an error that aborts the public
- # push. The caller (in _redact_and_push) catches
- # exceptions and logs the failure; the public repo
- # is NOT updated in that case.
- #
- # Tripwire patterns (each on a single line):
- # - A line with both a numbered/bulleted list
- # marker AND a Critical token.
- # - A heading line containing "Critical" alone
- # (e.g., "### Critical Findings").
- # - A severity field line "**Severity**: Critical".
- # Plain prose mentions of the word "critical"
- # elsewhere (e.g., "critical infrastructure",
- # "remediate within 48h for Critical") are
- # tolerated — they describe the redaction policy
- # rather than leak finding content.
- tripwire_patterns = [
- re.compile(
- r'^\s*(?:\d+\.|[-*])\s+.*?'
- r'(?:\(\s*Critical\s*\)|\[\s*Critical\s*\]'
- r'|\*\*\s*Critical\s*\*\*|🔴'
- r'|Severity\s*:?\s*Critical\b)',
- re.IGNORECASE | re.MULTILINE,
- ),
- re.compile(
- r'^#{1,6}\s+(?:\d+\.\d+\s+)?Critical\b',
- re.IGNORECASE | re.MULTILINE,
- ),
- re.compile(
- r'^\s*\*\*Severity\*\*\s*:?\s*Critical\b',
- re.IGNORECASE | re.MULTILINE,
- ),
- ]
- surviving_leaks = []
- for pat in tripwire_patterns:
- for m in pat.finditer(redacted):
- surviving_leaks.append(m.group(0)[:120])
- if surviving_leaks:
- # Aborting raises out of redact_consolidated;
- # the calling _redact_and_push wraps push in
- # try/except and will log the failure without
- # updating the public repo.
- msg = (
- f"REDACTION TRIPWIRE: {len(surviving_leaks)} "
- f"Critical leak(s) survived redaction. "
- f"Public push aborted. Samples: "
- f"{surviving_leaks[:3]}"
- )
- raise RuntimeError(msg)
-
- # 3c.1. Renumber the Top N Risks numbered list and update
- # its heading to match the surviving count. After 3c
- # drops Critical risks (e.g. item 1 of a Top 5 list),
- # the survivors keep their original numbers (2, 3, 4, 5)
- # and the heading still says "Top 5 Risks" — both visible
- # in the public report on the May 20 mina L1 run. This
- # pass renumbers survivors sequentially from 1 and
- # rewrites the heading to "Top {survivor_count} Risks".
- #
- # Scope: only the section under a heading matching
- # `^#{2,6} Top N Risks`. List renumbering does not apply
- # to numbered lists elsewhere in the document
- # (remediation steps, acceptance criteria, etc.) —
- # those should keep their original numbering even when
- # individual items happen to mention Critical findings.
- #
- # Safety: code-fenced regions are skipped exactly as in
- # 3a-3c. If no Top N Risks heading exists, this is a
- # no-op.
- def _renumber_top_risks(text):
- lines = text.split('\n')
- out = []
- in_fence = False
- top_heading_re = re.compile(
- r'^(#{2,6})\s+Top\s+(\d+)\s+Risks?\s*$',
- re.IGNORECASE,
- )
- boundary_re = re.compile(r'^#{1,6}(\s|$)')
- # Only match top-level list items (no leading
- # indent). Sub-bullets inside a risk's description
- # — common pattern when a finding's narrative
- # includes its own numbered breakdown — should
- # keep their original numbering.
- list_item_re = re.compile(r'^\d+\.\s')
- i = 0
- while i < len(lines):
- line = lines[i]
- stripped = line.lstrip()
- if stripped.startswith('```'):
- in_fence = not in_fence
- out.append(line)
- i += 1
- continue
- if in_fence:
- out.append(line)
- i += 1
- continue
- m = top_heading_re.match(line)
- if not m:
- out.append(line)
- i += 1
- continue
- # Found Top N Risks heading. Park a placeholder
- # in the output; rewrite it after counting the
- # surviving items in the section below.
- heading_prefix = m.group(1)
- heading_idx = len(out)
- out.append(line) # placeholder
- i += 1
- survivor_count = 0
- while i < len(lines):
- nxt = lines[i]
- nxt_stripped = nxt.lstrip()
- if nxt_stripped.startswith('```'):
- in_fence = not in_fence
- out.append(nxt)
- i += 1
- continue
- if (not in_fence) and boundary_re.match(nxt_stripped):
- break # next heading; stop scanning
- if (not in_fence) and list_item_re.match(nxt):
- survivor_count += 1
- n = survivor_count # bind for closure
- nxt = list_item_re.sub(
- lambda mm, n=n: f"{n}. ",
- nxt,
- count=1,
- )
- out.append(nxt)
- i += 1
- if survivor_count > 0:
- out[heading_idx] = f"{heading_prefix} Top {survivor_count} Risks"
- return '\n'.join(out)
- redacted = _renumber_top_risks(redacted)
-
- sorted_ids = sorted(redacted_ids,
- key=lambda s: int(re.search(r'(\d+)', s).group(1)) if re.search(r'(\d+)', s) else 0)
-
- # Drop "FINDING-A through FINDING-B" ranges. If the entire
- # range is redacted, drop the whole expression. Otherwise
- # rewrite to "FINDING-X, FINDING-Y, ..." with only the
- # surviving IDs, then let the per-ID stripping below clean
- # up redacted ones.
- def _strip_range(m):
- a = m.group(1)
- b = m.group(2)
- try:
- a_num = int(re.search(r'(\d+)', a).group(1))
- b_num = int(re.search(r'(\d+)', b).group(1))
- except Exception:
- return m.group(0)
- survivors = [
- f"FINDING-{n:03d}"
- for n in range(a_num, b_num + 1)
- if f"FINDING-{n:03d}" not in redacted_ids
- ]
- if not survivors:
- return ""
- return ", ".join(survivors)
- redacted = re.sub(
- r'(FINDING-\d+)\s+through\s+(FINDING-\d+)',
- _strip_range,
- redacted,
- )
-
- # Drop comma-separated occurrences of redacted IDs
- for fid in sorted_ids:
- redacted = re.sub(
- r',\s*' + re.escape(fid) + r'\b',
- '',
- redacted,
- )
- redacted = re.sub(
- r'\b' + re.escape(fid) + r'\s*,\s*',
- '',
- redacted,
- )
- # Bare leftover - could be in a table cell on its own
- redacted = re.sub(
- r'\b' + re.escape(fid) + r'\b',
- '',
- redacted,
- )
-
- # Scrub "Nx Critical" / "N× Critical" / "N Critical" phrases
- # in surviving table cells — the count is now wrong and
- # naming the redacted severity defeats the purpose of the
- # carve-out. Preserve other severity counts in the cell.
- def _strip_critical_phrases(m):
- cell = m.group(0)
- # Drop the "Nx Critical, " or "N× Critical, " segments
- cell = re.sub(
- r'\d+\s*[x×]\s*Critical\s*,?\s*',
- '',
- cell,
- flags=re.IGNORECASE,
- )
- # Tidy up trailing/leading commas
- cell = re.sub(r',\s*\|', ' |', cell)
- cell = re.sub(r'\|\s*,', '| ', cell)
- return cell
- # Apply to lines that look like table rows
- redacted = re.sub(
- r'\|[^\n]*Critical[^\n]*\|',
- _strip_critical_phrases,
- redacted,
- )
-
- # Clean up leftover artifacts: empty list items,
- # cells starting with stray ", ", double commas, leading
- # whitespace from removed ranges, and full Cross-Reference
- # Matrix rows whose Finding ID col is now empty.
- redacted = re.sub(r'\|\s*,\s*', '| ', redacted)
- redacted = re.sub(r',\s*,', ',', redacted)
- # Collapse multiple spaces inside cells (not at line start).
- # Use [ \t] not \s to avoid eating newlines, which would
- # weld the end of a table to the start of the next section.
- redacted = re.sub(r'\|[ \t]{2,}', '| ', redacted)
- # Drop Cross-Reference Matrix rows whose Finding ID cell
- # is now empty (left by redacting FINDING-001 etc.).
- # Anchor to line start with re.MULTILINE and use
- # [ \t]+ (NOT \s+) so the regex cannot cross newlines.
- # The previous \s+ form ate the trailing pipe of the
- # Severity Distribution alignment row plus the next
- # row whenever it was Critical/High/Medium/Low — exactly
- # the mangled table seen in the May 19 public report.
- redacted = re.sub(
- r'^\|[ \t]+\|[ \t]+(Critical|High|Medium|Low)\b[^\n]*\n',
- '',
- redacted,
- flags=re.MULTILINE,
- )
-
- # Polish: tables left empty by Critical-row removal get
- # replaced with an explanatory notice. This catches things
- # like a Top 5 Risks table where every row was Critical
- # and got stripped — we don't want to leave a bare header
- # + alignment row with no data, which renders awkwardly
- # on GitHub. Detect by walking line-by-line: a header
- # row followed by an alignment row followed by anything
- # other than another `|` row means the table is empty.
- #
- # Note: we do this even when no critical_findings were
- # present in the report, to handle other paths that may
- # produce empty tables. The cost is negligible.
- def _replace_empty_tables(text, redacted_count):
- out_lines = []
- lines = text.split('\n')
- i = 0
- in_fence = False
- while i < len(lines):
- line = lines[i]
- stripped = line.lstrip()
- if stripped.startswith('```'):
- in_fence = not in_fence
- out_lines.append(line)
- i += 1
- continue
- if in_fence:
- out_lines.append(line)
- i += 1
- continue
- # Look for header + alignment + (no data rows) pattern.
- # Header: line starts and ends with `|` and isn't an
- # alignment row.
- # Alignment: line is `|` separators with `:` and `-`.
- # No data: walking forward from after the alignment
- # row, the next non-blank line isn't a `|`-form data
- # row (or is a `|`-form alignment row, weird but
- # possible).
- is_header = (
- stripped.startswith('|')
- and stripped.rstrip().endswith('|')
- and not re.match(r'^\s*\|[\s:|-]+\|\s*$', line)
- and i + 1 < len(lines)
- )
- if is_header:
- next_line = lines[i + 1]
- is_alignment = (
- next_line.lstrip().startswith('|')
- and next_line.rstrip().endswith('|')
- and re.match(r'^\s*\|[\s:|-]+\|\s*$', next_line)
- )
- if is_alignment:
- # Look at the line immediately after alignment.
- # Skip up to a small number of blank lines that
- # might be cosmetic padding.
- j = i + 2
- blanks_skipped = 0
- while (
- j < len(lines)
- and not lines[j].strip()
- and blanks_skipped < 2
- ):
- j += 1
- blanks_skipped += 1
- # A data row is a `|`-prefixed line that is
- # NOT an alignment row.
- has_data = False
- if j < len(lines):
- nxt = lines[j]
- nxt_strip = nxt.lstrip()
- if (
- nxt_strip.startswith('|')
- and nxt.rstrip().endswith('|')
- and not re.match(r'^\s*\|[\s:|-]+\|\s*$', nxt)
- ):
- has_data = True
- if not has_data:
- # Empty table — replace with notice.
- notice_text = (
- f"> _All entries in this section were Critical findings "
- f"and have been redacted. {redacted_count} Critical "
- f"{'finding has' if redacted_count == 1 else 'findings have'} "
- f"been forwarded to the project's PMC private mailing list "
- f"for triage through proper channels._"
- )
- out_lines.append(notice_text)
- # Advance past header + alignment, but
- # do NOT consume the blank lines or
- # following content — leave them as
- # natural section separators.
- i += 2
- continue
- out_lines.append(line)
- i += 1
- return '\n'.join(out_lines)
-
- if critical_findings:
- redacted = _replace_empty_tables(redacted, len(critical_findings))
-
- # 3d. Title-based leak scrub. After all the regex strippers
- # have done their best, walk the document one more time and
- # drop any line that contains a redacted finding's TITLE
- # (extracted up at block-detection time). This is the
- # authoritative leak catcher — it uses the actual content
- # of the redacted finding rather than guessing at format,
- # so it catches Top 5 Risks paragraphs, cross-reference
- # entries, and any future format the consolidate LLM
- # invents. We also strip immediately-following continuation
- # lines (paragraph wrap, indented continuations) until we
- # hit a blank line or a clear structural boundary.
- #
- # Titles need to be at least 6 words / 30 chars to be safe
- # to substring-match on — shorter titles risk false
- # positives against unrelated text. Below the threshold we
- # fall back to whole-line containment with word boundaries.
- redacted_titles = [
- cf["title"] for cf in critical_findings
- if cf.get("title") and len(cf["title"]) >= 6
- ]
- if redacted_titles:
- def _strip_title_leaks(text, titles):
- out = []
- lines = text.split('\n')
- in_fence = False
- i = 0
- while i < len(lines):
- line = lines[i]
- stripped = line.lstrip()
- if stripped.startswith('```'):
- in_fence = not in_fence
- out.append(line)
- i += 1
- continue
- if in_fence:
- out.append(line)
- i += 1
- continue
- # Does this line contain any redacted title?
- matched_title = None
- for t in titles:
- # Use literal substring match (case-
- # insensitive). Titles are distinctive
- # enough that this is reliable.
- if t.lower() in line.lower():
- matched_title = t
- break
- if matched_title is None:
- out.append(line)
- i += 1
- continue
- # Drop this line. Also drop following
- # continuation lines until we hit a blank
- # line, a heading, a table separator, or a
- # new list item — whichever comes first.
- i += 1
- while i < len(lines):
- nxt = lines[i]
- nxt_strip = nxt.lstrip()
- if not nxt_strip:
- # blank line ends the dropped block;
- # consume it too so we don't leave
- # an orphan paragraph break
- i += 1
- break
- if nxt_strip.startswith('```'):
- break
- if re.match(r'^#{1,6}\s', nxt_strip):
- break
- if re.match(r'^\s*(?:\d+\.|[-*])\s+\S', nxt):
- break
- if re.match(r'^\|[\s:|-]+\|\s*$', nxt):
- break
- # otherwise it's a continuation line
- # (wrapped prose, indented sub-bullet) —
- # drop it
- i += 1
- return '\n'.join(out)
- redacted = _strip_title_leaks(redacted, redacted_titles)
-
- # 3e. Severity-distribution table regeneration. The
- # in-place regex editing above is fragile against malformed
- # tables that the consolidate LLM occasionally emits
- # (separator and data rows glued together, missing rows,
- # etc). Rather than chasing each malformation, locate the
- # Severity Distribution section and rebuild its table
- # cleanly from the post-redaction findings.
- #
- # We count surviving findings by walking remaining finding
- # blocks for their `**Severity:** X` field. This is robust
- # — it doesn't depend on what shape the original table was
- # in.
- def _rebuild_severity_table(text):
- counts = {"Critical": 0, "High": 0, "Medium": 0,
- "Low": 0, "Info": 0}
- # Find every surviving finding block and count its
- # severity.
- surviving_pattern = re.compile(
- r'####\s+[^\n]+\n[\s\S]*?(?=####\s|##\s|\n---\n|\Z)',
- re.MULTILINE,
- )
- # Severity appears in several formats in practice:
- # - Table cell, bold label: `| **Severity** | 🟠 High |`
- # - Table cell, plain label: `| Severity | ⚪ Info |` (FINDING-020 used this)
- # - Inline, colon inside: `**Severity:** 🟠 High`
- # - Inline, colon after: `**Severity**: 🟠 High`
- # The "Info" severity uses the full word "Informational"
- # in some findings. The previous regex only matched the
- # inline-with-colon-inside form and only the short "Info"
- # name — so on the May 19 run it counted ZERO surviving
- # findings, total stayed 0, the function returned text
- # unchanged, and the malformed table that stripper 787
- # left behind never got regenerated.
- #
- # Two-form regex: form A is `**Severity:**` (colon
- # inside the bold acts as implicit separator). Form B
- # is bold-or-plain `Severity` followed by an explicit
- # `|` or `:` separator. The required separator/internal
- # colon is what keeps this from over-matching prose
- # like "the severity was high".
- sev_re = re.compile(
- r'(?:\*\*Severity:\*\*'
- r'|(?:\*\*)?Severity(?:\*\*)?\s*[|:])'
- r'\s*(?:🔴|🟠|🟡|🔵|⚪|🟢)?\s*\**'
- r'(Critical|High|Medium|Low|Info(?:rmational)?)\b',
- re.IGNORECASE,
- )
- for m in surviving_pattern.finditer(text):
- blk = m.group(0)
- sev_m = sev_re.search(blk)
- if sev_m:
- raw_sev = sev_m.group(1).capitalize()
- # Normalize "Informational" → "Info" so it
- # maps to the counts dict key.
- key = "Info" if raw_sev.lower().startswith("info") else raw_sev
- counts[key] = counts.get(key, 0) + 1
- total = sum(counts.values())
- if total == 0:
- return text # nothing to regenerate against
-
- def pct(n):
- return f"{(100.0 * n / total):.1f}%" if total else "0.0%"
-
- fresh_table = "\n".join([
- "| Severity | Count | Percentage |",
- "|----------|-------|------------|",
- f"| Critical | {counts['Critical']} | {pct(counts['Critical'])} |",
- f"| High | {counts['High']} | {pct(counts['High'])} |",
- f"| Medium | {counts['Medium']} | {pct(counts['Medium'])} |",
- f"| Low | {counts['Low']} | {pct(counts['Low'])} |",
- f"| Info | {counts['Info']} | {pct(counts['Info'])} |",
- ])
-
- # Find the Severity Distribution heading and replace
- # the immediately-following table block (everything
- # from the heading's next non-blank `|`-line through
- # the last `|`-line of that block).
- heading_re = re.compile(
- r'(^#{2,4}\s+Severity\s+Distribution[^\n]*\n+)',
- re.IGNORECASE | re.MULTILINE,
- )
- h_match = heading_re.search(text)
- if not h_match:
- return text
-
- start = h_match.end()
- # advance past blank lines
- j = start
- while j < len(text) and text[j] in ('\n', ' ', '\t'):
- if text[j] == '\n':
- j += 1
- continue
- break
- # find table end: scan forward while lines start with `|`
- # or are blank, until two consecutive non-`|`-non-blank
- # lines (i.e. table ended). simpler: consume contiguous
- # `|` lines and one trailing blank.
- table_end = j
- lines_after = text[j:].split('\n')
- consumed = 0
- for L in lines_after:
- if L.lstrip().startswith('|'):
- consumed += len(L) + 1 # +1 for the \n
- continue
- # allow one blank inside the table, then stop
- if not L.strip():
- consumed += len(L) + 1
- continue
- break
- table_end = j + consumed
-
- return text[:start] + "\n" + fresh_table + "\n\n" + text[table_end:]
-
- redacted = _rebuild_severity_table(redacted)
-
- # 3f. Defense-in-depth final leak check. After every stripper
- # above has run, scan the output for the redacted findings'
- # titles and IDs. If any survive, prepend a visible LEAK
- # warning to the report. The push still happens so the
- # pipeline doesn't break, but the warning is impossible to
- # miss for anyone reading the published file.
- #
- # False-positive guard: title length >= 20 chars (short
- # titles are common phrases that may legitimately appear in
- # surviving finding descriptions); only count matches
- # OUTSIDE code fences (code examples often reproduce
- # vulnerability descriptions). IDs only count when they
- # match a clear FINDING-/ASVS- pattern with a word boundary.
- def _final_leak_check(text, findings):
- # Strip code fences for scanning — code examples often
- # legitimately reproduce vulnerability text
- no_fences = re.sub(r'```[\s\S]*?```', '', text)
- leaks = []
- for cf in findings:
- title = (cf.get("title") or "").strip()
- fid = (cf.get("id") or "").strip()
- if title and len(title) >= 20:
- idx = no_fences.lower().find(title.lower())
- if idx >= 0:
- ctx = no_fences[max(0, idx - 40):idx + len(title) + 40]
- leaks.append({
- "type": "title",
- "value": title,
- "context": " ".join(ctx.split()),
- })
- if fid and fid != "?" and re.match(r'^(FINDING|ASVS|CVE)[-_]', fid, re.IGNORECASE):
- m = re.search(r'\b' + re.escape(fid) + r'\b', no_fences)
- if m:
- idx = m.start()
- ctx = no_fences[max(0, idx - 40):idx + len(fid) + 40]
- leaks.append({
- "type": "id",
- "value": fid,
- "context": " ".join(ctx.split()),
- })
- return leaks
-
- leaks_detected = _final_leak_check(redacted, critical_findings)
- if leaks_detected:
- print(f"!!! REDACTOR LEAK CHECK: {len(leaks_detected)} possible leaks "
- f"survived all strippers", flush=True)
- for l in leaks_detected[:10]:
- print(f" - {l['type'].upper()}: '{l['value']}' "
- f"@ \"...{l['context']}...\"", flush=True)
-
- notice = (
- f"\n\n> **Note:** {len(critical_findings)} Critical "
- f"{'finding has' if len(critical_findings) == 1 else 'findings have'} "
- f"been redacted from this report and forwarded to the project's "
- f"PMC private mailing list.\n\n"
- )
- first_sep = redacted.find("\n---\n")
- if first_sep > 0:
- redacted = redacted[:first_sep + 5] + notice + redacted[first_sep + 5:]
- else:
- redacted = notice + redacted
- return redacted, critical_findings, leaks_detected
-
- def redact_issues(content):
- """Strip Critical issues from the issues.md file.
-
- Same robust structured matching as redact_consolidated. Issues
- use a different block delimiter (`## Issue: ...`) but we look
- for the same structured severity signals.
- """
- issue_pattern = re.compile(
- r'(##\s+Issue:[^\n]*\n[\s\S]*?)(?=##\s+Issue:|\Z)',
- re.MULTILINE,
- )
- redacted = content
- removed_count = 0
-
- def is_critical_issue(block):
- # Issue files have an explicit Priority field
- if re.search(r'\*\*Priority:?\*\*:?\s*Critical\b|priority:\s*critical\b',
- block, re.IGNORECASE):
- return True
- # Severity field (issues sometimes have both)
- if re.search(r'\*\*Severity:?\*\*:?\s*Critical\b', block, re.IGNORECASE):
- return True
- # Finding ID token
- if re.search(r'ASVS-\d+-CRIT(?:ICAL)?-\d+', block, re.IGNORECASE):
- return True
- # Old format
- if re.search(r'🔴\s*Critical\b', block, re.IGNORECASE):
- return True
- return False
-
- for match in issue_pattern.finditer(content):
- block = match.group(1)
- if is_critical_issue(block):
- redacted = redacted.replace(match.group(1), "")
- removed_count += 1
- return redacted, removed_count
-
- def build_email_body(critical_findings, repo_name, commit):
- lines = [
- f"ASVS Security Audit: Critical Findings", "",
- f"Repository: {repo_name}",
- f"Commit: {commit}",
- f"Critical findings: {len(critical_findings)}", "",
- f"The following Critical severity findings were identified",
- f"and have been redacted from the public report.", "",
- f"Full report: https://github.com/{private_repo}/tree/main/{output_directory}/consolidated.md", "",
- ]
- for cf in critical_findings:
- lines.append("---")
- lines.append("")
- lines.append(cf["block"])
- lines.append("")
- return "\n".join(lines)
-
- async def send_email(recipient, subject, body):
- import smtplib
- from email.mime.text import MIMEText
- msg = MIMEText(body, "plain", "utf-8")
- msg["Subject"] = subject
- msg["From"] = "tooling-agents@apache.org"
- msg["To"] = recipient
- try:
- smtp = smtplib.SMTP("mail-relay.apache.org", 587, timeout=30)
- smtp.starttls()
- smtp.send_message(msg)
- smtp.quit()
- print(f" Email sent to {recipient}", flush=True)
- except Exception as e:
- print(f" Email FAILED to {recipient}: {e}", flush=True)
- failures.append(f"email to {recipient}: {e}")
-
- async def read_file_from_github(repo, token, filepath):
- headers = {"Authorization": f"token {token}", "Accept": "application/vnd.github.v3+json"}
- resp = await http_client.get(
- f"https://api.github.com/repos/{repo}/contents/{filepath}",
- headers=headers,
- )
- if resp.status_code == 200:
- data = resp.json()
- return base64.b64decode(data["content"]).decode("utf-8", errors="replace")
- print(f" WARNING: Could not read {repo}/{filepath}: {resp.status_code}", flush=True)
- return None
-
# =============================================================
# ASVS-level filtering
# =============================================================
@@ -2307,7 +1002,7 @@ async def run(input_dict, tools):
#
# Outputs are written to audit-reports-filtered:{output_dir}
# in CouchDB; the four _*.md analysis artifacts also get
- # pushed to {private_repo}/{output_directory}/ when a private
+ # pushed to {output_repo}/{output_directory}/ when an output
# repo + PAT are configured.
#
# Fail-soft end-to-end: if the filter fails or returns no
@@ -2324,18 +1019,17 @@ async def run(input_dict, tools):
f"output_directory: {output_directory}",
f"source_id: {source_id}",
]
- # One PAT covers both jobs: GitHub repo-root fetch (against
- # source_repo) and private-repo push (against private_repo).
- # Prefer private_token because the artifact push is the
- # consequential side-effect; falls back to source_token for
- # the fetch leg. If source is private and private_token
- # lacks access, the fetch will quietly 404 and the filter
- # will still work on whatever it found in the source ns.
- filter_pat = private_token or source_token
+ # The relevance filter optionally pushes its four _*.md
+ # analysis artifacts to a repo. With the carve-out removed
+ # there's one destination: output_repo. Prefer output_token
+ # for the push; fall back to source_token for the source-repo
+ # fetch leg. The filter agent's input key is still named
+ # `private_repo` internally — we feed output_repo into it.
+ filter_pat = output_token or source_token
if filter_pat:
filter_input_lines.append(f"pat: {filter_pat}")
- if private_repo:
- filter_input_lines.append(f"private_repo: {private_repo}")
+ if output_repo:
+ filter_input_lines.append(f"private_repo: {output_repo}")
if supplemental_data:
filter_input_lines.append(
f"audit_guidance_namespaces: {supplemental_data}"
@@ -2444,294 +1138,11 @@ async def run(input_dict, tools):
print(f" Traceback:\n{tb}", flush=True)
failures.append(f"consolidation: {err_type}: {err_msg}")
- # =============================================================
- # Step 5: Carve-out — redact and publish
- # =============================================================
- if carve_out and consolidate and successes:
- print(f"\n{'='*60}\nStep 5: Redacting critical findings for public report\n{'='*60}", flush=True)
- # Read consolidate's outputs from the namespace it mirrors
- # them into, NOT from GitHub. GitHub's contents API is
- # eventually consistent: reading a file from there
- # immediately after pushing it 404s reliably enough that it
- # broke the redactor's issues.md fetch on the May 19 run.
- # The namespace (consolidation:{owner}/{repo}/{dirs_key}) is
- # strongly consistent and is the same one consolidate already
- # uses for its intermediate state. consolidate writes keys
- # `final:consolidated.md` and `final:issues.md` for exactly
- # this purpose. If either is missing, fail loudly — silent
- # warnings hid the problem last time.
- consolidated_content = None
- issues_content = None
- try:
- push_owner, push_repo_only = push_repo.split("/", 1)
- _consol_dirs_key = "+".join(sorted(pass_prefixes))
- _consol_ns_name = f"consolidation:{push_owner}/{push_repo_only}/{_consol_dirs_key}"
- _consol_ns = data_store.use_namespace(_consol_ns_name)
- consolidated_content = _consol_ns.get("final:consolidated.md")
- issues_content = _consol_ns.get("final:issues.md")
- if consolidated_content is None:
- msg = (f"redact: consolidate did not mirror final:consolidated.md "
- f"to namespace {_consol_ns_name}; cannot redact")
- print(f" ERROR: {msg}", flush=True)
- failures.append(msg)
- if issues_content is None:
- msg = (f"redact: consolidate did not mirror final:issues.md "
- f"to namespace {_consol_ns_name}; cannot redact")
- print(f" ERROR: {msg}", flush=True)
- failures.append(msg)
- except Exception as _ns_e:
- msg = f"redact: namespace read failed: {type(_ns_e).__name__}: {_ns_e}"
- print(f" ERROR: {msg}", flush=True)
- failures.append(msg)
-
- # Track what actually gets pushed so the completion summary
- # doesn't lie. Previous summary printed
- # "Redacted consolidated and issues pushed to ..."
- # unconditionally — and on May 19 issues.md was never pushed
- # (it 404'd on read) but the summary still claimed success.
- consolidated_pushed = False
- issues_pushed = False
-
- critical_findings = []
- if consolidated_content:
- redacted_consolidated, critical_findings, consolidated_leaks = redact_consolidated(consolidated_content)
- print(f" Redacted {len(critical_findings)} critical findings", flush=True)
- if consolidated_leaks:
- # ─── Leak detected: route around the public push ────
- # Build the warning banner here in the orchestrator
- # rather than in the redactor so the redactor stays a
- # pure transform. Banner goes ONLY on the private-repo
- # quarantine file; the public repo gets a clean
- # placeholder explaining the report is under review.
- leak_summary_lines = [
- f"- **{l['type'].upper()}:** `{l['value']}` — context: `...{l['context']}...`"
- for l in consolidated_leaks[:10]
- ]
- leak_banner = (
- "> # ⚠️ CARVE-OUT LEAK DETECTED — DO NOT REDISTRIBUTE ⚠️\n"
- ">\n"
- "> The post-redaction defense-in-depth scan found references to "
- f"redacted Critical findings still present in this file ({len(consolidated_leaks)} "
- f"detection{'s' if len(consolidated_leaks) != 1 else ''}). The "
- "automated pipeline withheld this report from the public repo and "
- "wrote it here for manual inspection.\n"
- ">\n"
- "> ## Detected references\n"
- ">\n"
- + "\n".join(f"> {ln}" for ln in leak_summary_lines)
- + "\n>\n"
- "> ## Next steps\n"
- ">\n"
- "> 1. Verify each detection — if any are real leaks, identify "
- "where the stripper missed and patch the redactor.\n"
- "> 2. After fixing, re-run the carve-out manually or via a "
- "re-audit of the same commit.\n"
- "> 3. If detections are false positives (a surviving finding "
- "happens to mention a redacted finding's title), the public push "
- "can be done by hand from this content with the banner removed.\n\n"
- "---\n\n"
- )
-
- # 1) Push the leaky-with-banner version to the PRIVATE repo
- quarantine_filename = "_redaction_warning_consolidated.md"
- try:
- q_result = await gofannon_client.call(
- agent_name="asvs_push_github",
- input_dict={
- "inputText": json.dumps({
- "repo": private_repo, "token": private_token,
- "directory": output_directory,
- "filename": quarantine_filename,
- }),
- "commitMessage": (
- f"ASVS audit: redaction warning ({len(consolidated_leaks)} "
- f"suspected leak{'s' if len(consolidated_leaks) != 1 else ''}) "
- f"[source: {source_id}]"
- ),
- "fileContents": leak_banner + redacted_consolidated,
- }
- )
- q_output = q_result.get("outputText", "") if isinstance(q_result, dict) else ""
- if q_output and "\"content\"" in q_output and "\"commit\"" in q_output:
- print(f" Quarantine pushed: {private_repo}/{output_directory}/{quarantine_filename}", flush=True)
- else:
- err_msg = q_output[:300] if q_output else "(no outputText)"
- failures.append(f"quarantine push: {err_msg}")
- print(f" Quarantine push FAILED: {err_msg}", flush=True)
- except Exception as e:
- typed = type(e).__name__
- detail = str(e) or f"{typed} (no detail)"
- failures.append(f"quarantine push: {detail}")
- print(f" Quarantine push FAILED: {detail}", flush=True)
-
- # 2) Push a clean placeholder to the PUBLIC repo so
- # the URL still resolves but doesn't expose leaks
- public_placeholder = (
- f"# Security Audit Report — Pending Review\n\n"
- f"This ASVS security audit report has been withheld from "
- f"publication pending manual review.\n\n"
- f"**Status:** Under review "
- f"({len(consolidated_leaks)} detection"
- f"{'s' if len(consolidated_leaks) != 1 else ''} from the "
- f"post-redaction defense-in-depth scan)\n\n"
- f"**Source:** {source_id}\n\n"
- f"The audit pipeline's automated redaction process detected "
- f"references to Critical-severity findings that should not be "
- f"disclosed publicly. Per the project's coordinated-disclosure "
- f"policy, the report has not been published until those references "
- f"have been verified and either removed or confirmed as false "
- f"positives.\n\n"
- f"For coordinated disclosure of Critical findings, contact the "
- f"project's security team via the channels documented at the "
- f"project's `SECURITY.md` or `/security` documentation.\n\n"
- f"_This placeholder will be replaced with the full redacted "
- f"report after review completes._\n"
- )
- try:
- p_result = await gofannon_client.call(
- agent_name="asvs_push_github",
- input_dict={
- "inputText": json.dumps({
- "repo": output_repo, "token": output_token,
- "directory": output_directory,
- "filename": "consolidated.md",
- }),
- "commitMessage": (
- f"ASVS {level or 'full'} audit: placeholder "
- f"(report withheld pending review) [source: {source_id}]"
- ),
- "fileContents": public_placeholder,
- }
- )
- p_output = p_result.get("outputText", "") if isinstance(p_result, dict) else ""
- if p_output and "\"content\"" in p_output and "\"commit\"" in p_output:
- print(f" Public placeholder pushed to {output_repo}", flush=True)
- consolidated_pushed = True
- else:
- err_msg = p_output[:300] if p_output else "(no outputText)"
- failures.append(f"public placeholder push: {err_msg}")
- print(f" Public placeholder push FAILED: {err_msg}", flush=True)
- except Exception as e:
- typed = type(e).__name__
- detail = str(e) or f"{typed} (no detail)"
- failures.append(f"public placeholder push: {detail}")
- print(f" Public placeholder push FAILED: {detail}", flush=True)
-
- # Surface as a failure so the run summary doesn't claim
- # everything was clean.
- failures.append(
- f"carve-out leak check: {len(consolidated_leaks)} suspected "
- f"leak(s); public report replaced with placeholder, full "
- f"version in {private_repo}/{output_directory}/{quarantine_filename}"
- )
- else:
- # ─── No leaks: normal public push ─────────────────────
- try:
- push_result = await gofannon_client.call(
- agent_name="asvs_push_github",
- input_dict={
- "inputText": json.dumps({
- "repo": output_repo, "token": output_token,
- "directory": output_directory, "filename": "consolidated.md",
- }),
- "commitMessage": f"ASVS {level or 'full'} audit: consolidated report (redacted) [source: {source_id}]",
- "fileContents": redacted_consolidated,
- }
- )
- output_text = push_result.get("outputText", "") if isinstance(push_result, dict) else ""
- if not output_text or "\"content\"" not in output_text or "\"commit\"" not in output_text:
- err_msg = output_text[:300] if output_text else "(no outputText)"
- try:
- parsed = json.loads(output_text) if output_text else {}
- if isinstance(parsed, dict) and "message" in parsed:
- err_msg = parsed["message"]
- except Exception:
- pass
- failures.append(f"redacted consolidated push to {output_repo}: {err_msg}")
- print(f" Push redacted consolidated.md to {output_repo} FAILED: {err_msg}", flush=True)
- else:
- print(f" Pushed redacted consolidated.md to {output_repo}", flush=True)
- consolidated_pushed = True
- except Exception as e:
- typed = type(e).__name__
- detail = str(e) or f"{typed} (no detail)"
- failures.append(f"redacted consolidated push: {detail}")
- print(f" Push redacted consolidated.md FAILED: {detail}", flush=True)
-
- if issues_content:
- redacted_issues, removed_count = redact_issues(issues_content)
- print(f" Redacted {removed_count} critical issues", flush=True)
- try:
- push_result = await gofannon_client.call(
- agent_name="asvs_push_github",
- input_dict={
- "inputText": json.dumps({
- "repo": output_repo, "token": output_token,
- "directory": output_directory, "filename": "issues.md",
- }),
- "commitMessage": f"ASVS {level or 'full'} audit: issues (redacted) [source: {source_id}]",
- "fileContents": redacted_issues,
- }
- )
- output_text = push_result.get("outputText", "") if isinstance(push_result, dict) else ""
- if not output_text or "\"content\"" not in output_text or "\"commit\"" not in output_text:
- err_msg = output_text[:300] if output_text else "(no outputText)"
- try:
- parsed = json.loads(output_text) if output_text else {}
- if isinstance(parsed, dict) and "message" in parsed:
- err_msg = parsed["message"]
- except Exception:
- pass
- failures.append(f"redacted issues push to {output_repo}: {err_msg}")
- print(f" Push redacted issues.md to {output_repo} FAILED: {err_msg}", flush=True)
- else:
- print(f" Pushed redacted issues.md to {output_repo}", flush=True)
- issues_pushed = True
- except Exception as e:
- typed = type(e).__name__
- detail = str(e) or f"{typed} (no detail)"
- failures.append(f"redacted issues push: {detail}")
- print(f" Push redacted issues.md FAILED: {detail}", flush=True)
-
- # Per-section reports are no longer pushed to GitHub (see
- # reports_namespace above), so there's nothing per-section to
- # redact-and-push here. Public consumers of apache/tooling-agents
- # see only the redacted consolidated.md and issues.md, which
- # contain redaction notices ("N Critical findings have been
- # redacted...") so the existence of redacted findings is still
- # disclosed without their content.
-
- # Truthful completion summary. The previous unconditional
- # "Redacted consolidated and issues pushed" message hid the
- # May 19 issues.md failure entirely; the WARNING three lines
- # earlier was the only signal.
- pushed_files = []
- if consolidated_pushed:
- pushed_files.append("consolidated.md")
- if issues_pushed:
- pushed_files.append("issues.md")
- if pushed_files:
- print(f" Pushed redacted {' and '.join(pushed_files)} to {output_repo}", flush=True)
- if consolidated_content and not consolidated_pushed:
- print(f" WARNING: consolidated.md NOT pushed to {output_repo} (see failures above)", flush=True)
- if issues_content and not issues_pushed:
- print(f" WARNING: issues.md NOT pushed to {output_repo} (see failures above)", flush=True)
-
- if notify_email and critical_findings:
- print(f" Emailing {len(critical_findings)} critical findings to {notify_email}", flush=True)
- email_subject = f"[ASVS Audit] {len(critical_findings)} Critical findings in {repo_owner_name}"
- email_body = build_email_body(critical_findings, repo_owner_name, commit_hash)
- await send_email(notify_email, email_subject, email_body)
-
# =============================================================
# Summary
# =============================================================
print(f"\n{'='*60}\nComplete: {len(successes)} succeeded, {len(failures)} failed", flush=True)
- if carve_out:
- print(f" Full reports: {private_repo}/{output_directory}/", flush=True)
- print(f" Redacted reports: {output_repo}/{output_directory}/", flush=True)
- else:
- print(f" Reports: {output_repo}/{output_directory}/", flush=True)
+ print(f" Reports: {output_repo}/{output_directory}/", flush=True)
if failures:
for f in failures[:20]:
print(f" - {f}", flush=True)
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@tooling.apache.org
For additional commands, e-mail: commits-help@tooling.apache.org